diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000000..da1fc67b06 --- /dev/null +++ b/.clang-format @@ -0,0 +1,33 @@ +--- +Language: Cpp +BasedOnStyle: Mozilla + +AllowAllParametersOfDeclarationOnNextLine: false +AllowShortBlocksOnASingleLine: true +AllowShortFunctionsOnASingleLine: true +AllowShortIfStatementsOnASingleLine: false +AlignAfterOpenBracket: Align +AlignConsecutiveAssignments: false +AlignConsecutiveDeclarations: false +AlwaysBreakAfterReturnType: None +AlwaysBreakAfterDefinitionReturnType: None +BinPackArguments: false +BinPackParameters: false +BreakBeforeBinaryOperators: NonAssignment +BreakConstructorInitializers: BeforeComma +ColumnLimit: 120 +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: true +DerivePointerAlignment: true +FixNamespaceComments: true +IndentWidth: 4 +IndentWrappedFunctionNames: true +IncludeBlocks: Regroup +NamespaceIndentation: None +PointerAlignment: Left +SortIncludes: true +SpacesBeforeTrailingComments: 3 +Standard: Cpp11 +UseTab: Never +... diff --git a/CMakeLists.txt b/CMakeLists.txt index 0ed9ec5cb5..34ea2df18f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -345,6 +345,14 @@ if(IWYU_FOUND) add_custom_target(checkHEADERS DEPENDS $ENV{ALL_HEADER_RULES}) endif(IWYU_FOUND) +find_package2(PRIVATE ClangFormat) +if(ClangFormat_FOUND) + add_custom_target(FormatCheck + ${CMAKE_COMMAND} -E env FAIRROOT_GIT_CLANG_FORMAT_BIN=${GIT_CLANG_FORMAT_BIN} ${CMAKE_SOURCE_DIR}/check-format.sh + WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} + ) +endif() + if(${CMAKE_BUILD_TYPE} MATCHES PROFILE) set(BUILD_UNITTESTS ON) endif() diff --git a/FairRoot_format_test.cmake b/FairRoot_format_test.cmake new file mode 100644 index 0000000000..09dedb5282 --- /dev/null +++ b/FairRoot_format_test.cmake @@ -0,0 +1,35 @@ +################################################################################ +# Copyright (C) 2020 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" # +################################################################################ + +cmake_host_system_information(RESULT fqdn QUERY FQDN) + +set(CTEST_SOURCE_DIRECTORY .) +set(CTEST_BINARY_DIRECTORY build) +Set(CTEST_PROJECT_NAME "FairRoot") +set(CTEST_CMAKE_GENERATOR "Unix Makefiles") +set(CTEST_USE_LAUNCHERS ON) + +if ("$ENV{CTEST_SITE}" STREQUAL "") + set(CTEST_SITE "${fqdn}") +else() + set(CTEST_SITE $ENV{CTEST_SITE}) +endif() + +if ("$ENV{LABEL}" STREQUAL "") + set(CTEST_BUILD_NAME "format-check") +else() + set(CTEST_BUILD_NAME $ENV{LABEL}) +endif() + +ctest_start(Experimental TRACK Checks) + +ctest_configure(OPTIONS "-DDISABLE_COLOR=ON") + +ctest_build(TARGET FormatCheck FLAGS "") + +ctest_submit() diff --git a/Jenkinsfile b/Jenkinsfile index 38f1ba0522..580d9eeb1c 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -4,55 +4,79 @@ def specToLabel(Map spec) { return "${spec.os}-${spec.arch}-${spec.compiler}-FairSoft_${spec.fairsoft}" } -def jobMatrix(String prefix, List specs, Closure callback) { +def jobMatrix(String prefix, String type, List specs, Closure callback) { def nodes = [:] for (spec in specs) { def label = specToLabel(spec) def os = spec.os def compiler = spec.compiler def fairsoft = spec.fairsoft - nodes["${prefix}/${label}"] = { + def job = label + if (spec.containsKey('check')) { + job = spec.check + } + nodes["${type}/${job}"] = { node(label) { - githubNotify(context: "${prefix}/${label}", description: 'Building ...', status: 'PENDING') + githubNotify(context: "${prefix}/${type}/${job}", description: 'Building ...', status: 'PENDING') try { deleteDir() checkout scm - sh """\ - echo "export SIMPATH=\${SIMPATH_PREFIX}${fairsoft}" >> Dart.cfg - echo "export FAIRSOFT_VERSION=${fairsoft}" >> Dart.cfg - """ + def env = '' + if (spec.containsKey('check')) { + env = 'env.sh' + if (os =~ /Debian8/) { + sh """\ + echo "#!/bin/bash" >> ${env} + echo ". /etc/profile.d/modules.sh" >> ${env} + echo "module use /cvmfs/it.gsi.de/modulefiles" >> ${env} + echo "module load cmake" >> ${env} + echo "module load compiler/gcc/9.1.0" >> ${env} + """ + } + sh """\ + echo "export SIMPATH=\${SIMPATH_PREFIX}${fairsoft}" >> ${env} + echo "export LABEL='\${JOB_BASE_NAME} ${spec.check}'" >> ${env} + echo "export PATH=\${CHECKS_PREFIX}${spec.check}/bin:\\\$PATH" >> ${env} + """ + } else { + env = 'Dart.cfg' + sh """\ + echo "export SIMPATH=\${SIMPATH_PREFIX}${fairsoft}" >> ${env} + echo "export FAIRSOFT_VERSION=${fairsoft}" >> ${env} + """ - if (os =~ /Debian8/ && compiler =~ /gcc9/) { - sh '''\ - echo "source /etc/profile.d/modules.sh" >> Dart.cfg - echo "module use /cvmfs/it.gsi.de/modulefiles" >> Dart.cfg - echo "module load compiler/gcc/9.1.0" >> Dart.cfg - ''' - } + if (os =~ /Debian8/ && compiler =~ /gcc9/) { + sh """\ + echo ". /etc/profile.d/modules.sh" >> ${env} + echo "module use /cvmfs/it.gsi.de/modulefiles" >> ${env} + echo "module load compiler/gcc/9.1.0" >> ${env} + """ + } - if (os =~ /MacOS/) { - sh "echo \"export EXTRA_FLAGS=\\\"-DCMAKE_CXX_COMPILER=clang++;-DCMAKE_C_COMPILER=clang\\\"\" >> Dart.cfg" - } else { - sh "echo \"export EXTRA_FLAGS=\\\"-DCMAKE_CXX_COMPILER=g++;-DCMAKE_C_COMPILER=gcc\\\"\" >> Dart.cfg" - } + if (os =~ /MacOS/) { + sh "echo \"export EXTRA_FLAGS=\\\"-DCMAKE_CXX_COMPILER=clang++;-DCMAKE_C_COMPILER=clang\\\"\" >> ${env}" + } else { + sh "echo \"export EXTRA_FLAGS=\\\"-DCMAKE_CXX_COMPILER=g++;-DCMAKE_C_COMPILER=gcc\\\"\" >> ${env}" + } - sh '''\ - echo "export BUILDDIR=$PWD/build" >> Dart.cfg - echo "export SOURCEDIR=$PWD" >> Dart.cfg - echo "export PATH=\\\$SIMPATH/bin:\\\$PATH" >> Dart.cfg - echo "export GIT_BRANCH=$JOB_BASE_NAME" >> Dart.cfg - echo "echo \\\$PATH" >> Dart.cfg - ''' - sh 'cat Dart.cfg' + sh """\ + echo "export BUILDDIR=\${PWD}/build" >> ${env} + echo "export SOURCEDIR=\${PWD}" >> ${env} + echo "export PATH=\\\$SIMPATH/bin:\\\$PATH" >> ${env} + echo "export GIT_BRANCH=\${JOB_BASE_NAME}" >> ${env} + echo "echo \\\$PATH" >> ${env} + """ + } + sh "cat ${env}" - callback.call(spec, label) + callback.call(spec, job, env) deleteDir() - githubNotify(context: "${prefix}/${label}", description: 'Success', status: 'SUCCESS') + githubNotify(context: "${prefix}/${type}/${job}", description: 'Success', status: 'SUCCESS') } catch (e) { deleteDir() - githubNotify(context: "${prefix}/${label}", description: 'Error', status: 'ERROR') + githubNotify(context: "${prefix}/${type}/${job}", description: 'Error', status: 'ERROR') throw e } } @@ -67,7 +91,7 @@ pipeline{ stage("Run CI Matrix") { steps{ script { - def build_jobs = jobMatrix('alfa-ci/build', [ + def builds = jobMatrix('alfa-ci', 'build', [ [os: 'Debian8', arch: 'x86_64', compiler: 'gcc9', fairsoft: 'dev'], [os: 'Debian8', arch: 'x86_64', compiler: 'gcc9', fairsoft: 'dev_mt'], [os: 'MacOS10.13', arch: 'x86_64', compiler: 'AppleLLVM10.0.0', fairsoft: 'dev'], @@ -76,11 +100,17 @@ pipeline{ [os: 'MacOS10.13', arch: 'x86_64', compiler: 'AppleLLVM10.0.0', fairsoft: 'jun19_patches_mt'], [os: 'MacOS10.14', arch: 'x86_64', compiler: 'AppleLLVM10.0.0', fairsoft: 'dev'], [os: 'MacOS10.14', arch: 'x86_64', compiler: 'AppleLLVM10.0.0', fairsoft: 'dev_mt'], - ]) { spec, label -> - sh './Dart.sh alfa_ci Dart.cfg' + ]) { spec, label, config -> + sh "./Dart.sh alfa_ci ${config}" + } + + def checks = jobMatrix('alfa-ci', 'check', [ + [os: 'Debian8', arch: 'x86_64', compiler: 'gcc9', fairsoft: 'dev', check: 'format'], + ]) { spec, check, env -> + sh ". ./${env} && ctest -S FairRoot_${check}_test.cmake -VV" } - parallel(build_jobs) + parallel(checks + builds) } } } diff --git a/MbsAPI/fLmd.c b/MbsAPI/fLmd.c index 7419a5fdd3..35fac89216 100644 --- a/MbsAPI/fLmd.c +++ b/MbsAPI/fLmd.c @@ -1,40 +1,40 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ -#include #include -#include #include -#include -#include +#include +#include #include +#include +#include #ifdef Lynx /* LynxOS */ -#include #include #include +#include #endif #ifdef Linux /* Linux */ -#include #include #include +#include #endif #ifdef Solaris /* Solaris */ -#include #include #include +#include #endif #ifdef Darwin /* Max OS X */ -#include #include #include +#include #define fgetpos64 fgetpos #define fopen64 fopen #define fseeko64 fseek @@ -43,15 +43,10 @@ #ifndef _HAS_CLOCK_REALTIME /* just some dummies for compilation, we will never write lmd with time header in go4*/ #define CLOCK_REALTIME 1 -int clock_gettime(int clockid, struct timespec* tp) -{ - return 0; -} +int clock_gettime(int clockid, struct timespec* tp) { return 0; } #endif #endif - - #ifdef WIN32 #include #include @@ -61,1186 +56,1266 @@ int clock_gettime(int clockid, struct timespec* tp) #define fseeko64 fseek #define fpos64_t fpos_t -struct timespec { - long tv_sec; /* seconds */ - long tv_nsec; /* nanoseconds */ +struct timespec +{ + long tv_sec; /* seconds */ + long tv_nsec; /* nanoseconds */ }; #if defined(_MSC_VER) || defined(_MSC_EXTENSIONS) -#define DELTA_EPOCH_IN_MICROSECS 11644473600000000Ui64 +#define DELTA_EPOCH_IN_MICROSECS 11644473600000000Ui64 #else -#define DELTA_EPOCH_IN_MICROSECS 11644473600000000ULL +#define DELTA_EPOCH_IN_MICROSECS 11644473600000000ULL #endif #define CLOCK_REALTIME 1 int clock_gettime(int clockid, struct timespec* tp) { - FILETIME ft; - unsigned __int64 tmpres = 0; + FILETIME ft; + unsigned __int64 tmpres = 0; - tp->tv_sec = 0; - tp->tv_nsec = 0; + tp->tv_sec = 0; + tp->tv_nsec = 0; - GetSystemTimeAsFileTime(&ft); + GetSystemTimeAsFileTime(&ft); - tmpres |= ft.dwHighDateTime; - tmpres <<= 32; - tmpres |= ft.dwLowDateTime; + tmpres |= ft.dwHighDateTime; + tmpres <<= 32; + tmpres |= ft.dwLowDateTime; - /*converting file time to unix epoch*/ - tmpres /= 10; /*convert into microseconds*/ - tmpres -= DELTA_EPOCH_IN_MICROSECS; - tp->tv_sec = (long)(tmpres / 1000000UL); - tp->tv_nsec = (long)(tmpres % 1000000UL) * 1000; + /*converting file time to unix epoch*/ + tmpres /= 10; /*convert into microseconds*/ + tmpres -= DELTA_EPOCH_IN_MICROSECS; + tp->tv_sec = (long)(tmpres / 1000000UL); + tp->tv_nsec = (long)(tmpres % 1000000UL) * 1000; - return 0; + return 0; } #endif #include "fLmd.h" -int32_t fLmdWriteBuffer(sLmdControl*, char*, uint32_t); +int32_t fLmdWriteBuffer(sLmdControl*, char*, uint32_t); uint32_t fLmdCleanup(sLmdControl*); -void fLmdOffsetResize(sLmdControl*, uint32_t); -uint32_t fLmdOffsetSet(sLmdControl*, uint32_t ); +void fLmdOffsetResize(sLmdControl*, uint32_t); +uint32_t fLmdOffsetSet(sLmdControl*, uint32_t); uint32_t fLmdOffsetRead(sLmdControl*); uint32_t fLmdOffsetWrite(sLmdControl*); lmdoff_t fLmdOffsetGet(sLmdControl*, uint32_t); -void fLmdOffsetElements(sLmdControl*, uint32_t, uint32_t*, uint32_t*); +void fLmdOffsetElements(sLmdControl*, uint32_t, uint32_t*, uint32_t*); #define OFFSET__ENTRIES 250000 //=============================================================== -uint32_t fLmdPutOpen( - sLmdControl* pLmdControl, - char* Filename, - sMbsFileHeader* pBuffHead, // LMD__STANDARD_HEADER (NULL) or address - uint32_t iBytes, // LMD__NO_BUFFER (0) or buffer size - uint32_t iOver, // LMD__[NO_]OVERWRITE - uint32_t iUseOffset, // LMD__[NO_]INDEX - uint32_t iLargeFile) // LMD__[NO_]LARGE_FILE +uint32_t fLmdPutOpen(sLmdControl* pLmdControl, + char* Filename, + sMbsFileHeader* pBuffHead, // LMD__STANDARD_HEADER (NULL) or address + uint32_t iBytes, // LMD__NO_BUFFER (0) or buffer size + uint32_t iOver, // LMD__[NO_]OVERWRITE + uint32_t iUseOffset, // LMD__[NO_]INDEX + uint32_t iLargeFile) // LMD__[NO_]LARGE_FILE { - int32_t iReturn; - struct timespec clock; - - memset(pLmdControl,0,sizeof(sLmdControl)); - - // allocate header or take extern - if(pBuffHead == LMD__STANDARD_HEADER) { - pLmdControl->pMbsFileHeader= (sMbsFileHeader*)malloc(sizeof(sMbsFileHeader)); - memset(pLmdControl->pMbsFileHeader,0,sizeof(sMbsFileHeader)); - pLmdControl->iInternHeader=1; - } else { - pLmdControl->pMbsFileHeader= pBuffHead; - pLmdControl->iInternHeader=0; - } - - clock_gettime(CLOCK_REALTIME,&clock); - pLmdControl->pMbsFileHeader->iTimeSpecSec=clock.tv_sec; - pLmdControl->pMbsFileHeader->iTimeSpecNanoSec=clock.tv_nsec; - - pLmdControl->pMbsFileHeader->iType=LMD__TYPE_FILE_HEADER_101_1; - pLmdControl->pMbsFileHeader->iEndian=1; - size_t len=strlen(Filename); - if (len < sizeof(pLmdControl->cFile)) { - strncpy(pLmdControl->cFile,Filename, len); - } else { - strncpy(pLmdControl->cFile,Filename, sizeof(pLmdControl->cFile)-1); - } - // optionally allocate buffer - if(iBytes > 0) { - pLmdControl->pBuffer=(int16_t*)malloc(iBytes); - pLmdControl->iInternBuffer=1; - } - pLmdControl->iBufferWords=iBytes/2; - pLmdControl->iLeftWords=iBytes/2; - // open file - if(iOver == LMD__NO_OVERWRITE) { // do not overwrite - if((pLmdControl->fFile=(FILE*)fopen64(Filename,"r") )!=NULL) { - printf("fLmdPutOpen: File exists: %s\n",Filename); - fLmdCleanup(pLmdControl); - fclose(pLmdControl->fFile); - return(PUTLMD__FILE_EXIST); - } - } - - if((pLmdControl->fFile=(FILE*)fopen64(Filename,"w+") )== NULL) { - printf("fLmdPutOpen: Error open file %s\n",Filename); - fLmdCleanup(pLmdControl); - return(PUTLMD__OPEN_ERR); - } - - if(iLargeFile == LMD__LARGE_FILE) { pLmdControl->iOffsetSize=8; } - else { pLmdControl->iOffsetSize=4; } - pLmdControl->pMbsFileHeader->iOffsetSize=pLmdControl->iOffsetSize; - - // write header - iReturn=fLmdWriteBuffer(pLmdControl,(char*)pLmdControl->pMbsFileHeader, - (pLmdControl->pMbsFileHeader->iUsedWords)*2+sizeof(sMbsFileHeader)); - pLmdControl->iBytes+=iReturn; - - if(iUseOffset == LMD__INDEX) { fLmdOffsetResize(pLmdControl,iReturn/4); } // create and set first value - printf("fLmdPutOpen: %s. Bytes:%d over:%d table:%d large:%d.\n", - Filename,iBytes,iOver,iUseOffset,iLargeFile); - return(LMD__SUCCESS); + int32_t iReturn; + struct timespec clock; + + memset(pLmdControl, 0, sizeof(sLmdControl)); + + // allocate header or take extern + if (pBuffHead == LMD__STANDARD_HEADER) { + pLmdControl->pMbsFileHeader = (sMbsFileHeader*)malloc(sizeof(sMbsFileHeader)); + memset(pLmdControl->pMbsFileHeader, 0, sizeof(sMbsFileHeader)); + pLmdControl->iInternHeader = 1; + } else { + pLmdControl->pMbsFileHeader = pBuffHead; + pLmdControl->iInternHeader = 0; + } + + clock_gettime(CLOCK_REALTIME, &clock); + pLmdControl->pMbsFileHeader->iTimeSpecSec = clock.tv_sec; + pLmdControl->pMbsFileHeader->iTimeSpecNanoSec = clock.tv_nsec; + + pLmdControl->pMbsFileHeader->iType = LMD__TYPE_FILE_HEADER_101_1; + pLmdControl->pMbsFileHeader->iEndian = 1; + size_t len = strlen(Filename); + if (len < sizeof(pLmdControl->cFile)) { + strncpy(pLmdControl->cFile, Filename, len); + } else { + strncpy(pLmdControl->cFile, Filename, sizeof(pLmdControl->cFile) - 1); + } + // optionally allocate buffer + if (iBytes > 0) { + pLmdControl->pBuffer = (int16_t*)malloc(iBytes); + pLmdControl->iInternBuffer = 1; + } + pLmdControl->iBufferWords = iBytes / 2; + pLmdControl->iLeftWords = iBytes / 2; + // open file + if (iOver == LMD__NO_OVERWRITE) { // do not overwrite + if ((pLmdControl->fFile = (FILE*)fopen64(Filename, "r")) != NULL) { + printf("fLmdPutOpen: File exists: %s\n", Filename); + fLmdCleanup(pLmdControl); + fclose(pLmdControl->fFile); + return (PUTLMD__FILE_EXIST); + } + } + + if ((pLmdControl->fFile = (FILE*)fopen64(Filename, "w+")) == NULL) { + printf("fLmdPutOpen: Error open file %s\n", Filename); + fLmdCleanup(pLmdControl); + return (PUTLMD__OPEN_ERR); + } + + if (iLargeFile == LMD__LARGE_FILE) { + pLmdControl->iOffsetSize = 8; + } else { + pLmdControl->iOffsetSize = 4; + } + pLmdControl->pMbsFileHeader->iOffsetSize = pLmdControl->iOffsetSize; + + // write header + iReturn = fLmdWriteBuffer(pLmdControl, + (char*)pLmdControl->pMbsFileHeader, + (pLmdControl->pMbsFileHeader->iUsedWords) * 2 + sizeof(sMbsFileHeader)); + pLmdControl->iBytes += iReturn; + + if (iUseOffset == LMD__INDEX) { + fLmdOffsetResize(pLmdControl, iReturn / 4); + } // create and set first value + printf("fLmdPutOpen: %s. Bytes:%d over:%d table:%d large:%d.\n", Filename, iBytes, iOver, iUseOffset, iLargeFile); + return (LMD__SUCCESS); } //=============================================================== -uint32_t fLmdPutElement( - sLmdControl* pLmdControl, - sMbsHeader* pHeader) +uint32_t fLmdPutElement(sLmdControl* pLmdControl, sMbsHeader* pHeader) { - uint32_t* ps, *pd, i, elements; - int64_t fileleft,used; - int32_t iReturn; - - // enough space left? - if(pLmdControl->iOffsetEntries && (pLmdControl->iOffsetSize == 4)) { - elements=pLmdControl->iElements+2; - used=pLmdControl->iBytes/4; - fileleft=0xffffffff - used - (4+elements); // size of table - if((int64_t)(pHeader->iWords/2+2) > fileleft) { - printf("fLmdPutElement: File size exceed\n"); - return(PUTLMD__EXCEED); - } - } - // save largest size in header - if((pHeader->iWords+4) > pLmdControl->pMbsFileHeader->iMaxWords) { - pLmdControl->pMbsFileHeader->iMaxWords=pHeader->iWords+4; - } - // no buffer, write element directly - if(pLmdControl->iBufferWords == 0) { - pLmdControl->pMbsHeader=pHeader; - iReturn=fLmdWriteBuffer(pLmdControl,(char*)pHeader,(pHeader->iWords+4)*2); - pLmdControl->iBytes+=iReturn; - if(iReturn != (pHeader->iWords+4)*2) { - printf("fLmdPutElement: Write error \n"); - return(LMD__FAILURE); + uint32_t *ps, *pd, i, elements; + int64_t fileleft, used; + int32_t iReturn; + + // enough space left? + if (pLmdControl->iOffsetEntries && (pLmdControl->iOffsetSize == 4)) { + elements = pLmdControl->iElements + 2; + used = pLmdControl->iBytes / 4; + fileleft = 0xffffffff - used - (4 + elements); // size of table + if ((int64_t)(pHeader->iWords / 2 + 2) > fileleft) { + printf("fLmdPutElement: File size exceed\n"); + return (PUTLMD__EXCEED); + } + } + // save largest size in header + if ((pHeader->iWords + 4) > pLmdControl->pMbsFileHeader->iMaxWords) { + pLmdControl->pMbsFileHeader->iMaxWords = pHeader->iWords + 4; + } + // no buffer, write element directly + if (pLmdControl->iBufferWords == 0) { + pLmdControl->pMbsHeader = pHeader; + iReturn = fLmdWriteBuffer(pLmdControl, (char*)pHeader, (pHeader->iWords + 4) * 2); + pLmdControl->iBytes += iReturn; + if (iReturn != (pHeader->iWords + 4) * 2) { + printf("fLmdPutElement: Write error \n"); + return (LMD__FAILURE); + } + pLmdControl->pMbsFileHeader->iElements++; + pLmdControl->iElements++; + if (pLmdControl->iOffsetEntries) { + fLmdOffsetSet(pLmdControl, iReturn / 4); + } + return (LMD__SUCCESS); + + } // end no buffer + if ((pHeader->iWords + 4) > pLmdControl->iLeftWords) { // flash buffer to file + iReturn = fLmdWriteBuffer( + pLmdControl, (char*)pLmdControl->pBuffer, (pLmdControl->iBufferWords - pLmdControl->iLeftWords) * 2); + pLmdControl->iBytes += iReturn; + if (iReturn != (pLmdControl->iBufferWords - pLmdControl->iLeftWords) * 2) { + return (LMD__FAILURE); + } + pLmdControl->iLeftWords = pLmdControl->iBufferWords; // buffer free + } + if ((pHeader->iWords + 4) > pLmdControl->iLeftWords) { // element too big for buffer + printf("fLmdPutElement: Element too big: %d words\n", pHeader->iWords + 4); + return (PUTLMD__TOOBIG); + } + // copy to buffer + ps = (uint32_t*)pHeader; + pd = (uint32_t*)pLmdControl->pBuffer + (pLmdControl->iBufferWords - pLmdControl->iLeftWords) / 2; + iReturn = (pHeader->iWords + 4) / 2; // here 32b words + for (i = 0; i < iReturn; i++) { + *pd++ = *ps++; } pLmdControl->pMbsFileHeader->iElements++; pLmdControl->iElements++; - if(pLmdControl->iOffsetEntries) { fLmdOffsetSet(pLmdControl,iReturn/4); } - return(LMD__SUCCESS); - - } // end no buffer - if((pHeader->iWords+4) > pLmdControl->iLeftWords) { // flash buffer to file - iReturn=fLmdWriteBuffer(pLmdControl, (char*)pLmdControl->pBuffer, - (pLmdControl->iBufferWords-pLmdControl->iLeftWords)*2); - pLmdControl->iBytes+=iReturn; - if(iReturn != (pLmdControl->iBufferWords-pLmdControl->iLeftWords)*2) { return(LMD__FAILURE); } - pLmdControl->iLeftWords=pLmdControl->iBufferWords; // buffer free - } - if((pHeader->iWords+4) > pLmdControl->iLeftWords) { // element too big for buffer - printf("fLmdPutElement: Element too big: %d words\n",pHeader->iWords+4); - return(PUTLMD__TOOBIG); - } - // copy to buffer - ps=(uint32_t*)pHeader; - pd=(uint32_t*)pLmdControl->pBuffer+(pLmdControl->iBufferWords-pLmdControl->iLeftWords)/2; - iReturn=(pHeader->iWords+4)/2; // here 32b words - for(i=0; ipMbsFileHeader->iElements++; - pLmdControl->iElements++; - pLmdControl->iLeftWords -= (pHeader->iWords+4); - if(pLmdControl->iOffsetEntries) { fLmdOffsetSet(pLmdControl,iReturn); } - return(LMD__SUCCESS); + pLmdControl->iLeftWords -= (pHeader->iWords + 4); + if (pLmdControl->iOffsetEntries) { + fLmdOffsetSet(pLmdControl, iReturn); + } + return (LMD__SUCCESS); } //=============================================================== -uint32_t fLmdPutBuffer( - sLmdControl* pLmdControl, - sMbsHeader* pHeader, - uint32_t Items) +uint32_t fLmdPutBuffer(sLmdControl* pLmdControl, sMbsHeader* pHeader, uint32_t Items) { - sMbsHeader* pH; - uint32_t Bytes=0,TotalBytes=0,i, elements; - int64_t fileleft,used; - int32_t iReturn; - - // check if total buffer fits in file - if(pLmdControl->iOffsetEntries && (pLmdControl->iOffsetSize == 4)) { - pH=pHeader; // SL 16.11.2009 - pH was not initialized in this branch - elements=pLmdControl->iElements+Items+2; - used=pLmdControl->iBytes/4; - fileleft=0xffffffff - used - (4+elements); // size of table - for(i=0; iiWords)*2; - TotalBytes += Bytes; - pH=(sMbsHeader*)((int16_t*)pH + Bytes/2); - } - if((int64_t)TotalBytes/4 > fileleft) { - printf("fLmdPutElement: File size exceed\n"); - return(PUTLMD__EXCEED); - } - Bytes=0; - TotalBytes=0; - } - pH=pHeader; - for(i=0; iiElements++; - Bytes = (4+pH->iWords)*2; - TotalBytes += Bytes; - if(pLmdControl->iOffsetEntries) { fLmdOffsetSet(pLmdControl,Bytes/4); } - if((pH->iWords+4) > pLmdControl->pMbsFileHeader->iMaxWords) { - pLmdControl->pMbsFileHeader->iMaxWords=pH->iWords+4; - } - pH=(sMbsHeader*)((int16_t*)pH+Bytes/2); - } - iReturn=fLmdWriteBuffer(pLmdControl,(char*)pHeader,TotalBytes); - pLmdControl->iBytes+=iReturn; - if(iReturn != TotalBytes) { return(LMD__FAILURE); } - else { - pLmdControl->pMbsFileHeader->iElements += Items; - return(LMD__SUCCESS); - } + sMbsHeader* pH; + uint32_t Bytes = 0, TotalBytes = 0, i, elements; + int64_t fileleft, used; + int32_t iReturn; + + // check if total buffer fits in file + if (pLmdControl->iOffsetEntries && (pLmdControl->iOffsetSize == 4)) { + pH = pHeader; // SL 16.11.2009 - pH was not initialized in this branch + elements = pLmdControl->iElements + Items + 2; + used = pLmdControl->iBytes / 4; + fileleft = 0xffffffff - used - (4 + elements); // size of table + for (i = 0; i < Items; i++) { + Bytes = (4 + pH->iWords) * 2; + TotalBytes += Bytes; + pH = (sMbsHeader*)((int16_t*)pH + Bytes / 2); + } + if ((int64_t)TotalBytes / 4 > fileleft) { + printf("fLmdPutElement: File size exceed\n"); + return (PUTLMD__EXCEED); + } + Bytes = 0; + TotalBytes = 0; + } + pH = pHeader; + for (i = 0; i < Items; i++) { + pLmdControl->iElements++; + Bytes = (4 + pH->iWords) * 2; + TotalBytes += Bytes; + if (pLmdControl->iOffsetEntries) { + fLmdOffsetSet(pLmdControl, Bytes / 4); + } + if ((pH->iWords + 4) > pLmdControl->pMbsFileHeader->iMaxWords) { + pLmdControl->pMbsFileHeader->iMaxWords = pH->iWords + 4; + } + pH = (sMbsHeader*)((int16_t*)pH + Bytes / 2); + } + iReturn = fLmdWriteBuffer(pLmdControl, (char*)pHeader, TotalBytes); + pLmdControl->iBytes += iReturn; + if (iReturn != TotalBytes) { + return (LMD__FAILURE); + } else { + pLmdControl->pMbsFileHeader->iElements += Items; + return (LMD__SUCCESS); + } } //=============================================================== -uint32_t fLmdPutClose( - sLmdControl* pLmdControl) +uint32_t fLmdPutClose(sLmdControl* pLmdControl) { - int32_t iReturn;//,i; -// lmdoff_t current,c; - - if(pLmdControl->iBufferWords > pLmdControl->iLeftWords) { // write last buffer - iReturn=fLmdWriteBuffer(pLmdControl, (char*)pLmdControl->pBuffer, - (pLmdControl->iBufferWords-pLmdControl->iLeftWords)*2); - pLmdControl->iBytes+=iReturn; - if(iReturn != (pLmdControl->iBufferWords-pLmdControl->iLeftWords)*2) { - printf("fLmdPutClose: Error writing last buffer. Closing file.\n"); - // rewind file and rewrite header - rewind(pLmdControl->fFile); /* rewind file, rewrite header */ - fLmdWriteBuffer(pLmdControl, (char*)pLmdControl->pMbsFileHeader, - sizeof(sMbsFileHeader)); - fLmdCleanup(pLmdControl); - return(LMD__FAILURE); - } - } - if(pLmdControl->iOffsetEntries) - if(fLmdOffsetWrite(pLmdControl) != LMD__SUCCESS) { - pLmdControl->pMbsFileHeader->iTableOffset=0; // table could not be written - } - - // rewind file and rewrite header - rewind(pLmdControl->fFile); /* rewind file, rewrite header */ - fLmdWriteBuffer(pLmdControl, (char*)pLmdControl->pMbsFileHeader, - sizeof(sMbsFileHeader)); - return(fLmdGetClose(pLmdControl)); + int32_t iReturn; //,i; + // lmdoff_t current,c; + + if (pLmdControl->iBufferWords > pLmdControl->iLeftWords) { // write last buffer + iReturn = fLmdWriteBuffer( + pLmdControl, (char*)pLmdControl->pBuffer, (pLmdControl->iBufferWords - pLmdControl->iLeftWords) * 2); + pLmdControl->iBytes += iReturn; + if (iReturn != (pLmdControl->iBufferWords - pLmdControl->iLeftWords) * 2) { + printf("fLmdPutClose: Error writing last buffer. Closing file.\n"); + // rewind file and rewrite header + rewind(pLmdControl->fFile); /* rewind file, rewrite header */ + fLmdWriteBuffer(pLmdControl, (char*)pLmdControl->pMbsFileHeader, sizeof(sMbsFileHeader)); + fLmdCleanup(pLmdControl); + return (LMD__FAILURE); + } + } + if (pLmdControl->iOffsetEntries) + if (fLmdOffsetWrite(pLmdControl) != LMD__SUCCESS) { + pLmdControl->pMbsFileHeader->iTableOffset = 0; // table could not be written + } + + // rewind file and rewrite header + rewind(pLmdControl->fFile); /* rewind file, rewrite header */ + fLmdWriteBuffer(pLmdControl, (char*)pLmdControl->pMbsFileHeader, sizeof(sMbsFileHeader)); + return (fLmdGetClose(pLmdControl)); } #ifndef FILEONLY //=============================================================== -uint32_t fLmdConnectMbs( - sLmdControl* pLmdControl, - char* Nodename, - uint32_t iPort, - uint32_t* iBufferBytes) // LMD__GET_EVENTS (NULL) or address to return buffer size +uint32_t fLmdConnectMbs(sLmdControl* pLmdControl, + char* Nodename, + uint32_t iPort, + uint32_t* iBufferBytes) // LMD__GET_EVENTS (NULL) or address to return buffer size { - int32_t stat; - sMbsTransportInfo sMbs; - - if(iPort == 0) { pLmdControl->iPort=PORT__TRANS; } - else { pLmdControl->iPort=iPort; } - memset(pLmdControl,0,sizeof(sLmdControl)); - pLmdControl->pTCP=(struct s_tcpcomm*)malloc(sizeof(struct s_tcpcomm)); - pLmdControl->iTCPowner=1; - if(pLmdControl->iPort==PORT__TRANS) { - printf("fLmdConnectMbs: Connect to transport server %s port %d\n",Nodename,pLmdControl->iPort); - } - if(pLmdControl->iPort==PORT__STREAM) { - printf("fLmdConnectMbs: Connect to stream server %s port %d\n",Nodename,pLmdControl->iPort); - } - stat=f_stc_connectserver(Nodename,pLmdControl->iPort,&pLmdControl->iTCP,pLmdControl->pTCP); - if (stat != STC__SUCCESS) { - printf ("fLmdConnectMbs: Error connect to %s \n",Nodename); - fLmdCleanup(pLmdControl); - return(LMD__FAILURE); - } - stat=f_stc_read((int32_t*)&sMbs, sizeof(sMbsTransportInfo),pLmdControl->iTCP,3); - if (stat != STC__SUCCESS) { - printf ("fLmdConnectMbs: Error read info from %s \n",Nodename); - fLmdCleanup(pLmdControl); - return(LMD__FAILURE); - } - if(sMbs.iEndian != 1) { pLmdControl->iSwap=1; } - if(pLmdControl->iSwap) { fLmdSwap4((uint32_t*)&sMbs,sizeof(sMbsTransportInfo)/4); } - if(sMbs.iBuffers > 1) { - printf("fLmdConnectMbs: Event spanning not supported!\n"); - fLmdCleanup(pLmdControl); - return(LMD__FAILURE); - } - if(sMbs.iStreams > 0) { - printf("fLmdConnectMbs: MBS not in DABC mode!\n"); - fLmdCleanup(pLmdControl); - return(LMD__FAILURE); - } - size_t len=strlen(Nodename); + int32_t stat; + sMbsTransportInfo sMbs; + + if (iPort == 0) { + pLmdControl->iPort = PORT__TRANS; + } else { + pLmdControl->iPort = iPort; + } + memset(pLmdControl, 0, sizeof(sLmdControl)); + pLmdControl->pTCP = (struct s_tcpcomm*)malloc(sizeof(struct s_tcpcomm)); + pLmdControl->iTCPowner = 1; + if (pLmdControl->iPort == PORT__TRANS) { + printf("fLmdConnectMbs: Connect to transport server %s port %d\n", Nodename, pLmdControl->iPort); + } + if (pLmdControl->iPort == PORT__STREAM) { + printf("fLmdConnectMbs: Connect to stream server %s port %d\n", Nodename, pLmdControl->iPort); + } + stat = f_stc_connectserver(Nodename, pLmdControl->iPort, &pLmdControl->iTCP, pLmdControl->pTCP); + if (stat != STC__SUCCESS) { + printf("fLmdConnectMbs: Error connect to %s \n", Nodename); + fLmdCleanup(pLmdControl); + return (LMD__FAILURE); + } + stat = f_stc_read((int32_t*)&sMbs, sizeof(sMbsTransportInfo), pLmdControl->iTCP, 3); + if (stat != STC__SUCCESS) { + printf("fLmdConnectMbs: Error read info from %s \n", Nodename); + fLmdCleanup(pLmdControl); + return (LMD__FAILURE); + } + if (sMbs.iEndian != 1) { + pLmdControl->iSwap = 1; + } + if (pLmdControl->iSwap) { + fLmdSwap4((uint32_t*)&sMbs, sizeof(sMbsTransportInfo) / 4); + } + if (sMbs.iBuffers > 1) { + printf("fLmdConnectMbs: Event spanning not supported!\n"); + fLmdCleanup(pLmdControl); + return (LMD__FAILURE); + } + if (sMbs.iStreams > 0) { + printf("fLmdConnectMbs: MBS not in DABC mode!\n"); + fLmdCleanup(pLmdControl); + return (LMD__FAILURE); + } + size_t len = strlen(Nodename); if (len < sizeof(pLmdControl->cFile)) { - strncpy(pLmdControl->cFile,Nodename, len); + strncpy(pLmdControl->cFile, Nodename, len); } else { - strncpy(pLmdControl->cFile,Nodename, sizeof(pLmdControl->cFile)-1); + strncpy(pLmdControl->cFile, Nodename, sizeof(pLmdControl->cFile) - 1); } - if(iBufferBytes == LMD__GET_EVENTS) { // use internal buffer for fLmdGetMbsEvent - pLmdControl->pBuffer = (int16_t*) malloc(sMbs.iMaxBytes); - pLmdControl->iBufferWords=sMbs.iMaxBytes/2; - pLmdControl->iInternBuffer=1; + if (iBufferBytes == LMD__GET_EVENTS) { // use internal buffer for fLmdGetMbsEvent + pLmdControl->pBuffer = (int16_t*)malloc(sMbs.iMaxBytes); + pLmdControl->iBufferWords = sMbs.iMaxBytes / 2; + pLmdControl->iInternBuffer = 1; } else { - *iBufferBytes=sMbs.iMaxBytes; + *iBufferBytes = sMbs.iMaxBytes; } - return(LMD__SUCCESS); + return (LMD__SUCCESS); } //=============================================================== -uint32_t fLmdInitMbs( - sLmdControl* pLmdControl, - char* Nodename, - uint32_t iMaxBytes, - uint32_t iBuffers, - uint32_t iStreams, - uint32_t iPort, - uint32_t iTimeout) +uint32_t fLmdInitMbs(sLmdControl* pLmdControl, + char* Nodename, + uint32_t iMaxBytes, + uint32_t iBuffers, + uint32_t iStreams, + uint32_t iPort, + uint32_t iTimeout) { -// int32_t stat; - - if(iBuffers > 1) {printf("fLmdInitMbs: Event spanning not supported!\n"); return(LMD__FAILURE);} - if(iStreams > 0) {printf("fLmdInitMbs: MBS not in DABC mode!\n"); return(LMD__FAILURE);} - pLmdControl->iPort=iPort; - size_t len=strlen(Nodename); - if (len < sizeof(pLmdControl->cFile)) { - strncpy(pLmdControl->cFile,Nodename, len); - } else { - strncpy(pLmdControl->cFile,Nodename, sizeof(pLmdControl->cFile)-1); - } - if(pLmdControl->pBuffer == NULL) { pLmdControl->pBuffer= (int16_t*) malloc(iMaxBytes); } - pLmdControl->iBufferWords=iMaxBytes/2; - pLmdControl->iInternBuffer=1; - pLmdControl->iTCP=pLmdControl->pTCP->socket; - pLmdControl->iTcpTimeout=iTimeout; - pLmdControl->iTCPowner=0; - return(LMD__SUCCESS); + // int32_t stat; + + if (iBuffers > 1) { + printf("fLmdInitMbs: Event spanning not supported!\n"); + return (LMD__FAILURE); + } + if (iStreams > 0) { + printf("fLmdInitMbs: MBS not in DABC mode!\n"); + return (LMD__FAILURE); + } + pLmdControl->iPort = iPort; + size_t len = strlen(Nodename); + if (len < sizeof(pLmdControl->cFile)) { + strncpy(pLmdControl->cFile, Nodename, len); + } else { + strncpy(pLmdControl->cFile, Nodename, sizeof(pLmdControl->cFile) - 1); + } + if (pLmdControl->pBuffer == NULL) { + pLmdControl->pBuffer = (int16_t*)malloc(iMaxBytes); + } + pLmdControl->iBufferWords = iMaxBytes / 2; + pLmdControl->iInternBuffer = 1; + pLmdControl->iTCP = pLmdControl->pTCP->socket; + pLmdControl->iTcpTimeout = iTimeout; + pLmdControl->iTCPowner = 0; + return (LMD__SUCCESS); } //=============================================================== uint32_t fLmdCloseMbs(sLmdControl* pLmdControl) { - int32_t stat; - const char cClose[12] = "CLOSE"; - // send request buffer for stream server - if(pLmdControl->iPort == PORT__STREAM) { - stat=f_stc_write(cClose,12,pLmdControl->iTCP); - if(stat != STC__SUCCESS) - { - printf("fLmdCloseMbs: Error writing CLOSE with f_stc_write!\n"); - } - } - stat=f_stc_close(pLmdControl->pTCP); - pLmdControl->pMbsFileHeader = NULL; // was reference only - if(pLmdControl->iTCPowner==0) { pLmdControl->pTCP=NULL; } // was reference only - fLmdCleanup(pLmdControl); - return(stat); + int32_t stat; + const char cClose[12] = "CLOSE"; + // send request buffer for stream server + if (pLmdControl->iPort == PORT__STREAM) { + stat = f_stc_write(cClose, 12, pLmdControl->iTCP); + if (stat != STC__SUCCESS) { + printf("fLmdCloseMbs: Error writing CLOSE with f_stc_write!\n"); + } + } + stat = f_stc_close(pLmdControl->pTCP); + pLmdControl->pMbsFileHeader = NULL; // was reference only + if (pLmdControl->iTCPowner == 0) { + pLmdControl->pTCP = NULL; + } // was reference only + fLmdCleanup(pLmdControl); + return (stat); } //=============================================================== uint32_t fLmdGetMbsEvent(sLmdControl* pLmdControl, sMbsHeader** event) { - uint32_t stat; - sMbsHeader* pM; - *event=NULL; - if(pLmdControl->iLeftWords == 0) { // get new buffer - stat=fLmdGetMbsBuffer(pLmdControl,NULL,0,NULL,NULL); - if(stat != LMD__SUCCESS) { - return(stat); - } - // first event behind header: - pLmdControl->pMbsHeader=(sMbsHeader*)(pLmdControl->pBuffer+sizeof(sMbsBufferHeader)/2); - } - pM=pLmdControl->pMbsHeader; // current to be returned - pLmdControl->iLeftWords -= (pLmdControl->pMbsHeader->iWords+4); - pLmdControl->pMbsHeader = - (sMbsHeader*)((int16_t*)pLmdControl->pMbsHeader + - pLmdControl->pMbsHeader->iWords+4); - pLmdControl->iElements++; - *event=pM; - return(LMD__SUCCESS); + uint32_t stat; + sMbsHeader* pM; + *event = NULL; + if (pLmdControl->iLeftWords == 0) { // get new buffer + stat = fLmdGetMbsBuffer(pLmdControl, NULL, 0, NULL, NULL); + if (stat != LMD__SUCCESS) { + return (stat); + } + // first event behind header: + pLmdControl->pMbsHeader = (sMbsHeader*)(pLmdControl->pBuffer + sizeof(sMbsBufferHeader) / 2); + } + pM = pLmdControl->pMbsHeader; // current to be returned + pLmdControl->iLeftWords -= (pLmdControl->pMbsHeader->iWords + 4); + pLmdControl->pMbsHeader = (sMbsHeader*)((int16_t*)pLmdControl->pMbsHeader + pLmdControl->pMbsHeader->iWords + 4); + pLmdControl->iElements++; + *event = pM; + return (LMD__SUCCESS); } //=============================================================== -uint32_t fLmdGetMbsBuffer( - sLmdControl* pLmdControl, - sMbsBufferHeader* pBuffer, - uint32_t iBytes, - uint32_t* iElements, - uint32_t* iBytesUsed) +uint32_t fLmdGetMbsBuffer(sLmdControl* pLmdControl, + sMbsBufferHeader* pBuffer, + uint32_t iBytes, + uint32_t* iElements, + uint32_t* iBytesUsed) { -// sMbsHeader* pm; - sMbsBufferHeader* pBuf; - uint32_t usedBytes=0,leftBytes=0;//, *ps, *pd, i,ii, elem=0, size=0; - int32_t iReturn; - const char cRequest[12] = "GETEVT"; - - leftBytes=iBytes; - pBuf=pBuffer; - if(pBuf == NULL) { - pBuf=(sMbsBufferHeader*)pLmdControl->pBuffer; // internal buffer - leftBytes=pLmdControl->iBufferWords*2; // size of this buffer - } - if(pBuf == NULL) { - printf("fLmdGetMbsBuffer: Need buffer to read\n"); - return(LMD__FAILURE); - } - if(leftBytes < sizeof(sMbsBufferHeader)) { - printf("fLmdGetMbsBuffer: %s buffer size %d too small for %lx bytes\n", - pLmdControl->cFile,leftBytes,sizeof(sMbsBufferHeader)); - return(LMD__FAILURE); - } - // send request buffer for stream server - if(pLmdControl->iPort == PORT__STREAM) { - iReturn=f_stc_write(cRequest,12,pLmdControl->iTCP); - if(iReturn != STC__SUCCESS) - { - return(LMD__FAILURE); - } - } - iReturn=f_stc_read((int32_t*)pBuf,sizeof(sMbsBufferHeader),pLmdControl->iTCP,pLmdControl->iTcpTimeout); - if(iReturn == STC__TIMEOUT) { return(LMD__TIMEOUT); } - if(iReturn != STC__SUCCESS) { return(LMD__FAILURE); } - if(pLmdControl->iSwap) { fLmdSwap4((uint32_t*)pBuf,sizeof(sMbsBufferHeader)/4); } - if(leftBytes < (sizeof(sMbsBufferHeader)+2*pBuf->iUsedWords)) { - printf("fLmdGetMbsBuffer: %s buffer size %d too small for %lx bytes\n", - pLmdControl->cFile,leftBytes,sizeof(sMbsBufferHeader)+2*pBuf->iMaxWords); - return(LMD__FAILURE); - } - usedBytes=pBuf->iUsedWords*2; - if((pBuf->iType&0xffff) == 100) { - iReturn=f_stc_read((int32_t*)(pBuf+1),usedBytes,pLmdControl->iTCP,-1); - } - if(iReturn == STC__TIMEOUT) { return(LMD__TIMEOUT); } - if(iReturn != STC__SUCCESS) { return(LMD__FAILURE); } - if(pLmdControl->iSwap) { fLmdSwap4((uint32_t*)(pBuf+1),usedBytes/4); } - if(iBytesUsed != NULL) { *iBytesUsed =usedBytes+sizeof(sMbsBufferHeader); } - if(iElements != NULL) { *iElements =pBuf->iElements; } - pLmdControl->iBytes += usedBytes; - pLmdControl->iLeftWords = usedBytes/2; // without header - pLmdControl->pMbsFileHeader = (sMbsFileHeader*)pBuf; - return(LMD__SUCCESS); + // sMbsHeader* pm; + sMbsBufferHeader* pBuf; + uint32_t usedBytes = 0, leftBytes = 0; //, *ps, *pd, i,ii, elem=0, size=0; + int32_t iReturn; + const char cRequest[12] = "GETEVT"; + + leftBytes = iBytes; + pBuf = pBuffer; + if (pBuf == NULL) { + pBuf = (sMbsBufferHeader*)pLmdControl->pBuffer; // internal buffer + leftBytes = pLmdControl->iBufferWords * 2; // size of this buffer + } + if (pBuf == NULL) { + printf("fLmdGetMbsBuffer: Need buffer to read\n"); + return (LMD__FAILURE); + } + if (leftBytes < sizeof(sMbsBufferHeader)) { + printf("fLmdGetMbsBuffer: %s buffer size %d too small for %lx bytes\n", + pLmdControl->cFile, + leftBytes, + sizeof(sMbsBufferHeader)); + return (LMD__FAILURE); + } + // send request buffer for stream server + if (pLmdControl->iPort == PORT__STREAM) { + iReturn = f_stc_write(cRequest, 12, pLmdControl->iTCP); + if (iReturn != STC__SUCCESS) { + return (LMD__FAILURE); + } + } + iReturn = f_stc_read((int32_t*)pBuf, sizeof(sMbsBufferHeader), pLmdControl->iTCP, pLmdControl->iTcpTimeout); + if (iReturn == STC__TIMEOUT) { + return (LMD__TIMEOUT); + } + if (iReturn != STC__SUCCESS) { + return (LMD__FAILURE); + } + if (pLmdControl->iSwap) { + fLmdSwap4((uint32_t*)pBuf, sizeof(sMbsBufferHeader) / 4); + } + if (leftBytes < (sizeof(sMbsBufferHeader) + 2 * pBuf->iUsedWords)) { + printf("fLmdGetMbsBuffer: %s buffer size %d too small for %lx bytes\n", + pLmdControl->cFile, + leftBytes, + sizeof(sMbsBufferHeader) + 2 * pBuf->iMaxWords); + return (LMD__FAILURE); + } + usedBytes = pBuf->iUsedWords * 2; + if ((pBuf->iType & 0xffff) == 100) { + iReturn = f_stc_read((int32_t*)(pBuf + 1), usedBytes, pLmdControl->iTCP, -1); + } + if (iReturn == STC__TIMEOUT) { + return (LMD__TIMEOUT); + } + if (iReturn != STC__SUCCESS) { + return (LMD__FAILURE); + } + if (pLmdControl->iSwap) { + fLmdSwap4((uint32_t*)(pBuf + 1), usedBytes / 4); + } + if (iBytesUsed != NULL) { + *iBytesUsed = usedBytes + sizeof(sMbsBufferHeader); + } + if (iElements != NULL) { + *iElements = pBuf->iElements; + } + pLmdControl->iBytes += usedBytes; + pLmdControl->iLeftWords = usedBytes / 2; // without header + pLmdControl->pMbsFileHeader = (sMbsFileHeader*)pBuf; + return (LMD__SUCCESS); } #endif // endif FILEONLY //=============================================================== -uint32_t fLmdGetOpen( - sLmdControl* pLmdControl, - char* Filename, - sMbsFileHeader* pBuffHead, // LMD__INTERNAL_HEADER (NULL) or address of file header - uint32_t iBytes, // LMD__NO_BUFFER (0) or LMD__MIN_BUFFER or internal buffersize - uint32_t iUseOffset) // LMD__[NO_]INDEX +uint32_t fLmdGetOpen(sLmdControl* pLmdControl, + char* Filename, + sMbsFileHeader* pBuffHead, // LMD__INTERNAL_HEADER (NULL) or address of file header + uint32_t iBytes, // LMD__NO_BUFFER (0) or LMD__MIN_BUFFER or internal buffersize + uint32_t iUseOffset) // LMD__[NO_]INDEX { - int32_t iReturn; - uint32_t bufferBytes=0;//,l=0,i,h[12]; -// lmdoff_t to; - - memset(pLmdControl,0,sizeof(sLmdControl)); - if(pBuffHead == LMD__INTERNAL_HEADER) { - pLmdControl->pMbsFileHeader= (sMbsFileHeader*)malloc(sizeof(sMbsFileHeader)); - pLmdControl->iInternHeader=1; - } else { - pLmdControl->pMbsFileHeader= pBuffHead; - pLmdControl->iInternHeader=0; - } - memset(pLmdControl->pMbsFileHeader,0,sizeof(sMbsFileHeader)); - - // copy file name to control structure - size_t len=strlen(Filename); - if ( len < sizeof(pLmdControl->cFile)) { - strncpy(pLmdControl->cFile, Filename, len); - } else { - strncpy(pLmdControl->cFile, Filename, sizeof(pLmdControl->cFile)-1); - } - if((pLmdControl->fFile=(FILE*)fopen64(Filename,"r"))== NULL) { - printf("fLmdGetOpen: File not found: %s\n",Filename); - fLmdCleanup(pLmdControl); - return(GETLMD__NOFILE); - } - - /* read header */ - iReturn=fLmdReadBuffer(pLmdControl, - (char*)pLmdControl->pMbsFileHeader, - sizeof(sMbsFileHeader)); - if(iReturn!=sizeof(sMbsFileHeader)) { - printf("fLmdGetOpen: LMD format error: no LMD file: %s\n",Filename); - fLmdGetClose(pLmdControl); - return(GETLMD__NOLMDFILE); - } - // check type and subtype, and endian - if(pLmdControl->pMbsFileHeader->iEndian != 1) { pLmdControl->iSwap=1; } - if(pLmdControl->iSwap) { - printf("do swap !!!\n"); - fLmdSwap4((uint32_t*)pLmdControl->pMbsFileHeader,sizeof(sMbsFileHeader)/4); - fLmdSwap8((uint64_t*)&pLmdControl->pMbsFileHeader->iTableOffset,1); - } - if(pLmdControl->pMbsFileHeader->iType != LMD__TYPE_FILE_HEADER_101_1) { - printf("fLmdGetOpen: LMD format error: no LMD file: %s, type is %0x\n", - Filename,pLmdControl->pMbsFileHeader->iType); - fLmdGetClose(pLmdControl); - return(GETLMD__NOLMDFILE); - } - - if((iUseOffset == LMD__INDEX)&&(pLmdControl->pMbsFileHeader->iTableOffset > 0)) { - // printf("fLmdGetOpen: use table in file: %s\n",Filename); - pLmdControl->iOffsetSize=pLmdControl->pMbsFileHeader->iOffsetSize; - iReturn=fLmdOffsetRead(pLmdControl); // read offset table - if(iReturn != LMD__SUCCESS) { - printf("fLmdGetOpen: Index format error: %s\n",Filename); - fLmdGetClose(pLmdControl); - return(iReturn); - } - } - - pLmdControl->iBytes+=iReturn; - // more of header? - if( (pLmdControl->pMbsFileHeader->iUsedWords > 0) && (pLmdControl->pMbsFileHeader->iUsedWords < UINT32_MAX/2) ) { - // Read this additional information without swapping. - // Could be mostly strings. Caller must know. - pLmdControl->cHeader=malloc(pLmdControl->pMbsFileHeader->iUsedWords*2); - iReturn=fLmdReadBuffer(pLmdControl,pLmdControl->cHeader, - pLmdControl->pMbsFileHeader->iUsedWords*2 ); - if(iReturn!=pLmdControl->pMbsFileHeader->iUsedWords*2) { - printf("fLmdGetOpen: LMD format error: no LMD file: %s\n",Filename); - fLmdGetClose(pLmdControl); - return(GETLMD__NOLMDFILE); - } - } - - bufferBytes=iBytes; - if(bufferBytes < pLmdControl->pMbsFileHeader->iMaxWords*2 && (pLmdControl->pMbsFileHeader->iMaxWords < UINT32_MAX/2) ) { - bufferBytes=pLmdControl->pMbsFileHeader->iMaxWords*2; - } - fLmdPrintFileHeader(1,pLmdControl->pMbsFileHeader); - pLmdControl->pBuffer=(int16_t*)malloc(bufferBytes); - pLmdControl->iBufferWords=bufferBytes/2; // will be increased if necessary - - printf("fLmdGetOpen: %s words %u\n", Filename, pLmdControl->iBufferWords); - - pLmdControl->iLeftWords = 0; // buffer empty, read with first fLmdGetElement - pLmdControl->pMbsHeader = NULL; - return(LMD__SUCCESS); -} -//=============================================================== -uint32_t fLmdGetBuffer( - sLmdControl* pLmdControl, - sMbsHeader* pMbsHeader, - uint32_t iBytes, - uint32_t* iElements, - uint32_t* iBytesUsed) -{ + int32_t iReturn; + uint32_t bufferBytes = 0; //,l=0,i,h[12]; + // lmdoff_t to; - sMbsHeader* pm; - uint32_t elem=0,leftBytes=0, used, elem_sz;//, *ps, *pd, i,ii, size=0; - int32_t iReturn; - - if(iBytes < pLmdControl->pMbsFileHeader->iMaxWords) { - printf("fLmdGetBuffer: %s buffer size %d too small for %d bytes\n", - pLmdControl->cFile,iBytes,pLmdControl->pMbsFileHeader->iMaxWords); - return(LMD__FAILURE); - } - if(pMbsHeader == NULL) { - printf("fLmdGetBuffer: Need buffer to read\n"); - return(LMD__FAILURE); - } - *iBytesUsed=0; - *iElements=0; - if(pLmdControl->iElements == pLmdControl->pMbsFileHeader->iElements) { return(GETLMD__EOFILE); } - - // Offset table - if(pLmdControl->iOffsetEntries) { // use offsets to read elements fitting in buffer - fLmdOffsetElements(pLmdControl,iBytes, &elem, &used); - //printf("Read %d bytes of %d, elements %d\n",used,iBytes,elem); - iReturn=fLmdReadBuffer(pLmdControl,(char*)pMbsHeader,used); - if(iReturn <= 0) { - printf("fLmdGetBuffer: EOF: %s\n",pLmdControl->cFile); - return(GETLMD__EOFILE); - } - if(iReturn!=used) { - printf("fLmdGetBuffer: LMD read error: unexpected EOF: %s %u %u\n", - pLmdControl->cFile, iReturn, used); - return(GETLMD__NOLMDFILE); - } - *iBytesUsed=used; - *iElements=elem; - if(pLmdControl->iSwap) { fLmdSwap4((uint32_t*)pMbsHeader,iReturn/4); } - pLmdControl->iBytes+=iReturn; - return(LMD__SUCCESS); - } - // no offset table - // do we have fragment stored? - leftBytes = pLmdControl->iLeftWords*2; - if(leftBytes>0) { - if (leftBytes > iBytes) { - printf("fLmdGetBuffer: stored piece of data (%u) larger than provided buffer (%u)\n", - leftBytes, iBytes); - return(LMD__FAILURE); - } - - if (pLmdControl->pMbsHeader==0) { - printf("fLmdGetBuffer: Internal error pMbsHeader==0\n"); - return(LMD__FAILURE); - } - - memcpy(pMbsHeader, pLmdControl->pMbsHeader, leftBytes); - } - iReturn = fLmdReadBuffer(pLmdControl,(char*)pMbsHeader+leftBytes, iBytes-leftBytes); - if(iReturn <= 0) { - printf("fLmdGetBuffer: EOF: %s\n",pLmdControl->cFile); - if (leftBytes>0) { - printf("fLmdGetBuffer: EOF while we have some rest data (%u)\n", leftBytes); + memset(pLmdControl, 0, sizeof(sLmdControl)); + if (pBuffHead == LMD__INTERNAL_HEADER) { + pLmdControl->pMbsFileHeader = (sMbsFileHeader*)malloc(sizeof(sMbsFileHeader)); + pLmdControl->iInternHeader = 1; } else { - return(GETLMD__EOFILE); - } - } - - if(iReturn > (iBytes-leftBytes)) { - printf("fLmdGetBuffer: LMD read error %s - too many bytes read %u wants %u", - pLmdControl->cFile, iReturn, iBytes-leftBytes); - return(GETLMD__NOLMDFILE); - } - - if(pLmdControl->iSwap) { fLmdSwap4((uint32_t*)pMbsHeader+leftBytes/4,iReturn/4); } - pLmdControl->iBytes += iReturn; - leftBytes += iReturn; // thats what is in the buffer - // step through buffer to get number of elements and size - pm=pMbsHeader; - while(leftBytes >=8) { - if(pm->iType == LMD__TYPE_FILE_INDEX_101_2) { break; } // file index is last - elem_sz = (pm->iWords+4)*2; - if(elem_sz > leftBytes) { break; } // pm valid but incomplete data - - *iBytesUsed += elem_sz; - *iElements += 1; - pLmdControl->iElements++; - pm = (sMbsHeader*)((char*)pm + elem_sz); - leftBytes -= elem_sz; - } - //printf("Read %d bytes of %d, elements %d\n",*iBytesUsed,iBytes,*iElements); - // fragment left? copy to internal buffer - if(leftBytes>0) { - if(leftBytes > pLmdControl->iBufferWords*2) { - printf("fLmdGetBuffer: ERROR: internal buffer overflow. Needed:%d available:%d\n", - leftBytes,pLmdControl->iBufferWords*2); - return(LMD__FAILURE); - } else { - memcpy(pLmdControl->pBuffer,pm,leftBytes); + pLmdControl->pMbsFileHeader = pBuffHead; + pLmdControl->iInternHeader = 0; } - } - pLmdControl->iLeftWords = leftBytes/2; - if (pLmdControl->iLeftWords>0) { - pLmdControl->pMbsHeader = (sMbsHeader*)pLmdControl->pBuffer; - } else { - pLmdControl->pMbsHeader = 0; - } - - return(LMD__SUCCESS); -} -//=============================================================== -uint32_t fLmdGetElement(sLmdControl* pLmdControl, uint32_t iEvent, sMbsHeader** event) -{ - sMbsHeader* pM; - uint32_t i, evsz;//, *ps, *pd; - int32_t iReturn; - *event=NULL; - - if(iEvent == LMD__NO_INDEX) { - if(pLmdControl->pBuffer==NULL) { return(GETLMD__NOBUFFER); } // internal buffer needed - if(pLmdControl->pMbsFileHeader->iElements==0) { return(GETLMD__NOMORE); } - - if (pLmdControl->pMbsHeader == 0) - { - // second, try to read more bytes + memset(pLmdControl->pMbsFileHeader, 0, sizeof(sMbsFileHeader)); - iReturn = fLmdReadBuffer(pLmdControl, - (char*)(pLmdControl->pBuffer+pLmdControl->iLeftWords), - (pLmdControl->iBufferWords-pLmdControl->iLeftWords)*2); + // copy file name to control structure + size_t len = strlen(Filename); + if (len < sizeof(pLmdControl->cFile)) { + strncpy(pLmdControl->cFile, Filename, len); + } else { + strncpy(pLmdControl->cFile, Filename, sizeof(pLmdControl->cFile) - 1); + } + if ((pLmdControl->fFile = (FILE*)fopen64(Filename, "r")) == NULL) { + printf("fLmdGetOpen: File not found: %s\n", Filename); + fLmdCleanup(pLmdControl); + return (GETLMD__NOFILE); + } - if(iReturn <= 0) { printf("fLmdGetElement: EOF\n"); return(GETLMD__EOFILE); } + /* read header */ + iReturn = fLmdReadBuffer(pLmdControl, (char*)pLmdControl->pMbsFileHeader, sizeof(sMbsFileHeader)); + if (iReturn != sizeof(sMbsFileHeader)) { + printf("fLmdGetOpen: LMD format error: no LMD file: %s\n", Filename); + fLmdGetClose(pLmdControl); + return (GETLMD__NOLMDFILE); + } + // check type and subtype, and endian + if (pLmdControl->pMbsFileHeader->iEndian != 1) { + pLmdControl->iSwap = 1; + } + if (pLmdControl->iSwap) { + printf("do swap !!!\n"); + fLmdSwap4((uint32_t*)pLmdControl->pMbsFileHeader, sizeof(sMbsFileHeader) / 4); + fLmdSwap8((uint64_t*)&pLmdControl->pMbsFileHeader->iTableOffset, 1); + } + if (pLmdControl->pMbsFileHeader->iType != LMD__TYPE_FILE_HEADER_101_1) { + printf("fLmdGetOpen: LMD format error: no LMD file: %s, type is %0x\n", + Filename, + pLmdControl->pMbsFileHeader->iType); + fLmdGetClose(pLmdControl); + return (GETLMD__NOLMDFILE); + } - if(pLmdControl->iSwap) { fLmdSwap4((uint32_t*)(pLmdControl->pBuffer+pLmdControl->iLeftWords),iReturn/4); } + if ((iUseOffset == LMD__INDEX) && (pLmdControl->pMbsFileHeader->iTableOffset > 0)) { + // printf("fLmdGetOpen: use table in file: %s\n",Filename); + pLmdControl->iOffsetSize = pLmdControl->pMbsFileHeader->iOffsetSize; + iReturn = fLmdOffsetRead(pLmdControl); // read offset table + if (iReturn != LMD__SUCCESS) { + printf("fLmdGetOpen: Index format error: %s\n", Filename); + fLmdGetClose(pLmdControl); + return (iReturn); + } + } - pLmdControl->iBytes += iReturn; - pLmdControl->pMbsHeader=(sMbsHeader*)pLmdControl->pBuffer; - pLmdControl->iLeftWords += iReturn/2; + pLmdControl->iBytes += iReturn; + // more of header? + if ((pLmdControl->pMbsFileHeader->iUsedWords > 0) && (pLmdControl->pMbsFileHeader->iUsedWords < UINT32_MAX / 2)) { + // Read this additional information without swapping. + // Could be mostly strings. Caller must know. + pLmdControl->cHeader = malloc(pLmdControl->pMbsFileHeader->iUsedWords * 2); + iReturn = fLmdReadBuffer(pLmdControl, pLmdControl->cHeader, pLmdControl->pMbsFileHeader->iUsedWords * 2); + if (iReturn != pLmdControl->pMbsFileHeader->iUsedWords * 2) { + printf("fLmdGetOpen: LMD format error: no LMD file: %s\n", Filename); + fLmdGetClose(pLmdControl); + return (GETLMD__NOLMDFILE); + } } - // check if we need to read extra data - else if((pLmdControl->iLeftWords < 4) || - (pLmdControl->pMbsHeader->iWords+4 > pLmdControl->iLeftWords)) - { - // first copy old data, if it exists - if (pLmdControl->iLeftWords > 0) { - memmove(pLmdControl->pBuffer, pLmdControl->pMbsHeader, pLmdControl->iLeftWords*2); -// printf("copy to the begin rest %u bytes", pLmdControl->iLeftWords*2); - } - // second, try to read more bytes + bufferBytes = iBytes; + if (bufferBytes < pLmdControl->pMbsFileHeader->iMaxWords * 2 + && (pLmdControl->pMbsFileHeader->iMaxWords < UINT32_MAX / 2)) { + bufferBytes = pLmdControl->pMbsFileHeader->iMaxWords * 2; + } + fLmdPrintFileHeader(1, pLmdControl->pMbsFileHeader); + pLmdControl->pBuffer = (int16_t*)malloc(bufferBytes); + pLmdControl->iBufferWords = bufferBytes / 2; // will be increased if necessary - iReturn = fLmdReadBuffer(pLmdControl, - (char*)(pLmdControl->pBuffer+pLmdControl->iLeftWords), - (pLmdControl->iBufferWords-pLmdControl->iLeftWords)*2); + printf("fLmdGetOpen: %s words %u\n", Filename, pLmdControl->iBufferWords); - if(iReturn <= 0) { printf("fLmdGetElement: EOF\n"); return(GETLMD__EOFILE); } + pLmdControl->iLeftWords = 0; // buffer empty, read with first fLmdGetElement + pLmdControl->pMbsHeader = NULL; + return (LMD__SUCCESS); +} +//=============================================================== +uint32_t fLmdGetBuffer(sLmdControl* pLmdControl, + sMbsHeader* pMbsHeader, + uint32_t iBytes, + uint32_t* iElements, + uint32_t* iBytesUsed) +{ - if(pLmdControl->iSwap) { fLmdSwap4((uint32_t*)(pLmdControl->pBuffer+pLmdControl->iLeftWords),iReturn/4); } + sMbsHeader* pm; + uint32_t elem = 0, leftBytes = 0, used, elem_sz; //, *ps, *pd, i,ii, size=0; + int32_t iReturn; - pLmdControl->iBytes += iReturn; - pLmdControl->pMbsHeader=(sMbsHeader*)pLmdControl->pBuffer; - pLmdControl->iLeftWords += iReturn/2; + if (iBytes < pLmdControl->pMbsFileHeader->iMaxWords) { + printf("fLmdGetBuffer: %s buffer size %d too small for %d bytes\n", + pLmdControl->cFile, + iBytes, + pLmdControl->pMbsFileHeader->iMaxWords); + return (LMD__FAILURE); + } + if (pMbsHeader == NULL) { + printf("fLmdGetBuffer: Need buffer to read\n"); + return (LMD__FAILURE); + } + *iBytesUsed = 0; + *iElements = 0; + if (pLmdControl->iElements == pLmdControl->pMbsFileHeader->iElements) { + return (GETLMD__EOFILE); } - // check if read buffer enough for event + // Offset table + if (pLmdControl->iOffsetEntries) { // use offsets to read elements fitting in buffer + fLmdOffsetElements(pLmdControl, iBytes, &elem, &used); + // printf("Read %d bytes of %d, elements %d\n",used,iBytes,elem); + iReturn = fLmdReadBuffer(pLmdControl, (char*)pMbsHeader, used); + if (iReturn <= 0) { + printf("fLmdGetBuffer: EOF: %s\n", pLmdControl->cFile); + return (GETLMD__EOFILE); + } + if (iReturn != used) { + printf("fLmdGetBuffer: LMD read error: unexpected EOF: %s %u %u\n", pLmdControl->cFile, iReturn, used); + return (GETLMD__NOLMDFILE); + } + *iBytesUsed = used; + *iElements = elem; + if (pLmdControl->iSwap) { + fLmdSwap4((uint32_t*)pMbsHeader, iReturn / 4); + } + pLmdControl->iBytes += iReturn; + return (LMD__SUCCESS); + } + // no offset table + // do we have fragment stored? + leftBytes = pLmdControl->iLeftWords * 2; + if (leftBytes > 0) { + if (leftBytes > iBytes) { + printf("fLmdGetBuffer: stored piece of data (%u) larger than provided buffer (%u)\n", leftBytes, iBytes); + return (LMD__FAILURE); + } + + if (pLmdControl->pMbsHeader == 0) { + printf("fLmdGetBuffer: Internal error pMbsHeader==0\n"); + return (LMD__FAILURE); + } + + memcpy(pMbsHeader, pLmdControl->pMbsHeader, leftBytes); + } + iReturn = fLmdReadBuffer(pLmdControl, (char*)pMbsHeader + leftBytes, iBytes - leftBytes); + if (iReturn <= 0) { + printf("fLmdGetBuffer: EOF: %s\n", pLmdControl->cFile); + if (leftBytes > 0) { + printf("fLmdGetBuffer: EOF while we have some rest data (%u)\n", leftBytes); + } else { + return (GETLMD__EOFILE); + } + } - evsz = (pLmdControl->pMbsHeader->iWords + 4) * 2; + if (iReturn > (iBytes - leftBytes)) { + printf("fLmdGetBuffer: LMD read error %s - too many bytes read %u wants %u", + pLmdControl->cFile, + iReturn, + iBytes - leftBytes); + return (GETLMD__NOLMDFILE); + } - if (evsz > pLmdControl->iLeftWords*2) { - printf ("fLmdGetElement: Error, full element %u does not fit in buffer %u", - evsz, pLmdControl->iLeftWords*2); - return (GETLMD__TOOBIG); + if (pLmdControl->iSwap) { + fLmdSwap4((uint32_t*)pMbsHeader + leftBytes / 4, iReturn / 4); + } + pLmdControl->iBytes += iReturn; + leftBytes += iReturn; // thats what is in the buffer + // step through buffer to get number of elements and size + pm = pMbsHeader; + while (leftBytes >= 8) { + if (pm->iType == LMD__TYPE_FILE_INDEX_101_2) { + break; + } // file index is last + elem_sz = (pm->iWords + 4) * 2; + if (elem_sz > leftBytes) { + break; + } // pm valid but incomplete data + + *iBytesUsed += elem_sz; + *iElements += 1; + pLmdControl->iElements++; + pm = (sMbsHeader*)((char*)pm + elem_sz); + leftBytes -= elem_sz; + } + // printf("Read %d bytes of %d, elements %d\n",*iBytesUsed,iBytes,*iElements); + // fragment left? copy to internal buffer + if (leftBytes > 0) { + if (leftBytes > pLmdControl->iBufferWords * 2) { + printf("fLmdGetBuffer: ERROR: internal buffer overflow. Needed:%d available:%d\n", + leftBytes, + pLmdControl->iBufferWords * 2); + return (LMD__FAILURE); + } else { + memcpy(pLmdControl->pBuffer, pm, leftBytes); + } + } + pLmdControl->iLeftWords = leftBytes / 2; + if (pLmdControl->iLeftWords > 0) { + pLmdControl->pMbsHeader = (sMbsHeader*)pLmdControl->pBuffer; + } else { + pLmdControl->pMbsHeader = 0; } - pLmdControl->pMbsFileHeader->iElements--; - pM = pLmdControl->pMbsHeader; - pLmdControl->pMbsHeader = (sMbsHeader*) ((char*) pM + evsz); - pLmdControl->iLeftWords -= evsz/2; - pLmdControl->iElements++; - *event=pM; - return(LMD__SUCCESS); - } - // get indexed event - if(pLmdControl->iOffsetEntries) { - if(iEvent >= pLmdControl->iOffsetEntries) { return(GETLMD__OUTOF_RANGE); } - int val = fseeko64(pLmdControl->fFile,fLmdOffsetGet(pLmdControl,iEvent-1)*4,SEEK_SET); - if(0 != val) - { - return(GETLMD__EOFILE); - } - i=(fLmdOffsetGet(pLmdControl,iEvent)-fLmdOffsetGet(pLmdControl,iEvent-1)); - iReturn=fLmdReadBuffer(pLmdControl,(char*)pLmdControl->pBuffer,i*4); - if(iReturn <= 0) {printf("fLmdGetElement: EOF\n"); return(GETLMD__EOFILE);} - if(iReturn!=(i*4)) { - printf("fLmdGetBuffer: LMD read error: unexpected EOF: %s\n",pLmdControl->cFile); - return(GETLMD__EOFILE); - } - if(pLmdControl->iSwap) { fLmdSwap4((uint32_t*)pLmdControl->pBuffer,iReturn/4); } - pLmdControl->pMbsHeader=(sMbsHeader*)pLmdControl->pBuffer; - if((pLmdControl->pMbsHeader->iWords+4) != i*2) { - printf("fLmdGetElement: Error Event %d: size from table is %d, header %d\n", - iEvent,i/2,pLmdControl->pMbsHeader->iWords+4); - return(GETLMD__SIZE_ERROR); - } - pLmdControl->iBytes+=iReturn; - *event=pLmdControl->pMbsHeader; - return(LMD__SUCCESS); - } else { return(GETLMD__NOMORE); } - // return zero if no more events + return (LMD__SUCCESS); +} +//=============================================================== +uint32_t fLmdGetElement(sLmdControl* pLmdControl, uint32_t iEvent, sMbsHeader** event) +{ + sMbsHeader* pM; + uint32_t i, evsz; //, *ps, *pd; + int32_t iReturn; + *event = NULL; + + if (iEvent == LMD__NO_INDEX) { + if (pLmdControl->pBuffer == NULL) { + return (GETLMD__NOBUFFER); + } // internal buffer needed + if (pLmdControl->pMbsFileHeader->iElements == 0) { + return (GETLMD__NOMORE); + } + + if (pLmdControl->pMbsHeader == 0) { + // second, try to read more bytes + + iReturn = fLmdReadBuffer(pLmdControl, + (char*)(pLmdControl->pBuffer + pLmdControl->iLeftWords), + (pLmdControl->iBufferWords - pLmdControl->iLeftWords) * 2); + + if (iReturn <= 0) { + printf("fLmdGetElement: EOF\n"); + return (GETLMD__EOFILE); + } + + if (pLmdControl->iSwap) { + fLmdSwap4((uint32_t*)(pLmdControl->pBuffer + pLmdControl->iLeftWords), iReturn / 4); + } + + pLmdControl->iBytes += iReturn; + pLmdControl->pMbsHeader = (sMbsHeader*)pLmdControl->pBuffer; + pLmdControl->iLeftWords += iReturn / 2; + } + // check if we need to read extra data + else if ((pLmdControl->iLeftWords < 4) || (pLmdControl->pMbsHeader->iWords + 4 > pLmdControl->iLeftWords)) { + // first copy old data, if it exists + if (pLmdControl->iLeftWords > 0) { + memmove(pLmdControl->pBuffer, pLmdControl->pMbsHeader, pLmdControl->iLeftWords * 2); + // printf("copy to the begin rest %u bytes", pLmdControl->iLeftWords*2); + } + + // second, try to read more bytes + + iReturn = fLmdReadBuffer(pLmdControl, + (char*)(pLmdControl->pBuffer + pLmdControl->iLeftWords), + (pLmdControl->iBufferWords - pLmdControl->iLeftWords) * 2); + + if (iReturn <= 0) { + printf("fLmdGetElement: EOF\n"); + return (GETLMD__EOFILE); + } + + if (pLmdControl->iSwap) { + fLmdSwap4((uint32_t*)(pLmdControl->pBuffer + pLmdControl->iLeftWords), iReturn / 4); + } + + pLmdControl->iBytes += iReturn; + pLmdControl->pMbsHeader = (sMbsHeader*)pLmdControl->pBuffer; + pLmdControl->iLeftWords += iReturn / 2; + } + + // check if read buffer enough for event + + evsz = (pLmdControl->pMbsHeader->iWords + 4) * 2; + + if (evsz > pLmdControl->iLeftWords * 2) { + printf( + "fLmdGetElement: Error, full element %u does not fit in buffer %u", evsz, pLmdControl->iLeftWords * 2); + return (GETLMD__TOOBIG); + } + + pLmdControl->pMbsFileHeader->iElements--; + pM = pLmdControl->pMbsHeader; + pLmdControl->pMbsHeader = (sMbsHeader*)((char*)pM + evsz); + pLmdControl->iLeftWords -= evsz / 2; + pLmdControl->iElements++; + *event = pM; + return (LMD__SUCCESS); + } + // get indexed event + if (pLmdControl->iOffsetEntries) { + if (iEvent >= pLmdControl->iOffsetEntries) { + return (GETLMD__OUTOF_RANGE); + } + int val = fseeko64(pLmdControl->fFile, fLmdOffsetGet(pLmdControl, iEvent - 1) * 4, SEEK_SET); + if (0 != val) { + return (GETLMD__EOFILE); + } + i = (fLmdOffsetGet(pLmdControl, iEvent) - fLmdOffsetGet(pLmdControl, iEvent - 1)); + iReturn = fLmdReadBuffer(pLmdControl, (char*)pLmdControl->pBuffer, i * 4); + if (iReturn <= 0) { + printf("fLmdGetElement: EOF\n"); + return (GETLMD__EOFILE); + } + if (iReturn != (i * 4)) { + printf("fLmdGetBuffer: LMD read error: unexpected EOF: %s\n", pLmdControl->cFile); + return (GETLMD__EOFILE); + } + if (pLmdControl->iSwap) { + fLmdSwap4((uint32_t*)pLmdControl->pBuffer, iReturn / 4); + } + pLmdControl->pMbsHeader = (sMbsHeader*)pLmdControl->pBuffer; + if ((pLmdControl->pMbsHeader->iWords + 4) != i * 2) { + printf("fLmdGetElement: Error Event %d: size from table is %d, header %d\n", + iEvent, + i / 2, + pLmdControl->pMbsHeader->iWords + 4); + return (GETLMD__SIZE_ERROR); + } + pLmdControl->iBytes += iReturn; + *event = pLmdControl->pMbsHeader; + return (LMD__SUCCESS); + } else { + return (GETLMD__NOMORE); + } + // return zero if no more events } //=============================================================== uint32_t fLmdGetClose(sLmdControl* pLmdControl) { - fLmdCleanup(pLmdControl); // cleanup except fFile - if(fclose(pLmdControl->fFile)!=0) { - pLmdControl->fFile=NULL; - return(LMD__CLOSE_ERR); - } - pLmdControl->fFile=NULL; - return(LMD__SUCCESS); + fLmdCleanup(pLmdControl); // cleanup except fFile + if (fclose(pLmdControl->fFile) != 0) { + pLmdControl->fFile = NULL; + return (LMD__CLOSE_ERR); + } + pLmdControl->fFile = NULL; + return (LMD__SUCCESS); } //=============================================================== int32_t fLmdReadBuffer(sLmdControl* pLmdControl, char* buffer, uint32_t bytes) { - int32_t IObytes; - IObytes=(int32_t)fread(buffer,1,bytes,pLmdControl->fFile); - //if(IObytes < bytes) printf("Read %s: request %d bytes, got %d\n",pLmdControl->cFile,bytes,IObytes); - return(IObytes); + int32_t IObytes; + IObytes = (int32_t)fread(buffer, 1, bytes, pLmdControl->fFile); + // if(IObytes < bytes) printf("Read %s: request %d bytes, got %d\n",pLmdControl->cFile,bytes,IObytes); + return (IObytes); } //=============================================================== int32_t fLmdWriteBuffer(sLmdControl* pLmdControl, char* buffer, uint32_t bytes) { - int32_t IObytes; - IObytes=(int32_t)fwrite(buffer,1,bytes,pLmdControl->fFile); - //if(IObytes < bytes) printf("Write %s: request %d bytes, put %d\n", - // pLmdControl->cFile,bytes,IObytes); - return(IObytes); + int32_t IObytes; + IObytes = (int32_t)fwrite(buffer, 1, bytes, pLmdControl->fFile); + // if(IObytes < bytes) printf("Write %s: request %d bytes, put %d\n", + // pLmdControl->cFile,bytes,IObytes); + return (IObytes); } //=============================================================== uint64_t fLmdGetBytesWritten(sLmdControl* pLmdControl) { - uint64_t bytes; - bytes=pLmdControl->iBytes; - // add pending data size in current buffer - if(pLmdControl->iBufferWords > pLmdControl->iLeftWords) { - bytes += (pLmdControl->iBufferWords - pLmdControl->iLeftWords)*2; - } - // add table size which will be written at close - if ((pLmdControl->pOffset4!=NULL)||(pLmdControl->pOffset8!=NULL)) { - bytes += (pLmdControl->iElements+1)*pLmdControl->iOffsetSize; - } - return(bytes); + uint64_t bytes; + bytes = pLmdControl->iBytes; + // add pending data size in current buffer + if (pLmdControl->iBufferWords > pLmdControl->iLeftWords) { + bytes += (pLmdControl->iBufferWords - pLmdControl->iLeftWords) * 2; + } + // add table size which will be written at close + if ((pLmdControl->pOffset4 != NULL) || (pLmdControl->pOffset8 != NULL)) { + bytes += (pLmdControl->iElements + 1) * pLmdControl->iOffsetSize; + } + return (bytes); } //=============================================================== uint32_t fLmdCleanup(sLmdControl* pLmdControl) { -// do not clean fFile - if(pLmdControl->pTCP != NULL) { free(pLmdControl->pTCP); } - if(pLmdControl->cHeader != NULL) { free(pLmdControl->cHeader); } - if(pLmdControl->pOffset4 != NULL) { free(pLmdControl->pOffset4); } - if(pLmdControl->pOffset8 != NULL) { free(pLmdControl->pOffset8); } - if(pLmdControl->pBuffer != NULL && pLmdControl->iInternBuffer) { - free(pLmdControl->pBuffer); - } - if(pLmdControl->pMbsFileHeader != NULL && pLmdControl->iInternHeader) { - free(pLmdControl->pMbsFileHeader); - } - pLmdControl->pTCP=NULL; - pLmdControl->cHeader=NULL; - pLmdControl->pBuffer=NULL; - pLmdControl->pOffset4=NULL; - pLmdControl->pOffset8=NULL; - pLmdControl->pMbsFileHeader=NULL; - pLmdControl->pMbsHeader=NULL; - return (LMD__SUCCESS); + // do not clean fFile + if (pLmdControl->pTCP != NULL) { + free(pLmdControl->pTCP); + } + if (pLmdControl->cHeader != NULL) { + free(pLmdControl->cHeader); + } + if (pLmdControl->pOffset4 != NULL) { + free(pLmdControl->pOffset4); + } + if (pLmdControl->pOffset8 != NULL) { + free(pLmdControl->pOffset8); + } + if (pLmdControl->pBuffer != NULL && pLmdControl->iInternBuffer) { + free(pLmdControl->pBuffer); + } + if (pLmdControl->pMbsFileHeader != NULL && pLmdControl->iInternHeader) { + free(pLmdControl->pMbsFileHeader); + } + pLmdControl->pTCP = NULL; + pLmdControl->cHeader = NULL; + pLmdControl->pBuffer = NULL; + pLmdControl->pOffset4 = NULL; + pLmdControl->pOffset8 = NULL; + pLmdControl->pMbsFileHeader = NULL; + pLmdControl->pMbsHeader = NULL; + return (LMD__SUCCESS); } //=============================================================== // can be called after GetOpen or ConnectMbs uint32_t fLmdGetSwap(sLmdControl* pLmdControl) { - if(pLmdControl != NULL) { - return(pLmdControl->iSwap); - } else { return(-1); } + if (pLmdControl != NULL) { + return (pLmdControl->iSwap); + } else { + return (-1); + } } //=============================================================== // can be called after PutOpen or before PutClose -void fLmdSetWrittenEndian(sLmdControl* pLmdControl,uint32_t iE) +void fLmdSetWrittenEndian(sLmdControl* pLmdControl, uint32_t iE) { - if(pLmdControl->pMbsFileHeader != NULL) { - pLmdControl->pMbsFileHeader->iWrittenEndian=iE; - } else { printf("fLmdSetWrittenEndian: No file header allocated!"); } + if (pLmdControl->pMbsFileHeader != NULL) { + pLmdControl->pMbsFileHeader->iWrittenEndian = iE; + } else { + printf("fLmdSetWrittenEndian: No file header allocated!"); + } } //=============================================================== // can be called after GetOpen or GetMbsEvent -uint32_t fLmdGetWrittenEndian(sLmdControl* pLmdControl) +uint32_t fLmdGetWrittenEndian(sLmdControl* pLmdControl) { - if(pLmdControl->pMbsFileHeader != NULL) { - return(pLmdControl->pMbsFileHeader->iWrittenEndian); - } else { printf("fLmdGetWrittenEndian: No file header allocated!"); } - return(LMD__ENDIAN_UNKNOWN); + if (pLmdControl->pMbsFileHeader != NULL) { + return (pLmdControl->pMbsFileHeader->iWrittenEndian); + } else { + printf("fLmdGetWrittenEndian: No file header allocated!"); + } + return (LMD__ENDIAN_UNKNOWN); } //=============================================================== sLmdControl* fLmdAllocateControl() { - sLmdControl* x; - x=(sLmdControl*)malloc(sizeof(sLmdControl)); - memset(x,0,sizeof(sLmdControl)); - return(x); + sLmdControl* x; + x = (sLmdControl*)malloc(sizeof(sLmdControl)); + memset(x, 0, sizeof(sLmdControl)); + return (x); } //=============================================================== -void fLmdOffsetElements(sLmdControl* pLmdControl, - uint32_t bytes, - uint32_t* elements, - uint32_t* used) +void fLmdOffsetElements(sLmdControl* pLmdControl, uint32_t bytes, uint32_t* elements, uint32_t* used) { - lmdoff_t* off1,*off2; - uint32_t elem=0,i,*iff1,*iff2; - - if(pLmdControl->iOffsetSize == 4) { - iff1=pLmdControl->pOffset4+pLmdControl->iElements; - iff2=iff1; - for(i=pLmdControl->iElements; iiOffsetEntries-1; i++) { - if((*(iff1+1)-*iff2)>bytes/4) { break; } - iff1++; - elem++; - pLmdControl->iElements++; - } - *used=(*iff1-*iff2)*4; - *elements=elem; - } else if(pLmdControl->iOffsetSize == 8) { - off1=pLmdControl->pOffset8+pLmdControl->iElements; - off2=off1; - for(i=pLmdControl->iElements; iiOffsetEntries-1; i++) { - if((*(off1+1)-*off2)>bytes/4) { break; } - off1++; - elem++; - pLmdControl->iElements++; - } - *used=(*off1-*off2)*4; - *elements=elem; - } + lmdoff_t *off1, *off2; + uint32_t elem = 0, i, *iff1, *iff2; + + if (pLmdControl->iOffsetSize == 4) { + iff1 = pLmdControl->pOffset4 + pLmdControl->iElements; + iff2 = iff1; + for (i = pLmdControl->iElements; i < pLmdControl->iOffsetEntries - 1; i++) { + if ((*(iff1 + 1) - *iff2) > bytes / 4) { + break; + } + iff1++; + elem++; + pLmdControl->iElements++; + } + *used = (*iff1 - *iff2) * 4; + *elements = elem; + } else if (pLmdControl->iOffsetSize == 8) { + off1 = pLmdControl->pOffset8 + pLmdControl->iElements; + off2 = off1; + for (i = pLmdControl->iElements; i < pLmdControl->iOffsetEntries - 1; i++) { + if ((*(off1 + 1) - *off2) > bytes / 4) { + break; + } + off1++; + elem++; + pLmdControl->iElements++; + } + *used = (*off1 - *off2) * 4; + *elements = elem; + } } //=============================================================== uint32_t fLmdOffsetRead(sLmdControl* pLmdControl) { - int32_t iReturn; - sMbsHeader* pTableHead; - - pTableHead=(sMbsHeader*)malloc(16); // header with 8 bytes data for future use. - - int val = fseeko64(pLmdControl->fFile,(lmdoff_t)pLmdControl->pMbsFileHeader->iTableOffset*4,SEEK_SET); - if(0 != val) - { - free(pTableHead); - return(GETLMD__NOLMDFILE); - } - iReturn=fLmdReadBuffer(pLmdControl, (char*)pTableHead,16); - if(iReturn!=16) { - printf("fLmdGetBuffer: LMD read error: unexpected EOF: %s\n",pLmdControl->cFile); - free(pTableHead); - return(GETLMD__NOLMDFILE); - } - if(pLmdControl->iSwap) { fLmdSwap4((uint32_t*)pTableHead,4); } - if(pTableHead->iType != LMD__TYPE_FILE_INDEX_101_2) { - printf("fLmdOffsetTable: LMD format error: no index table: %s, type %0x\n", - pLmdControl->cFile,pTableHead->iType); + int32_t iReturn; + sMbsHeader* pTableHead; + + pTableHead = (sMbsHeader*)malloc(16); // header with 8 bytes data for future use. + + int val = fseeko64(pLmdControl->fFile, (lmdoff_t)pLmdControl->pMbsFileHeader->iTableOffset * 4, SEEK_SET); + if (0 != val) { + free(pTableHead); + return (GETLMD__NOLMDFILE); + } + iReturn = fLmdReadBuffer(pLmdControl, (char*)pTableHead, 16); + if (iReturn != 16) { + printf("fLmdGetBuffer: LMD read error: unexpected EOF: %s\n", pLmdControl->cFile); + free(pTableHead); + return (GETLMD__NOLMDFILE); + } + if (pLmdControl->iSwap) { + fLmdSwap4((uint32_t*)pTableHead, 4); + } + if (pTableHead->iType != LMD__TYPE_FILE_INDEX_101_2) { + printf( + "fLmdOffsetTable: LMD format error: no index table: %s, type %0x\n", pLmdControl->cFile, pTableHead->iType); + free(pTableHead); + return (GETLMD__NOLMDFILE); + } + // printf("Table: words:%d type:%08x\n",pTableHead->iWords,pTableHead->iType); free(pTableHead); - return(GETLMD__NOLMDFILE); - } - //printf("Table: words:%d type:%08x\n",pTableHead->iWords,pTableHead->iType); - free(pTableHead); - pLmdControl->iOffsetEntries=pLmdControl->pMbsFileHeader->iElements+1; - pLmdControl->pOffset8=(lmdoff_t*)malloc(pLmdControl->iOffsetEntries*pLmdControl->iOffsetSize); - iReturn=fLmdReadBuffer(pLmdControl, - (char*)pLmdControl->pOffset8, - pLmdControl->iOffsetEntries*pLmdControl->iOffsetSize); - if(iReturn!=pLmdControl->iOffsetEntries*pLmdControl->iOffsetSize) { - printf("fLmdOffsetTable: LMD format error: no index table: %s\n",pLmdControl->cFile); - pLmdControl->iOffsetEntries=0; - return(GETLMD__NOLMDFILE); - } - if(pLmdControl->iSwap) { - fLmdSwap4((uint32_t*)pLmdControl->pOffset8,iReturn/4); - if(pLmdControl->iOffsetSize == 8) { - fLmdSwap8((uint64_t*)pLmdControl->pOffset8,iReturn/8); - } - } - // go back behing header - val = fseeko64(pLmdControl->fFile,(lmdoff_t)sizeof(sMbsFileHeader),SEEK_SET); - if(0 != val) - { - return(GETLMD__NOLMDFILE); - } - // use small table - if(pLmdControl->iOffsetSize == 4) { - pLmdControl->pOffset4= (uint32_t*)pLmdControl->pOffset8; - pLmdControl->pOffset8=NULL; - } - return(LMD__SUCCESS); + pLmdControl->iOffsetEntries = pLmdControl->pMbsFileHeader->iElements + 1; + pLmdControl->pOffset8 = (lmdoff_t*)malloc(pLmdControl->iOffsetEntries * pLmdControl->iOffsetSize); + iReturn = fLmdReadBuffer( + pLmdControl, (char*)pLmdControl->pOffset8, pLmdControl->iOffsetEntries * pLmdControl->iOffsetSize); + if (iReturn != pLmdControl->iOffsetEntries * pLmdControl->iOffsetSize) { + printf("fLmdOffsetTable: LMD format error: no index table: %s\n", pLmdControl->cFile); + pLmdControl->iOffsetEntries = 0; + return (GETLMD__NOLMDFILE); + } + if (pLmdControl->iSwap) { + fLmdSwap4((uint32_t*)pLmdControl->pOffset8, iReturn / 4); + if (pLmdControl->iOffsetSize == 8) { + fLmdSwap8((uint64_t*)pLmdControl->pOffset8, iReturn / 8); + } + } + // go back behing header + val = fseeko64(pLmdControl->fFile, (lmdoff_t)sizeof(sMbsFileHeader), SEEK_SET); + if (0 != val) { + return (GETLMD__NOLMDFILE); + } + // use small table + if (pLmdControl->iOffsetSize == 4) { + pLmdControl->pOffset4 = (uint32_t*)pLmdControl->pOffset8; + pLmdControl->pOffset8 = NULL; + } + return (LMD__SUCCESS); } //=============================================================== uint32_t fLmdOffsetWrite(sLmdControl* pLmdControl) { - int32_t iReturn; - char* pbuf; - lmdoff_t current; - sMbsHeader* pTableHead; - pTableHead=(sMbsHeader*)malloc(16); // header with 8 bytes data for future use. - memset(pTableHead,0,16); - pTableHead->iWords=(pLmdControl->iElements+1)*pLmdControl->iOffsetSize/2+4; - pTableHead->iType=LMD__TYPE_FILE_INDEX_101_2; - /* printf("Table: words:%d type:%08x offbytes:%d\n", */ - /* pTableHead->iWords,pTableHead->iType,pLmdControl->iOffsetSize); */ - iReturn=fgetpos64(pLmdControl->fFile,(fpos64_t*) ¤t); - iReturn=fLmdWriteBuffer(pLmdControl, (char*)pTableHead,16); - free(pTableHead); - pbuf=(char*)pLmdControl->pOffset4; // try short table - if(pbuf == NULL) { pbuf=(char*)pLmdControl->pOffset8; } - iReturn=fLmdWriteBuffer(pLmdControl, pbuf, - (pLmdControl->iElements+1)*pLmdControl->iOffsetSize); - if(pLmdControl->pOffset8) { - pLmdControl->pMbsFileHeader->iTableOffset = *(pLmdControl->pOffset8+pLmdControl->iElements); - } - if(pLmdControl->pOffset4) { - pLmdControl->pMbsFileHeader->iTableOffset = *(pLmdControl->pOffset4+pLmdControl->iElements); - } - if(current/4 != pLmdControl->pMbsFileHeader->iTableOffset) { - printf("Table offset mismatch: current:%lld calculated:%lld, cur-cal %lld\n", - (long long int)(current/4), - (long long int)(pLmdControl->pMbsFileHeader->iTableOffset), - (long long int)(current/4-pLmdControl->pMbsFileHeader->iTableOffset)); - return(LMD__FAILURE); - } - if(iReturn != (pLmdControl->iElements+1)*pLmdControl->iOffsetSize) { - printf("Table write error \n"); - return(LMD__FAILURE); - } - return(LMD__SUCCESS); + int32_t iReturn; + char* pbuf; + lmdoff_t current; + sMbsHeader* pTableHead; + pTableHead = (sMbsHeader*)malloc(16); // header with 8 bytes data for future use. + memset(pTableHead, 0, 16); + pTableHead->iWords = (pLmdControl->iElements + 1) * pLmdControl->iOffsetSize / 2 + 4; + pTableHead->iType = LMD__TYPE_FILE_INDEX_101_2; + /* printf("Table: words:%d type:%08x offbytes:%d\n", */ + /* pTableHead->iWords,pTableHead->iType,pLmdControl->iOffsetSize); */ + iReturn = fgetpos64(pLmdControl->fFile, (fpos64_t*)¤t); + iReturn = fLmdWriteBuffer(pLmdControl, (char*)pTableHead, 16); + free(pTableHead); + pbuf = (char*)pLmdControl->pOffset4; // try short table + if (pbuf == NULL) { + pbuf = (char*)pLmdControl->pOffset8; + } + iReturn = fLmdWriteBuffer(pLmdControl, pbuf, (pLmdControl->iElements + 1) * pLmdControl->iOffsetSize); + if (pLmdControl->pOffset8) { + pLmdControl->pMbsFileHeader->iTableOffset = *(pLmdControl->pOffset8 + pLmdControl->iElements); + } + if (pLmdControl->pOffset4) { + pLmdControl->pMbsFileHeader->iTableOffset = *(pLmdControl->pOffset4 + pLmdControl->iElements); + } + if (current / 4 != pLmdControl->pMbsFileHeader->iTableOffset) { + printf("Table offset mismatch: current:%lld calculated:%lld, cur-cal %lld\n", + (long long int)(current / 4), + (long long int)(pLmdControl->pMbsFileHeader->iTableOffset), + (long long int)(current / 4 - pLmdControl->pMbsFileHeader->iTableOffset)); + return (LMD__FAILURE); + } + if (iReturn != (pLmdControl->iElements + 1) * pLmdControl->iOffsetSize) { + printf("Table write error \n"); + return (LMD__FAILURE); + } + return (LMD__SUCCESS); } //=============================================================== uint32_t fLmdOffsetSet(sLmdControl* pLmdControl, uint32_t lwords) { -// int32_t iReturn; - if(pLmdControl->iElements >= pLmdControl->iOffsetEntries) { fLmdOffsetResize(pLmdControl,0); } - if(pLmdControl->pOffset8) { - *(pLmdControl->pOffset8+pLmdControl->iElements)= - *(pLmdControl->pOffset8+pLmdControl->iElements-1)+(lmdoff_t)lwords; - } - if(pLmdControl->pOffset4) { - *(pLmdControl->pOffset4+pLmdControl->iElements)= - *(pLmdControl->pOffset4+pLmdControl->iElements-1)+lwords; - } - return(LMD__SUCCESS); + // int32_t iReturn; + if (pLmdControl->iElements >= pLmdControl->iOffsetEntries) { + fLmdOffsetResize(pLmdControl, 0); + } + if (pLmdControl->pOffset8) { + *(pLmdControl->pOffset8 + pLmdControl->iElements) = + *(pLmdControl->pOffset8 + pLmdControl->iElements - 1) + (lmdoff_t)lwords; + } + if (pLmdControl->pOffset4) { + *(pLmdControl->pOffset4 + pLmdControl->iElements) = + *(pLmdControl->pOffset4 + pLmdControl->iElements - 1) + lwords; + } + return (LMD__SUCCESS); } //=============================================================== lmdoff_t fLmdOffsetGet(sLmdControl* pLmdControl, uint32_t index) { - if(pLmdControl->pOffset8) { - return(*(pLmdControl->pOffset8+index)); - } - if(pLmdControl->pOffset4) { - return((lmdoff_t)*(pLmdControl->pOffset4+index)); - } - return 0; + if (pLmdControl->pOffset8) { + return (*(pLmdControl->pOffset8 + index)); + } + if (pLmdControl->pOffset4) { + return ((lmdoff_t) * (pLmdControl->pOffset4 + index)); + } + return 0; } //=============================================================== void fLmdOffsetResize(sLmdControl* pLmdControl, uint32_t firstValue) { - lmdoff_t* new; - uint32_t oldEntries,newEntries; - - oldEntries=pLmdControl->iOffsetEntries; - newEntries=oldEntries+OFFSET__ENTRIES; - new=(lmdoff_t*)malloc(newEntries*pLmdControl->iOffsetSize); - memset(new,0,newEntries*pLmdControl->iOffsetSize); - if(oldEntries > 0) { //table was expanded - //printf("Resize table %d to %d entries\n",oldEntries,newEntries); - if(pLmdControl->pOffset8) { - memcpy(new,pLmdControl->pOffset8,oldEntries*pLmdControl->iOffsetSize); - free(pLmdControl->pOffset8); - //pLmdControl->pOffset8=new; - pLmdControl->pOffset8 = (lmdoff_t*)malloc(newEntries*pLmdControl->iOffsetSize); - memcpy(pLmdControl->pOffset8,new,newEntries*pLmdControl->iOffsetSize); - } - if(pLmdControl->pOffset4) { - memcpy(new,pLmdControl->pOffset4,oldEntries*pLmdControl->iOffsetSize); - free(pLmdControl->pOffset4); - //pLmdControl->pOffset4=(uint32_t*)new; - pLmdControl->pOffset4 =(uint32_t*)malloc(newEntries*pLmdControl->iOffsetSize); - memcpy(pLmdControl->pOffset4,new,newEntries*pLmdControl->iOffsetSize); - } - } else { // table was new - //printf("Create table %d entries, first offset %d\n",newEntries,firstValue); - if(pLmdControl->iOffsetSize==8) { - //pLmdControl->pOffset8=new; - pLmdControl->pOffset8 = (lmdoff_t*)malloc(newEntries*pLmdControl->iOffsetSize); - memcpy(pLmdControl->pOffset8,new,newEntries*pLmdControl->iOffsetSize); - *pLmdControl->pOffset8=(lmdoff_t)firstValue; - } - if(pLmdControl->iOffsetSize==4) { - //pLmdControl->pOffset4=(uint32_t*)new; - pLmdControl->pOffset4 =(uint32_t*)malloc(newEntries*pLmdControl->iOffsetSize); - memcpy(pLmdControl->pOffset4,new,newEntries*pLmdControl->iOffsetSize); - *pLmdControl->pOffset4=firstValue; - } - } - free(new); - pLmdControl->iOffsetEntries=newEntries; + lmdoff_t* new; + uint32_t oldEntries, newEntries; + + oldEntries = pLmdControl->iOffsetEntries; + newEntries = oldEntries + OFFSET__ENTRIES; + new = (lmdoff_t*)malloc(newEntries * pLmdControl->iOffsetSize); + memset(new, 0, newEntries * pLmdControl->iOffsetSize); + if (oldEntries > 0) { // table was expanded + // printf("Resize table %d to %d entries\n",oldEntries,newEntries); + if (pLmdControl->pOffset8) { + memcpy(new, pLmdControl->pOffset8, oldEntries * pLmdControl->iOffsetSize); + free(pLmdControl->pOffset8); + // pLmdControl->pOffset8=new; + pLmdControl->pOffset8 = (lmdoff_t*)malloc(newEntries * pLmdControl->iOffsetSize); + memcpy(pLmdControl->pOffset8, new, newEntries * pLmdControl->iOffsetSize); + } + if (pLmdControl->pOffset4) { + memcpy(new, pLmdControl->pOffset4, oldEntries * pLmdControl->iOffsetSize); + free(pLmdControl->pOffset4); + // pLmdControl->pOffset4=(uint32_t*)new; + pLmdControl->pOffset4 = (uint32_t*)malloc(newEntries * pLmdControl->iOffsetSize); + memcpy(pLmdControl->pOffset4, new, newEntries * pLmdControl->iOffsetSize); + } + } else { // table was new + // printf("Create table %d entries, first offset %d\n",newEntries,firstValue); + if (pLmdControl->iOffsetSize == 8) { + // pLmdControl->pOffset8=new; + pLmdControl->pOffset8 = (lmdoff_t*)malloc(newEntries * pLmdControl->iOffsetSize); + memcpy(pLmdControl->pOffset8, new, newEntries * pLmdControl->iOffsetSize); + *pLmdControl->pOffset8 = (lmdoff_t)firstValue; + } + if (pLmdControl->iOffsetSize == 4) { + // pLmdControl->pOffset4=(uint32_t*)new; + pLmdControl->pOffset4 = (uint32_t*)malloc(newEntries * pLmdControl->iOffsetSize); + memcpy(pLmdControl->pOffset4, new, newEntries * pLmdControl->iOffsetSize); + *pLmdControl->pOffset4 = firstValue; + } + } + free(new); + pLmdControl->iOffsetEntries = newEntries; } //=============================================================== void fLmdPrintBufferHeader(uint32_t iVerbose, sMbsBufferHeader* pMbsBufferHeader) { - if(iVerbose) { - if(pMbsBufferHeader) { - printf("BfHd: # %d, DataWords:%d Type:%08x Elements:%d sec:%d.%d MaxWords:%d\n", - pMbsBufferHeader->iBuffer, - pMbsBufferHeader->iUsedWords, - pMbsBufferHeader->iType, - pMbsBufferHeader->iElements, - pMbsBufferHeader->iTimeSpecSec, - pMbsBufferHeader->iTimeSpecNanoSec/1000, - pMbsBufferHeader->iMaxWords); - } - } + if (iVerbose) { + if (pMbsBufferHeader) { + printf("BfHd: # %d, DataWords:%d Type:%08x Elements:%d sec:%d.%d MaxWords:%d\n", + pMbsBufferHeader->iBuffer, + pMbsBufferHeader->iUsedWords, + pMbsBufferHeader->iType, + pMbsBufferHeader->iElements, + pMbsBufferHeader->iTimeSpecSec, + pMbsBufferHeader->iTimeSpecNanoSec / 1000, + pMbsBufferHeader->iMaxWords); + } + } } //=============================================================== void fLmdPrintFileHeader(uint32_t iVerbose, sMbsFileHeader* pMbsFileHeader) { - if(iVerbose) { - if(pMbsFileHeader) { - printf("FiHd: DataWords:%d Type:%d.%d Elements:%d sec:%d.%d MaxWords:%d Index: %llx[%d]\n", - pMbsFileHeader->iUsedWords, - pMbsFileHeader->iType&0xffff, - pMbsFileHeader->iType>>16, - pMbsFileHeader->iElements, - pMbsFileHeader->iTimeSpecSec, - pMbsFileHeader->iTimeSpecNanoSec/1000, - pMbsFileHeader->iMaxWords, - (long long unsigned int)(pMbsFileHeader->iTableOffset), - pMbsFileHeader->iOffsetSize); - } - } + if (iVerbose) { + if (pMbsFileHeader) { + printf("FiHd: DataWords:%d Type:%d.%d Elements:%d sec:%d.%d MaxWords:%d Index: %llx[%d]\n", + pMbsFileHeader->iUsedWords, + pMbsFileHeader->iType & 0xffff, + pMbsFileHeader->iType >> 16, + pMbsFileHeader->iElements, + pMbsFileHeader->iTimeSpecSec, + pMbsFileHeader->iTimeSpecNanoSec / 1000, + pMbsFileHeader->iMaxWords, + (long long unsigned int)(pMbsFileHeader->iTableOffset), + pMbsFileHeader->iOffsetSize); + } + } } //=============================================================== void fLmdPrintHeader(uint32_t iVerbose, sMbsHeader* pMbsHeader) { - if(iVerbose) { - if(pMbsHeader) { - printf("ElHd: words:%d type:%08x\n", - pMbsHeader->iWords, - pMbsHeader->iType); + if (iVerbose) { + if (pMbsHeader) { + printf("ElHd: words:%d type:%08x\n", pMbsHeader->iWords, pMbsHeader->iType); + } } - } } //=============================================================== void fLmdPrintEvent(uint32_t iVerbose, sMbsEventHeader* pMbsEventHeader) { - if(iVerbose) { - if(pMbsEventHeader) { - printf("EvHd: words:%6d type:%08x trigger:%2d #:%4d\n", - pMbsEventHeader->iWords, - pMbsEventHeader->iType, - pMbsEventHeader->iTrigger>>16, - pMbsEventHeader->iEventNumber); - } - } + if (iVerbose) { + if (pMbsEventHeader) { + printf("EvHd: words:%6d type:%08x trigger:%2d #:%4d\n", + pMbsEventHeader->iWords, + pMbsEventHeader->iType, + pMbsEventHeader->iTrigger >> 16, + pMbsEventHeader->iEventNumber); + } + } } //=============================================================== void fLmdPrintControl(uint32_t iVerbose, sLmdControl* pLmdControl) { - if(iVerbose) { - printf("Ctrl: file:%s words:%d left:%d bytes read:%lld elements:%d\n", - pLmdControl->cFile, - pLmdControl->iBufferWords, - pLmdControl->iLeftWords, - (long long int)(pLmdControl->iBytes), - pLmdControl->iElements - ); - fLmdPrintFileHeader(iVerbose,pLmdControl->pMbsFileHeader); - fLmdPrintEvent(iVerbose,(sMbsEventHeader*)pLmdControl->pMbsHeader); - } + if (iVerbose) { + printf("Ctrl: file:%s words:%d left:%d bytes read:%lld elements:%d\n", + pLmdControl->cFile, + pLmdControl->iBufferWords, + pLmdControl->iLeftWords, + (long long int)(pLmdControl->iBytes), + pLmdControl->iElements); + fLmdPrintFileHeader(iVerbose, pLmdControl->pMbsFileHeader); + fLmdPrintEvent(iVerbose, (sMbsEventHeader*)pLmdControl->pMbsHeader); + } } //=============================================================== void fLmdSwap4(uint32_t* array, uint32_t items) { - uint32_t i, *pp; - pp=array; - for(i=0; i> 24) + - ((*pp >> 8)&0x0000ff00) + - ((*pp << 8)&0x00ff0000) + - (*pp << 24); - //printf("to %08x \n",*pp); - pp++; - } + uint32_t i, *pp; + pp = array; + for (i = 0; i < items; i++) { + // printf("Swap 4 %08x ",*pp); + *pp = (*pp >> 24) + ((*pp >> 8) & 0x0000ff00) + ((*pp << 8) & 0x00ff0000) + (*pp << 24); + // printf("to %08x \n",*pp); + pp++; + } } //=============================================================== void fLmdSwap8(uint64_t* array, uint32_t items) { - uint64_t* pp; - uint32_t i;//,x; - pp=array; - for(i=0; i> 32); - //printf("to %016llx\n",*pp,*(pp+1)); - pp++; - } + uint64_t* pp; + uint32_t i; //,x; + pp = array; + for (i = 0; i < items; i++) { + // printf("Swap 8 %016llx ",*pp); + *pp = (*pp << 32) + (*pp >> 32); + // printf("to %016llx\n",*pp,*(pp+1)); + pp++; + } } - diff --git a/MbsAPI/fLmd.h b/MbsAPI/fLmd.h index eedf752e65..93109b7ee9 100644 --- a/MbsAPI/fLmd.h +++ b/MbsAPI/fLmd.h @@ -1,95 +1,96 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef MbsLmdStruct #define MbsLmdStruct -#include - #include "sMbs.h" +#include + #ifndef FILEONLY #include "f_stccomm.h" #endif -#define LMD__SUCCESS 0 -#define LMD__FAILURE 1 -#define LMD__CLOSE_ERR 3 -#define GETLMD__NOFILE 2 -#define GETLMD__NOLMDFILE 4 -#define GETLMD__EOFILE 5 -#define GETLMD__NOMORE 6 -#define GETLMD__NOBUFFER 7 -#define GETLMD__TOOBIG 8 +#define LMD__SUCCESS 0 +#define LMD__FAILURE 1 +#define LMD__CLOSE_ERR 3 +#define GETLMD__NOFILE 2 +#define GETLMD__NOLMDFILE 4 +#define GETLMD__EOFILE 5 +#define GETLMD__NOMORE 6 +#define GETLMD__NOBUFFER 7 +#define GETLMD__TOOBIG 8 #define GETLMD__OUTOF_RANGE 9 #define GETLMD__SIZE_ERROR 10 -#define LMD__TIMEOUT 50 -#define PUTLMD__FILE_EXIST 101 -#define PUTLMD__TOOBIG 102 -#define PUTLMD__OPEN_ERR 103 -#define PUTLMD__EXCEED 104 -#define PORT__TRANS 6000 -#define PORT__STREAM 6002 +#define LMD__TIMEOUT 50 +#define PUTLMD__FILE_EXIST 101 +#define PUTLMD__TOOBIG 102 +#define PUTLMD__OPEN_ERR 103 +#define PUTLMD__EXCEED 104 +#define PORT__TRANS 6000 +#define PORT__STREAM 6002 -typedef struct { - FILE* fFile; /* file descripter or server No. */ - int16_t* pBuffer; /* pointer to internal buffer */ - uint32_t iBufferWords; /* internal buffer size */ - uint32_t iLeftWords; /* left words in buffer */ - uint32_t iInternHeader; /* has intern allocated header buffer */ - uint32_t iInternBuffer; /* has intern allocated buffer */ - uint32_t iElements; /* events since open */ - uint64_t iBytes; /* bytes since open */ - char cFile[512]; /* channel name */ - uint32_t iSwap; - uint32_t iVerbose; - char* cHeader; /* header data buffer */ - uint32_t* pOffset4; /* offset table */ - lmdoff_t* pOffset8; /* long offset table */ - lmdoff_t oTableOffset; /* greater zero when Long offset in file */ - uint32_t iOffsetSize; /* Offset size, 4 or 8 [bytes] */ - uint32_t iOffsetEntries;/* offset table length */ - sMbsFileHeader* pMbsFileHeader; - sMbsHeader* pMbsHeader; - struct s_tcpcomm* pTCP; - uint32_t iTCP; - uint32_t iPort; - uint32_t iTcpTimeout; - uint32_t iTCPowner; +typedef struct +{ + FILE* fFile; /* file descripter or server No. */ + int16_t* pBuffer; /* pointer to internal buffer */ + uint32_t iBufferWords; /* internal buffer size */ + uint32_t iLeftWords; /* left words in buffer */ + uint32_t iInternHeader; /* has intern allocated header buffer */ + uint32_t iInternBuffer; /* has intern allocated buffer */ + uint32_t iElements; /* events since open */ + uint64_t iBytes; /* bytes since open */ + char cFile[512]; /* channel name */ + uint32_t iSwap; + uint32_t iVerbose; + char* cHeader; /* header data buffer */ + uint32_t* pOffset4; /* offset table */ + lmdoff_t* pOffset8; /* long offset table */ + lmdoff_t oTableOffset; /* greater zero when Long offset in file */ + uint32_t iOffsetSize; /* Offset size, 4 or 8 [bytes] */ + uint32_t iOffsetEntries; /* offset table length */ + sMbsFileHeader* pMbsFileHeader; + sMbsHeader* pMbsHeader; + struct s_tcpcomm* pTCP; + uint32_t iTCP; + uint32_t iPort; + uint32_t iTcpTimeout; + uint32_t iTCPowner; } sLmdControl; sLmdControl* fLmdAllocateControl(); -uint32_t fLmdPutOpen(sLmdControl*,char*,sMbsFileHeader*,uint32_t,uint32_t,uint32_t,uint32_t); -uint32_t fLmdPutElement(sLmdControl*,sMbsHeader*); -uint32_t fLmdPutBuffer(sLmdControl*, sMbsHeader*,uint32_t); -uint32_t fLmdPutClose(sLmdControl*); +uint32_t fLmdPutOpen(sLmdControl*, char*, sMbsFileHeader*, uint32_t, uint32_t, uint32_t, uint32_t); +uint32_t fLmdPutElement(sLmdControl*, sMbsHeader*); +uint32_t fLmdPutBuffer(sLmdControl*, sMbsHeader*, uint32_t); +uint32_t fLmdPutClose(sLmdControl*); #ifndef FILEONLY -uint32_t fLmdConnectMbs(sLmdControl*,char*,uint32_t,uint32_t*); -uint32_t fLmdInitMbs(sLmdControl*,char*,uint32_t,uint32_t,uint32_t,uint32_t,uint32_t); -uint32_t fLmdGetMbsBuffer(sLmdControl*,sMbsBufferHeader*,uint32_t,uint32_t*,uint32_t*); -uint32_t fLmdGetMbsEvent(sLmdControl*,sMbsHeader**); -uint32_t fLmdCloseMbs(sLmdControl*); +uint32_t fLmdConnectMbs(sLmdControl*, char*, uint32_t, uint32_t*); +uint32_t fLmdInitMbs(sLmdControl*, char*, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t); +uint32_t fLmdGetMbsBuffer(sLmdControl*, sMbsBufferHeader*, uint32_t, uint32_t*, uint32_t*); +uint32_t fLmdGetMbsEvent(sLmdControl*, sMbsHeader**); +uint32_t fLmdCloseMbs(sLmdControl*); #endif -uint32_t fLmdGetOpen(sLmdControl*,char*,sMbsFileHeader*,uint32_t,uint32_t); -uint32_t fLmdGetBuffer(sLmdControl*,sMbsHeader*,uint32_t,uint32_t*,uint32_t*); -int32_t fLmdReadBuffer(sLmdControl*,char*,uint32_t); -uint32_t fLmdGetElement(sLmdControl*,uint32_t,sMbsHeader**); -uint32_t fLmdGetClose(sLmdControl*); -void fLmdPrintBufferHeader(uint32_t,sMbsBufferHeader*); -void fLmdPrintFileHeader(uint32_t,sMbsFileHeader*); -void fLmdPrintHeader(uint32_t,sMbsHeader*); -void fLmdPrintEvent(uint32_t,sMbsEventHeader*); -void fLmdPrintControl(uint32_t,sLmdControl*); -void fLmdVerbose(sLmdControl*,uint32_t); -void fLmdSwap4(uint32_t*,uint32_t); -void fLmdSwap8(uint64_t*,uint32_t); -void fLmdSetWrittenEndian(sLmdControl*,uint32_t); -uint32_t fLmdGetWrittenEndian(sLmdControl*); -uint32_t fLmdGetSwap(sLmdControl*); -uint64_t fLmdGetBytesWritten(sLmdControl*); +uint32_t fLmdGetOpen(sLmdControl*, char*, sMbsFileHeader*, uint32_t, uint32_t); +uint32_t fLmdGetBuffer(sLmdControl*, sMbsHeader*, uint32_t, uint32_t*, uint32_t*); +int32_t fLmdReadBuffer(sLmdControl*, char*, uint32_t); +uint32_t fLmdGetElement(sLmdControl*, uint32_t, sMbsHeader**); +uint32_t fLmdGetClose(sLmdControl*); +void fLmdPrintBufferHeader(uint32_t, sMbsBufferHeader*); +void fLmdPrintFileHeader(uint32_t, sMbsFileHeader*); +void fLmdPrintHeader(uint32_t, sMbsHeader*); +void fLmdPrintEvent(uint32_t, sMbsEventHeader*); +void fLmdPrintControl(uint32_t, sLmdControl*); +void fLmdVerbose(sLmdControl*, uint32_t); +void fLmdSwap4(uint32_t*, uint32_t); +void fLmdSwap8(uint64_t*, uint32_t); +void fLmdSetWrittenEndian(sLmdControl*, uint32_t); +uint32_t fLmdGetWrittenEndian(sLmdControl*); +uint32_t fLmdGetSwap(sLmdControl*); +uint64_t fLmdGetBytesWritten(sLmdControl*); #endif diff --git a/MbsAPI/f_evt.c b/MbsAPI/f_evt.c index 029078207f..bb7984b3a2 100644 --- a/MbsAPI/f_evt.c +++ b/MbsAPI/f_evt.c @@ -1,23 +1,23 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ -#include "typedefs.h" #include "f_stccomm.h" +#include "typedefs.h" #ifdef RFIO -#define RFIO_open rfio_open +#define RFIO_open rfio_open #define RFIO_close rfio_close -#define RFIO_read rfio_read +#define RFIO_read rfio_read #define RFIO_lseek rfio_lseek -#include "rawapin.h" /* RFIO stuff */ +#include "rawapin.h" /* RFIO stuff */ #else -#define RFIO_open open +#define RFIO_open open #define RFIO_close close -#define RFIO_read read +#define RFIO_read read #define RFIO_lseek lseek #endif @@ -25,125 +25,122 @@ #undef unix #endif -#ifdef GSI__LINUX /* Linux */ +#ifdef GSI__LINUX /* Linux */ #undef unix #endif -#ifdef GSI__SOLARIS /* Solaris */ +#ifdef GSI__SOLARIS /* Solaris */ #undef unix #endif -#ifdef GSI__WINNT /* Windows NT */ +#ifdef GSI__WINNT /* Windows NT */ #endif #ifdef GSI__AIX #define AIX_DEC #endif -#ifdef unix /* DEC OSF/1 */ +#ifdef unix /* DEC OSF/1 */ #define AIX_DEC #endif #ifdef GSI__WINNT -#include +#include #include -#include -#include #include #include -#include #include #include -#include -#define DEF_FILE_ACCE S_IREAD|S_IWRITE /* rw */ -#define GET__OPEN_FLAG O_RDONLY|O_BINARY -#define PUT__OPEN_APD_FLAG O_RDWR|O_APPEND -#define PUT__CRT_FLAG O_CREAT|O_RDWR +#include +#include +#include +#define DEF_FILE_ACCE S_IREAD | S_IWRITE /* rw */ +#define GET__OPEN_FLAG O_RDONLY | O_BINARY +#define PUT__OPEN_APD_FLAG O_RDWR | O_APPEND +#define PUT__CRT_FLAG O_CREAT | O_RDWR #define PUT__CRT_OPT "" #include -#define WS_VERSION_REQD 0x0101 -#define WS_VERSION_MAJOR HIBYTE(WS_VERSION_REQD) -#define WS_VERSION_MINOR LOBYTE(WS_VERSION_REQD) -#define MIN_SOCKETS_REQD 6 +#define WS_VERSION_REQD 0x0101 +#define WS_VERSION_MAJOR HIBYTE(WS_VERSION_REQD) +#define WS_VERSION_MINOR LOBYTE(WS_VERSION_REQD) +#define MIN_SOCKETS_REQD 6 // WSADATA wsaData; #endif #ifdef Linux /* Linux */ -#include -#include #include -#include -#include #include #include +#include +#include +#include +#include #include #include #include -#include -#define DEF_FILE_ACCE S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH /* rw-r--r-- */ +#include +#define DEF_FILE_ACCE S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH /* rw-r--r-- */ #define GET__OPEN_FLAG O_RDONLY -#define PUT__OPEN_APD_FLAG O_RDWR|O_APPEND -#define PUT__CRT_FLAG O_CREAT|O_RDWR +#define PUT__OPEN_APD_FLAG O_RDWR | O_APPEND +#define PUT__CRT_FLAG O_CREAT | O_RDWR #define PUT__CRT_OPT "" #endif #ifdef Solaris /* Linux */ -#include -#include #include -#include -#include #include #include +#include +#include +#include +#include #include #include #include -#include -#define DEF_FILE_ACCE S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH /* rw-r--r-- */ +#include +#define DEF_FILE_ACCE S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH /* rw-r--r-- */ #define GET__OPEN_FLAG O_RDONLY -#define PUT__OPEN_APD_FLAG O_RDWR|O_APPEND -#define PUT__CRT_FLAG O_CREAT|O_RDWR +#define PUT__OPEN_APD_FLAG O_RDWR | O_APPEND +#define PUT__CRT_FLAG O_CREAT | O_RDWR #define PUT__CRT_OPT "" #endif #ifdef Darwin /* MaxOS X */ -#include -#include #include -#include -#include #include #include +#include +#include +#include +#include #include #include #include -#include -#define DEF_FILE_ACCE S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH /* rw-r--r-- */ +#include +#define DEF_FILE_ACCE S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH /* rw-r--r-- */ #define GET__OPEN_FLAG O_RDONLY -#define PUT__OPEN_APD_FLAG O_RDWR|O_APPEND -#define PUT__CRT_FLAG O_CREAT|O_RDWR +#define PUT__OPEN_APD_FLAG O_RDWR | O_APPEND +#define PUT__CRT_FLAG O_CREAT | O_RDWR #define PUT__CRT_OPT "" #endif - - #ifdef _AIX -#include -#include #include -#include -#include #include #include +#include +#include +#include +#include #include #include #include -#include -#define DEF_FILE_ACCE S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH /* rw-r--r-- */ +#include +#define DEF_FILE_ACCE S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH /* rw-r--r-- */ #define GET__OPEN_FLAG O_RDONLY -#define PUT__OPEN_APD_FLAG O_RDWR|O_APPEND -#define PUT__CRT_FLAG O_CREAT|O_RDWR +#define PUT__OPEN_APD_FLAG O_RDWR | O_APPEND +#define PUT__CRT_FLAG O_CREAT | O_RDWR #define PUT__CRT_OPT "" #endif @@ -163,7 +160,7 @@ #include "portnum_def.h" INTS4 f_evt_get_newbuf(s_evt_channel*); -INTS4 f_evt_check_buf(CHARS*,INTS4*, INTS4*, INTS4*, INTS4*); +INTS4 f_evt_check_buf(CHARS*, INTS4*, INTS4*, INTS4*, INTS4*); INTS4 f_evt_ini_bufhe(s_evt_channel* ps_chan); INTS4 f_evt_swap_filhe(s_bufhe*); INTS4 f_ut_utime(INTS4, INTS4, CHARS*); @@ -171,7 +168,7 @@ INTS4 f_ut_utime(INTS4, INTS4, CHARS*); static struct s_tcpcomm s_tcpcomm_st_evt; static CHARS c_temp[MAX_BUF_LGTH]; static int l_gl_rev_port = PORT__EVENT_SERV; -//static int l_gl_evt_check = 0; +// static int l_gl_evt_check = 0; /*1+ C Procedure *************+****************************************/ /* */ @@ -194,7 +191,6 @@ static int l_gl_rev_port = PORT__EVENT_SERV; /*+ Updates : Date Purpose */ /*1- C Procedure *************+****************************************/ - /*****************+***********+****************************************/ /* */ /* GSI, Gesellschaft fuer Schwerionenforschung mbH */ @@ -229,36 +225,53 @@ static int l_gl_rev_port = PORT__EVENT_SERV; /* INTS4 f_evt_get_subevent( */ /* s_ve10_1 *, INTS4, INTS4 **, INTS4 **, INTS4 *); */ /*1- C Procedure *************+****************************************/ -INTS4 f_evt_get_subevent(s_ve10_1* ps_ve10_1, INTS4 l_subevent, INTS4** pl_se, INTS4** pl_d,INTS4* pl_lwords) +INTS4 f_evt_get_subevent(s_ve10_1* ps_ve10_1, INTS4 l_subevent, INTS4** pl_se, INTS4** pl_d, INTS4* pl_lwords) { - s_ves10_1* ps_ves10_1; - INTS4 l_total,l_sub,l_sum; - INTS4 /*l,*/ll,/*l_status,*/*pl_next; - - if(ps_ve10_1 == NULL) { return(GETEVT__FAILURE); } - pl_next = (INTS4*) (ps_ve10_1 + 1); - l_total = ps_ve10_1->l_dlen-4; /* total words in subevents */ - l_sum = 0; - ll=0; - while(l_sum < l_total) { - ps_ves10_1 = (s_ves10_1*) pl_next; - ll++; - if(ll == l_subevent) { - if(pl_lwords != NULL) { *pl_lwords = ps_ves10_1->l_dlen/2-1; } - if(pl_se != NULL) { *pl_se = (INTS4*) ps_ves10_1; } - if(pl_d != NULL) { *pl_d = (INTS4*) (ps_ves10_1+1); } - return(GETEVT__SUCCESS); - } - l_sub = ps_ves10_1->l_dlen+4; /* total words of subevent */ - l_sum += l_sub; - pl_next = (INTS4*)(ps_ves10_1); - pl_next += l_sub/2; - } - if(pl_lwords != NULL) { *pl_lwords = ll; } - if(pl_se != NULL) { *pl_se = NULL; } - if(pl_d != NULL) { *pl_d = NULL; } - if(l_subevent == 0) { return(ll); } - else { return(GETEVT__NOMORE); } + s_ves10_1* ps_ves10_1; + INTS4 l_total, l_sub, l_sum; + INTS4 /*l,*/ ll, /*l_status,*/ *pl_next; + + if (ps_ve10_1 == NULL) { + return (GETEVT__FAILURE); + } + pl_next = (INTS4*)(ps_ve10_1 + 1); + l_total = ps_ve10_1->l_dlen - 4; /* total words in subevents */ + l_sum = 0; + ll = 0; + while (l_sum < l_total) { + ps_ves10_1 = (s_ves10_1*)pl_next; + ll++; + if (ll == l_subevent) { + if (pl_lwords != NULL) { + *pl_lwords = ps_ves10_1->l_dlen / 2 - 1; + } + if (pl_se != NULL) { + *pl_se = (INTS4*)ps_ves10_1; + } + if (pl_d != NULL) { + *pl_d = (INTS4*)(ps_ves10_1 + 1); + } + return (GETEVT__SUCCESS); + } + l_sub = ps_ves10_1->l_dlen + 4; /* total words of subevent */ + l_sum += l_sub; + pl_next = (INTS4*)(ps_ves10_1); + pl_next += l_sub / 2; + } + if (pl_lwords != NULL) { + *pl_lwords = ll; + } + if (pl_se != NULL) { + *pl_se = NULL; + } + if (pl_d != NULL) { + *pl_d = NULL; + } + if (l_subevent == 0) { + return (ll); + } else { + return (GETEVT__NOMORE); + } } /*****************+***********+****************************************/ /* */ @@ -290,170 +303,197 @@ INTS4 f_evt_get_subevent(s_ve10_1* ps_ve10_1, INTS4 l_subevent, INTS4** pl_se, I /* INTS4 f_evt_type( */ /* s_bufhe *,s_evhe *, INTS4, INTS4, INTS4, INTS4); */ /*1- C Procedure *************+****************************************/ -INTS4 f_evt_type(s_bufhe* ps_bufhe,s_evhe* ps_evhe, INTS4 l_subid,INTS4 l_long,INTS4 l_hex,INTS4 l_data) +INTS4 f_evt_type(s_bufhe* ps_bufhe, s_evhe* ps_evhe, INTS4 l_subid, INTS4 l_long, INTS4 l_hex, INTS4 l_data) { - s_ves10_1* ps_ves10_1; - s_ve10_1* ps_ve10_1; - s_filhe* ps_filhe; -// INTS2* pi_data; - INTS4* pl_data; - INTS4 /*l_mode,*/l_s; - INTS4 l,ll,l_status,l_ldata,l_used; - CHARS c_line[132]; - CHARS c_full[132]; - CHARS c_time[32]; - - strcpy(c_full," "); - l_ldata=l_data; - if((l_hex+l_long) > 0) { l_ldata=1; } - - /* Print buffer header (file header) */ - if(ps_bufhe != NULL) { - sprintf(c_line,"--------------------------------------------------------"); - printf("%s\n",c_line); - /* calculate real buffer size */ - ll=ps_bufhe->l_dlen*2; - if(ll%512 > 0) { ll += 512-ll%512; } - /* file header */ - l_status = f_ut_utime(ps_bufhe->l_time[0],ps_bufhe->l_time[1],c_time); + s_ves10_1* ps_ves10_1; + s_ve10_1* ps_ve10_1; + s_filhe* ps_filhe; + // INTS2* pi_data; + INTS4* pl_data; + INTS4 /*l_mode,*/ l_s; + INTS4 l, ll, l_status, l_ldata, l_used; + CHARS c_line[132]; + CHARS c_full[132]; + CHARS c_time[32]; + + strcpy(c_full, " "); + l_ldata = l_data; + if ((l_hex + l_long) > 0) { + l_ldata = 1; + } + + /* Print buffer header (file header) */ + if (ps_bufhe != NULL) { + sprintf(c_line, "--------------------------------------------------------"); + printf("%s\n", c_line); + /* calculate real buffer size */ + ll = ps_bufhe->l_dlen * 2; + if (ll % 512 > 0) { + ll += 512 - ll % 512; + } + /* file header */ + l_status = f_ut_utime(ps_bufhe->l_time[0], ps_bufhe->l_time[1], c_time); #ifdef VMS - if(1 != l_status) printf("f_evt_type: error in f_ut_utime!"); + if (1 != l_status) + printf("f_evt_type: error in f_ut_utime!"); #else - if(0 != l_status) printf("f_evt_type: error in f_ut_utime!"); + if (0 != l_status) + printf("f_evt_type: error in f_ut_utime!"); #endif - - if(ps_bufhe->i_type == 2000) { - ps_filhe=(s_filhe*)ps_bufhe; - sprintf(c_line,"File header info:"); - printf("%s\n",c_line); - sprintf(c_line,"Size: %d [%d b], used %d [b]",ps_filhe->filhe_dlen,ll,ps_filhe->filhe_used*2); - printf("%s\n",c_line); - sprintf(c_line,"Label: %s",ps_filhe->filhe_label); - printf("%s\n",c_line); - sprintf(c_line,"File: %s",ps_filhe->filhe_file); - printf("%s\n",c_line); - sprintf(c_line,"User: %s",ps_filhe->filhe_user); - printf("%s\n",c_line); - sprintf(c_line,"Time: %s",ps_filhe->filhe_time); - printf("%s\n",c_line); - sprintf(c_line,"Run: %s",ps_filhe->filhe_run); - printf("%s\n",c_line); - sprintf(c_line,"Exp: %s",ps_filhe->filhe_exp); - printf("%s\n",c_line); - for(ll=0; llfilhe_lines; ll++) { - sprintf(c_line,"comment: %s",ps_filhe->s_strings[ll].string); - printf("%s\n",c_line); - } - } else { - l_used=ps_bufhe->i_used; - if(ps_bufhe->l_dlen > MAX__DLEN) { l_used=ps_bufhe->l_free[2]; } - sprintf(c_line,"Buffer %9d, Length %5d[w] Size %5d[b] used %5d[w] %s", - ps_bufhe->l_buf, - ps_bufhe->l_dlen, - ll,l_used, - c_time); - printf("%s\n",c_line); - sprintf(c_line," Events %3d Type/Subtype %5d %5d FragEnd=%d FragBegin=%d Total %5d[w]", - ps_bufhe->l_evt, - ps_bufhe->i_type, - ps_bufhe->i_subtype, - ps_bufhe->h_end, - ps_bufhe->h_begin, - ps_bufhe->l_free[1]); - printf("%s\n",c_line); - } - sprintf(c_line,"--------------------------------------------------------"); - printf("%s\n",c_line); - } - - if(ps_evhe == NULL) { return(0); } - - /* print event 4,x or 6,x */ - if(ps_evhe->i_type != 10) { - sprintf(c_line,"Event type %d, subtype %d, data longwords %d", - ps_evhe->i_type,ps_evhe->i_subtype,ps_evhe->l_dlen/2); - printf("%s\n",c_line); - if((l_ldata != 0) & ((ps_evhe->i_type == 4)|(ps_evhe->i_type == 6))) { - /* output data, assume data as longword */ - pl_data = (INTS4*)ps_evhe; - pl_data += 2; - for(l=0; ll_dlen/2; l++) { - sprintf(c_line,"%08x ",*pl_data); - strcat(c_full,c_line); - pl_data++; - if(l%8 == 7) { - printf("%s\n",c_full); - strcpy(c_full," "); + + if (ps_bufhe->i_type == 2000) { + ps_filhe = (s_filhe*)ps_bufhe; + sprintf(c_line, "File header info:"); + printf("%s\n", c_line); + sprintf(c_line, "Size: %d [%d b], used %d [b]", ps_filhe->filhe_dlen, ll, ps_filhe->filhe_used * 2); + printf("%s\n", c_line); + sprintf(c_line, "Label: %s", ps_filhe->filhe_label); + printf("%s\n", c_line); + sprintf(c_line, "File: %s", ps_filhe->filhe_file); + printf("%s\n", c_line); + sprintf(c_line, "User: %s", ps_filhe->filhe_user); + printf("%s\n", c_line); + sprintf(c_line, "Time: %s", ps_filhe->filhe_time); + printf("%s\n", c_line); + sprintf(c_line, "Run: %s", ps_filhe->filhe_run); + printf("%s\n", c_line); + sprintf(c_line, "Exp: %s", ps_filhe->filhe_exp); + printf("%s\n", c_line); + for (ll = 0; ll < ps_filhe->filhe_lines; ll++) { + sprintf(c_line, "comment: %s", ps_filhe->s_strings[ll].string); + printf("%s\n", c_line); + } + } else { + l_used = ps_bufhe->i_used; + if (ps_bufhe->l_dlen > MAX__DLEN) { + l_used = ps_bufhe->l_free[2]; + } + sprintf(c_line, + "Buffer %9d, Length %5d[w] Size %5d[b] used %5d[w] %s", + ps_bufhe->l_buf, + ps_bufhe->l_dlen, + ll, + l_used, + c_time); + printf("%s\n", c_line); + sprintf(c_line, + " Events %3d Type/Subtype %5d %5d FragEnd=%d FragBegin=%d Total %5d[w]", + ps_bufhe->l_evt, + ps_bufhe->i_type, + ps_bufhe->i_subtype, + ps_bufhe->h_end, + ps_bufhe->h_begin, + ps_bufhe->l_free[1]); + printf("%s\n", c_line); } - } - if(strlen(c_full) > 2) { printf("%s\n",c_full); } - } - return(0); - } - - /* Print event 10,1 */ - ps_ve10_1 = (s_ve10_1*)ps_evhe; - /* Print event header */ - sprintf(c_line,"Event %9d Type/Subtype %5d %5d Length %5d[w] Trigger %2d", - ps_ve10_1->l_count, - ps_ve10_1->i_type, - ps_ve10_1->i_subtype, - ps_ve10_1->l_dlen, - ps_ve10_1->i_trigger); - printf("%s\n",c_line); - - /********************/ - l_s=0; - l_status=0; - while(l_status == 0) { - l_s++; - l_status=f_evt_get_subevent(ps_ve10_1,l_s,(INTS4**)&ps_ves10_1,(INTS4**)&pl_data,(INTS4*)&ll); - if(l_status == 0) { - if((l_subid < 0)|(l_subid == ps_ves10_1->i_procid)) { - sprintf(c_line," SubEv ID %6d Type/Subtype %5d %5d Length %5d[w] Control %2d Subcrate %2d", - ps_ves10_1->i_procid, - ps_ves10_1->i_type, - ps_ves10_1->i_subtype, - ps_ves10_1->l_dlen, - ps_ves10_1->h_control, - ps_ves10_1->h_subcrate); - printf("%s\n",c_line); - if(l_ldata != 0) { - /* output data */ - if((l_long != 0) | (l_hex != 0)) { - /* In this case we assume data as one longword per channel */ - for(l=0; l>16)&0xffff,*pl_data&0xffff); } - else { sprintf(c_line,"%8d ",*pl_data); } - strcat(c_full,c_line); - pl_data++; - if(l%8 == 7) { - printf("%s\n",c_full); - strcpy(c_full," "); - } - } - if(strlen(c_full) > 2) { printf("%s\n",c_full); } - strcpy(c_full," "); - } else { - /* In this case we assume data as two words per channel */ - for(l=0; l>16)&0xffff); - strcat(c_full,c_line); - pl_data++; - if(l%4 == 3) { - printf("%s\n",c_full); - strcpy(c_full," "); - } - } - if(strlen(c_full) > 2) { printf("%s\n",c_full); } - strcpy(c_full," "); - } + sprintf(c_line, "--------------------------------------------------------"); + printf("%s\n", c_line); + } + + if (ps_evhe == NULL) { + return (0); + } + + /* print event 4,x or 6,x */ + if (ps_evhe->i_type != 10) { + sprintf(c_line, + "Event type %d, subtype %d, data longwords %d", + ps_evhe->i_type, + ps_evhe->i_subtype, + ps_evhe->l_dlen / 2); + printf("%s\n", c_line); + if ((l_ldata != 0) & ((ps_evhe->i_type == 4) | (ps_evhe->i_type == 6))) { + /* output data, assume data as longword */ + pl_data = (INTS4*)ps_evhe; + pl_data += 2; + for (l = 0; l < ps_evhe->l_dlen / 2; l++) { + sprintf(c_line, "%08x ", *pl_data); + strcat(c_full, c_line); + pl_data++; + if (l % 8 == 7) { + printf("%s\n", c_full); + strcpy(c_full, " "); + } + } + if (strlen(c_full) > 2) { + printf("%s\n", c_full); + } + } + return (0); + } + + /* Print event 10,1 */ + ps_ve10_1 = (s_ve10_1*)ps_evhe; + /* Print event header */ + sprintf(c_line, + "Event %9d Type/Subtype %5d %5d Length %5d[w] Trigger %2d", + ps_ve10_1->l_count, + ps_ve10_1->i_type, + ps_ve10_1->i_subtype, + ps_ve10_1->l_dlen, + ps_ve10_1->i_trigger); + printf("%s\n", c_line); + + /********************/ + l_s = 0; + l_status = 0; + while (l_status == 0) { + l_s++; + l_status = f_evt_get_subevent(ps_ve10_1, l_s, (INTS4**)&ps_ves10_1, (INTS4**)&pl_data, (INTS4*)&ll); + if (l_status == 0) { + if ((l_subid < 0) | (l_subid == ps_ves10_1->i_procid)) { + sprintf(c_line, + " SubEv ID %6d Type/Subtype %5d %5d Length %5d[w] Control %2d Subcrate %2d", + ps_ves10_1->i_procid, + ps_ves10_1->i_type, + ps_ves10_1->i_subtype, + ps_ves10_1->l_dlen, + ps_ves10_1->h_control, + ps_ves10_1->h_subcrate); + printf("%s\n", c_line); + if (l_ldata != 0) { + /* output data */ + if ((l_long != 0) | (l_hex != 0)) { + /* In this case we assume data as one longword per channel */ + for (l = 0; l < ll; l++) { + if (l_hex != 0) { + sprintf(c_line, "%04x.%04x ", (*pl_data >> 16) & 0xffff, *pl_data & 0xffff); + } else { + sprintf(c_line, "%8d ", *pl_data); + } + strcat(c_full, c_line); + pl_data++; + if (l % 8 == 7) { + printf("%s\n", c_full); + strcpy(c_full, " "); + } + } + if (strlen(c_full) > 2) { + printf("%s\n", c_full); + } + strcpy(c_full, " "); + } else { + /* In this case we assume data as two words per channel */ + for (l = 0; l < ll; l++) { + sprintf(c_line, "%8d%8d", *pl_data & 0xffff, (*pl_data >> 16) & 0xffff); + strcat(c_full, c_line); + pl_data++; + if (l % 4 == 3) { + printf("%s\n", c_full); + strcpy(c_full, " "); + } + } + if (strlen(c_full) > 2) { + printf("%s\n", c_full); + } + strcpy(c_full, " "); + } + } + } } - } } - } - return(0); + return (0); } /*1+ C Main ****************+******************************************/ /*+ Module : f_evt_rev_port */ @@ -472,9 +512,9 @@ INTS4 f_evt_type(s_bufhe* ps_bufhe,s_evhe* ps_evhe, INTS4 l_subid,INTS4 l_long,I /*1- C Main ****************+******************************************/ INTS4 f_evt_rev_port(INTS4 l_port) { - l_gl_rev_port=l_port; - printf("Use remote event server port %d\n",l_port); - return 0; + l_gl_rev_port = l_port; + printf("Use remote event server port %d\n", l_port); + return 0; } /*1+ C Main ****************+******************************************/ /*+ Module : f_evt_get_open */ @@ -512,160 +552,176 @@ INTS4 f_evt_rev_port(INTS4 l_port) /*+ FUNCTION : Opens the input channel and save context in s_chan. */ /*+ NOTE : Up to four input channels can be opened. */ /*1- C Main ****************+******************************************/ -INTS4 f_evt_get_open(INTS4 l_mode, CHARS* pc_server, s_evt_channel* ps_chan, - CHARS** ps_info, INTS4 l_sample, INTS4 l_param) +INTS4 f_evt_get_open(INTS4 l_mode, + CHARS* pc_server, + s_evt_channel* ps_chan, + CHARS** ps_info, + INTS4 l_sample, + INTS4 l_param) { - INTS4 l_swap, l_swap_head, l_is_goosybuf, l_filehead=0, l_size, l_size_head, l_dummy, l_header_size; -// INTS2* pi; - CHARS c_file[256], *pc_temp; - s_filhe* ps_filhe; - struct s_varstr { - INTS2 i_varstr; - CHARS c_varstr[128]; - }/* s_varstr_file*/; - INTS4 l_status;//,ll; - int val; - -// P.-A. Loizeau, 2015/11/26: -// In case of STREAM mode, catch the case where the user provided -// a nonstandard stream port, extract the value and clean the server -// name. Usefull with DABC MBS streams where the port can be user set. - INTS4 i_streamport = PORT__STREAM_SERV; - if( (GETEVT__STREAM == l_mode ) && ( (pc_temp=strchr(pc_server,':')) != NULL )) { -// printf("input string: %s!\n", pc_server); - pc_server = strtok( pc_server, ":"); - CHARS* pc_streamport = strtok( NULL, ":"); - - i_streamport = atoi(pc_streamport); -// printf("output string: %s! Port: %s %i\n", pc_server, pc_streamport, i_streamport); - } + INTS4 l_swap, l_swap_head, l_is_goosybuf, l_filehead = 0, l_size, l_size_head, l_dummy, l_header_size; + // INTS2* pi; + CHARS c_file[256], *pc_temp; + s_filhe* ps_filhe; + struct s_varstr + { + INTS2 i_varstr; + CHARS c_varstr[128]; + } /* s_varstr_file*/; + INTS4 l_status; //,ll; + int val; + + // P.-A. Loizeau, 2015/11/26: + // In case of STREAM mode, catch the case where the user provided + // a nonstandard stream port, extract the value and clean the server + // name. Usefull with DABC MBS streams where the port can be user set. + INTS4 i_streamport = PORT__STREAM_SERV; + if ((GETEVT__STREAM == l_mode) && ((pc_temp = strchr(pc_server, ':')) != NULL)) { + // printf("input string: %s!\n", pc_server); + pc_server = strtok(pc_server, ":"); + CHARS* pc_streamport = strtok(NULL, ":"); + + i_streamport = atoi(pc_streamport); + // printf("output string: %s! Port: %s %i\n", pc_server, pc_streamport, i_streamport); + } #ifndef GSI__WINNT -// disable automatic detection of RFIO on Windows while file name can contain ":" - if((pc_temp=strchr(pc_server,':')) != NULL) { - l_mode=GETEVT__RFIO; - /* printf("rfio file %s\n",pc_server);*/ - } + // disable automatic detection of RFIO on Windows while file name can contain ":" + if ((pc_temp = strchr(pc_server, ':')) != NULL) { + l_mode = GETEVT__RFIO; + /* printf("rfio file %s\n",pc_server);*/ + } #endif #ifndef RFIO - if(l_mode == GETEVT__RFIO) { - printf("rfio not supported!\n"); - return(GETEVT__NOFILE); - } + if (l_mode == GETEVT__RFIO) { + printf("rfio not supported!\n"); + return (GETEVT__NOFILE); + } #endif - if(ps_info != NULL) { *ps_info=NULL; } - // when timeout is already set by f_evt_timeout(), do not overwrite - if(ps_chan->l_timeout==0) { ps_chan->l_timeout=-1; } /* no timeout */ - - if (strlen(pc_server) < sizeof(ps_chan->c_channel)) { // length of pc_server < 128 - strncpy(ps_chan->c_channel,pc_server,sizeof(ps_chan->c_channel)-1); - } else { - printf("file name to long!\n"); - return(GETEVT__NOFILE); - } - - switch(l_mode) { - case GETEVT__FILE : + if (ps_info != NULL) { + *ps_info = NULL; + } + // when timeout is already set by f_evt_timeout(), do not overwrite + if (ps_chan->l_timeout == 0) { + ps_chan->l_timeout = -1; + } /* no timeout */ - if (strlen(pc_server) < sizeof(c_file)) { // length of pc_server < 256 - strncpy(c_file,pc_server,sizeof(c_file)-1); + if (strlen(pc_server) < sizeof(ps_chan->c_channel)) { // length of pc_server < 128 + strncpy(ps_chan->c_channel, pc_server, sizeof(ps_chan->c_channel) - 1); } else { - printf("file name to long!\n"); - return(GETEVT__NOFILE); + printf("file name to long!\n"); + return (GETEVT__NOFILE); } - if(strlen(c_file) < 5) { strcat(c_file,".lmd"); } - else { - pc_temp = (CHARS*) &c_file[strlen(c_file)-4]; - if((strcmp(pc_temp,".LMD") != 0) && - (strcmp(pc_temp,".lmd") != 0)) { strcat(c_file,".lmd"); } - } + switch (l_mode) { + case GETEVT__FILE: - if((ps_chan->l_channel_no=open(c_file,GET__OPEN_FLAG))== -1) { - return(GETEVT__NOFILE); - } - /* read first 512 bytes */ - if(read(ps_chan->l_channel_no,c_temp,MIN_BUF_LGTH)!=MIN_BUF_LGTH) { - printf("LMD format error: no LMD file: %s\n",c_file); - close(ps_chan->l_channel_no); - ps_chan->l_channel_no=-1; - return(GETEVT__NOLMDFILE); - } -// DABC - ps_chan->pLmd=NULL; - if((*((INTS4*)(c_temp+4)) == LMD__TYPE_FILE_HEADER_101_1)|| - (*((INTS4*)(c_temp+4)) == 0x65000100)) { - close(ps_chan->l_channel_no); - ps_chan->pLmd=fLmdAllocateControl(); - fLmdGetOpen(ps_chan->pLmd,c_file,NULL,LMD__BUFFER,LMD__NO_INDEX); - ps_chan->l_server_type=l_mode; - return GETEVT__SUCCESS; - } -// -- DABC - /* check for file header, return size and swap */ - f_evt_check_buf(c_temp, &l_size_head, &l_is_goosybuf, &l_swap_head, &l_filehead); - if(((l_is_goosybuf==0)&(l_filehead==0))|(l_size_head==0)) { - printf("LMD format error: swap=%d, header=%d, isLMD=%d, size=%d\n",l_swap_head,l_filehead,l_is_goosybuf,l_size_head); - close(ps_chan->l_channel_no); - ps_chan->l_channel_no=-1; - return(GETEVT__NOLMDFILE); - } + if (strlen(pc_server) < sizeof(c_file)) { // length of pc_server < 256 + strncpy(c_file, pc_server, sizeof(c_file) - 1); + } else { + printf("file name to long!\n"); + return (GETEVT__NOFILE); + } - /* read file header and first buffer and check for goosy header */ - if(l_filehead == 1) { - val = lseek(ps_chan->l_channel_no, 0, SEEK_SET); /* rewind file */ - if(-1 == val) - { - return(GETEVT__FAILURE); - } - l_header_size=l_size_head; - if(((s_filhe*)c_temp)->filhe_dlen > MAX__DLEN) { - l_header_size=((s_filhe*)c_temp)->filhe_used*2+48; - // printf("Large buffer, read short header %d bytes\n",l_header_size); - } - if(read(ps_chan->l_channel_no,c_temp,l_header_size)!=l_header_size) { - printf("LMD format error: no LMD file: %s\n",c_file); - close(ps_chan->l_channel_no); - ps_chan->l_channel_no=-1; - return(GETEVT__NOLMDFILE); - } - if(read(ps_chan->l_channel_no,c_temp,MIN_BUF_LGTH)!=MIN_BUF_LGTH) { - close(ps_chan->l_channel_no); - ps_chan->l_channel_no=-1; - return(GETEVT__RDERR); - } - f_evt_check_buf(c_temp, &l_size, &l_is_goosybuf, &l_swap, &l_dummy); - if((l_is_goosybuf==0)|(l_size!=l_size_head)|(l_swap!=l_swap_head)) { - printf("LMD format error: swap=%d, isLMD=%d, size=%d\n",l_swap,l_is_goosybuf,l_size); - close(ps_chan->l_channel_no); - ps_chan->l_channel_no=-1; - return(GETEVT__NOLMDFILE); - } - }/* check buffer behind header */ - ps_chan->l_buf_size=l_size_head; - val = lseek(ps_chan->l_channel_no, 0, SEEK_SET); /* rewind file */ - if(-1 == val) - { - return(GETEVT__FAILURE); - } - if(ps_info != NULL) { *ps_info=NULL; } - /* found file header */ - if(l_filehead == 1) { - if(read(ps_chan->l_channel_no,c_temp,l_header_size)!=l_header_size) { - printf("LMD format error: no LMD file: %s\n",c_file); - close(ps_chan->l_channel_no); - ps_chan->l_channel_no=-1; - return(GETEVT__NOLMDFILE); - } - ps_filhe = (s_filhe*) c_temp; - if(ps_info != NULL) {/* if user want file header be returned */ - if( l_swap_head ==1) { f_evt_swap_filhe((s_bufhe*)ps_filhe); } - *ps_info=c_temp; /* now , get file header and return */ - } - /* + if (strlen(c_file) < 5) { + strcat(c_file, ".lmd"); + } else { + pc_temp = (CHARS*)&c_file[strlen(c_file) - 4]; + if ((strcmp(pc_temp, ".LMD") != 0) && (strcmp(pc_temp, ".lmd") != 0)) { + strcat(c_file, ".lmd"); + } + } + + if ((ps_chan->l_channel_no = open(c_file, GET__OPEN_FLAG)) == -1) { + return (GETEVT__NOFILE); + } + /* read first 512 bytes */ + if (read(ps_chan->l_channel_no, c_temp, MIN_BUF_LGTH) != MIN_BUF_LGTH) { + printf("LMD format error: no LMD file: %s\n", c_file); + close(ps_chan->l_channel_no); + ps_chan->l_channel_no = -1; + return (GETEVT__NOLMDFILE); + } + // DABC + ps_chan->pLmd = NULL; + if ((*((INTS4*)(c_temp + 4)) == LMD__TYPE_FILE_HEADER_101_1) || (*((INTS4*)(c_temp + 4)) == 0x65000100)) { + close(ps_chan->l_channel_no); + ps_chan->pLmd = fLmdAllocateControl(); + fLmdGetOpen(ps_chan->pLmd, c_file, NULL, LMD__BUFFER, LMD__NO_INDEX); + ps_chan->l_server_type = l_mode; + return GETEVT__SUCCESS; + } + // -- DABC + /* check for file header, return size and swap */ + f_evt_check_buf(c_temp, &l_size_head, &l_is_goosybuf, &l_swap_head, &l_filehead); + if (((l_is_goosybuf == 0) & (l_filehead == 0)) | (l_size_head == 0)) { + printf("LMD format error: swap=%d, header=%d, isLMD=%d, size=%d\n", + l_swap_head, + l_filehead, + l_is_goosybuf, + l_size_head); + close(ps_chan->l_channel_no); + ps_chan->l_channel_no = -1; + return (GETEVT__NOLMDFILE); + } + + /* read file header and first buffer and check for goosy header */ + if (l_filehead == 1) { + val = lseek(ps_chan->l_channel_no, 0, SEEK_SET); /* rewind file */ + if (-1 == val) { + return (GETEVT__FAILURE); + } + l_header_size = l_size_head; + if (((s_filhe*)c_temp)->filhe_dlen > MAX__DLEN) { + l_header_size = ((s_filhe*)c_temp)->filhe_used * 2 + 48; + // printf("Large buffer, read short header %d bytes\n",l_header_size); + } + if (read(ps_chan->l_channel_no, c_temp, l_header_size) != l_header_size) { + printf("LMD format error: no LMD file: %s\n", c_file); + close(ps_chan->l_channel_no); + ps_chan->l_channel_no = -1; + return (GETEVT__NOLMDFILE); + } + if (read(ps_chan->l_channel_no, c_temp, MIN_BUF_LGTH) != MIN_BUF_LGTH) { + close(ps_chan->l_channel_no); + ps_chan->l_channel_no = -1; + return (GETEVT__RDERR); + } + f_evt_check_buf(c_temp, &l_size, &l_is_goosybuf, &l_swap, &l_dummy); + if ((l_is_goosybuf == 0) | (l_size != l_size_head) | (l_swap != l_swap_head)) { + printf("LMD format error: swap=%d, isLMD=%d, size=%d\n", l_swap, l_is_goosybuf, l_size); + close(ps_chan->l_channel_no); + ps_chan->l_channel_no = -1; + return (GETEVT__NOLMDFILE); + } + } /* check buffer behind header */ + ps_chan->l_buf_size = l_size_head; + val = lseek(ps_chan->l_channel_no, 0, SEEK_SET); /* rewind file */ + if (-1 == val) { + return (GETEVT__FAILURE); + } + if (ps_info != NULL) { + *ps_info = NULL; + } + /* found file header */ + if (l_filehead == 1) { + if (read(ps_chan->l_channel_no, c_temp, l_header_size) != l_header_size) { + printf("LMD format error: no LMD file: %s\n", c_file); + close(ps_chan->l_channel_no); + ps_chan->l_channel_no = -1; + return (GETEVT__NOLMDFILE); + } + ps_filhe = (s_filhe*)c_temp; + if (ps_info != NULL) { /* if user want file header be returned */ + if (l_swap_head == 1) { + f_evt_swap_filhe((s_bufhe*)ps_filhe); + } + *ps_info = c_temp; /* now , get file header and return */ + } + /* printf("type %d, subtype %d\n",ps_filhe->filhe_type,ps_filhe->filhe_subtype); printf("strings %d %d %d %d %d %x\n", ps_filhe->filhe_label_l, @@ -681,153 +737,185 @@ INTS4 f_evt_get_open(INTS4 l_mode, CHARS* pc_server, s_evt_channel* ps_chan, pi += 40; } */ - } /* file header */ - - /* points to a real buffer start */ - /* and read header buffer, if there */ - ps_chan->l_io_buf_size=ps_chan->l_buf_size; - /* may larger, but must multiplexed */ - break; - case GETEVT__STREAM : - /* initialize connection with stream server */ -// P.-A. Loizeau, 2015/11/26: -// In case of STREAM mode, catch the case where the user provided -// a nonstandard stream port, extract the value and clean the server -// name. Usefull with DABC MBS streams where the port can be user set. -// if(f_stc_connectserver(pc_server,PORT__STREAM_SERV,&ps_chan->l_channel_no, - if(f_stc_connectserver(pc_server,i_streamport,&ps_chan->l_channel_no, - &s_tcpcomm_st_evt)!=STC__SUCCESS) { - return(GETEVT__NOSERVER); - } - - l_status=f_stc_read(c_temp,16,ps_chan->l_channel_no,ps_chan->l_timeout); - if(l_status == STC__TIMEOUT) { return(GETEVT__TIMEOUT); } - if(l_status != STC__SUCCESS) { return(GETEVT__RDERR); } - - if( *((INTS4*)(c_temp))!=1) { f_evt_swap(c_temp, 16); } - ps_chan->l_buf_size=*((INTS4*)(c_temp+4)); /* buffer size */ - ps_chan->l_bufs_in_stream=*((INTS4*)(c_temp+8)); - /* # buffers per stream */ - ps_chan->l_stream_bufs = 0; /* counter */ - - ps_chan->l_io_buf_size=(ps_chan->l_buf_size)*(ps_chan->l_bufs_in_stream); -// DABC - ps_chan->pLmd=NULL; - if(*((INTS4*)(c_temp+12)) == 0) { - ps_chan->pLmd=fLmdAllocateControl(); - ps_chan->pLmd->pTCP=&s_tcpcomm_st_evt; - fLmdInitMbs(ps_chan->pLmd,pc_server,ps_chan->l_buf_size,ps_chan->l_bufs_in_stream,0,PORT__STREAM_SERV,ps_chan->l_timeout); - printf("f_evt_get_open for STREAM: setting timeout=%d n",ps_chan->l_timeout); + } /* file header */ + + /* points to a real buffer start */ + /* and read header buffer, if there */ + ps_chan->l_io_buf_size = ps_chan->l_buf_size; + /* may larger, but must multiplexed */ + break; + case GETEVT__STREAM: + /* initialize connection with stream server */ + // P.-A. Loizeau, 2015/11/26: + // In case of STREAM mode, catch the case where the user provided + // a nonstandard stream port, extract the value and clean the server + // name. Usefull with DABC MBS streams where the port can be user set. + // if(f_stc_connectserver(pc_server,PORT__STREAM_SERV,&ps_chan->l_channel_no, + if (f_stc_connectserver(pc_server, i_streamport, &ps_chan->l_channel_no, &s_tcpcomm_st_evt) + != STC__SUCCESS) { + return (GETEVT__NOSERVER); + } - ps_chan->l_server_type=l_mode; - return GETEVT__SUCCESS; - } -// -- DABC - break; - case GETEVT__TRANS : - /* initialize connection with stream server */ - if(f_stc_connectserver(pc_server,PORT__TRANSPORT,&ps_chan->l_channel_no, - &s_tcpcomm_st_evt)!=STC__SUCCESS) { - return(GETEVT__NOSERVER); - } - - l_status=f_stc_read(c_temp,16,ps_chan->l_channel_no,ps_chan->l_timeout); - if(l_status == STC__TIMEOUT) { return(GETEVT__TIMEOUT); } - if(l_status != STC__SUCCESS) { return(GETEVT__RDERR); } - - if( *((INTS4*)(c_temp))!=1) { f_evt_swap(c_temp, 16); } - ps_chan->l_buf_size=*((INTS4*)(c_temp+4)); /* buffer size */ - ps_chan->l_bufs_in_stream=*((INTS4*)(c_temp+8)); - /* # buffers per stream */ - ps_chan->l_io_buf_size=ps_chan->l_buf_size; -// DABC - ps_chan->pLmd=NULL; - if(*((INTS4*)(c_temp+12)) == 0) { - ps_chan->pLmd=fLmdAllocateControl(); - ps_chan->pLmd->pTCP=&s_tcpcomm_st_evt; - fLmdInitMbs(ps_chan->pLmd,pc_server,ps_chan->l_buf_size,ps_chan->l_bufs_in_stream,0,PORT__TRANSPORT,ps_chan->l_timeout); - ps_chan->l_server_type=l_mode; - return GETEVT__SUCCESS; - } -// -- DABC - break; - case GETEVT__REVSERV : -// if(f_evcli_con(ps_chan, pc_server, l_gl_rev_port, -1, l_sample)!=STC__SUCCESS) { -// return(GETEVT__NOSERVER); -// } - break; - case GETEVT__EVENT : -// if(f_evcli_con(ps_chan, pc_server, l_gl_rev_port, -1, l_sample)!=STC__SUCCESS) { -// return(GETEVT__NOSERVER); -// } - break; + l_status = f_stc_read(c_temp, 16, ps_chan->l_channel_no, ps_chan->l_timeout); + if (l_status == STC__TIMEOUT) { + return (GETEVT__TIMEOUT); + } + if (l_status != STC__SUCCESS) { + return (GETEVT__RDERR); + } + + if (*((INTS4*)(c_temp)) != 1) { + f_evt_swap(c_temp, 16); + } + ps_chan->l_buf_size = *((INTS4*)(c_temp + 4)); /* buffer size */ + ps_chan->l_bufs_in_stream = *((INTS4*)(c_temp + 8)); + /* # buffers per stream */ + ps_chan->l_stream_bufs = 0; /* counter */ + + ps_chan->l_io_buf_size = (ps_chan->l_buf_size) * (ps_chan->l_bufs_in_stream); + // DABC + ps_chan->pLmd = NULL; + if (*((INTS4*)(c_temp + 12)) == 0) { + ps_chan->pLmd = fLmdAllocateControl(); + ps_chan->pLmd->pTCP = &s_tcpcomm_st_evt; + fLmdInitMbs(ps_chan->pLmd, + pc_server, + ps_chan->l_buf_size, + ps_chan->l_bufs_in_stream, + 0, + PORT__STREAM_SERV, + ps_chan->l_timeout); + printf("f_evt_get_open for STREAM: setting timeout=%d n", ps_chan->l_timeout); + + ps_chan->l_server_type = l_mode; + return GETEVT__SUCCESS; + } + // -- DABC + break; + case GETEVT__TRANS: + /* initialize connection with stream server */ + if (f_stc_connectserver(pc_server, PORT__TRANSPORT, &ps_chan->l_channel_no, &s_tcpcomm_st_evt) + != STC__SUCCESS) { + return (GETEVT__NOSERVER); + } + + l_status = f_stc_read(c_temp, 16, ps_chan->l_channel_no, ps_chan->l_timeout); + if (l_status == STC__TIMEOUT) { + return (GETEVT__TIMEOUT); + } + if (l_status != STC__SUCCESS) { + return (GETEVT__RDERR); + } + + if (*((INTS4*)(c_temp)) != 1) { + f_evt_swap(c_temp, 16); + } + ps_chan->l_buf_size = *((INTS4*)(c_temp + 4)); /* buffer size */ + ps_chan->l_bufs_in_stream = *((INTS4*)(c_temp + 8)); + /* # buffers per stream */ + ps_chan->l_io_buf_size = ps_chan->l_buf_size; + // DABC + ps_chan->pLmd = NULL; + if (*((INTS4*)(c_temp + 12)) == 0) { + ps_chan->pLmd = fLmdAllocateControl(); + ps_chan->pLmd->pTCP = &s_tcpcomm_st_evt; + fLmdInitMbs(ps_chan->pLmd, + pc_server, + ps_chan->l_buf_size, + ps_chan->l_bufs_in_stream, + 0, + PORT__TRANSPORT, + ps_chan->l_timeout); + ps_chan->l_server_type = l_mode; + return GETEVT__SUCCESS; + } + // -- DABC + break; + case GETEVT__REVSERV: + // if(f_evcli_con(ps_chan, pc_server, l_gl_rev_port, -1, l_sample)!=STC__SUCCESS) { + // return(GETEVT__NOSERVER); + // } + break; + case GETEVT__EVENT: + // if(f_evcli_con(ps_chan, pc_server, l_gl_rev_port, -1, l_sample)!=STC__SUCCESS) { + // return(GETEVT__NOSERVER); + // } + break; #ifdef RFIO - case GETEVT__RFIO : - ps_chan->l_channel_no=-1; - ps_chan->l_channel_no=RFIO_open(pc_server,GET__OPEN_FLAG,0); - if(ps_chan->l_channel_no < 0) { return(GETEVT__NOSERVER); } - /* read first 512 bytes */ - if(RFIO_read(ps_chan->l_channel_no,c_temp,MIN_BUF_LGTH)!=MIN_BUF_LGTH) { - printf("LMD format error: no LMD file: %s\n",pc_server); - RFIO_close(ps_chan->l_channel_no); - ps_chan->l_channel_no=-1; - return(GETEVT__NOLMDFILE); - } - /* check for file header, return size and swap */ - f_evt_check_buf(c_temp, &l_size_head, &l_is_goosybuf, &l_swap_head, &l_filehead); - if(((l_is_goosybuf==0)&(l_filehead==0))|(l_size_head==0)) { - printf("LMD format error: swap=%d, header=%d, isLMD=%d, size=%d\n",l_swap_head,l_filehead,l_is_goosybuf,l_size_head); - RFIO_close(ps_chan->l_channel_no); - ps_chan->l_channel_no=-1; - return(GETEVT__NOLMDFILE); - } - /* read file header and first buffer and check for goosy header */ - if(l_filehead == 1) { - val = RFIO_lseek(ps_chan->l_channel_no, 0, SEEK_SET); /* rewind file */ - if(-1 == val) - { - return(GETEVT__FAILURE); - } - if(RFIO_read(ps_chan->l_channel_no,c_temp,l_size_head)!=l_size_head) { - printf("LMD format error: no LMD file: %s\n",pc_server); - RFIO_close(ps_chan->l_channel_no); - ps_chan->l_channel_no=-1; - return(GETEVT__NOLMDFILE); - } - if(RFIO_read(ps_chan->l_channel_no,c_temp,MIN_BUF_LGTH)!=MIN_BUF_LGTH) { - RFIO_close(ps_chan->l_channel_no); - ps_chan->l_channel_no=-1; - return(GETEVT__RDERR); - } - f_evt_check_buf(c_temp, &l_size, &l_is_goosybuf, &l_swap, &l_dummy); - if((l_is_goosybuf==0)|(l_size!=l_size_head)|(l_swap!=l_swap_head)) { - printf("LMD format error: swap=%d, isLMD=%d, size=%d\n",l_swap,l_is_goosybuf,l_size); - RFIO_close(ps_chan->l_channel_no); - ps_chan->l_channel_no=-1; - return(GETEVT__NOLMDFILE); - } - }/* check buffer behind header */ - ps_chan->l_buf_size=l_size_head; - val = RFIO_lseek(ps_chan->l_channel_no, 0, SEEK_SET); /* rewind file */ - if(-1 == val) - { - return(GETEVT__FAILURE); - } - if(ps_info != NULL) { *ps_info=NULL; } - /* found file header */ - if(l_filehead == 1) { - if(RFIO_read(ps_chan->l_channel_no,c_temp,l_size_head)!=l_size_head) { - printf("LMD format error: no LMD file: %s\n",pc_server); - RFIO_close(ps_chan->l_channel_no); - ps_chan->l_channel_no=-1; - return(GETEVT__NOLMDFILE); - } - ps_filhe=(s_filhe*)c_temp; - if(ps_info != NULL) { /* if user want file header be returned */ - if( l_swap_head ==1) { f_evt_swap_filhe((s_bufhe*)ps_filhe); } - *ps_info=c_temp; /* now , get file header and return */ - } - /* + case GETEVT__RFIO: + ps_chan->l_channel_no = -1; + ps_chan->l_channel_no = RFIO_open(pc_server, GET__OPEN_FLAG, 0); + if (ps_chan->l_channel_no < 0) { + return (GETEVT__NOSERVER); + } + /* read first 512 bytes */ + if (RFIO_read(ps_chan->l_channel_no, c_temp, MIN_BUF_LGTH) != MIN_BUF_LGTH) { + printf("LMD format error: no LMD file: %s\n", pc_server); + RFIO_close(ps_chan->l_channel_no); + ps_chan->l_channel_no = -1; + return (GETEVT__NOLMDFILE); + } + /* check for file header, return size and swap */ + f_evt_check_buf(c_temp, &l_size_head, &l_is_goosybuf, &l_swap_head, &l_filehead); + if (((l_is_goosybuf == 0) & (l_filehead == 0)) | (l_size_head == 0)) { + printf("LMD format error: swap=%d, header=%d, isLMD=%d, size=%d\n", + l_swap_head, + l_filehead, + l_is_goosybuf, + l_size_head); + RFIO_close(ps_chan->l_channel_no); + ps_chan->l_channel_no = -1; + return (GETEVT__NOLMDFILE); + } + /* read file header and first buffer and check for goosy header */ + if (l_filehead == 1) { + val = RFIO_lseek(ps_chan->l_channel_no, 0, SEEK_SET); /* rewind file */ + if (-1 == val) { + return (GETEVT__FAILURE); + } + if (RFIO_read(ps_chan->l_channel_no, c_temp, l_size_head) != l_size_head) { + printf("LMD format error: no LMD file: %s\n", pc_server); + RFIO_close(ps_chan->l_channel_no); + ps_chan->l_channel_no = -1; + return (GETEVT__NOLMDFILE); + } + if (RFIO_read(ps_chan->l_channel_no, c_temp, MIN_BUF_LGTH) != MIN_BUF_LGTH) { + RFIO_close(ps_chan->l_channel_no); + ps_chan->l_channel_no = -1; + return (GETEVT__RDERR); + } + f_evt_check_buf(c_temp, &l_size, &l_is_goosybuf, &l_swap, &l_dummy); + if ((l_is_goosybuf == 0) | (l_size != l_size_head) | (l_swap != l_swap_head)) { + printf("LMD format error: swap=%d, isLMD=%d, size=%d\n", l_swap, l_is_goosybuf, l_size); + RFIO_close(ps_chan->l_channel_no); + ps_chan->l_channel_no = -1; + return (GETEVT__NOLMDFILE); + } + } /* check buffer behind header */ + ps_chan->l_buf_size = l_size_head; + val = RFIO_lseek(ps_chan->l_channel_no, 0, SEEK_SET); /* rewind file */ + if (-1 == val) { + return (GETEVT__FAILURE); + } + if (ps_info != NULL) { + *ps_info = NULL; + } + /* found file header */ + if (l_filehead == 1) { + if (RFIO_read(ps_chan->l_channel_no, c_temp, l_size_head) != l_size_head) { + printf("LMD format error: no LMD file: %s\n", pc_server); + RFIO_close(ps_chan->l_channel_no); + ps_chan->l_channel_no = -1; + return (GETEVT__NOLMDFILE); + } + ps_filhe = (s_filhe*)c_temp; + if (ps_info != NULL) { /* if user want file header be returned */ + if (l_swap_head == 1) { + f_evt_swap_filhe((s_bufhe*)ps_filhe); + } + *ps_info = c_temp; /* now , get file header and return */ + } + /* printf("type %d, subtype %d\n",ps_filhe->filhe_type,ps_filhe->filhe_subtype); printf("strings %d %d %d %d %d %x\n", ps_filhe->filhe_label_l, @@ -843,30 +931,32 @@ INTS4 f_evt_get_open(INTS4 l_mode, CHARS* pc_server, s_evt_channel* ps_chan, pi += 40; } */ - }/* file header */ - ps_chan->l_io_buf_size=ps_chan->l_buf_size; - break; + } /* file header */ + ps_chan->l_io_buf_size = ps_chan->l_buf_size; + break; #endif - default : - if(ps_info != NULL) { *ps_info=NULL; } - return(GETEVT__NOSERVER); - } /* end of switch */ - - if((l_mode != GETEVT__EVENT)&(l_mode != GETEVT__REVSERV)) { - if( (ps_chan->pc_io_buf=malloc(ps_chan->l_io_buf_size))==NULL) { - printf("Memory allocation error\n"); - exit(2); - } - ps_chan->l_evt_buf_size=ps_chan->l_io_buf_size; - if( (ps_chan->pc_evt_buf=malloc(ps_chan->l_evt_buf_size))==NULL) { - printf("Memory allocation error\n"); - exit(2); - } - } /* l_mode != GETEVT__EVENT */ - ps_chan->l_server_type=l_mode; - ps_chan->l_first_get=1; /* so we will first call f_getvet_get */ - return GETEVT__SUCCESS; -} /* end of f_evt_get_open */ + default: + if (ps_info != NULL) { + *ps_info = NULL; + } + return (GETEVT__NOSERVER); + } /* end of switch */ + + if ((l_mode != GETEVT__EVENT) & (l_mode != GETEVT__REVSERV)) { + if ((ps_chan->pc_io_buf = malloc(ps_chan->l_io_buf_size)) == NULL) { + printf("Memory allocation error\n"); + exit(2); + } + ps_chan->l_evt_buf_size = ps_chan->l_io_buf_size; + if ((ps_chan->pc_evt_buf = malloc(ps_chan->l_evt_buf_size)) == NULL) { + printf("Memory allocation error\n"); + exit(2); + } + } /* l_mode != GETEVT__EVENT */ + ps_chan->l_server_type = l_mode; + ps_chan->l_first_get = 1; /* so we will first call f_getvet_get */ + return GETEVT__SUCCESS; +} /* end of f_evt_get_open */ /*1+ C Main ****************+******************************************/ /*+ Module : f_evt_get_event */ @@ -896,165 +986,186 @@ INTS4 f_evt_get_open(INTS4 l_mode, CHARS* pc_server, s_evt_channel* ps_chan, /*1- C Main ****************+******************************************/ INTS4 f_evt_get_event(s_evt_channel* ps_chan, INTS4** ppl_buffer, INTS4** ppl_goobuf) { - INTS4 l_temp,l_prev_ok=1, l_stat=LMD__SUCCESS, l_used; - s_bufhe* ps_bufhe_cur; -// s_ve10_1* ps_ve10_1; - sMbsHeader* pevt; + INTS4 l_temp, l_prev_ok = 1, l_stat = LMD__SUCCESS, l_used; + s_bufhe* ps_bufhe_cur; + // s_ve10_1* ps_ve10_1; + sMbsHeader* pevt; + + // DABC + if (ps_chan->pLmd != NULL) { + if (ps_chan->l_server_type == GETEVT__TRANS) { + l_stat = fLmdGetMbsEvent(ps_chan->pLmd, &pevt); + } else if (ps_chan->l_server_type == GETEVT__STREAM) { + l_stat = fLmdGetMbsEvent(ps_chan->pLmd, &pevt); + } else if (ps_chan->l_server_type == GETEVT__FILE) { + l_stat = fLmdGetElement(ps_chan->pLmd, LMD__NO_INDEX, &pevt); + } else { + pevt = NULL; + } -// DABC - if(ps_chan->pLmd != NULL) { - if(ps_chan->l_server_type == GETEVT__TRANS) { - l_stat=fLmdGetMbsEvent(ps_chan->pLmd, &pevt); - } else if(ps_chan->l_server_type == GETEVT__STREAM) { - l_stat=fLmdGetMbsEvent(ps_chan->pLmd, &pevt); - } else if(ps_chan->l_server_type == GETEVT__FILE) { - l_stat=fLmdGetElement(ps_chan->pLmd,LMD__NO_INDEX, &pevt); - } else { - pevt = NULL; - } - -// any error, then pointer is null - if(pevt==NULL) { - if (ps_chan->l_server_type == GETEVT__FILE) { - if(l_stat == GETLMD__NOMORE) { return(GETEVT__NOMORE); } - if(l_stat == GETLMD__EOFILE) { return(GETEVT__NOMORE); } - if(l_stat == GETLMD__NOBUFFER) { return(GETEVT__FAILURE); } - return(GETEVT__RDERR); - } else { - if(l_stat == LMD__TIMEOUT) { return(GETEVT__TIMEOUT); } - else { return (GETEVT__RDERR); } - } - } -// OK - if(ppl_goobuf) { *ppl_goobuf = NULL; } - *ppl_buffer = (INTS4*)pevt; - return(GETEVT__SUCCESS); - } -// -- DABC -// if((ps_chan->l_server_type == GETEVT__EVENT)|(ps_chan->l_server_type == GETEVT__REVSERV)) { -// *ppl_goobuf = NULL; -// if(f_evcli_evt(ps_chan) != STC__SUCCESS) { /* no more event, get new buffer */ -// l_stat=f_evcli_buf(ps_chan); -// if(l_stat == STC__TIMEOUT) { return(GETEVT__TIMEOUT); } -// if(l_stat != STC__SUCCESS) { return(GETEVT__FAILURE); } -// } -// *ppl_buffer = (INTS4*) ps_chan->pc_evt_buf; -// return(GETEVT__SUCCESS); -// } - - /* e.g. read_buffer is 16384, GOOSY buffer may be only 2048, * - * this ps_chan->l_io_buf_posi indicats when the read_buffer is finished */ - - if(ps_chan->l_first_get==1) { - ps_chan->l_buf_posi=0; /* goosy buffer position */ - ps_chan->l_buf_lmt=0; /* end of this goosy buffer */ - ps_chan->l_io_buf_posi=MAX_LONG; /* Iuput buffer(for read file) position */ - ps_chan->l_first_buf=1; /* boolean */ - ps_chan->l_first_get=0; /* boolean */ - } - /* why we need this part codes? beacause we may (open, get, close) * - * and (open, get, close) again!!! Especially when we use m-histo * - * so the second or later (open,get,close) should reset these * - * static value */ - - ps_chan->l_evt_buf_posi=0; - /* above, internal event buffer position, internal buffer will be returned */ - - while(1) { - /* if previous goosy buffer has finished, read a new buffer from i/o buffer, + // any error, then pointer is null + if (pevt == NULL) { + if (ps_chan->l_server_type == GETEVT__FILE) { + if (l_stat == GETLMD__NOMORE) { + return (GETEVT__NOMORE); + } + if (l_stat == GETLMD__EOFILE) { + return (GETEVT__NOMORE); + } + if (l_stat == GETLMD__NOBUFFER) { + return (GETEVT__FAILURE); + } + return (GETEVT__RDERR); + } else { + if (l_stat == LMD__TIMEOUT) { + return (GETEVT__TIMEOUT); + } else { + return (GETEVT__RDERR); + } + } + } + // OK + if (ppl_goobuf) { + *ppl_goobuf = NULL; + } + *ppl_buffer = (INTS4*)pevt; + return (GETEVT__SUCCESS); + } + // -- DABC + // if((ps_chan->l_server_type == GETEVT__EVENT)|(ps_chan->l_server_type == GETEVT__REVSERV)) { + // *ppl_goobuf = NULL; + // if(f_evcli_evt(ps_chan) != STC__SUCCESS) { /* no more event, get new buffer */ + // l_stat=f_evcli_buf(ps_chan); + // if(l_stat == STC__TIMEOUT) { return(GETEVT__TIMEOUT); } + // if(l_stat != STC__SUCCESS) { return(GETEVT__FAILURE); } + // } + // *ppl_buffer = (INTS4*) ps_chan->pc_evt_buf; + // return(GETEVT__SUCCESS); + // } + + /* e.g. read_buffer is 16384, GOOSY buffer may be only 2048, * + * this ps_chan->l_io_buf_posi indicats when the read_buffer is finished */ + + if (ps_chan->l_first_get == 1) { + ps_chan->l_buf_posi = 0; /* goosy buffer position */ + ps_chan->l_buf_lmt = 0; /* end of this goosy buffer */ + ps_chan->l_io_buf_posi = MAX_LONG; /* Iuput buffer(for read file) position */ + ps_chan->l_first_buf = 1; /* boolean */ + ps_chan->l_first_get = 0; /* boolean */ + } + /* why we need this part codes? beacause we may (open, get, close) * + * and (open, get, close) again!!! Especially when we use m-histo * + * so the second or later (open,get,close) should reset these * + * static value */ + + ps_chan->l_evt_buf_posi = 0; + /* above, internal event buffer position, internal buffer will be returned */ + + while (1) { + /* if previous goosy buffer has finished, read a new buffer from i/o buffer, or from file if i/o buffer is all readout */ - while (ps_chan->l_buf_posi >= ps_chan->l_buf_lmt) { - /* if this i/o buffer is read to end */ - /* end of this read_buffer which may contain several GOOSY buffers*/ - if(ps_chan->l_io_buf_posi>=ps_chan->l_io_buf_size) { - if((l_temp=f_evt_get_newbuf(ps_chan))!=GETEVT__SUCCESS) { return(l_temp); } - ps_chan->l_io_buf_posi=0; - } /* end of real read server */ - ps_chan->ps_bufhe = (s_bufhe*) (ps_chan->pc_io_buf+ps_chan->l_io_buf_posi); - l_prev_ok = (ps_chan->l_buf_no == (ps_chan->ps_bufhe->l_buf-1)); - ps_chan->l_buf_no = ps_chan->ps_bufhe->l_buf; - if(ps_chan->ps_bufhe->i_type == 2000) { /* file header */ - printf("Unsolicited file header found!\n"); - ps_chan->l_io_buf_posi += ps_chan->l_buf_size; - ps_chan->l_buf_posi = ps_chan->l_io_buf_posi; - ps_chan->l_buf_lmt = ps_chan->l_io_buf_posi; - } else { - l_used=ps_chan->ps_bufhe->l_free[2]; // large buffers HE, Oct 2007 - if(ps_chan->ps_bufhe->l_dlen <= MAX__DLEN) { l_used=ps_chan->ps_bufhe->i_used; } - ps_chan->l_buf_posi = ps_chan->l_io_buf_posi + sizeof(s_bufhe); - ps_chan->l_buf_lmt = ps_chan->l_buf_posi + l_used*2; - ps_chan->l_io_buf_posi += ps_chan->l_buf_size; - } - } /* end of read file while loop */ - - /* now, ps_chan->l_buf_posi points to start of an event or spanned event */ - ps_chan->ps_ve10_1 = (s_ve10_1*) (ps_chan->pc_io_buf + ps_chan->l_buf_posi); - if( (ps_chan->l_evt_buf_posi != 0) || ((ps_chan->ps_bufhe->h_end==1) && (ps_chan->l_first_buf==1)) ) { /* if this is a spanned part of an event */ - ps_chan->l_buf_posi += sizeof(s_evhe); - ps_chan->l_frag_len = ps_chan->ps_ve10_1->l_dlen*2; - } else { /* if this is a real start of an event */ - ps_chan->l_frag_len = (ps_chan->ps_ve10_1->l_dlen-4)*2 + sizeof(s_ve10_1); - } - - if(ps_chan->l_frag_len + ps_chan->l_buf_posi > ps_chan->l_buf_lmt) { - return(GETEVT__FRAGMENT); - } - - /* if ps_chan->l_buf_posi is not start of an event and ps_chan->l_first_buf =1 * - * then skip to next event */ - if((ps_chan->ps_bufhe->h_end==1)&&((ps_chan->l_first_buf==1) || (l_prev_ok == 0))) { - /* if the first buffer is spanned at begin, then skip */ - ps_chan->l_first_buf=0; /* 24-Apr-1996 */ - l_prev_ok=1; /* 2001 HE */ - ps_chan->l_evt_buf_posi=0; /* 2001 HE stuff in event buffer obsolete */ - ps_chan->l_buf_posi += ps_chan->l_frag_len; - /* now,ps_chan->l_buf_posi points to start of an event or spanned event */ - continue; /* continue "while" loop */ - } - - ps_chan->l_first_buf=0; - - /* if ps_chan->l_buf_posi is start of an event and the event is not * - * spanned, then return pointer */ - if( (ps_chan->l_evt_buf_posi==0) && - ( (ps_chan->ps_bufhe->h_begin==0) || ((ps_chan->l_buf_posi+ps_chan->l_frag_len) < ps_chan->l_buf_lmt) ) ) { - *ppl_buffer = (INTS4*)(ps_chan->pc_io_buf+ps_chan->l_buf_posi); - ps_chan->l_buf_posi += ps_chan->l_frag_len; - ps_chan->l_evt_buf_posi = 0; - if(ppl_goobuf) { *ppl_goobuf = (INTS4*) (ps_chan->ps_bufhe); } - return(GETEVT__SUCCESS); - } - - /* 2001 HE if we start a spanned event, save buffer header of first buffer */ - if(ps_chan->l_evt_buf_posi==0) { - memcpy((CHARS*)&ps_chan->s_bufhe_1,(CHARS*)ps_chan->ps_bufhe,sizeof(s_bufhe)); - ps_bufhe_cur=(s_bufhe*)&ps_chan->s_bufhe_1; - } - /* copy the part of this event which in this buffer into * - * internal buffer, data will be moved by realloc function */ - if(ps_chan->l_evt_buf_sizel_evt_buf_posi+ps_chan->l_frag_len) { - ps_chan->l_evt_buf_size=ps_chan->l_evt_buf_posi+ps_chan->l_frag_len; - if( (ps_chan->pc_evt_buf=realloc - (ps_chan->pc_evt_buf, ps_chan->l_evt_buf_size))==NULL) { - printf("Memory allocation error\n"); - exit(2); - } - } - memcpy(ps_chan->pc_evt_buf+ps_chan->l_evt_buf_posi,ps_chan->pc_io_buf+ps_chan->l_buf_posi, - ps_chan->l_frag_len); - ps_chan->l_buf_posi += ps_chan->l_frag_len; - if(ps_chan->l_evt_buf_posi == 0) { - } - ps_chan->l_evt_buf_posi += ps_chan->l_frag_len; + while (ps_chan->l_buf_posi >= ps_chan->l_buf_lmt) { + /* if this i/o buffer is read to end */ + /* end of this read_buffer which may contain several GOOSY buffers*/ + if (ps_chan->l_io_buf_posi >= ps_chan->l_io_buf_size) { + if ((l_temp = f_evt_get_newbuf(ps_chan)) != GETEVT__SUCCESS) { + return (l_temp); + } + ps_chan->l_io_buf_posi = 0; + } /* end of real read server */ + ps_chan->ps_bufhe = (s_bufhe*)(ps_chan->pc_io_buf + ps_chan->l_io_buf_posi); + l_prev_ok = (ps_chan->l_buf_no == (ps_chan->ps_bufhe->l_buf - 1)); + ps_chan->l_buf_no = ps_chan->ps_bufhe->l_buf; + if (ps_chan->ps_bufhe->i_type == 2000) { /* file header */ + printf("Unsolicited file header found!\n"); + ps_chan->l_io_buf_posi += ps_chan->l_buf_size; + ps_chan->l_buf_posi = ps_chan->l_io_buf_posi; + ps_chan->l_buf_lmt = ps_chan->l_io_buf_posi; + } else { + l_used = ps_chan->ps_bufhe->l_free[2]; // large buffers HE, Oct 2007 + if (ps_chan->ps_bufhe->l_dlen <= MAX__DLEN) { + l_used = ps_chan->ps_bufhe->i_used; + } + ps_chan->l_buf_posi = ps_chan->l_io_buf_posi + sizeof(s_bufhe); + ps_chan->l_buf_lmt = ps_chan->l_buf_posi + l_used * 2; + ps_chan->l_io_buf_posi += ps_chan->l_buf_size; + } + } /* end of read file while loop */ + + /* now, ps_chan->l_buf_posi points to start of an event or spanned event */ + ps_chan->ps_ve10_1 = (s_ve10_1*)(ps_chan->pc_io_buf + ps_chan->l_buf_posi); + if ((ps_chan->l_evt_buf_posi != 0) + || ((ps_chan->ps_bufhe->h_end == 1) + && (ps_chan->l_first_buf == 1))) { /* if this is a spanned part of an event */ + ps_chan->l_buf_posi += sizeof(s_evhe); + ps_chan->l_frag_len = ps_chan->ps_ve10_1->l_dlen * 2; + } else { /* if this is a real start of an event */ + ps_chan->l_frag_len = (ps_chan->ps_ve10_1->l_dlen - 4) * 2 + sizeof(s_ve10_1); + } - if((ps_chan->ps_bufhe->h_begin!=1)||(ps_chan->l_buf_posil_buf_lmt)) { - /* change event header's l_dlen */ - ((s_ve10_1*)(ps_chan->pc_evt_buf))->l_dlen=ps_chan->l_evt_buf_posi/2-4; - *ppl_buffer=(INTS4*)(ps_chan->pc_evt_buf); - if(ppl_goobuf) { *ppl_goobuf=(INTS4*)(ps_bufhe_cur); } - return(GETEVT__SUCCESS); - } - }/* if this event spanned to next buffer, then loop */ + if (ps_chan->l_frag_len + ps_chan->l_buf_posi > ps_chan->l_buf_lmt) { + return (GETEVT__FRAGMENT); + } + + /* if ps_chan->l_buf_posi is not start of an event and ps_chan->l_first_buf =1 * + * then skip to next event */ + if ((ps_chan->ps_bufhe->h_end == 1) && ((ps_chan->l_first_buf == 1) || (l_prev_ok == 0))) { + /* if the first buffer is spanned at begin, then skip */ + ps_chan->l_first_buf = 0; /* 24-Apr-1996 */ + l_prev_ok = 1; /* 2001 HE */ + ps_chan->l_evt_buf_posi = 0; /* 2001 HE stuff in event buffer obsolete */ + ps_chan->l_buf_posi += ps_chan->l_frag_len; + /* now,ps_chan->l_buf_posi points to start of an event or spanned event */ + continue; /* continue "while" loop */ + } + + ps_chan->l_first_buf = 0; + + /* if ps_chan->l_buf_posi is start of an event and the event is not * + * spanned, then return pointer */ + if ((ps_chan->l_evt_buf_posi == 0) + && ((ps_chan->ps_bufhe->h_begin == 0) + || ((ps_chan->l_buf_posi + ps_chan->l_frag_len) < ps_chan->l_buf_lmt))) { + *ppl_buffer = (INTS4*)(ps_chan->pc_io_buf + ps_chan->l_buf_posi); + ps_chan->l_buf_posi += ps_chan->l_frag_len; + ps_chan->l_evt_buf_posi = 0; + if (ppl_goobuf) { + *ppl_goobuf = (INTS4*)(ps_chan->ps_bufhe); + } + return (GETEVT__SUCCESS); + } + + /* 2001 HE if we start a spanned event, save buffer header of first buffer */ + if (ps_chan->l_evt_buf_posi == 0) { + memcpy((CHARS*)&ps_chan->s_bufhe_1, (CHARS*)ps_chan->ps_bufhe, sizeof(s_bufhe)); + ps_bufhe_cur = (s_bufhe*)&ps_chan->s_bufhe_1; + } + /* copy the part of this event which in this buffer into * + * internal buffer, data will be moved by realloc function */ + if (ps_chan->l_evt_buf_size < ps_chan->l_evt_buf_posi + ps_chan->l_frag_len) { + ps_chan->l_evt_buf_size = ps_chan->l_evt_buf_posi + ps_chan->l_frag_len; + if ((ps_chan->pc_evt_buf = realloc(ps_chan->pc_evt_buf, ps_chan->l_evt_buf_size)) == NULL) { + printf("Memory allocation error\n"); + exit(2); + } + } + memcpy(ps_chan->pc_evt_buf + ps_chan->l_evt_buf_posi, + ps_chan->pc_io_buf + ps_chan->l_buf_posi, + ps_chan->l_frag_len); + ps_chan->l_buf_posi += ps_chan->l_frag_len; + if (ps_chan->l_evt_buf_posi == 0) {} + ps_chan->l_evt_buf_posi += ps_chan->l_frag_len; + + if ((ps_chan->ps_bufhe->h_begin != 1) || (ps_chan->l_buf_posi < ps_chan->l_buf_lmt)) { + /* change event header's l_dlen */ + ((s_ve10_1*)(ps_chan->pc_evt_buf))->l_dlen = ps_chan->l_evt_buf_posi / 2 - 4; + *ppl_buffer = (INTS4*)(ps_chan->pc_evt_buf); + if (ppl_goobuf) { + *ppl_goobuf = (INTS4*)(ps_bufhe_cur); + } + return (GETEVT__SUCCESS); + } + } /* if this event spanned to next buffer, then loop */ } /* end of f_evt_get_event */ /*1+ C Main ******************+****************************************/ @@ -1077,64 +1188,95 @@ INTS4 f_evt_get_event(s_evt_channel* ps_chan, INTS4** ppl_buffer, INTS4** ppl_go /*1- C Main ******************+****************************************/ INTS4 f_evt_get_close(s_evt_channel* ps_chan) { - INTS4 l_close_failure; -// INTS4 l_status; - -// DABC - if(ps_chan->pLmd != NULL) { - if(ps_chan->l_server_type == GETEVT__TRANS) { fLmdCloseMbs(ps_chan->pLmd); } - else if(ps_chan->l_server_type == GETEVT__STREAM) { fLmdCloseMbs(ps_chan->pLmd); } - else if(ps_chan->l_server_type == GETEVT__FILE) { fLmdGetClose(ps_chan->pLmd); } - free(ps_chan->pLmd); - ps_chan->pLmd=NULL; - return GETEVT__SUCCESS; - } -// -- DABC - l_close_failure=0; - if(ps_chan->l_channel_no >= 0) { - switch(ps_chan->l_server_type) { - case GETEVT__FILE : - if(close(ps_chan->l_channel_no)==-1) { l_close_failure=1; } - if(ps_chan->pc_io_buf != NULL) { free(ps_chan->pc_io_buf); } - if(ps_chan->pc_evt_buf != NULL) { free(ps_chan->pc_evt_buf); } - break; - case GETEVT__STREAM : - /* disconnect with stream server */ - f_stc_write("CLOSE", 6, ps_chan->l_channel_no); - if(f_stc_discclient(ps_chan->l_channel_no)!=STC__SUCCESS) { l_close_failure=1; } - if(f_stc_close(&s_tcpcomm_st_evt)!=STC__SUCCESS) { l_close_failure=1; } - if(ps_chan->pc_io_buf != NULL) { free(ps_chan->pc_io_buf); } - if(ps_chan->pc_evt_buf != NULL) { free(ps_chan->pc_evt_buf); } - break; - case GETEVT__TRANS : - /* disconnect with stream server */ - if(f_stc_discclient(ps_chan->l_channel_no)!=STC__SUCCESS) { l_close_failure=1; } - if(f_stc_close(&s_tcpcomm_st_evt)!=STC__SUCCESS) { l_close_failure=1; } - if(ps_chan->pc_io_buf != NULL) { free(ps_chan->pc_io_buf); } - if(ps_chan->pc_evt_buf != NULL) { free(ps_chan->pc_evt_buf); } - break; - case GETEVT__REVSERV : - case GETEVT__EVENT : -// if(f_evcli_close(ps_chan)!=STC__SUCCESS) { l_close_failure=1; } - break; - case GETEVT__RFIO : - RFIO_close(ps_chan->l_channel_no); - ps_chan->l_channel_no=-1; - if(ps_chan->pc_io_buf != NULL) { free(ps_chan->pc_io_buf); } - if(ps_chan->pc_evt_buf != NULL) { free(ps_chan->pc_evt_buf); } - break; - default : - l_close_failure=1; - } /* end of switch */ - ps_chan->pc_io_buf=NULL; - ps_chan->l_channel_no=-1; - if(l_close_failure==1) { return(GETEVT__CLOSE_ERR); } + INTS4 l_close_failure; + // INTS4 l_status; + + // DABC + if (ps_chan->pLmd != NULL) { + if (ps_chan->l_server_type == GETEVT__TRANS) { + fLmdCloseMbs(ps_chan->pLmd); + } else if (ps_chan->l_server_type == GETEVT__STREAM) { + fLmdCloseMbs(ps_chan->pLmd); + } else if (ps_chan->l_server_type == GETEVT__FILE) { + fLmdGetClose(ps_chan->pLmd); + } + free(ps_chan->pLmd); + ps_chan->pLmd = NULL; + return GETEVT__SUCCESS; + } + // -- DABC + l_close_failure = 0; + if (ps_chan->l_channel_no >= 0) { + switch (ps_chan->l_server_type) { + case GETEVT__FILE: + if (close(ps_chan->l_channel_no) == -1) { + l_close_failure = 1; + } + if (ps_chan->pc_io_buf != NULL) { + free(ps_chan->pc_io_buf); + } + if (ps_chan->pc_evt_buf != NULL) { + free(ps_chan->pc_evt_buf); + } + break; + case GETEVT__STREAM: + /* disconnect with stream server */ + f_stc_write("CLOSE", 6, ps_chan->l_channel_no); + if (f_stc_discclient(ps_chan->l_channel_no) != STC__SUCCESS) { + l_close_failure = 1; + } + if (f_stc_close(&s_tcpcomm_st_evt) != STC__SUCCESS) { + l_close_failure = 1; + } + if (ps_chan->pc_io_buf != NULL) { + free(ps_chan->pc_io_buf); + } + if (ps_chan->pc_evt_buf != NULL) { + free(ps_chan->pc_evt_buf); + } + break; + case GETEVT__TRANS: + /* disconnect with stream server */ + if (f_stc_discclient(ps_chan->l_channel_no) != STC__SUCCESS) { + l_close_failure = 1; + } + if (f_stc_close(&s_tcpcomm_st_evt) != STC__SUCCESS) { + l_close_failure = 1; + } + if (ps_chan->pc_io_buf != NULL) { + free(ps_chan->pc_io_buf); + } + if (ps_chan->pc_evt_buf != NULL) { + free(ps_chan->pc_evt_buf); + } + break; + case GETEVT__REVSERV: + case GETEVT__EVENT: + // if(f_evcli_close(ps_chan)!=STC__SUCCESS) { l_close_failure=1; } + break; + case GETEVT__RFIO: + RFIO_close(ps_chan->l_channel_no); + ps_chan->l_channel_no = -1; + if (ps_chan->pc_io_buf != NULL) { + free(ps_chan->pc_io_buf); + } + if (ps_chan->pc_evt_buf != NULL) { + free(ps_chan->pc_evt_buf); + } + break; + default: + l_close_failure = 1; + } /* end of switch */ + ps_chan->pc_io_buf = NULL; + ps_chan->l_channel_no = -1; + if (l_close_failure == 1) { + return (GETEVT__CLOSE_ERR); + } + return GETEVT__SUCCESS; + } return GETEVT__SUCCESS; - } - return GETEVT__SUCCESS; - -} /* end of f_evt_get_close */ +} /* end of f_evt_get_close */ /*1+ C Main ****************+******************************************/ /*+ Module : f_evt_put_open */ @@ -1165,130 +1307,135 @@ INTS4 f_evt_get_close(s_evt_channel* ps_chan) /*+ NOTE : Up to four output channels can be opened. */ /* User Example : In m_lea_user.c */ /*1- C Main ****************+******************************************/ -INTS4 f_evt_put_open(CHARS* pc_file, INTS4 l_size, INTS4 l_stream, - INTS4 l_type, INTS4 l_subtype, s_evt_channel* ps_chan, CHARS* ps_filhe) +INTS4 f_evt_put_open(CHARS* pc_file, + INTS4 l_size, + INTS4 l_stream, + INTS4 l_type, + INTS4 l_subtype, + s_evt_channel* ps_chan, + CHARS* ps_filhe) { - s_filhe* ps_file_head; - INTS4 l_write_size; - INTS4 l_status;//,ll; - time_t s_timet; - struct timeb s_timeb; - /* because "timeb" is not "typedef", so we must use "struct" */ - CHARS c_mode[80]; - CHARS c_file[256], *pc_temp; - struct s_varstr { - INTS2 i_varstr; - CHARS c_varstr[128]; - }/* s_varstr_file*/; - -// DABC - ps_chan->pLmd=NULL; - if(l_stream==0) { - ps_chan->pLmd=fLmdAllocateControl(); - l_status=fLmdPutOpen(ps_chan->pLmd,pc_file,NULL,l_size, - LMD__NO_OVERWRITE,LMD__INDEX,LMD__LARGE_FILE); - return(l_status); - } -// -- DABC + s_filhe* ps_file_head; + INTS4 l_write_size; + INTS4 l_status; //,ll; + time_t s_timet; + struct timeb s_timeb; + /* because "timeb" is not "typedef", so we must use "struct" */ + CHARS c_mode[80]; + CHARS c_file[256], *pc_temp; + struct s_varstr + { + INTS2 i_varstr; + CHARS c_varstr[128]; + } /* s_varstr_file*/; + + // DABC + ps_chan->pLmd = NULL; + if (l_stream == 0) { + ps_chan->pLmd = fLmdAllocateControl(); + l_status = fLmdPutOpen(ps_chan->pLmd, pc_file, NULL, l_size, LMD__NO_OVERWRITE, LMD__INDEX, LMD__LARGE_FILE); + return (l_status); + } + // -- DABC + + ps_chan->l_first_put = 1; + + ps_chan->l_buf_size = l_size; + ps_chan->l_bufs_in_stream = l_stream; + ps_chan->l_buf_type = l_type; + ps_chan->l_buf_subtype = l_subtype; + ps_chan->l_io_buf_size = ps_chan->l_buf_size * ps_chan->l_bufs_in_stream; + if ((ps_chan->pc_io_buf = malloc(ps_chan->l_io_buf_size)) == NULL) { + printf("Memory allocation error\n"); + exit(2); + } - ps_chan->l_first_put=1; - - ps_chan->l_buf_size=l_size; - ps_chan->l_bufs_in_stream=l_stream; - ps_chan->l_buf_type=l_type; - ps_chan->l_buf_subtype=l_subtype; - ps_chan->l_io_buf_size=ps_chan->l_buf_size * ps_chan->l_bufs_in_stream; - if( (ps_chan->pc_io_buf=malloc(ps_chan->l_io_buf_size))==NULL) { - printf("Memory allocation error\n"); - exit(2); - } - - size_t len=strlen(pc_file); - if (len < sizeof(c_file)) { - strncpy(c_file,pc_file, len); - } else { - strncpy(c_file,pc_file, sizeof(c_file)-1); - } - if(strlen(c_file) < 5) { strcat(c_file,".lmd"); } - else { - pc_temp = (CHARS*) &c_file[strlen(c_file)-4]; - if((strcmp(pc_temp,".LMD") != 0) && - (strcmp(pc_temp,".lmd") != 0)) { strcat(c_file,".lmd"); } - } - if((ps_chan->l_channel_no=open(c_file,PUT__OPEN_APD_FLAG) )!= -1) { - return(PUTEVT__FILE_EXIST); - } else { - if((ps_chan->l_channel_no=open(c_file,PUT__CRT_FLAG, - DEF_FILE_ACCE) )== -1) { - return(PUTEVT__FAILURE); - } - /* open OK */ - else { - /* output file header */ - ps_file_head=(s_filhe*)ps_chan->pc_io_buf; - /* if user specify file header */ - if(ps_filhe != NULL) { - memcpy(ps_file_head, ps_filhe,ps_chan->l_buf_size ); - } else { - memset( ps_file_head, '\0', ps_chan->l_buf_size); - sprintf(ps_file_head->filhe_run, "Pid %d", getpid()); - ps_file_head->filhe_run_l=strlen(ps_file_head->filhe_run); - } - ps_file_head->filhe_dlen=ps_chan->l_buf_size/2; - ps_file_head->filhe_subtype=1; - ps_file_head->filhe_type=2000; - ftime(&s_timeb); - ps_file_head->filhe_stime[0]=(INTS4)s_timeb.time; - ps_file_head->filhe_stime[1]=(INTS4)s_timeb.millitm; - ps_file_head->filhe_free[0]=1; - ps_file_head->filhe_file_l=strlen(c_file);/* not include \0 */ - strcpy(ps_file_head->filhe_file, c_file); - char* username = getenv("USER"); - if (username) { - size_t len = strlen(username); - // maximum length for user array in s_filhe is 30 - if (len < sizeof(ps_file_head->filhe_user) ) { - strncpy(ps_file_head->filhe_user, username, len);/* user name */ - } else { - strncpy(ps_file_head->filhe_user, username, sizeof(ps_file_head->filhe_user)-1);/* user name */ - } - } - ps_file_head->filhe_user_l=strlen(ps_file_head->filhe_user); + size_t len = strlen(pc_file); + if (len < sizeof(c_file)) { + strncpy(c_file, pc_file, len); + } else { + strncpy(c_file, pc_file, sizeof(c_file) - 1); + } + if (strlen(c_file) < 5) { + strcat(c_file, ".lmd"); + } else { + pc_temp = (CHARS*)&c_file[strlen(c_file) - 4]; + if ((strcmp(pc_temp, ".LMD") != 0) && (strcmp(pc_temp, ".lmd") != 0)) { + strcat(c_file, ".lmd"); + } + } + if ((ps_chan->l_channel_no = open(c_file, PUT__OPEN_APD_FLAG)) != -1) { + return (PUTEVT__FILE_EXIST); + } else { + if ((ps_chan->l_channel_no = open(c_file, PUT__CRT_FLAG, DEF_FILE_ACCE)) == -1) { + return (PUTEVT__FAILURE); + } + /* open OK */ + else { + /* output file header */ + ps_file_head = (s_filhe*)ps_chan->pc_io_buf; + /* if user specify file header */ + if (ps_filhe != NULL) { + memcpy(ps_file_head, ps_filhe, ps_chan->l_buf_size); + } else { + memset(ps_file_head, '\0', ps_chan->l_buf_size); + sprintf(ps_file_head->filhe_run, "Pid %d", getpid()); + ps_file_head->filhe_run_l = strlen(ps_file_head->filhe_run); + } + ps_file_head->filhe_dlen = ps_chan->l_buf_size / 2; + ps_file_head->filhe_subtype = 1; + ps_file_head->filhe_type = 2000; + ftime(&s_timeb); + ps_file_head->filhe_stime[0] = (INTS4)s_timeb.time; + ps_file_head->filhe_stime[1] = (INTS4)s_timeb.millitm; + ps_file_head->filhe_free[0] = 1; + ps_file_head->filhe_file_l = strlen(c_file); /* not include \0 */ + strcpy(ps_file_head->filhe_file, c_file); + char* username = getenv("USER"); + if (username) { + size_t len = strlen(username); + // maximum length for user array in s_filhe is 30 + if (len < sizeof(ps_file_head->filhe_user)) { + strncpy(ps_file_head->filhe_user, username, len); /* user name */ + } else { + strncpy(ps_file_head->filhe_user, username, sizeof(ps_file_head->filhe_user) - 1); /* user name */ + } + } + ps_file_head->filhe_user_l = strlen(ps_file_head->filhe_user); - /* get calendar time + /* get calendar time The returned string from ctime is of the format Www Mmm dd hh:mm:ss yyyy The string is followed by a new-line character ('\n') and terminated with a null-character. The strinh has a length of 25 characters */ - time(&s_timet); - char* temptime = ctime(&s_timet); + time(&s_timet); + char* temptime = ctime(&s_timet); - if ( strlen(temptime) < sizeof(c_mode)) { - strncpy(c_mode, temptime, sizeof(c_mode)-1); - } else { - return(PUTEVT__FAILURE); - } + if (strlen(temptime) < sizeof(c_mode)) { + strncpy(c_mode, temptime, sizeof(c_mode) - 1); + } else { + return (PUTEVT__FAILURE); + } - if ( strlen(&c_mode[4]) < sizeof(ps_file_head->filhe_time)) { - strncpy(ps_file_head->filhe_time, &c_mode[4], sizeof(ps_file_head->filhe_time)-1); - } else { - return(PUTEVT__FAILURE); - } + if (strlen(&c_mode[4]) < sizeof(ps_file_head->filhe_time)) { + strncpy(ps_file_head->filhe_time, &c_mode[4], sizeof(ps_file_head->filhe_time) - 1); + } else { + return (PUTEVT__FAILURE); + } - // Remove the terminating new-line character - ps_file_head->filhe_time[20]=' '; - l_write_size=write(ps_chan->l_channel_no,(CHARS*)ps_file_head, - ps_chan->l_buf_size); - if(l_write_size==-1) { - return(PUTEVT__WRERR); - } - if(l_write_size!=ps_chan->l_buf_size) { - return(PUTEVT__TOOBIG); - } - return(PUTEVT__SUCCESS); + // Remove the terminating new-line character + ps_file_head->filhe_time[20] = ' '; + l_write_size = write(ps_chan->l_channel_no, (CHARS*)ps_file_head, ps_chan->l_buf_size); + if (l_write_size == -1) { + return (PUTEVT__WRERR); + } + if (l_write_size != ps_chan->l_buf_size) { + return (PUTEVT__TOOBIG); + } + return (PUTEVT__SUCCESS); + } } - } } /* end of f_evt_put_open */ /*1+ C Main ****************+******************************************/ @@ -1314,116 +1461,140 @@ INTS4 f_evt_put_open(CHARS* pc_file, INTS4 l_size, INTS4 l_stream, INTS4 f_evt_put_event(s_evt_channel* ps_chan, INTS4* pl_evt_buf) { - INTS4 l_evt_buf_posi; - INTS4 l_buf_remain_size; /* net free space of I/O buffer */ - INTS4 l_write_size, l_temp, l_free; - INTS4 l_status; - CHARS* pc_addr; - s_bufhe* ps_bufhe; + INTS4 l_evt_buf_posi; + INTS4 l_buf_remain_size; /* net free space of I/O buffer */ + INTS4 l_write_size, l_temp, l_free; + INTS4 l_status; + CHARS* pc_addr; + s_bufhe* ps_bufhe; + + // DABC + if (ps_chan->pLmd != NULL) { + l_status = fLmdPutElement(ps_chan->pLmd, (sMbsHeader*)pl_evt_buf); + return (l_status); + } + // -- DABC + if (ps_chan->l_first_put == 1) { + ps_chan->l_first_put = 0; + ps_chan->l_io_buf_posi = 0; + ps_chan->l_buf_no = 1; + } + l_evt_buf_posi = 0; + ps_chan->l_evt_size = (((s_ve10_1*)(pl_evt_buf))->l_dlen) * 2 + sizeof(s_evhe); + + /* get l_buf_remain_size is available size in stream */ + l_buf_remain_size = ps_chan->l_io_buf_size - ps_chan->l_io_buf_posi; + l_temp = (l_buf_remain_size / ps_chan->l_buf_size) * (sizeof(s_bufhe) + sizeof(s_evhe)); + l_buf_remain_size -= l_temp; /* minus space occupied by buffer header and spanned event header */ + + if (ps_chan->l_evt_size > l_buf_remain_size) { /* output this i/o buffer */ + memset(ps_chan->pc_io_buf + ps_chan->l_io_buf_posi, '\0', ps_chan->l_io_buf_size - ps_chan->l_io_buf_posi); + /* clear rest of this GOOSY buffer */ + l_temp = (ps_chan->l_io_buf_posi / ps_chan->l_buf_size) * ps_chan->l_buf_size; + if (ps_chan->l_io_buf_posi % ps_chan->l_buf_size == 0) { + l_temp -= ps_chan->l_buf_size; + } + /* l_temp points to start of last GOOSY buf in i/o buf area */ + ps_chan->ps_bufhe = (s_bufhe*)(ps_chan->pc_io_buf + l_temp); + if (l_temp == 0) { + ps_chan->ps_bufhe->h_end = 0; + } /* first buf in stream, no end */ + else { + ps_chan->ps_bufhe->h_end = ((s_bufhe*)((CHARS*)ps_chan->ps_bufhe - ps_chan->l_buf_size))->h_begin; + } + ps_chan->ps_bufhe->h_begin = 0; /* evt has end, so not spanned to next buf */ + for (l_temp = 0; l_temp < ps_chan->l_io_buf_size; l_temp += ps_chan->l_buf_size) { + pc_addr = ps_chan->pc_io_buf + l_temp; + ps_bufhe = (s_bufhe*)pc_addr; + if (ps_bufhe->l_evt > 0) { /* do not write empty buffers */ + l_write_size = write(ps_chan->l_channel_no, pc_addr, ps_chan->l_buf_size); + if (l_write_size == -1) { + return (PUTEVT__WRERR); + } + if (l_write_size != ps_chan->l_buf_size) { + return (PUTEVT__TOOBIG); + } + } else { + ps_chan->l_buf_no--; + } /* decrement buffer number for not written buffer */ + } /* buffer output loop */ + ps_chan->l_io_buf_posi = 0; + ps_chan->ps_bufhe = (s_bufhe*)ps_chan->pc_io_buf; + /* get l_buf_remain_size of new stream */ + l_buf_remain_size = ps_chan->l_io_buf_size; + l_temp = (l_buf_remain_size / ps_chan->l_buf_size) * (sizeof(s_bufhe) + sizeof(s_evhe)); + l_buf_remain_size -= l_temp; /* minus space occupied by buf header and spanned event header */ + l_buf_remain_size += sizeof(s_evhe); /* 1st buf always no span */ + /* if event can not fit in a new stream, then error */ + if (ps_chan->l_evt_size > l_buf_remain_size) { + return (PUTEVT__TOO_SMALLS); + } + } -// DABC - if(ps_chan->pLmd != NULL) { - l_status=fLmdPutElement(ps_chan->pLmd,(sMbsHeader*)pl_evt_buf); - return(l_status); - } -// -- DABC - if(ps_chan->l_first_put==1) { - ps_chan->l_first_put=0; - ps_chan->l_io_buf_posi=0; - ps_chan->l_buf_no=1; - } - l_evt_buf_posi=0; - ps_chan->l_evt_size=( ((s_ve10_1*)(pl_evt_buf))->l_dlen)*2 + sizeof(s_evhe); - - /* get l_buf_remain_size is available size in stream */ - l_buf_remain_size = ps_chan->l_io_buf_size - ps_chan->l_io_buf_posi; - l_temp = (l_buf_remain_size / ps_chan->l_buf_size)*(sizeof(s_bufhe)+sizeof(s_evhe) ); - l_buf_remain_size -= l_temp;/* minus space occupied by buffer header and spanned event header */ - - if(ps_chan->l_evt_size>l_buf_remain_size) { /* output this i/o buffer */ - memset(ps_chan->pc_io_buf+ps_chan->l_io_buf_posi, '\0', ps_chan->l_io_buf_size-ps_chan->l_io_buf_posi); - /* clear rest of this GOOSY buffer */ - l_temp=(ps_chan->l_io_buf_posi/ps_chan->l_buf_size)*ps_chan->l_buf_size; - if(ps_chan->l_io_buf_posi%ps_chan->l_buf_size == 0) { l_temp -= ps_chan->l_buf_size; } - /* l_temp points to start of last GOOSY buf in i/o buf area */ - ps_chan->ps_bufhe=(s_bufhe*)(ps_chan->pc_io_buf + l_temp); - if(l_temp==0) { ps_chan->ps_bufhe->h_end = 0; } /* first buf in stream, no end */ - else { ps_chan->ps_bufhe->h_end = ((s_bufhe*)((CHARS*)ps_chan->ps_bufhe - ps_chan->l_buf_size))->h_begin; } - ps_chan->ps_bufhe->h_begin = 0; /* evt has end, so not spanned to next buf */ - for(l_temp=0; l_templ_io_buf_size; l_temp+=ps_chan->l_buf_size) { - pc_addr = ps_chan->pc_io_buf+l_temp; - ps_bufhe=(s_bufhe*)pc_addr; - if(ps_bufhe->l_evt>0) { /* do not write empty buffers */ - l_write_size=write(ps_chan->l_channel_no, pc_addr,ps_chan->l_buf_size); - if(l_write_size==-1) { return(PUTEVT__WRERR); } - if(l_write_size!=ps_chan->l_buf_size) { return(PUTEVT__TOOBIG); } - } else { ps_chan->l_buf_no--; } /* decrement buffer number for not written buffer */ - } /* buffer output loop */ - ps_chan->l_io_buf_posi=0; - ps_chan->ps_bufhe=(s_bufhe*)ps_chan->pc_io_buf; - /* get l_buf_remain_size of new stream */ - l_buf_remain_size = ps_chan->l_io_buf_size; - l_temp = (l_buf_remain_size / ps_chan->l_buf_size) * (sizeof(s_bufhe)+sizeof(s_evhe) ); - l_buf_remain_size -= l_temp; /* minus space occupied by buf header and spanned event header */ - l_buf_remain_size += sizeof(s_evhe);/* 1st buf always no span */ - /* if event can not fit in a new stream, then error */ - if(ps_chan->l_evt_size>l_buf_remain_size) { return(PUTEVT__TOO_SMALLS); } - } - - if(ps_chan->l_io_buf_posi==0) { f_evt_ini_bufhe(ps_chan); } /* init all buffer headers */ - - /* write event into i/o buf till end of event, change ps_chan->l_io_buf_posi */ - while(l_evt_buf_posil_evt_size) { - ps_chan->ps_ve10_1 = (s_ve10_1*)(ps_chan->pc_io_buf + ps_chan->l_io_buf_posi); - if((ps_chan->l_io_buf_posi%ps_chan->l_buf_size)==0) { - ps_chan->l_io_buf_posi += sizeof(s_bufhe); - ps_chan->ps_ve10_1 = (s_ve10_1*)(ps_chan->pc_io_buf + ps_chan->l_io_buf_posi); /* behind header */ - if(l_evt_buf_posi != 0) { - ps_chan->l_io_buf_posi += sizeof(s_evhe); /* behind element header */ - l_write_size=(ps_chan->l_io_buf_posi/ps_chan->l_buf_size)*ps_chan->l_buf_size; + if (ps_chan->l_io_buf_posi == 0) { + f_evt_ini_bufhe(ps_chan); + } /* init all buffer headers */ + + /* write event into i/o buf till end of event, change ps_chan->l_io_buf_posi */ + while (l_evt_buf_posi < ps_chan->l_evt_size) { + ps_chan->ps_ve10_1 = (s_ve10_1*)(ps_chan->pc_io_buf + ps_chan->l_io_buf_posi); + if ((ps_chan->l_io_buf_posi % ps_chan->l_buf_size) == 0) { + ps_chan->l_io_buf_posi += sizeof(s_bufhe); + ps_chan->ps_ve10_1 = (s_ve10_1*)(ps_chan->pc_io_buf + ps_chan->l_io_buf_posi); /* behind header */ + if (l_evt_buf_posi != 0) { + ps_chan->l_io_buf_posi += sizeof(s_evhe); /* behind element header */ + l_write_size = (ps_chan->l_io_buf_posi / ps_chan->l_buf_size) * ps_chan->l_buf_size; + /* l_write_size points to start of this GOOSY buf in i/o buf area */ + ps_chan->ps_bufhe = (s_bufhe*)(ps_chan->pc_io_buf + l_write_size); + ps_chan->ps_bufhe->i_used += sizeof(s_evhe) / 2; + } + } + l_write_size = (ps_chan->l_io_buf_posi / ps_chan->l_buf_size) * ps_chan->l_buf_size; /* l_write_size points to start of this GOOSY buf in i/o buf area */ - ps_chan->ps_bufhe=(s_bufhe*)(ps_chan->pc_io_buf + l_write_size); - ps_chan->ps_bufhe->i_used += sizeof(s_evhe)/2; - } - } - l_write_size=(ps_chan->l_io_buf_posi/ps_chan->l_buf_size)*ps_chan->l_buf_size; - /* l_write_size points to start of this GOOSY buf in i/o buf area */ - ps_chan->ps_bufhe=(s_bufhe*)(ps_chan->pc_io_buf + l_write_size); - l_write_size = l_write_size + ps_chan->l_buf_size - ps_chan->l_io_buf_posi; - /* l_write_size is remain free space in this GOOSY buf */ - if(l_write_size>(ps_chan->l_evt_size-l_evt_buf_posi)) { - l_write_size=(ps_chan->l_evt_size-l_evt_buf_posi); - } - memcpy(ps_chan->pc_io_buf + ps_chan->l_io_buf_posi, (CHARS*)pl_evt_buf + l_evt_buf_posi, l_write_size); - ps_chan->ps_bufhe->l_evt ++; /* number of fragments */ - ps_chan->l_io_buf_posi += l_write_size; - l_evt_buf_posi += l_write_size; - ps_chan->ps_bufhe->i_used += l_write_size/2; - /* if the remain free space of GOOSY buffer does not large enough * - * to hold even a event header, then turn to next GOOSY buffer and * - * fill buffer header. or 8 long words aligned ???????? */ - l_free=(ps_chan->l_io_buf_posi/ps_chan->l_buf_size)*ps_chan->l_buf_size; - /* l_free points to start of this GOOSY buf in i/o buf area */ - l_free = l_free + ps_chan->l_buf_size - ps_chan->l_io_buf_posi; - if(l_free==ps_chan->l_buf_size) { l_free=0; } - /* l_free is remain free space in this GOOSY buf */ - if(l_freel_io_buf_posi += l_free; } - /* change spanned evt header l_dlen */ - if(l_evt_buf_posi!=l_write_size) { - ps_chan->ps_ve10_1->l_dlen= l_write_size/2; - ps_chan->ps_ve10_1->i_subtype = ps_chan->l_buf_subtype; - ps_chan->ps_ve10_1->i_type = ps_chan->l_buf_type; - } else { ps_chan->ps_ve10_1->l_dlen= (l_write_size-sizeof(s_evhe))/2; } /* header of first frag */ - if((ps_chan->l_io_buf_posi%ps_chan->l_buf_size)==0) { - if(l_evt_buf_posil_evt_size) { ps_chan->ps_bufhe->h_begin = 1; } - if(ps_chan->l_io_buf_posi > ps_chan->l_buf_size) { /* so first buf in stream */ - ps_chan->ps_bufhe->h_end = ((s_bufhe*)((CHARS*)ps_chan->ps_bufhe - ps_chan->l_buf_size))->h_begin; - } - ps_chan->ps_bufhe->l_free[1] = ((s_ve10_1*)(pl_evt_buf))->l_dlen; /* lgth of last event in buf */ - } /* end of processs prev buffer head and ... */ + ps_chan->ps_bufhe = (s_bufhe*)(ps_chan->pc_io_buf + l_write_size); + l_write_size = l_write_size + ps_chan->l_buf_size - ps_chan->l_io_buf_posi; + /* l_write_size is remain free space in this GOOSY buf */ + if (l_write_size > (ps_chan->l_evt_size - l_evt_buf_posi)) { + l_write_size = (ps_chan->l_evt_size - l_evt_buf_posi); + } + memcpy(ps_chan->pc_io_buf + ps_chan->l_io_buf_posi, (CHARS*)pl_evt_buf + l_evt_buf_posi, l_write_size); + ps_chan->ps_bufhe->l_evt++; /* number of fragments */ + ps_chan->l_io_buf_posi += l_write_size; + l_evt_buf_posi += l_write_size; + ps_chan->ps_bufhe->i_used += l_write_size / 2; + /* if the remain free space of GOOSY buffer does not large enough * + * to hold even a event header, then turn to next GOOSY buffer and * + * fill buffer header. or 8 long words aligned ???????? */ + l_free = (ps_chan->l_io_buf_posi / ps_chan->l_buf_size) * ps_chan->l_buf_size; + /* l_free points to start of this GOOSY buf in i/o buf area */ + l_free = l_free + ps_chan->l_buf_size - ps_chan->l_io_buf_posi; + if (l_free == ps_chan->l_buf_size) { + l_free = 0; + } + /* l_free is remain free space in this GOOSY buf */ + if (l_free < sizeof(s_ve10_1)) { + ps_chan->l_io_buf_posi += l_free; + } + /* change spanned evt header l_dlen */ + if (l_evt_buf_posi != l_write_size) { + ps_chan->ps_ve10_1->l_dlen = l_write_size / 2; + ps_chan->ps_ve10_1->i_subtype = ps_chan->l_buf_subtype; + ps_chan->ps_ve10_1->i_type = ps_chan->l_buf_type; + } else { + ps_chan->ps_ve10_1->l_dlen = (l_write_size - sizeof(s_evhe)) / 2; + } /* header of first frag */ + if ((ps_chan->l_io_buf_posi % ps_chan->l_buf_size) == 0) { + if (l_evt_buf_posi < ps_chan->l_evt_size) { + ps_chan->ps_bufhe->h_begin = 1; + } + if (ps_chan->l_io_buf_posi > ps_chan->l_buf_size) { /* so first buf in stream */ + ps_chan->ps_bufhe->h_end = ((s_bufhe*)((CHARS*)ps_chan->ps_bufhe - ps_chan->l_buf_size))->h_begin; + } + ps_chan->ps_bufhe->l_free[1] = ((s_ve10_1*)(pl_evt_buf))->l_dlen; /* lgth of last event in buf */ + } /* end of processs prev buffer head and ... */ - } /* end of write event into i/o buf till end of event */ - return(PUTEVT__SUCCESS); + } /* end of write event into i/o buf till end of event */ + return (PUTEVT__SUCCESS); } /* end of f_evt_put_event */ /*1+ C Main ****************+******************************************/ @@ -1448,26 +1619,26 @@ INTS4 f_evt_put_event(s_evt_channel* ps_chan, INTS4* pl_evt_buf) INTS4 f_evt_put_buffer(s_evt_channel* ps_chan, s_bufhe* ps_bufhe) { - INTS4 l_write_size;//, l_temp, l_free; - INTS4 l_status; -// CHARS* pc_addr; - -// DABC - if(ps_chan->pLmd != NULL) { - l_status=fLmdPutBuffer(ps_chan->pLmd,(sMbsHeader*)(ps_bufhe+1),ps_bufhe->l_evt); - return(l_status); - } -// -- DABC - ps_chan->l_io_buf_posi = ps_chan->l_buf_size; - ps_chan->l_io_buf_size = ps_chan->l_buf_size; - l_write_size=write(ps_chan->l_channel_no, (CHARS*) ps_bufhe, ps_chan->l_buf_size); - if(l_write_size==-1) { - return(PUTEVT__WRERR); - } - if(l_write_size!=ps_chan->l_buf_size) { - return(PUTEVT__TOOBIG); - } - return PUTEVT__SUCCESS; + INTS4 l_write_size; //, l_temp, l_free; + INTS4 l_status; + // CHARS* pc_addr; + + // DABC + if (ps_chan->pLmd != NULL) { + l_status = fLmdPutBuffer(ps_chan->pLmd, (sMbsHeader*)(ps_bufhe + 1), ps_bufhe->l_evt); + return (l_status); + } + // -- DABC + ps_chan->l_io_buf_posi = ps_chan->l_buf_size; + ps_chan->l_io_buf_size = ps_chan->l_buf_size; + l_write_size = write(ps_chan->l_channel_no, (CHARS*)ps_bufhe, ps_chan->l_buf_size); + if (l_write_size == -1) { + return (PUTEVT__WRERR); + } + if (l_write_size != ps_chan->l_buf_size) { + return (PUTEVT__TOOBIG); + } + return PUTEVT__SUCCESS; } /* end of f_evt_put_buffer */ /*1+ C Main ****************+******************************************/ @@ -1492,69 +1663,70 @@ INTS4 f_evt_put_buffer(s_evt_channel* ps_chan, s_bufhe* ps_bufhe) INTS4 f_evt_put_close(s_evt_channel* ps_chan) { - INTS4 l_write_size, l_temp, l_temp2; - INTS4 l_status; -// CHARS* pc_addr; - -// DABC - if(ps_chan->pLmd != NULL) { - l_status=fLmdPutClose(ps_chan->pLmd); - return(l_status); - } -// -- DABC - if(ps_chan->l_first_put==1) { goto g_close; } - - /* if not the end of GOOSY buf, fill buffer header */ - if((ps_chan->l_io_buf_posi%ps_chan->l_buf_size)!=0) { - l_temp=(ps_chan->l_io_buf_posi/ps_chan->l_buf_size)*ps_chan->l_buf_size; - /* l_temp points to start of this GOOSY buf in i/o buf area */ - memset(ps_chan->pc_io_buf+ps_chan->l_io_buf_posi, '\0', - l_temp+ps_chan->l_buf_size-ps_chan->l_io_buf_posi); - /* clear rest of this GOOSY buffer */ - ps_chan->ps_bufhe=(s_bufhe*)(ps_chan->pc_io_buf + l_temp); - - ps_chan->ps_bufhe->l_dlen = (ps_chan->l_buf_size - sizeof(s_bufhe))/2; - ps_chan->ps_bufhe->h_begin = 0; /* evt has end, so not spanned to next buf */ - if(l_temp==0) { /* so fisrt buf in stream */ - ps_chan->ps_bufhe->h_end = 0; - } else - ps_chan->ps_bufhe->h_end = ((s_bufhe*)((CHARS*)ps_chan->ps_bufhe - ps_chan->l_buf_size)) - ->h_begin; - ps_chan->ps_bufhe->i_used = (ps_chan->l_io_buf_posi%ps_chan->l_buf_size - - sizeof(s_bufhe))/2; - } /* end of process of infilished buffer header */ - - /* if at the end of io buf, need not flush */ - if(ps_chan->l_io_buf_posi!=ps_chan->l_io_buf_size) { - if((ps_chan->l_io_buf_posi%ps_chan->l_buf_size)!=0) - l_write_size=(ps_chan->l_io_buf_posi/ps_chan->l_buf_size+1) * - ps_chan->l_buf_size; - else { - l_write_size=ps_chan->l_io_buf_posi; - } + INTS4 l_write_size, l_temp, l_temp2; + INTS4 l_status; + // CHARS* pc_addr; + + // DABC + if (ps_chan->pLmd != NULL) { + l_status = fLmdPutClose(ps_chan->pLmd); + return (l_status); + } + // -- DABC + if (ps_chan->l_first_put == 1) { + goto g_close; + } + + /* if not the end of GOOSY buf, fill buffer header */ + if ((ps_chan->l_io_buf_posi % ps_chan->l_buf_size) != 0) { + l_temp = (ps_chan->l_io_buf_posi / ps_chan->l_buf_size) * ps_chan->l_buf_size; + /* l_temp points to start of this GOOSY buf in i/o buf area */ + memset( + ps_chan->pc_io_buf + ps_chan->l_io_buf_posi, '\0', l_temp + ps_chan->l_buf_size - ps_chan->l_io_buf_posi); + /* clear rest of this GOOSY buffer */ + ps_chan->ps_bufhe = (s_bufhe*)(ps_chan->pc_io_buf + l_temp); + + ps_chan->ps_bufhe->l_dlen = (ps_chan->l_buf_size - sizeof(s_bufhe)) / 2; + ps_chan->ps_bufhe->h_begin = 0; /* evt has end, so not spanned to next buf */ + if (l_temp == 0) { /* so fisrt buf in stream */ + ps_chan->ps_bufhe->h_end = 0; + } else + ps_chan->ps_bufhe->h_end = ((s_bufhe*)((CHARS*)ps_chan->ps_bufhe - ps_chan->l_buf_size))->h_begin; + ps_chan->ps_bufhe->i_used = (ps_chan->l_io_buf_posi % ps_chan->l_buf_size - sizeof(s_bufhe)) / 2; + } /* end of process of infilished buffer header */ + + /* if at the end of io buf, need not flush */ + if (ps_chan->l_io_buf_posi != ps_chan->l_io_buf_size) { + if ((ps_chan->l_io_buf_posi % ps_chan->l_buf_size) != 0) + l_write_size = (ps_chan->l_io_buf_posi / ps_chan->l_buf_size + 1) * ps_chan->l_buf_size; + else { + l_write_size = ps_chan->l_io_buf_posi; + } - for(l_temp=0; l_templ_buf_size) { - /* why use this loop instead of write the whole io_buf out? because in + for (l_temp = 0; l_temp < l_write_size; l_temp += ps_chan->l_buf_size) { + /* why use this loop instead of write the whole io_buf out? because in VMS side, the record can only be l_buf_size big, not l_write_size big */ - l_temp2=write(ps_chan->l_channel_no, ps_chan->pc_io_buf+l_temp, - ps_chan->l_buf_size); - if(l_temp2==-1) { - return(PUTEVT__WRERR); - } - if(l_temp2!=ps_chan->l_buf_size) { - return(PUTEVT__TOOBIG); - } - } - } /* end of flush */ + l_temp2 = write(ps_chan->l_channel_no, ps_chan->pc_io_buf + l_temp, ps_chan->l_buf_size); + if (l_temp2 == -1) { + return (PUTEVT__WRERR); + } + if (l_temp2 != ps_chan->l_buf_size) { + return (PUTEVT__TOOBIG); + } + } + } /* end of flush */ g_close: - free(ps_chan->pc_io_buf); - /* free io buffer Memory */ + free(ps_chan->pc_io_buf); + /* free io buffer Memory */ - l_status=close(ps_chan->l_channel_no); - ps_chan->l_channel_no=-1; - if(l_status == -1) { return(PUTEVT__CLOSE_ERR); } - else { return PUTEVT__SUCCESS; } + l_status = close(ps_chan->l_channel_no); + ps_chan->l_channel_no = -1; + if (l_status == -1) { + return (PUTEVT__CLOSE_ERR); + } else { + return PUTEVT__SUCCESS; + } } /* end of f_evt_put_close */ /*1+ C Main ****************+******************************************/ @@ -1581,90 +1753,97 @@ INTS4 f_evt_put_close(s_evt_channel* ps_chan) /* message is copied into string, else */ /* f_evt_error prints the message on terminal. */ /*1- C Main ******************+****************************************/ -INTS4 f_evt_error( INTS4 l_error , CHARS* pc_dest , INTS4 l_out ) +INTS4 f_evt_error(INTS4 l_error, CHARS* pc_dest, INTS4 l_out) { - CHARS c_line[80]; - - switch( l_error ) { - case GETEVT__NOFILE : - sprintf(c_line,"-I-f_evt: no such input file"); - break; - case GETEVT__NOTAGFILE : - sprintf(c_line,"-I-f_evt: no such tag file"); - break; - case GETEVT__NOTAG : - sprintf(c_line,"-I-f_evt: no such event tag"); - break; - case GETEVT__TIMEOUT : - sprintf(c_line,"-I-f_evt: time out"); - break; - case GETEVT__NOSERVER : - sprintf(c_line,"-I-f_evt: no such server"); - break; - case GETEVT__RDERR : - sprintf(c_line,"-I-f_evt: read server error"); - break; - case GETEVT__TAGRDERR : - sprintf(c_line,"-I-f_evt: read tag file error"); - break; - case GETEVT__TAGWRERR : - sprintf(c_line,"-I-f_evt: write tag file error"); - break; - case GETEVT__FRAGMENT : - sprintf(c_line,"-I-f_evt: data format error"); - break; - case GETEVT__NOMORE : - sprintf(c_line,"-I-f_evt: no more event"); - break; - case GETEVT__CLOSE_ERR: - sprintf(c_line,"-I-f_evt: close server error"); - break; - case GETEVT__FAILURE : - sprintf(c_line,"-I-f_evt: failure"); - break; - case GETEVT__NOCHANNEL : - sprintf(c_line,"-I-f_evt: too many channels"); - break; - case GETEVT__NOLMDFILE : - sprintf(c_line,"-I-f_evt: input file is no LMD file"); - break; - case GETEVT__SUCCESS : - sprintf(c_line,"-I-f_evt: success"); - break; - case PUTEVT__FILE_EXIST : - sprintf(c_line,"-I-f_evt: output file already exist"); - break; - case PUTEVT__WRERR : - sprintf(c_line,"-I-f_evt: write file error"); - break; - case PUTEVT__TOOBIG : - sprintf(c_line,"-I-f_evt: output file too large"); - break; - case PUTEVT__TOO_SMALLS: - sprintf(c_line,"-I-f_evt: event can not fit in a stream"); - break; - case PUTEVT__CLOSE_ERR : - sprintf(c_line,"-I-f_evt: close output error"); - break; - case PUTEVT__FAILURE : - sprintf(c_line,"-I-f_evt: output failure"); - break; - case PUTEVT__NOCHANNEL : - sprintf(c_line,"-I-f_evt: too many channels"); - break; - default : - sprintf(c_line,"-I-f_evt: unknown message id %d",l_error); - if(l_out==0) { printf("%s\n",c_line); } - if(l_out==1) { strcpy(pc_dest,c_line); } - return GETEVT__FAILURE; - } /* end switch( l_error ) */ - - if(l_out==0) { printf("%s\n",c_line); } - if(l_out==1) { strcpy(pc_dest,c_line); } - - return GETEVT__SUCCESS; -} /* end of f_evt_error */ + CHARS c_line[80]; + + switch (l_error) { + case GETEVT__NOFILE: + sprintf(c_line, "-I-f_evt: no such input file"); + break; + case GETEVT__NOTAGFILE: + sprintf(c_line, "-I-f_evt: no such tag file"); + break; + case GETEVT__NOTAG: + sprintf(c_line, "-I-f_evt: no such event tag"); + break; + case GETEVT__TIMEOUT: + sprintf(c_line, "-I-f_evt: time out"); + break; + case GETEVT__NOSERVER: + sprintf(c_line, "-I-f_evt: no such server"); + break; + case GETEVT__RDERR: + sprintf(c_line, "-I-f_evt: read server error"); + break; + case GETEVT__TAGRDERR: + sprintf(c_line, "-I-f_evt: read tag file error"); + break; + case GETEVT__TAGWRERR: + sprintf(c_line, "-I-f_evt: write tag file error"); + break; + case GETEVT__FRAGMENT: + sprintf(c_line, "-I-f_evt: data format error"); + break; + case GETEVT__NOMORE: + sprintf(c_line, "-I-f_evt: no more event"); + break; + case GETEVT__CLOSE_ERR: + sprintf(c_line, "-I-f_evt: close server error"); + break; + case GETEVT__FAILURE: + sprintf(c_line, "-I-f_evt: failure"); + break; + case GETEVT__NOCHANNEL: + sprintf(c_line, "-I-f_evt: too many channels"); + break; + case GETEVT__NOLMDFILE: + sprintf(c_line, "-I-f_evt: input file is no LMD file"); + break; + case GETEVT__SUCCESS: + sprintf(c_line, "-I-f_evt: success"); + break; + case PUTEVT__FILE_EXIST: + sprintf(c_line, "-I-f_evt: output file already exist"); + break; + case PUTEVT__WRERR: + sprintf(c_line, "-I-f_evt: write file error"); + break; + case PUTEVT__TOOBIG: + sprintf(c_line, "-I-f_evt: output file too large"); + break; + case PUTEVT__TOO_SMALLS: + sprintf(c_line, "-I-f_evt: event can not fit in a stream"); + break; + case PUTEVT__CLOSE_ERR: + sprintf(c_line, "-I-f_evt: close output error"); + break; + case PUTEVT__FAILURE: + sprintf(c_line, "-I-f_evt: output failure"); + break; + case PUTEVT__NOCHANNEL: + sprintf(c_line, "-I-f_evt: too many channels"); + break; + default: + sprintf(c_line, "-I-f_evt: unknown message id %d", l_error); + if (l_out == 0) { + printf("%s\n", c_line); + } + if (l_out == 1) { + strcpy(pc_dest, c_line); + } + return GETEVT__FAILURE; + } /* end switch( l_error ) */ + if (l_out == 0) { + printf("%s\n", c_line); + } + if (l_out == 1) { + strcpy(pc_dest, c_line); + } + + return GETEVT__SUCCESS; +} /* end of f_evt_error */ /*1+ C Main ****************+******************************************/ /*+ Module : f_evt_get_buffer */ @@ -1689,63 +1868,73 @@ INTS4 f_evt_error( INTS4 l_error , CHARS* pc_dest , INTS4 l_out ) /*1- C Main ****************+******************************************/ INTS4 f_evt_get_buffer(s_evt_channel* ps_chan, INTS4* ps_buffer) { - INTS4 l_temp; - CHARS* pc_temp; - INTS4 l_status; - - pc_temp=(CHARS*)ps_chan->pc_io_buf; - switch(ps_chan->l_server_type) { - case GETEVT__FILE : - l_temp=read(ps_chan->l_channel_no,ps_buffer, ps_chan->l_buf_size); - if(l_temp == 0) - /* if end of file, then exit */ - { - ps_chan->l_io_buf_size = 0; - return(GETEVT__NOMORE); - } else if(l_temp == -1) { - ps_chan->l_io_buf_size = 0; - return(GETEVT__RDERR); - } - break; - case GETEVT__RFIO : - l_temp=RFIO_read(ps_chan->l_channel_no,(CHARS*)ps_buffer, ps_chan->l_buf_size); - if(l_temp == 0) { - ps_chan->l_io_buf_size = 0; - return(GETEVT__NOMORE); - } else if(l_temp == -1) { - ps_chan->l_io_buf_size = 0; - return(GETEVT__RDERR); - } - break; - case GETEVT__STREAM : - if(ps_chan->l_stream_bufs == 0) - if(f_stc_write("GETEVT", 7, ps_chan->l_channel_no)!=STC__SUCCESS) { - return(GETEVT__FAILURE); - } + INTS4 l_temp; + CHARS* pc_temp; + INTS4 l_status; + + pc_temp = (CHARS*)ps_chan->pc_io_buf; + switch (ps_chan->l_server_type) { + case GETEVT__FILE: + l_temp = read(ps_chan->l_channel_no, ps_buffer, ps_chan->l_buf_size); + if (l_temp == 0) + /* if end of file, then exit */ + { + ps_chan->l_io_buf_size = 0; + return (GETEVT__NOMORE); + } else if (l_temp == -1) { + ps_chan->l_io_buf_size = 0; + return (GETEVT__RDERR); + } + break; + case GETEVT__RFIO: + l_temp = RFIO_read(ps_chan->l_channel_no, (CHARS*)ps_buffer, ps_chan->l_buf_size); + if (l_temp == 0) { + ps_chan->l_io_buf_size = 0; + return (GETEVT__NOMORE); + } else if (l_temp == -1) { + ps_chan->l_io_buf_size = 0; + return (GETEVT__RDERR); + } + break; + case GETEVT__STREAM: + if (ps_chan->l_stream_bufs == 0) + if (f_stc_write("GETEVT", 7, ps_chan->l_channel_no) != STC__SUCCESS) { + return (GETEVT__FAILURE); + } + + l_status = f_stc_read(ps_buffer, ps_chan->l_buf_size, ps_chan->l_channel_no, ps_chan->l_timeout); + if (l_status == STC__TIMEOUT) { + return (GETEVT__TIMEOUT); + } + if (l_status != STC__SUCCESS) { + return (GETEVT__RDERR); + } + ps_chan->l_stream_bufs++; + if (ps_chan->l_stream_bufs == ps_chan->l_bufs_in_stream) { + ps_chan->l_stream_bufs = 0; + } + break; + case GETEVT__TRANS: + l_status = f_stc_read(ps_buffer, ps_chan->l_buf_size, ps_chan->l_channel_no, ps_chan->l_timeout); + if (l_status == STC__TIMEOUT) { + return (GETEVT__TIMEOUT); + } + if (l_status != STC__SUCCESS) { + return (GETEVT__RDERR); + } + break; + case GETEVT__REVSERV: + case GETEVT__EVENT: + default: + return (GETEVT__FAILURE); + } /* end of switch */ - l_status=f_stc_read(ps_buffer, ps_chan->l_buf_size, ps_chan->l_channel_no,ps_chan->l_timeout); - if(l_status == STC__TIMEOUT) { return(GETEVT__TIMEOUT); } - if(l_status != STC__SUCCESS) { return(GETEVT__RDERR); } - ps_chan->l_stream_bufs++; - if(ps_chan->l_stream_bufs == ps_chan->l_bufs_in_stream) { ps_chan->l_stream_bufs = 0; } - break; - case GETEVT__TRANS : - l_status=f_stc_read(ps_buffer, ps_chan->l_buf_size, ps_chan->l_channel_no,ps_chan->l_timeout); - if(l_status == STC__TIMEOUT) { return(GETEVT__TIMEOUT); } - if(l_status != STC__SUCCESS) { return(GETEVT__RDERR); } - break; - case GETEVT__REVSERV : - case GETEVT__EVENT : - default : - return(GETEVT__FAILURE); - } /* end of switch */ - - /* swap */ - if( ((s_bufhe*)(ps_buffer))->l_free[0] !=1) { - f_evt_swap((CHARS*)ps_buffer, ps_chan->l_buf_size); - } - - return(GETEVT__SUCCESS); + /* swap */ + if (((s_bufhe*)(ps_buffer))->l_free[0] != 1) { + f_evt_swap((CHARS*)ps_buffer, ps_chan->l_buf_size); + } + + return (GETEVT__SUCCESS); } /* end of f_evt_get_buffer */ /*1+ C Main ****************+******************************************/ /*+ Module : f_evt_skip_buffer */ @@ -1769,36 +1958,36 @@ INTS4 f_evt_get_buffer(s_evt_channel* ps_chan, INTS4* ps_buffer) /*1- C Main ****************+******************************************/ INTS4 f_evt_skip_buffer(s_evt_channel* ps_chan, INTS4 l_buffer) { - INTS4 l_temp; - CHARS* pc_temp; -// INTS4 l_status,ii; - - pc_temp=(CHARS*)ps_chan->pc_io_buf; - switch(ps_chan->l_server_type) { - case GETEVT__FILE : - l_temp=lseek(ps_chan->l_channel_no,l_buffer*ps_chan->l_buf_size,SEEK_CUR); - if(l_temp == -1) - /* if end of file, then exit */ - { - return(GETEVT__NOMORE); - } - break; - case GETEVT__RFIO : - l_temp=RFIO_lseek(ps_chan->l_channel_no,l_buffer*ps_chan->l_buf_size,SEEK_CUR); - if(l_temp == -1) { - return(GETEVT__NOMORE); - } - break; - case GETEVT__STREAM : - case GETEVT__TRANS : - case GETEVT__REVSERV : - case GETEVT__EVENT : - default : - return(GETEVT__FAILURE); - } /* end of switch */ - - ps_chan->l_first_get=1; /* so we will first call f_getevt_get */ - return(GETEVT__SUCCESS); + INTS4 l_temp; + CHARS* pc_temp; + // INTS4 l_status,ii; + + pc_temp = (CHARS*)ps_chan->pc_io_buf; + switch (ps_chan->l_server_type) { + case GETEVT__FILE: + l_temp = lseek(ps_chan->l_channel_no, l_buffer * ps_chan->l_buf_size, SEEK_CUR); + if (l_temp == -1) + /* if end of file, then exit */ + { + return (GETEVT__NOMORE); + } + break; + case GETEVT__RFIO: + l_temp = RFIO_lseek(ps_chan->l_channel_no, l_buffer * ps_chan->l_buf_size, SEEK_CUR); + if (l_temp == -1) { + return (GETEVT__NOMORE); + } + break; + case GETEVT__STREAM: + case GETEVT__TRANS: + case GETEVT__REVSERV: + case GETEVT__EVENT: + default: + return (GETEVT__FAILURE); + } /* end of switch */ + + ps_chan->l_first_get = 1; /* so we will first call f_getevt_get */ + return (GETEVT__SUCCESS); } /* end of f_evt_skip_buffer */ /*1+ C Main ****************+******************************************/ @@ -1823,8 +2012,8 @@ INTS4 f_evt_skip_buffer(s_evt_channel* ps_chan, INTS4 l_buffer) /*1- C Main ****************+******************************************/ INTS4 f_evt_timeout(s_evt_channel* ps_chan, INTS4 l_sec) { - ps_chan->l_timeout = l_sec; - return(GETEVT__SUCCESS); + ps_chan->l_timeout = l_sec; + return (GETEVT__SUCCESS); } /* end of f_evt_timeout */ /*1- C Main ****************+******************************************/ @@ -1843,25 +2032,25 @@ INTS4 f_evt_timeout(s_evt_channel* ps_chan, INTS4 l_sec) /*1- C Procedure ***********+******************************************/ INTS4 f_evt_swap(CHARS* pc_source, INTS4 l_length) { - CHARS* p_s, * p_d; - INTS4 l_save; - CHARS ch_temp; - - if(l_length%4 == 2) { - ch_temp=*(pc_source+l_length-2); - *(pc_source+l_length-2)=*(pc_source+l_length-1); - *(pc_source+l_length-1)=ch_temp; - } - l_length=(l_length/4)*4; /* aligned */ - for(p_d=pc_source,p_s=(CHARS*)&l_save; p_di_type == 2000) { - ps_filhe=(s_filhe*)ps_bufhe; - f_evt_swap((CHARS*)&ps_filhe->filhe_lines,4); /* number of comment lines ps_filhe->filhe_lines*/ - ps_filhe->filhe_label_l=ps_filhe->filhe_label_l>>8; - ps_filhe->filhe_file_l =ps_filhe->filhe_file_l >>8; - ps_filhe->filhe_user_l =ps_filhe->filhe_user_l >>8; - ps_filhe->filhe_run_l =ps_filhe->filhe_run_l >>8; - ps_filhe->filhe_exp_l =ps_filhe->filhe_exp_l >>8; - pi=(INTS2*)&ps_filhe->s_strings; - for(ii=0; iifilhe_lines; ii++) { - *pi=*pi>>8; - pi += 40; - } - } - - return(0); + // CHARS* p_s, * p_d; + INTS4 ii; + INTS2* pi; + s_filhe* ps_filhe; + + f_evt_swap((CHARS*)ps_bufhe, 48); + if (ps_bufhe->i_type == 2000) { + ps_filhe = (s_filhe*)ps_bufhe; + f_evt_swap((CHARS*)&ps_filhe->filhe_lines, 4); /* number of comment lines ps_filhe->filhe_lines*/ + ps_filhe->filhe_label_l = ps_filhe->filhe_label_l >> 8; + ps_filhe->filhe_file_l = ps_filhe->filhe_file_l >> 8; + ps_filhe->filhe_user_l = ps_filhe->filhe_user_l >> 8; + ps_filhe->filhe_run_l = ps_filhe->filhe_run_l >> 8; + ps_filhe->filhe_exp_l = ps_filhe->filhe_exp_l >> 8; + pi = (INTS2*)&ps_filhe->s_strings; + for (ii = 0; ii < ps_filhe->filhe_lines; ii++) { + *pi = *pi >> 8; + pi += 40; + } + } + + return (0); } /* end of f_evt_swap */ /*1- C Main ****************+******************************************/ @@ -1915,10 +2104,7 @@ INTS4 f_evt_swap_filhe(s_bufhe* ps_bufhe) /*+ Return type : int. */ /*+ Status codes: */ /*1- C Main ****************+******************************************/ -CHARS* f_evt_get_buffer_ptr(s_evt_channel* ps_chan) -{ - return(ps_chan->pc_io_buf); -} +CHARS* f_evt_get_buffer_ptr(s_evt_channel* ps_chan) { return (ps_chan->pc_io_buf); } /*1- C Main ****************+******************************************/ /*+ Module : f_evt_get_newbuf */ /*--------------------------------------------------------------------*/ @@ -1938,75 +2124,97 @@ CHARS* f_evt_get_buffer_ptr(s_evt_channel* ps_chan) /*1- C Main ****************+******************************************/ INTS4 f_evt_get_newbuf(s_evt_channel* ps_chan) { - INTS4 l_temp; - CHARS* pc_temp; - INTS4 l_status; - - pc_temp=(CHARS*)ps_chan->pc_io_buf; - switch(ps_chan->l_server_type) { - case GETEVT__FILE : - while(1) { - l_temp=read(ps_chan->l_channel_no,pc_temp, ps_chan->l_io_buf_size); - if(l_temp == 0) { return(GETEVT__NOMORE); } - if(l_temp == -1) { return(GETEVT__RDERR); } - if(l_temp < ps_chan->l_io_buf_size) { return(GETEVT__RDERR); } - break; /* skip out while(1) */ - } /* end of while(1) */ - break; - case GETEVT__STREAM : - if(f_stc_write("GETEVT", 7, ps_chan->l_channel_no)!=STC__SUCCESS) { - return(GETEVT__FAILURE); - } - - for(l_temp=0; l_templ_bufs_in_stream; l_temp++) { - l_status=f_stc_read(pc_temp, ps_chan->l_buf_size, ps_chan->l_channel_no,ps_chan->l_timeout); - if(l_status == STC__TIMEOUT) { return(GETEVT__TIMEOUT); } - if(l_status != STC__SUCCESS) { return(GETEVT__RDERR); } - pc_temp+=ps_chan->l_buf_size; - } - l_temp=((s_bufhe*)(ps_chan->pc_io_buf))->l_evt; - if( ((s_bufhe*)(ps_chan->pc_io_buf))->l_free[0] !=1) { // swap - f_evt_swap((CHARS*)&l_temp,4); - } - if(l_temp < 0) {// server will shutdown - printf("**** I-f_evt: Stream server request for disconnect!\n"); - f_evt_get_close(ps_chan); - return(GETEVT__RDERR); - } - /* if first buffer is empty, all are empty */ - if( ((s_bufhe*)(ps_chan->pc_io_buf))->l_evt == 0) { return(GETEVT__TIMEOUT); } - break; - case GETEVT__TRANS : - l_status=f_stc_read(pc_temp, ps_chan->l_buf_size, ps_chan->l_channel_no,ps_chan->l_timeout); - l_temp=((s_bufhe*)(ps_chan->pc_io_buf))->l_evt; - if( ((s_bufhe*)(ps_chan->pc_io_buf))->l_free[0] !=1) { // swap - f_evt_swap((CHARS*)&l_temp,4); - } - if(l_temp < 0) {// server will shutdown - printf("**** I-f_evt: Transport server request for disconnect!\n"); - f_evt_get_close(ps_chan); - return(GETEVT__RDERR); - } - if(l_status == STC__TIMEOUT) { return(GETEVT__TIMEOUT); } - if(l_status != STC__SUCCESS) { return(GETEVT__RDERR); } - break; - case GETEVT__RFIO : - l_temp=RFIO_read(ps_chan->l_channel_no,pc_temp, ps_chan->l_io_buf_size); - if(l_temp == 0) { return(GETEVT__NOMORE); } - if(l_temp == -1) { return(GETEVT__RDERR); } - if(l_temp < ps_chan->l_io_buf_size) { return(GETEVT__RDERR); } - break; - case GETEVT__REVSERV : - case GETEVT__EVENT : - default : - return(GETEVT__FAILURE); - } /* end of switch */ - - if( ((s_bufhe*)(ps_chan->pc_io_buf))->l_free[0] !=1) { // swap - f_evt_swap(ps_chan->pc_io_buf, ps_chan->l_io_buf_size); - } - - return(GETEVT__SUCCESS); + INTS4 l_temp; + CHARS* pc_temp; + INTS4 l_status; + + pc_temp = (CHARS*)ps_chan->pc_io_buf; + switch (ps_chan->l_server_type) { + case GETEVT__FILE: + while (1) { + l_temp = read(ps_chan->l_channel_no, pc_temp, ps_chan->l_io_buf_size); + if (l_temp == 0) { + return (GETEVT__NOMORE); + } + if (l_temp == -1) { + return (GETEVT__RDERR); + } + if (l_temp < ps_chan->l_io_buf_size) { + return (GETEVT__RDERR); + } + break; /* skip out while(1) */ + } /* end of while(1) */ + break; + case GETEVT__STREAM: + if (f_stc_write("GETEVT", 7, ps_chan->l_channel_no) != STC__SUCCESS) { + return (GETEVT__FAILURE); + } + + for (l_temp = 0; l_temp < ps_chan->l_bufs_in_stream; l_temp++) { + l_status = f_stc_read(pc_temp, ps_chan->l_buf_size, ps_chan->l_channel_no, ps_chan->l_timeout); + if (l_status == STC__TIMEOUT) { + return (GETEVT__TIMEOUT); + } + if (l_status != STC__SUCCESS) { + return (GETEVT__RDERR); + } + pc_temp += ps_chan->l_buf_size; + } + l_temp = ((s_bufhe*)(ps_chan->pc_io_buf))->l_evt; + if (((s_bufhe*)(ps_chan->pc_io_buf))->l_free[0] != 1) { // swap + f_evt_swap((CHARS*)&l_temp, 4); + } + if (l_temp < 0) { // server will shutdown + printf("**** I-f_evt: Stream server request for disconnect!\n"); + f_evt_get_close(ps_chan); + return (GETEVT__RDERR); + } + /* if first buffer is empty, all are empty */ + if (((s_bufhe*)(ps_chan->pc_io_buf))->l_evt == 0) { + return (GETEVT__TIMEOUT); + } + break; + case GETEVT__TRANS: + l_status = f_stc_read(pc_temp, ps_chan->l_buf_size, ps_chan->l_channel_no, ps_chan->l_timeout); + l_temp = ((s_bufhe*)(ps_chan->pc_io_buf))->l_evt; + if (((s_bufhe*)(ps_chan->pc_io_buf))->l_free[0] != 1) { // swap + f_evt_swap((CHARS*)&l_temp, 4); + } + if (l_temp < 0) { // server will shutdown + printf("**** I-f_evt: Transport server request for disconnect!\n"); + f_evt_get_close(ps_chan); + return (GETEVT__RDERR); + } + if (l_status == STC__TIMEOUT) { + return (GETEVT__TIMEOUT); + } + if (l_status != STC__SUCCESS) { + return (GETEVT__RDERR); + } + break; + case GETEVT__RFIO: + l_temp = RFIO_read(ps_chan->l_channel_no, pc_temp, ps_chan->l_io_buf_size); + if (l_temp == 0) { + return (GETEVT__NOMORE); + } + if (l_temp == -1) { + return (GETEVT__RDERR); + } + if (l_temp < ps_chan->l_io_buf_size) { + return (GETEVT__RDERR); + } + break; + case GETEVT__REVSERV: + case GETEVT__EVENT: + default: + return (GETEVT__FAILURE); + } /* end of switch */ + + if (((s_bufhe*)(ps_chan->pc_io_buf))->l_free[0] != 1) { // swap + f_evt_swap(ps_chan->pc_io_buf, ps_chan->l_io_buf_size); + } + + return (GETEVT__SUCCESS); } /* end of f_evt_get_newbuf */ /*1- C Main ****************+******************************************/ @@ -2030,78 +2238,81 @@ INTS4 f_evt_get_newbuf(s_evt_channel* ps_chan) /*1- C Main ****************+******************************************/ INTS4 f_evt_check_buf(CHARS* pc_head, INTS4* pl_size, INTS4* pl_is_goosybuf, INTS4* pl_swap, INTS4* pl_filehead) { - INTU4 l_size; - - *pl_is_goosybuf=0; - *pl_filehead=0; - *pl_size=0; - *pl_swap=0; - /* first check if it's file header */ - if( (((s_filhe*)(pc_head))->filhe_subtype==1)&& - (((s_filhe*)(pc_head))->filhe_type==2000) ) { - *pl_swap=0; - *pl_is_goosybuf=0; - *pl_filehead=1; - l_size=((s_bufhe*)(pc_head))->l_dlen*2; - if(l_size%512 > 0) { l_size += sizeof(s_bufhe); } - if((l_size>>24) > 0) { *pl_size=0; } - else { *pl_size=l_size; } - return(PUTEVT__SUCCESS); - } - f_evt_swap(pc_head, sizeof(s_filhe)); - if( (((s_filhe*)(pc_head))->filhe_subtype==1)&& - (((s_filhe*)(pc_head))->filhe_type==2000) ) { - *pl_swap=1; - *pl_is_goosybuf=0; - *pl_filehead=1; - l_size=((s_bufhe*)(pc_head))->l_dlen*2; - if(l_size%512 > 0) { l_size += sizeof(s_bufhe); } - if((l_size>>24) > 0) { *pl_size=0; } - else { *pl_size=l_size; } - return(PUTEVT__SUCCESS); - } - - /* if not file header, check if it's goosy buffer header */ - l_size=((s_bufhe*)(pc_head))->l_dlen*2; - if(l_size%512 > 0) { l_size += sizeof(s_bufhe); } - if( (((l_size>>24)== 0)&&(l_size > 0))&& - (((s_bufhe*)(pc_head))->h_begin<2)&& - (((s_bufhe*)(pc_head))->h_begin>=0)&& - (((s_bufhe*)(pc_head))->h_end<2)&& - (((s_bufhe*)(pc_head))->h_end>=0)&& - //(((s_bufhe *)(pc_head))->i_used<=(MAX_BUF_LGTH-sizeof(s_bufhe))/2)&& - ((((s_bufhe*)(pc_head))->i_used>0)||(((s_bufhe*)(pc_head))->l_free[2]>0))&& - //(((s_bufhe *)(pc_head))->i_used>0)&& - ( (((s_bufhe*)(pc_head))->l_free[0]==1)|| - (((s_bufhe*)(pc_head))->l_free[0]==0)|| - /* above, because some old lsm file forgot to set this bit, so it's zero */ - (((s_bufhe*)(pc_head))->l_free[0]==256*256*256) ) ) { - *pl_swap=1; /* !!!, because already swaped once */ - *pl_is_goosybuf=1; - *pl_size=l_size; - return(PUTEVT__SUCCESS); - } - f_evt_swap(pc_head, sizeof(s_filhe)); - l_size=((s_bufhe*)(pc_head))->l_dlen*2+sizeof(s_bufhe); - if( (((l_size>>24)== 0)&&(l_size > 0))&& - (((s_bufhe*)(pc_head))->l_dlen>0)&& - (((s_bufhe*)(pc_head))->h_begin<2)&& - (((s_bufhe*)(pc_head))->h_begin>=0)&& - (((s_bufhe*)(pc_head))->h_end<2)&& - (((s_bufhe*)(pc_head))->h_end>=0)&& - //(((s_bufhe *)(pc_head))->i_used<=(MAX_BUF_LGTH-sizeof(s_bufhe))/2)&& - ((((s_bufhe*)(pc_head))->i_used>0)||(((s_bufhe*)(pc_head))->l_free[2]>0))&& - //(((s_bufhe *)(pc_head))->i_used>0)&& - ( (((s_bufhe*)(pc_head))->l_free[0]==1)|| - (((s_bufhe*)(pc_head))->l_free[0]==0)|| - /* above, because some old lsm file forgot to set this bit, so it's zero */ - (((s_bufhe*)(pc_head))->l_free[0]==256*256*256) ) ) { - *pl_swap=0; /* !!!, because already swaped 2 times */ - *pl_is_goosybuf=1; - *pl_size=l_size; - return(PUTEVT__SUCCESS); - } - return(PUTEVT__SUCCESS); + INTU4 l_size; + + *pl_is_goosybuf = 0; + *pl_filehead = 0; + *pl_size = 0; + *pl_swap = 0; + /* first check if it's file header */ + if ((((s_filhe*)(pc_head))->filhe_subtype == 1) && (((s_filhe*)(pc_head))->filhe_type == 2000)) { + *pl_swap = 0; + *pl_is_goosybuf = 0; + *pl_filehead = 1; + l_size = ((s_bufhe*)(pc_head))->l_dlen * 2; + if (l_size % 512 > 0) { + l_size += sizeof(s_bufhe); + } + if ((l_size >> 24) > 0) { + *pl_size = 0; + } else { + *pl_size = l_size; + } + return (PUTEVT__SUCCESS); + } + f_evt_swap(pc_head, sizeof(s_filhe)); + if ((((s_filhe*)(pc_head))->filhe_subtype == 1) && (((s_filhe*)(pc_head))->filhe_type == 2000)) { + *pl_swap = 1; + *pl_is_goosybuf = 0; + *pl_filehead = 1; + l_size = ((s_bufhe*)(pc_head))->l_dlen * 2; + if (l_size % 512 > 0) { + l_size += sizeof(s_bufhe); + } + if ((l_size >> 24) > 0) { + *pl_size = 0; + } else { + *pl_size = l_size; + } + return (PUTEVT__SUCCESS); + } + + /* if not file header, check if it's goosy buffer header */ + l_size = ((s_bufhe*)(pc_head))->l_dlen * 2; + if (l_size % 512 > 0) { + l_size += sizeof(s_bufhe); + } + if ((((l_size >> 24) == 0) && (l_size > 0)) && (((s_bufhe*)(pc_head))->h_begin < 2) + && (((s_bufhe*)(pc_head))->h_begin >= 0) && (((s_bufhe*)(pc_head))->h_end < 2) + && (((s_bufhe*)(pc_head))->h_end >= 0) && + //(((s_bufhe *)(pc_head))->i_used<=(MAX_BUF_LGTH-sizeof(s_bufhe))/2)&& + ((((s_bufhe*)(pc_head))->i_used > 0) || (((s_bufhe*)(pc_head))->l_free[2] > 0)) && + //(((s_bufhe *)(pc_head))->i_used>0)&& + ((((s_bufhe*)(pc_head))->l_free[0] == 1) || (((s_bufhe*)(pc_head))->l_free[0] == 0) || + /* above, because some old lsm file forgot to set this bit, so it's zero */ + (((s_bufhe*)(pc_head))->l_free[0] == 256 * 256 * 256))) { + *pl_swap = 1; /* !!!, because already swaped once */ + *pl_is_goosybuf = 1; + *pl_size = l_size; + return (PUTEVT__SUCCESS); + } + f_evt_swap(pc_head, sizeof(s_filhe)); + l_size = ((s_bufhe*)(pc_head))->l_dlen * 2 + sizeof(s_bufhe); + if ((((l_size >> 24) == 0) && (l_size > 0)) && (((s_bufhe*)(pc_head))->l_dlen > 0) + && (((s_bufhe*)(pc_head))->h_begin < 2) && (((s_bufhe*)(pc_head))->h_begin >= 0) + && (((s_bufhe*)(pc_head))->h_end < 2) && (((s_bufhe*)(pc_head))->h_end >= 0) && + //(((s_bufhe *)(pc_head))->i_used<=(MAX_BUF_LGTH-sizeof(s_bufhe))/2)&& + ((((s_bufhe*)(pc_head))->i_used > 0) || (((s_bufhe*)(pc_head))->l_free[2] > 0)) && + //(((s_bufhe *)(pc_head))->i_used>0)&& + ((((s_bufhe*)(pc_head))->l_free[0] == 1) || (((s_bufhe*)(pc_head))->l_free[0] == 0) || + /* above, because some old lsm file forgot to set this bit, so it's zero */ + (((s_bufhe*)(pc_head))->l_free[0] == 256 * 256 * 256))) { + *pl_swap = 0; /* !!!, because already swaped 2 times */ + *pl_is_goosybuf = 1; + *pl_size = l_size; + return (PUTEVT__SUCCESS); + } + return (PUTEVT__SUCCESS); } /* end of f_evt_check_buf */ /*1- C Main ****************+******************************************/ @@ -2117,32 +2328,32 @@ INTS4 f_evt_check_buf(CHARS* pc_head, INTS4* pl_size, INTS4* pl_is_goosybuf, INT /*1- C Main ****************+******************************************/ INTS4 f_evt_ini_bufhe(s_evt_channel* ps_chan) { - INTS4 l_temp; - struct timeb s_timeb; - - /* because "timeb" is not "typedef", so we must use "struct" */ - - for(l_temp=0; l_templ_io_buf_size; l_temp += ps_chan->l_buf_size) { - ps_chan->ps_bufhe=(s_bufhe*)(ps_chan->pc_io_buf + l_temp); - ps_chan->ps_bufhe->l_dlen = (ps_chan->l_buf_size - sizeof(s_bufhe))/2; - ps_chan->ps_bufhe->i_subtype = ps_chan->l_buf_subtype; - ps_chan->ps_bufhe->i_type = ps_chan->l_buf_type; - ps_chan->ps_bufhe->h_begin = 0; - ps_chan->ps_bufhe->h_end = 0; - ps_chan->ps_bufhe->i_used = 0; - ps_chan->ps_bufhe->l_buf = ps_chan->l_buf_no; - ps_chan->l_buf_no++; - ps_chan->ps_bufhe->l_evt = 0; - ps_chan->ps_bufhe->l_current_i = 0; - ftime(&s_timeb); - ps_chan->ps_bufhe->l_time[0]=(INTS4)s_timeb.time; - ps_chan->ps_bufhe->l_time[1]=(INTS4)s_timeb.millitm; - ps_chan->ps_bufhe->l_free[0] = 1; /* for swap flag */ - ps_chan->ps_bufhe->l_free[1] = 0; - ps_chan->ps_bufhe->l_free[2] = 0; - ps_chan->ps_bufhe->l_free[3] = 0; - } - return(PUTEVT__SUCCESS); + INTS4 l_temp; + struct timeb s_timeb; + + /* because "timeb" is not "typedef", so we must use "struct" */ + + for (l_temp = 0; l_temp < ps_chan->l_io_buf_size; l_temp += ps_chan->l_buf_size) { + ps_chan->ps_bufhe = (s_bufhe*)(ps_chan->pc_io_buf + l_temp); + ps_chan->ps_bufhe->l_dlen = (ps_chan->l_buf_size - sizeof(s_bufhe)) / 2; + ps_chan->ps_bufhe->i_subtype = ps_chan->l_buf_subtype; + ps_chan->ps_bufhe->i_type = ps_chan->l_buf_type; + ps_chan->ps_bufhe->h_begin = 0; + ps_chan->ps_bufhe->h_end = 0; + ps_chan->ps_bufhe->i_used = 0; + ps_chan->ps_bufhe->l_buf = ps_chan->l_buf_no; + ps_chan->l_buf_no++; + ps_chan->ps_bufhe->l_evt = 0; + ps_chan->ps_bufhe->l_current_i = 0; + ftime(&s_timeb); + ps_chan->ps_bufhe->l_time[0] = (INTS4)s_timeb.time; + ps_chan->ps_bufhe->l_time[1] = (INTS4)s_timeb.millitm; + ps_chan->ps_bufhe->l_free[0] = 1; /* for swap flag */ + ps_chan->ps_bufhe->l_free[1] = 0; + ps_chan->ps_bufhe->l_free[2] = 0; + ps_chan->ps_bufhe->l_free[3] = 0; + } + return (PUTEVT__SUCCESS); } /* end of f_evt_ini_bufhe */ /*1+ C Main ****************+******************************************/ @@ -2173,275 +2384,307 @@ INTS4 f_evt_ini_bufhe(s_evt_channel* ps_chan) /*1- C Main ****************+******************************************/ INTS4 f_evt_tag_filter(s_ve10_1* ps_ve10_1) { - /* take it */ - return(1); -//if(ps_ve10_1 != NULL) -//{ -// printf("Filter %9d Type/Subtype %5d %5d Length %5d[w] Trigger %2d\n", -// ps_ve10_1->l_count, -// ps_ve10_1->i_type, -// ps_ve10_1->i_subtype, -// ps_ve10_1->l_dlen, -// ps_ve10_1->i_trigger); -// if(ps_ve10_1->l_count%2) return(1); /* take it */ -// else return(0); /* skip it */ -//} -//else printf("Initialized filter function\n"); -// return(0); + /* take it */ + return (1); + // if(ps_ve10_1 != NULL) + //{ + // printf("Filter %9d Type/Subtype %5d %5d Length %5d[w] Trigger %2d\n", + // ps_ve10_1->l_count, + // ps_ve10_1->i_type, + // ps_ve10_1->i_subtype, + // ps_ve10_1->l_dlen, + // ps_ve10_1->i_trigger); + // if(ps_ve10_1->l_count%2) return(1); /* take it */ + // else return(0); /* skip it */ + //} + // else printf("Initialized filter function\n"); + // return(0); } -INTS4 f_evt_cre_tagfile(CHARS* pc_lmd, CHARS* pc_tag,INTS4 (*e_filter)()) +INTS4 f_evt_cre_tagfile(CHARS* pc_lmd, CHARS* pc_tag, INTS4 (*e_filter)()) { - INTS4 ii,l_take_it,l_temp,l_chan,l_out,l_file_pos=0,l_bufnr=0,l_events=0; - INTS4 l_firste,*pl,l_len,l_last=-1,l_lin=0,l_fragsize;//, la_head[2]; - INTS4 l_swap, l_swap_head, l_is_goosybuf, l_filehead=0, l_size, l_size_head, l_dummy, l_evsize,l_evt_buf_size=0; -// INTS2* pi; - INTU4* ps,*pd; - CHARS /*c_lmd[128], c_tag[128], *pc_temp,*/*pc_evt_buf=NULL; - s_ve10_1* ps_ve10_1; - s_bufhe* ps_bufhe; - s_taghe s_taghe; - memset(&s_taghe, 0, sizeof(s_taghe)); - s_tag s_tag; - int val; - - ps_bufhe = (s_bufhe*)c_temp; - printf("LMD file %s, TAG file %s\n",pc_lmd,pc_tag); - /* get file attributes */ - if((l_chan=open(pc_lmd,GET__OPEN_FLAG))== -1) { return(GETEVT__NOFILE); } - /* read first 512 bytes */ - if(read(l_chan,c_temp,MIN_BUF_LGTH)!=MIN_BUF_LGTH) { - close(l_chan); - return(GETEVT__RDERR); - } - /* check for file header, return size and swap */ - f_evt_check_buf(c_temp, &l_size_head, &l_is_goosybuf, &l_swap_head, &l_filehead); - if(((l_is_goosybuf==0)&(l_filehead==0))|(l_size_head==0)) { - printf("LMD format error: swap=%d, header=%d, isLMD=%d, size=%d\n",l_swap_head,l_filehead,l_is_goosybuf,l_size_head); - close(l_chan); - return(GETEVT__NOLMDFILE); - } - /* read file header and first buffer and check for goosy header */ - if(l_filehead == 1) { - val = lseek(l_chan, 0, SEEK_SET); /* rewind file */ - if(-1 == val) - { - close(l_chan); - return(GETEVT__FAILURE); - } - if(read(l_chan,c_temp,l_size_head)!=l_size_head) { - close(l_chan); - return(GETEVT__RDERR); - } - if(read(l_chan,c_temp,MIN_BUF_LGTH)!=MIN_BUF_LGTH) { - close(l_chan); - return(GETEVT__RDERR); - } - f_evt_check_buf(c_temp, &l_size, &l_is_goosybuf, &l_swap, &l_dummy); - if((l_is_goosybuf==0)|(l_size!=l_size_head)|(l_swap!=l_swap_head)) { - printf("LMD format error: swap=%d, isLMD=%d, size=%d\n",l_swap,l_is_goosybuf,l_size); - close(l_chan); - return(GETEVT__NOLMDFILE); - } - }/* check buffer behind header */ - else { - l_size = 0; - l_swap = 0; - } - - val = lseek(l_chan, 0, SEEK_SET); /* rewind file */ - if(-1 == val) - { - close(l_chan); - return(GETEVT__FAILURE); - } + INTS4 ii, l_take_it, l_temp, l_chan, l_out, l_file_pos = 0, l_bufnr = 0, l_events = 0; + INTS4 l_firste, *pl, l_len, l_last = -1, l_lin = 0, l_fragsize; //, la_head[2]; + INTS4 l_swap, l_swap_head, l_is_goosybuf, l_filehead = 0, l_size, l_size_head, l_dummy, l_evsize, + l_evt_buf_size = 0; + // INTS2* pi; + INTU4 *ps, *pd; + CHARS /*c_lmd[128], c_tag[128], *pc_temp,*/* pc_evt_buf = NULL; + s_ve10_1* ps_ve10_1; + s_bufhe* ps_bufhe; + s_taghe s_taghe; + memset(&s_taghe, 0, sizeof(s_taghe)); + s_tag s_tag; + int val; + + ps_bufhe = (s_bufhe*)c_temp; + printf("LMD file %s, TAG file %s\n", pc_lmd, pc_tag); + /* get file attributes */ + if ((l_chan = open(pc_lmd, GET__OPEN_FLAG)) == -1) { + return (GETEVT__NOFILE); + } + /* read first 512 bytes */ + if (read(l_chan, c_temp, MIN_BUF_LGTH) != MIN_BUF_LGTH) { + close(l_chan); + return (GETEVT__RDERR); + } + /* check for file header, return size and swap */ + f_evt_check_buf(c_temp, &l_size_head, &l_is_goosybuf, &l_swap_head, &l_filehead); + if (((l_is_goosybuf == 0) & (l_filehead == 0)) | (l_size_head == 0)) { + printf("LMD format error: swap=%d, header=%d, isLMD=%d, size=%d\n", + l_swap_head, + l_filehead, + l_is_goosybuf, + l_size_head); + close(l_chan); + return (GETEVT__NOLMDFILE); + } + /* read file header and first buffer and check for goosy header */ + if (l_filehead == 1) { + val = lseek(l_chan, 0, SEEK_SET); /* rewind file */ + if (-1 == val) { + close(l_chan); + return (GETEVT__FAILURE); + } + if (read(l_chan, c_temp, l_size_head) != l_size_head) { + close(l_chan); + return (GETEVT__RDERR); + } + if (read(l_chan, c_temp, MIN_BUF_LGTH) != MIN_BUF_LGTH) { + close(l_chan); + return (GETEVT__RDERR); + } + f_evt_check_buf(c_temp, &l_size, &l_is_goosybuf, &l_swap, &l_dummy); + if ((l_is_goosybuf == 0) | (l_size != l_size_head) | (l_swap != l_swap_head)) { + printf("LMD format error: swap=%d, isLMD=%d, size=%d\n", l_swap, l_is_goosybuf, l_size); + close(l_chan); + return (GETEVT__NOLMDFILE); + } + } /* check buffer behind header */ + else { + l_size = 0; + l_swap = 0; + } + + val = lseek(l_chan, 0, SEEK_SET); /* rewind file */ + if (-1 == val) { + close(l_chan); + return (GETEVT__FAILURE); + } + + printf("Buffer swap %d, File header %d, LMD buffer %d, size %d[b]\n", l_swap, l_filehead, l_is_goosybuf, l_size); - printf("Buffer swap %d, File header %d, LMD buffer %d, size %d[b]\n",l_swap,l_filehead,l_is_goosybuf,l_size); + /* found file header, skip */ + if (l_filehead == 1) { + if (read(l_chan, c_temp, l_size) != l_size) { + close(l_chan); + return (GETEVT__RDERR); + } + l_file_pos += l_size; + l_bufnr++; + } - /* found file header, skip */ - if(l_filehead == 1) { - if(read(l_chan,c_temp,l_size)!=l_size) { - close(l_chan); - return(GETEVT__RDERR); + /* Open and create tag file */ + if ((l_out = open(pc_tag, PUT__CRT_FLAG, DEF_FILE_ACCE)) == -1) { + close(l_chan); + return (GETEVT__NOFILE); + } + ssize_t wcount = write(l_out, (CHARS*)&s_taghe, sizeof(s_taghe)); + if (wcount != sizeof(s_taghe)) { + close(l_chan); + close(l_out); + return (GETEVT__TAGWRERR); } - l_file_pos += l_size; - l_bufnr++; - } - /* Open and create tag file */ - if((l_out=open(pc_tag,PUT__CRT_FLAG,DEF_FILE_ACCE))== -1) - { - close(l_chan); - return(GETEVT__NOFILE); - } - ssize_t wcount = write(l_out,(CHARS*)&s_taghe,sizeof(s_taghe)); - if(wcount != sizeof(s_taghe)) - { - close(l_chan); - close(l_out); - return(GETEVT__TAGWRERR); - } - - /* Initialize filter function */ - //if(e_filter != NULL) { ii=(*e_filter)(NULL); } - - while(read(l_chan,c_temp,l_size)==l_size) { - l_file_pos=l_bufnr*l_size; - if(l_swap) { f_evt_swap(c_temp,l_size); } - if((ps_bufhe->h_end)&(ps_bufhe->h_begin)&(ps_bufhe->l_evt==1)) { - /* only fragment, next buffer */ - /* printf("Event fragment skipped Buffer %6d\n",l_bufnr);*/ - l_bufnr++; - continue; - } - ps_ve10_1=(s_ve10_1*)(ps_bufhe + 1); - pl = (INTS4*)ps_ve10_1; - l_file_pos += sizeof(s_bufhe); - /* skip fragment at begin */ - if(ps_bufhe->h_end) { - l_len = (*pl>>1)+2; - l_file_pos += (l_len<<2); /* bytes */ - ps_ve10_1=(s_ve10_1*)(pl+l_len); - pl = (INTS4*)ps_ve10_1; - ps_bufhe->l_evt--; - /* printf("Event fragment end skipped Buffer %6d\n",l_bufnr);*/ - } - for(ii=1; iil_evt; ii++) { /* except last element */ - /*printf("Event %10d pos %10d Buffer %6d\n",ps_ve10_1->l_count, l_file_pos,l_bufnr);*/ - if(e_filter != NULL) { l_take_it=(*e_filter)(ps_ve10_1); } - else { l_take_it=1; } - l_len = (*pl>>1)+2; - s_tag.l_event=ps_ve10_1->l_count; - s_tag.l_offset=l_file_pos; - if(l_take_it) { - l_events++; - if(ps_ve10_1->l_count != (l_last+1)) { - l_lin++; - if(l_lin == 1) { l_firste=ps_ve10_1->l_count; } - /* printf("New event number offset %d, index %d\n",ps_ve10_1->l_count,l_events);*/ - } - l_last=ps_ve10_1->l_count; - if(write(l_out,(CHARS*)&s_tag,sizeof(s_tag)) != sizeof(s_tag)) { - close(l_chan); - close(l_out); - return(GETEVT__TAGWRERR); + /* Initialize filter function */ + // if(e_filter != NULL) { ii=(*e_filter)(NULL); } + + while (read(l_chan, c_temp, l_size) == l_size) { + l_file_pos = l_bufnr * l_size; + if (l_swap) { + f_evt_swap(c_temp, l_size); } - } - l_file_pos += (l_len<<2); /* bytes */ - ps_ve10_1=(s_ve10_1*)(pl+l_len); - pl = (INTS4*)ps_ve10_1; - } - - if(ps_bufhe->l_evt > 0) { - if(ps_ve10_1->l_dlen < 4) printf("Buffer %d Event fragment %10d dlen %d ts %d %d trigger %d\n" - ,l_bufnr,ps_ve10_1->l_count,ps_ve10_1->l_dlen,ps_ve10_1->i_type, - ps_ve10_1->i_subtype,ps_ve10_1->i_trigger); - s_tag.l_event=ps_ve10_1->l_count; - if(ps_bufhe->h_begin) { - /* copy event to event buffer for filter function */ - if(e_filter != NULL) { - /* is event buffer big enough? */ - l_evsize=ps_bufhe->l_free[1]+4; /* total words */ - if(l_evt_buf_size < l_evsize*2) { - if(pc_evt_buf != NULL) { free(pc_evt_buf); } - l_evt_buf_size=l_evsize*2; - pc_evt_buf=(CHARS*)malloc(l_evt_buf_size); - } - if(NULL == pc_evt_buf) - { - l_evt_buf_size=l_evsize*2; - pc_evt_buf=(CHARS*)malloc(l_evt_buf_size); - } - /* copy event fragment to buffer */ - ps=(INTU4*)ps_ve10_1; - pd=(INTU4*)pc_evt_buf; - l_fragsize = ps_ve10_1->l_dlen+4; /* fragment size + header [w] */ - for(ii=0; iih_end) & (ps_bufhe->h_begin) & (ps_bufhe->l_evt == 1)) { + /* only fragment, next buffer */ + /* printf("Event fragment skipped Buffer %6d\n",l_bufnr);*/ l_bufnr++; - if(l_swap) { f_evt_swap(c_temp,l_size); } - ps = (INTU4*) (ps_bufhe+1); /* behind buffer header, fragment header */ - l_temp=(INTS4)*ps; /* fragment size [w] */ - ps += 2; /* to data behind fragment header */ - for(ii=0; iil_dlen=l_evsize-4; - /* rewind last buffer, will be read again by while loop */ - l_bufnr--; - val = lseek(l_chan, -l_size, SEEK_CUR); - if(-1 == val) - { - free(pc_evt_buf); - ps_ve10_1 = NULL; - pd = NULL; - close(l_chan); - close(l_out); - return(GETEVT__FAILURE); - } - } - s_tag.l_offset=-l_file_pos; - /* printf("Event %10d pos %10d Buffer -%6d\n",ps_ve10_1->l_count, l_file_pos,l_bufnr);*/ - } else { - s_tag.l_offset=l_file_pos; - /* printf("Event %10d pos %10d Buffer %6d\n",ps_ve10_1->l_count, l_file_pos,l_bufnr);*/ - } - if(e_filter != NULL) { l_take_it=(*e_filter)(ps_ve10_1); } - else { l_take_it=1; } - if(l_take_it) { - l_events++; - if(ps_ve10_1->l_count != (l_last+1)) { - l_lin++; - if(l_lin == 1) { l_firste=ps_ve10_1->l_count; } - /* printf("New event number offset %d, index %d\n",ps_ve10_1->l_count,l_events);*/ - } - l_last=ps_ve10_1->l_count; - if(write(l_out,(CHARS*)&s_tag,sizeof(s_tag)) != sizeof(s_tag)) { - close(l_chan); - close(l_out); - return(GETEVT__TAGWRERR); + continue; } - } + ps_ve10_1 = (s_ve10_1*)(ps_bufhe + 1); + pl = (INTS4*)ps_ve10_1; + l_file_pos += sizeof(s_bufhe); + /* skip fragment at begin */ + if (ps_bufhe->h_end) { + l_len = (*pl >> 1) + 2; + l_file_pos += (l_len << 2); /* bytes */ + ps_ve10_1 = (s_ve10_1*)(pl + l_len); + pl = (INTS4*)ps_ve10_1; + ps_bufhe->l_evt--; + /* printf("Event fragment end skipped Buffer %6d\n",l_bufnr);*/ + } + for (ii = 1; ii < ps_bufhe->l_evt; ii++) { /* except last element */ + /*printf("Event %10d pos %10d Buffer %6d\n",ps_ve10_1->l_count, l_file_pos,l_bufnr);*/ + if (e_filter != NULL) { + l_take_it = (*e_filter)(ps_ve10_1); + } else { + l_take_it = 1; + } + l_len = (*pl >> 1) + 2; + s_tag.l_event = ps_ve10_1->l_count; + s_tag.l_offset = l_file_pos; + if (l_take_it) { + l_events++; + if (ps_ve10_1->l_count != (l_last + 1)) { + l_lin++; + if (l_lin == 1) { + l_firste = ps_ve10_1->l_count; + } + /* printf("New event number offset %d, index %d\n",ps_ve10_1->l_count,l_events);*/ + } + l_last = ps_ve10_1->l_count; + if (write(l_out, (CHARS*)&s_tag, sizeof(s_tag)) != sizeof(s_tag)) { + close(l_chan); + close(l_out); + return (GETEVT__TAGWRERR); + } + } + l_file_pos += (l_len << 2); /* bytes */ + ps_ve10_1 = (s_ve10_1*)(pl + l_len); + pl = (INTS4*)ps_ve10_1; + } + + if (ps_bufhe->l_evt > 0) { + if (ps_ve10_1->l_dlen < 4) + printf("Buffer %d Event fragment %10d dlen %d ts %d %d trigger %d\n", + l_bufnr, + ps_ve10_1->l_count, + ps_ve10_1->l_dlen, + ps_ve10_1->i_type, + ps_ve10_1->i_subtype, + ps_ve10_1->i_trigger); + s_tag.l_event = ps_ve10_1->l_count; + if (ps_bufhe->h_begin) { + /* copy event to event buffer for filter function */ + if (e_filter != NULL) { + /* is event buffer big enough? */ + l_evsize = ps_bufhe->l_free[1] + 4; /* total words */ + if (l_evt_buf_size < l_evsize * 2) { + if (pc_evt_buf != NULL) { + free(pc_evt_buf); + } + l_evt_buf_size = l_evsize * 2; + pc_evt_buf = (CHARS*)malloc(l_evt_buf_size); + } + if (NULL == pc_evt_buf) { + l_evt_buf_size = l_evsize * 2; + pc_evt_buf = (CHARS*)malloc(l_evt_buf_size); + } + /* copy event fragment to buffer */ + ps = (INTU4*)ps_ve10_1; + pd = (INTU4*)pc_evt_buf; + l_fragsize = ps_ve10_1->l_dlen + 4; /* fragment size + header [w] */ + for (ii = 0; ii < l_fragsize / 2; ii++) { + *pd++ = *ps++; + } + /* loop over fragments */ + while (l_fragsize < l_evsize) { + if (read(l_chan, c_temp, l_size) != l_size) { + break; + } + l_bufnr++; + if (l_swap) { + f_evt_swap(c_temp, l_size); + } + ps = (INTU4*)(ps_bufhe + 1); /* behind buffer header, fragment header */ + l_temp = (INTS4)*ps; /* fragment size [w] */ + ps += 2; /* to data behind fragment header */ + for (ii = 0; ii < l_temp / 2; ii++) { + *pd++ = *ps++; + } + l_fragsize += l_temp; + } + if (l_fragsize < l_evsize) { + break; + } + ps_ve10_1 = (s_ve10_1*)pc_evt_buf; + ps_ve10_1->l_dlen = l_evsize - 4; + /* rewind last buffer, will be read again by while loop */ + l_bufnr--; + val = lseek(l_chan, -l_size, SEEK_CUR); + if (-1 == val) { + free(pc_evt_buf); + ps_ve10_1 = NULL; + pd = NULL; + close(l_chan); + close(l_out); + return (GETEVT__FAILURE); + } + } + s_tag.l_offset = -l_file_pos; + /* printf("Event %10d pos %10d Buffer -%6d\n",ps_ve10_1->l_count, l_file_pos,l_bufnr);*/ + } else { + s_tag.l_offset = l_file_pos; + /* printf("Event %10d pos %10d Buffer %6d\n",ps_ve10_1->l_count, l_file_pos,l_bufnr);*/ + } + if (e_filter != NULL) { + l_take_it = (*e_filter)(ps_ve10_1); + } else { + l_take_it = 1; + } + if (l_take_it) { + l_events++; + if (ps_ve10_1->l_count != (l_last + 1)) { + l_lin++; + if (l_lin == 1) { + l_firste = ps_ve10_1->l_count; + } + /* printf("New event number offset %d, index %d\n",ps_ve10_1->l_count,l_events);*/ + } + l_last = ps_ve10_1->l_count; + if (write(l_out, (CHARS*)&s_tag, sizeof(s_tag)) != sizeof(s_tag)) { + close(l_chan); + close(l_out); + return (GETEVT__TAGWRERR); + } + } + } + l_bufnr++; + /* if(l_bufnr > 3) break; */ + } + val = lseek(l_out, 0, SEEK_SET); /* rewind file */ + if (-1 == val) { + close(l_chan); + close(l_out); + return (GETEVT__FAILURE); + } + s_taghe.l_endian = 1; + s_taghe.l_version = 1; + s_taghe.l_bufsize = l_size; + s_taghe.l_buffers = l_bufnr; + s_taghe.l_events = l_events; + s_taghe.l_filesize = sizeof(s_tag) * l_events; + s_taghe.l_linear = (l_lin == 1); + s_taghe.l_first = l_firste; + s_taghe.l_last = s_tag.l_event; + if (write(l_out, (CHARS*)&s_taghe, sizeof(s_taghe)) != sizeof(s_taghe)) { + close(l_chan); + close(l_out); + return (GETEVT__TAGWRERR); } - l_bufnr++; - /* if(l_bufnr > 3) break; */ - } - val = lseek(l_out, 0, SEEK_SET); /* rewind file */ - if(-1 == val) - { close(l_chan); close(l_out); - return(GETEVT__FAILURE); - } - s_taghe.l_endian = 1; - s_taghe.l_version = 1; - s_taghe.l_bufsize = l_size; - s_taghe.l_buffers = l_bufnr; - s_taghe.l_events = l_events; - s_taghe.l_filesize = sizeof(s_tag)*l_events; - s_taghe.l_linear = (l_lin == 1); - s_taghe.l_first = l_firste; - s_taghe.l_last = s_tag.l_event; - if(write(l_out,(CHARS*)&s_taghe,sizeof(s_taghe)) != sizeof(s_taghe)) { - close(l_chan); - close(l_out); - return(GETEVT__TAGWRERR); - } - close(l_chan); - close(l_out); - printf("Buffers %6d, of size %d, Events %10d, first %d, last %d " - ,s_taghe.l_buffers - ,s_taghe.l_bufsize - ,s_taghe.l_events - ,s_taghe.l_first - ,s_taghe.l_last); - if(s_taghe.l_linear) { printf("linear\n"); } - else { printf("not linear\n"); } - - return(GETEVT__SUCCESS); + printf("Buffers %6d, of size %d, Events %10d, first %d, last %d ", + s_taghe.l_buffers, + s_taghe.l_bufsize, + s_taghe.l_events, + s_taghe.l_first, + s_taghe.l_last); + if (s_taghe.l_linear) { + printf("linear\n"); + } else { + printf("not linear\n"); + } + + return (GETEVT__SUCCESS); } /* end of f_evt_cre_tagfile */ /*1+ C Main ****************+******************************************/ /*+ Module : f_evt_get_tagopen */ @@ -2471,107 +2714,136 @@ INTS4 f_evt_cre_tagfile(CHARS* pc_lmd, CHARS* pc_tag,INTS4 (*e_filter)()) /* a standard f_evt_get_open is called. In this case */ /* following tag functions call standard f_evt_get functions. */ /*1- C Main ****************+******************************************/ -INTS4 f_evt_get_tagopen(s_evt_channel* ps_chan,CHARS* pc_tag,CHARS* pc_lmd, CHARS** ps_head, INTS4 l_prihe) +INTS4 f_evt_get_tagopen(s_evt_channel* ps_chan, CHARS* pc_tag, CHARS* pc_lmd, CHARS** ps_head, INTS4 l_prihe) { - INTS4 /*l_temp,*/ii; - s_bufhe* ps_bufhe; - - ps_chan->ps_tag = NULL; /* tagfile buffer */ - ps_chan->ps_taghe = NULL; - if(l_prihe) { printf("LMD file %s, TAG file %s\n",pc_lmd,pc_tag); } - - /* if tag file name not specified, do not try to open it SL:11.11.09*/ - if ((pc_tag==0) || (*pc_tag==0)) { - ps_chan->l_tagfile_no = -1; - } else { - ps_chan->l_tagfile_no = open(pc_tag, GET__OPEN_FLAG); - } - - /* open tag file and read header */ - if(ps_chan->l_tagfile_no == -1) { - /* no tag file, use normal open */ - /*=============================================*/ - ii=f_evt_get_open(GETEVT__FILE, pc_lmd, ps_chan, (CHARS**) &ps_bufhe,0,0); - *ps_head = (CHARS*) ps_bufhe; - if(ii!=GETEVT__SUCCESS) { - printf("Error opening input file %s\n",pc_lmd); - return (ii); - } - /* printf("No tag file for %s\n",pc_lmd); */ - if(l_prihe) { ii = f_evt_type(ps_bufhe,NULL,0,0,0,0); } - return(GETEVT__SUCCESS); - } - /*=============================================*/ - /* tag file found */ - ps_chan->ps_taghe = (s_taghe*)malloc(sizeof(s_taghe)); - if(read(ps_chan->l_tagfile_no,(CHARS*)ps_chan->ps_taghe,sizeof(s_taghe))!=sizeof(s_taghe)) { - free(ps_chan->ps_taghe); - ps_chan->ps_taghe = NULL; - close(ps_chan->l_tagfile_no); - return(GETEVT__TAGRDERR); - } - if(NULL == ps_chan->ps_taghe) - { - close(ps_chan->l_tagfile_no); - return(GETEVT__TAGRDERR); - } - if(ps_chan->ps_taghe->l_endian != 1) { ps_chan->l_tagswap=1; } - if(ps_chan->l_tagswap) { f_evt_swap((CHARS*)ps_chan->ps_taghe,sizeof(s_taghe)); } - if(l_prihe) { - printf("Buffers %6d, of size %d, Events %10d, first %d, last %d" - ,ps_chan->ps_taghe->l_buffers - ,ps_chan->ps_taghe->l_bufsize - ,ps_chan->ps_taghe->l_events - ,ps_chan->ps_taghe->l_first - ,ps_chan->ps_taghe->l_last); - if(ps_chan->ps_taghe->l_linear) { printf(" linear\n"); } - else { printf(" not linear\n"); } - } - if((ps_chan->l_channel_no=open(pc_lmd,GET__OPEN_FLAG))== -1) { - if(ps_chan->ps_taghe != NULL) { free(ps_chan->ps_taghe); } + INTS4 /*l_temp,*/ ii; + s_bufhe* ps_bufhe; + + ps_chan->ps_tag = NULL; /* tagfile buffer */ ps_chan->ps_taghe = NULL; - close(ps_chan->l_tagfile_no); - return(GETEVT__NOFILE); - } - /* read buffer header to check if we have to swap */ - ps_bufhe = (s_bufhe*)c_temp; - if (ps_chan->ps_taghe->l_bufsize >=0 && ps_chan->ps_taghe->l_bufsize < sizeof(c_temp)) { - if(read(ps_chan->l_channel_no,c_temp,ps_chan->ps_taghe->l_bufsize)!=ps_chan->ps_taghe->l_bufsize) { - if(ps_chan->ps_taghe != NULL) { free(ps_chan->ps_taghe); } - ps_chan->ps_taghe = NULL; - if(ps_chan->ps_tag != NULL) { free(ps_chan->ps_tag); } - ps_chan->ps_tag = NULL; - close(ps_chan->l_tagfile_no); - close(ps_chan->l_channel_no); - return(GETEVT__RDERR); - } - } - if(ps_chan->ps_taghe != NULL) { - if(ps_chan->ps_taghe->l_linear == 0) { - if (ps_chan->ps_taghe->l_filesize >=0 && ps_chan->ps_taghe->l_filesize < sizeof(s_tag)) { - ps_chan->ps_tag = (s_tag*)malloc(ps_chan->ps_taghe->l_filesize); - if(read(ps_chan->l_tagfile_no,(CHARS*)ps_chan->ps_tag,ps_chan->ps_taghe->l_filesize)!=ps_chan->ps_taghe->l_filesize) { - if(ps_chan->ps_taghe != NULL) { free(ps_chan->ps_taghe); } - ps_chan->ps_taghe = NULL; - if(ps_chan->ps_tag != NULL) { free(ps_chan->ps_tag); } - ps_chan->ps_tag = NULL; - close(ps_chan->l_tagfile_no); - close(ps_chan->l_channel_no); - return(GETEVT__TAGRDERR); + if (l_prihe) { + printf("LMD file %s, TAG file %s\n", pc_lmd, pc_tag); + } + + /* if tag file name not specified, do not try to open it SL:11.11.09*/ + if ((pc_tag == 0) || (*pc_tag == 0)) { + ps_chan->l_tagfile_no = -1; + } else { + ps_chan->l_tagfile_no = open(pc_tag, GET__OPEN_FLAG); + } + + /* open tag file and read header */ + if (ps_chan->l_tagfile_no == -1) { + /* no tag file, use normal open */ + /*=============================================*/ + ii = f_evt_get_open(GETEVT__FILE, pc_lmd, ps_chan, (CHARS**)&ps_bufhe, 0, 0); + *ps_head = (CHARS*)ps_bufhe; + if (ii != GETEVT__SUCCESS) { + printf("Error opening input file %s\n", pc_lmd); + return (ii); } - } + /* printf("No tag file for %s\n",pc_lmd); */ + if (l_prihe) { + ii = f_evt_type(ps_bufhe, NULL, 0, 0, 0, 0); + } + return (GETEVT__SUCCESS); + } + /*=============================================*/ + /* tag file found */ + ps_chan->ps_taghe = (s_taghe*)malloc(sizeof(s_taghe)); + if (read(ps_chan->l_tagfile_no, (CHARS*)ps_chan->ps_taghe, sizeof(s_taghe)) != sizeof(s_taghe)) { + free(ps_chan->ps_taghe); + ps_chan->ps_taghe = NULL; + close(ps_chan->l_tagfile_no); + return (GETEVT__TAGRDERR); + } + if (NULL == ps_chan->ps_taghe) { + close(ps_chan->l_tagfile_no); + return (GETEVT__TAGRDERR); + } + if (ps_chan->ps_taghe->l_endian != 1) { + ps_chan->l_tagswap = 1; + } + if (ps_chan->l_tagswap) { + f_evt_swap((CHARS*)ps_chan->ps_taghe, sizeof(s_taghe)); + } + if (l_prihe) { + printf("Buffers %6d, of size %d, Events %10d, first %d, last %d", + ps_chan->ps_taghe->l_buffers, + ps_chan->ps_taghe->l_bufsize, + ps_chan->ps_taghe->l_events, + ps_chan->ps_taghe->l_first, + ps_chan->ps_taghe->l_last); + if (ps_chan->ps_taghe->l_linear) { + printf(" linear\n"); + } else { + printf(" not linear\n"); + } + } + if ((ps_chan->l_channel_no = open(pc_lmd, GET__OPEN_FLAG)) == -1) { + if (ps_chan->ps_taghe != NULL) { + free(ps_chan->ps_taghe); + } + ps_chan->ps_taghe = NULL; + close(ps_chan->l_tagfile_no); + return (GETEVT__NOFILE); + } + /* read buffer header to check if we have to swap */ + ps_bufhe = (s_bufhe*)c_temp; + if (ps_chan->ps_taghe->l_bufsize >= 0 && ps_chan->ps_taghe->l_bufsize < sizeof(c_temp)) { + if (read(ps_chan->l_channel_no, c_temp, ps_chan->ps_taghe->l_bufsize) != ps_chan->ps_taghe->l_bufsize) { + if (ps_chan->ps_taghe != NULL) { + free(ps_chan->ps_taghe); + } + ps_chan->ps_taghe = NULL; + if (ps_chan->ps_tag != NULL) { + free(ps_chan->ps_tag); + } + ps_chan->ps_tag = NULL; + close(ps_chan->l_tagfile_no); + close(ps_chan->l_channel_no); + return (GETEVT__RDERR); + } + } + if (ps_chan->ps_taghe != NULL) { + if (ps_chan->ps_taghe->l_linear == 0) { + if (ps_chan->ps_taghe->l_filesize >= 0 && ps_chan->ps_taghe->l_filesize < sizeof(s_tag)) { + ps_chan->ps_tag = (s_tag*)malloc(ps_chan->ps_taghe->l_filesize); + if (read(ps_chan->l_tagfile_no, (CHARS*)ps_chan->ps_tag, ps_chan->ps_taghe->l_filesize) + != ps_chan->ps_taghe->l_filesize) { + if (ps_chan->ps_taghe != NULL) { + free(ps_chan->ps_taghe); + } + ps_chan->ps_taghe = NULL; + if (ps_chan->ps_tag != NULL) { + free(ps_chan->ps_tag); + } + ps_chan->ps_tag = NULL; + close(ps_chan->l_tagfile_no); + close(ps_chan->l_channel_no); + return (GETEVT__TAGRDERR); + } + } + } + } + if (ps_bufhe->l_free[0] != 1) { + ps_chan->l_lmdswap = 1; + } + if (ps_chan->l_lmdswap) { + f_evt_swap_filhe(ps_bufhe); + } + if (l_prihe) { + ii = f_evt_type(ps_bufhe, NULL, 0, 0, 0, 0); } - } - if(ps_bufhe->l_free[0] != 1) { ps_chan->l_lmdswap=1; } - if(ps_chan->l_lmdswap) { f_evt_swap_filhe(ps_bufhe); } - if(l_prihe) { ii = f_evt_type(ps_bufhe,NULL,0,0,0,0); } - if(ps_head != NULL) { - if(ps_bufhe->i_type == 2000) { *ps_head = (CHARS*)ps_bufhe; } - } - ps_chan->l_evt_buf_size=0; - ps_chan->pc_evt_buf=NULL; - ps_chan->l_io_buf_posi=0; /* keeps index of last event */ - return(GETEVT__SUCCESS); + if (ps_head != NULL) { + if (ps_bufhe->i_type == 2000) { + *ps_head = (CHARS*)ps_bufhe; + } + } + ps_chan->l_evt_buf_size = 0; + ps_chan->pc_evt_buf = NULL; + ps_chan->l_io_buf_posi = 0; /* keeps index of last event */ + return (GETEVT__SUCCESS); } /*1+ C Main ****************+******************************************/ @@ -2598,24 +2870,28 @@ INTS4 f_evt_get_tagopen(s_evt_channel* ps_chan,CHARS* pc_tag,CHARS* pc_lmd, CHAR /*+ FUNCTION : Get next event at current position, either in tag */ /* file, or in lmd file. Optional events are skipped. */ /*1- C Main ****************+******************************************/ -INTS4 f_evt_get_tagnext(s_evt_channel* ps_chan,INTS4 l_skip, INTS4** pl_event) +INTS4 f_evt_get_tagnext(s_evt_channel* ps_chan, INTS4 l_skip, INTS4** pl_event) { - INTS4 ii = 0,*pl=NULL,kk; - /* no tagfile */ - /*=============================================*/ - if(ps_chan->ps_taghe == NULL) { - for(kk=0; kk<=l_skip; kk++) { - ii=f_evt_get_event(ps_chan, (INTS4**) &pl, NULL); - if(ii != GETEVT__SUCCESS) { break; } - } - } - /*=============================================*/ - else { - /* l_io_buf_posi is the index of last event */ - ii=f_evt_get_tagevent(ps_chan,ps_chan->l_io_buf_posi+l_skip+1,1,(INTS4**)&pl); - } - if(pl_event != NULL) { *pl_event=pl; } - return(ii); + INTS4 ii = 0, *pl = NULL, kk; + /* no tagfile */ + /*=============================================*/ + if (ps_chan->ps_taghe == NULL) { + for (kk = 0; kk <= l_skip; kk++) { + ii = f_evt_get_event(ps_chan, (INTS4**)&pl, NULL); + if (ii != GETEVT__SUCCESS) { + break; + } + } + } + /*=============================================*/ + else { + /* l_io_buf_posi is the index of last event */ + ii = f_evt_get_tagevent(ps_chan, ps_chan->l_io_buf_posi + l_skip + 1, 1, (INTS4**)&pl); + } + if (pl_event != NULL) { + *pl_event = pl; + } + return (ii); } /*1+ C Main ****************+******************************************/ /*+ Module : f_evt_get_tagevent */ @@ -2644,153 +2920,195 @@ INTS4 f_evt_get_tagnext(s_evt_channel* ps_chan,INTS4 l_skip, INTS4** pl_event) /*+ FUNCTION : Get tag event. If no tag file is there, skip */ /* events, or look for event number */ /*1- C Main ****************+******************************************/ -INTS4 f_evt_get_tagevent(s_evt_channel* ps_chan,INTS4 l_value, INTS4 l_type, INTS4** pl_event) +INTS4 f_evt_get_tagevent(s_evt_channel* ps_chan, INTS4 l_value, INTS4 l_type, INTS4** pl_event) { - INTS4 /*l_temp,l_chan,l_tag,*/ii,kk,/*lb,l_tagbufs,l_tagrest,*/l_evt,l_off,l_typ,l_val,l_evsize,l_fragsize; - INTS4 la_head[2],*pl; - CHARS* pc; - s_ve10_1* ps_ve10_1; - s_bufhe* ps_bufhe; - s_tag* ps_tag; - s_tag s_tag_l; -// s_filhe* ps_filhe; -// s_evt_channel s_chan_i; - - l_typ=l_type; - l_val=l_value; - /* no tagfile */ - /*=============================================*/ - if(ps_chan->ps_taghe == NULL) { - /* search by index */ - if(l_type == 1) { - if(l_val == 0) { l_val=1; } - for(kk=0; kkl_count != l_val) { - ii=f_evt_get_event(ps_chan, (INTS4**) &ps_ve10_1, NULL); - if(ii != GETEVT__SUCCESS) { return(ii); } - } - *pl_event = (INTS4*)ps_ve10_1; - } - return(GETEVT__SUCCESS); - } - /*=============================================*/ - ps_ve10_1 = (s_ve10_1*)c_temp; - ps_bufhe = (s_bufhe*)c_temp; - - /* linear==1 means that event numbers are subsequent. */ - /* in that case we can calculate index from number */ - if(ps_chan->ps_taghe->l_linear) { - if(l_typ == 0) { l_val=l_value-ps_chan->ps_taghe->l_first+1; } - l_typ=1; - } - /* search by index or by value */ - if(l_typ == 1) { - if(l_val > ps_chan->ps_taghe->l_events) { - printf("Event index %d not found\n",l_val); - return(GETEVT__NOTAG); - } - if(l_val == 0) { l_val=1; } - ps_tag=(s_tag*)&s_tag_l; - int val = lseek(ps_chan->l_tagfile_no, (l_val-1)*sizeof(s_tag)+sizeof(s_taghe), SEEK_SET); /* set file offset*/ - if(-1 == val) - { - return(GETEVT__TAGRDERR); - } - if(read(ps_chan->l_tagfile_no,(CHARS*)ps_tag,sizeof(s_tag))!=sizeof(s_tag)) { - return(GETEVT__TAGRDERR); - } - if(ps_chan->l_tagswap) { f_evt_swap((CHARS*)ps_tag,sizeof(s_tag)); } - ps_chan->l_io_buf_posi=l_val; /* keeps index */ - } else { - ps_tag=ps_chan->ps_tag; - for(ii=1; ii<=ps_chan->ps_taghe->l_events; ii++) { - if(ps_tag->l_event == l_val) { break; } - ps_tag++; - } - if(ps_tag->l_event != l_val) { - printf("Event number %d not found\n",l_val); - return(GETEVT__NOTAG); - } - ps_chan->l_io_buf_posi=ii; /* keeps index of last event */ - } - /* now we have the requested event in ps_tag */ - l_off=ps_tag->l_offset; - if(l_off < 0) { l_off=((-l_off)/ps_chan->ps_taghe->l_bufsize)*ps_chan->ps_taghe->l_bufsize; } - l_evt=ps_tag->l_event; - /* full event in buffer, read */ - int val; - if(ps_tag->l_offset > 0) { + INTS4 /*l_temp,l_chan,l_tag,*/ ii, kk, /*lb,l_tagbufs,l_tagrest,*/ l_evt, l_off, l_typ, l_val, l_evsize, l_fragsize; + INTS4 la_head[2], *pl; + CHARS* pc; + s_ve10_1* ps_ve10_1; + s_bufhe* ps_bufhe; + s_tag* ps_tag; + s_tag s_tag_l; + // s_filhe* ps_filhe; + // s_evt_channel s_chan_i; + + l_typ = l_type; + l_val = l_value; + /* no tagfile */ + /*=============================================*/ + if (ps_chan->ps_taghe == NULL) { + /* search by index */ + if (l_type == 1) { + if (l_val == 0) { + l_val = 1; + } + for (kk = 0; kk < l_val; kk++) { + ii = f_evt_get_event(ps_chan, (INTS4**)&pl, NULL); + if (ii != GETEVT__SUCCESS) { + return (ii); + } + } + *pl_event = pl; + } else { /* search by event number */ + ii = f_evt_get_event(ps_chan, (INTS4**)&ps_ve10_1, NULL); + if (ii != GETEVT__SUCCESS) { + return (ii); + } + while (ps_ve10_1->l_count != l_val) { + ii = f_evt_get_event(ps_chan, (INTS4**)&ps_ve10_1, NULL); + if (ii != GETEVT__SUCCESS) { + return (ii); + } + } + *pl_event = (INTS4*)ps_ve10_1; + } + return (GETEVT__SUCCESS); + } + /*=============================================*/ ps_ve10_1 = (s_ve10_1*)c_temp; - val = lseek(ps_chan->l_channel_no, l_off, SEEK_SET); /* set file offset*/ - if(-1 == val) - { - return(GETEVT__TAGRDERR); - } - if(read(ps_chan->l_channel_no,c_temp,8)!=8) { return(GETEVT__RDERR); } - if(ps_chan->l_lmdswap) { f_evt_swap(c_temp,8); } - if(read(ps_chan->l_channel_no,(CHARS*)&c_temp[8],ps_ve10_1->l_dlen*2)!=ps_ve10_1->l_dlen*2) { return(GETEVT__RDERR); } - if(ps_chan->l_lmdswap) { f_evt_swap((CHARS*)&c_temp[8],ps_ve10_1->l_dlen*2); } - /*ii=f_evt_type(NULL,(s_evhe *)ps_ve10_1,-1,0,1,1);*/ - } else + ps_bufhe = (s_bufhe*)c_temp; + + /* linear==1 means that event numbers are subsequent. */ + /* in that case we can calculate index from number */ + if (ps_chan->ps_taghe->l_linear) { + if (l_typ == 0) { + l_val = l_value - ps_chan->ps_taghe->l_first + 1; + } + l_typ = 1; + } + /* search by index or by value */ + if (l_typ == 1) { + if (l_val > ps_chan->ps_taghe->l_events) { + printf("Event index %d not found\n", l_val); + return (GETEVT__NOTAG); + } + if (l_val == 0) { + l_val = 1; + } + ps_tag = (s_tag*)&s_tag_l; + int val = + lseek(ps_chan->l_tagfile_no, (l_val - 1) * sizeof(s_tag) + sizeof(s_taghe), SEEK_SET); /* set file offset*/ + if (-1 == val) { + return (GETEVT__TAGRDERR); + } + if (read(ps_chan->l_tagfile_no, (CHARS*)ps_tag, sizeof(s_tag)) != sizeof(s_tag)) { + return (GETEVT__TAGRDERR); + } + if (ps_chan->l_tagswap) { + f_evt_swap((CHARS*)ps_tag, sizeof(s_tag)); + } + ps_chan->l_io_buf_posi = l_val; /* keeps index */ + } else { + ps_tag = ps_chan->ps_tag; + for (ii = 1; ii <= ps_chan->ps_taghe->l_events; ii++) { + if (ps_tag->l_event == l_val) { + break; + } + ps_tag++; + } + if (ps_tag->l_event != l_val) { + printf("Event number %d not found\n", l_val); + return (GETEVT__NOTAG); + } + ps_chan->l_io_buf_posi = ii; /* keeps index of last event */ + } + /* now we have the requested event in ps_tag */ + l_off = ps_tag->l_offset; + if (l_off < 0) { + l_off = ((-l_off) / ps_chan->ps_taghe->l_bufsize) * ps_chan->ps_taghe->l_bufsize; + } + l_evt = ps_tag->l_event; + /* full event in buffer, read */ + int val; + if (ps_tag->l_offset > 0) { + ps_ve10_1 = (s_ve10_1*)c_temp; + val = lseek(ps_chan->l_channel_no, l_off, SEEK_SET); /* set file offset*/ + if (-1 == val) { + return (GETEVT__TAGRDERR); + } + if (read(ps_chan->l_channel_no, c_temp, 8) != 8) { + return (GETEVT__RDERR); + } + if (ps_chan->l_lmdswap) { + f_evt_swap(c_temp, 8); + } + if (read(ps_chan->l_channel_no, (CHARS*)&c_temp[8], ps_ve10_1->l_dlen * 2) != ps_ve10_1->l_dlen * 2) { + return (GETEVT__RDERR); + } + if (ps_chan->l_lmdswap) { + f_evt_swap((CHARS*)&c_temp[8], ps_ve10_1->l_dlen * 2); + } + /*ii=f_evt_type(NULL,(s_evhe *)ps_ve10_1,-1,0,1,1);*/ + } else /* spanning event begin, read to event buffer */ - { - val = lseek(ps_chan->l_channel_no, l_off, SEEK_SET); /* set file offset to buffer begin */ - if(-1 == val) { - return(GETEVT__TAGRDERR); - } - if(read(ps_chan->l_channel_no,c_temp,sizeof(s_bufhe))!=sizeof(s_bufhe)) { return(GETEVT__RDERR); } - if(ps_chan->l_lmdswap) { f_evt_swap(c_temp,sizeof(s_bufhe)); } - /* is event buffer big enough? */ - l_evsize=ps_bufhe->l_free[1]+4; /* total words */ - if(ps_chan->l_evt_buf_size < l_evsize*2) { - if(ps_chan->pc_evt_buf != NULL) { free(ps_chan->pc_evt_buf); } - ps_chan->l_evt_buf_size=l_evsize*2; - ps_chan->pc_evt_buf=(CHARS*)malloc(ps_chan->l_evt_buf_size); - } - l_fragsize=0; - ps_ve10_1 = (s_ve10_1*)ps_chan->pc_evt_buf; - val = lseek(ps_chan->l_channel_no, -ps_tag->l_offset, SEEK_SET); /* set file offset*/ - if(-1 == val) - { - return(GETEVT__TAGRDERR); - } - if(read(ps_chan->l_channel_no,ps_chan->pc_evt_buf,8)!=8) { return(GETEVT__RDERR); } - if(ps_chan->l_lmdswap) { f_evt_swap(ps_chan->pc_evt_buf,8); } - pc=ps_chan->pc_evt_buf+8; - /* read fragment */ - if(read(ps_chan->l_channel_no,pc,ps_ve10_1->l_dlen*2)!=ps_ve10_1->l_dlen*2) { return(GETEVT__RDERR); } - l_fragsize += ps_ve10_1->l_dlen+4; /* fragment size + header [w] */ - pc += ps_ve10_1->l_dlen*2; /* next in event buffer */ - ps_ve10_1->l_dlen=l_evsize-4; /* set correct event size */ - /* loop over fragments */ - while(l_fragsize < l_evsize) { - l_off += ps_chan->ps_taghe->l_bufsize; /* next buffer absolut address */ - val = lseek(ps_chan->l_channel_no,l_off+sizeof(s_bufhe), SEEK_SET); /* set file offset*/ - if(-1 == val) - { - return(GETEVT__TAGRDERR); - } - if(read(ps_chan->l_channel_no,(CHARS*)&la_head,8)!=8) { return(GETEVT__RDERR); } - if(ps_chan->l_lmdswap) { f_evt_swap((CHARS*)&la_head,8); } - if(read(ps_chan->l_channel_no,pc,la_head[0]*2)!=la_head[0]*2) { return(GETEVT__RDERR); } - pc += la_head[0]*2; - l_fragsize += la_head[0]; - } - /* now swap whole event in buffer */ - pc=ps_chan->pc_evt_buf+8; /* header already swapped */ - ps_ve10_1 = (s_ve10_1*)ps_chan->pc_evt_buf; - if(ps_chan->l_lmdswap) { f_evt_swap(pc,ps_ve10_1->l_dlen*2); } - } - *pl_event = (INTS4*)ps_ve10_1; - return(GETEVT__SUCCESS); + val = lseek(ps_chan->l_channel_no, l_off, SEEK_SET); /* set file offset to buffer begin */ + if (-1 == val) { + return (GETEVT__TAGRDERR); + } + if (read(ps_chan->l_channel_no, c_temp, sizeof(s_bufhe)) != sizeof(s_bufhe)) { + return (GETEVT__RDERR); + } + if (ps_chan->l_lmdswap) { + f_evt_swap(c_temp, sizeof(s_bufhe)); + } + /* is event buffer big enough? */ + l_evsize = ps_bufhe->l_free[1] + 4; /* total words */ + if (ps_chan->l_evt_buf_size < l_evsize * 2) { + if (ps_chan->pc_evt_buf != NULL) { + free(ps_chan->pc_evt_buf); + } + ps_chan->l_evt_buf_size = l_evsize * 2; + ps_chan->pc_evt_buf = (CHARS*)malloc(ps_chan->l_evt_buf_size); + } + l_fragsize = 0; + ps_ve10_1 = (s_ve10_1*)ps_chan->pc_evt_buf; + val = lseek(ps_chan->l_channel_no, -ps_tag->l_offset, SEEK_SET); /* set file offset*/ + if (-1 == val) { + return (GETEVT__TAGRDERR); + } + if (read(ps_chan->l_channel_no, ps_chan->pc_evt_buf, 8) != 8) { + return (GETEVT__RDERR); + } + if (ps_chan->l_lmdswap) { + f_evt_swap(ps_chan->pc_evt_buf, 8); + } + pc = ps_chan->pc_evt_buf + 8; + /* read fragment */ + if (read(ps_chan->l_channel_no, pc, ps_ve10_1->l_dlen * 2) != ps_ve10_1->l_dlen * 2) { + return (GETEVT__RDERR); + } + l_fragsize += ps_ve10_1->l_dlen + 4; /* fragment size + header [w] */ + pc += ps_ve10_1->l_dlen * 2; /* next in event buffer */ + ps_ve10_1->l_dlen = l_evsize - 4; /* set correct event size */ + /* loop over fragments */ + while (l_fragsize < l_evsize) { + l_off += ps_chan->ps_taghe->l_bufsize; /* next buffer absolut address */ + val = lseek(ps_chan->l_channel_no, l_off + sizeof(s_bufhe), SEEK_SET); /* set file offset*/ + if (-1 == val) { + return (GETEVT__TAGRDERR); + } + if (read(ps_chan->l_channel_no, (CHARS*)&la_head, 8) != 8) { + return (GETEVT__RDERR); + } + if (ps_chan->l_lmdswap) { + f_evt_swap((CHARS*)&la_head, 8); + } + if (read(ps_chan->l_channel_no, pc, la_head[0] * 2) != la_head[0] * 2) { + return (GETEVT__RDERR); + } + pc += la_head[0] * 2; + l_fragsize += la_head[0]; + } + /* now swap whole event in buffer */ + pc = ps_chan->pc_evt_buf + 8; /* header already swapped */ + ps_ve10_1 = (s_ve10_1*)ps_chan->pc_evt_buf; + if (ps_chan->l_lmdswap) { + f_evt_swap(pc, ps_ve10_1->l_dlen * 2); + } + } + *pl_event = (INTS4*)ps_ve10_1; + return (GETEVT__SUCCESS); } /* end of f_evt_ini_bufhe */ /*1+ C Main ****************+******************************************/ @@ -2809,24 +3127,28 @@ INTS4 f_evt_get_tagevent(s_evt_channel* ps_chan,INTS4 l_value, INTS4 l_type, INT /*1- C Main ****************+******************************************/ INTS4 f_evt_get_tagclose(s_evt_channel* ps_chan) { - /*=============================================*/ - if(ps_chan->ps_taghe == NULL) { - f_evt_get_close(ps_chan); - return(GETEVT__SUCCESS); - } - /*=============================================*/ - free(ps_chan->ps_taghe); - if(ps_chan->ps_tag != NULL) { free(ps_chan->ps_tag); } - if(ps_chan->pc_evt_buf != NULL) { free(ps_chan->pc_evt_buf); } - close(ps_chan->l_tagfile_no); - close(ps_chan->l_channel_no); - memset((void*)ps_chan, 0, sizeof(s_evt_channel)); /* clear memory */ - return(GETEVT__SUCCESS); + /*=============================================*/ + if (ps_chan->ps_taghe == NULL) { + f_evt_get_close(ps_chan); + return (GETEVT__SUCCESS); + } + /*=============================================*/ + free(ps_chan->ps_taghe); + if (ps_chan->ps_tag != NULL) { + free(ps_chan->ps_tag); + } + if (ps_chan->pc_evt_buf != NULL) { + free(ps_chan->pc_evt_buf); + } + close(ps_chan->l_tagfile_no); + close(ps_chan->l_channel_no); + memset((void*)ps_chan, 0, sizeof(s_evt_channel)); /* clear memory */ + return (GETEVT__SUCCESS); } s_evt_channel* f_evt_control() { - s_evt_channel* x; - x=(s_evt_channel*)malloc(sizeof(s_evt_channel)); - memset(x,0,sizeof(s_evt_channel)); - return(x); + s_evt_channel* x; + x = (s_evt_channel*)malloc(sizeof(s_evt_channel)); + memset(x, 0, sizeof(s_evt_channel)); + return (x); } diff --git a/MbsAPI/f_evt.h b/MbsAPI/f_evt.h index 1a2970653e..5a04f0b4e9 100644 --- a/MbsAPI/f_evt.h +++ b/MbsAPI/f_evt.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /***************** f_evt.h ******************************/ @@ -14,99 +14,101 @@ /* ++++++++++++++++ include UNIX standard headers +++++++++++++++++++++++++ */ #if MBS_ENDIAN == 1 +#include "s_bufhe.h" +#include "s_evhe.h" #include "s_ve10_1.h" #include "s_ves10_1.h" -#include "s_evhe.h" -#include "s_bufhe.h" #else +#include "s_bufhe_swap.h" +#include "s_evhe_swap.h" #include "s_ve10_1_swap.h" #include "s_ves10_1_swap.h" -#include "s_evhe_swap.h" -#include "s_bufhe_swap.h" #endif #define MAX_BUF_LGTH 32768 #define MIN_BUF_LGTH 512 -#define MAX_BUFS_IN_STREAM 100 /* at a maximum, 100 buffers per stream */ -#define MAX_LONG 99999999 /* maximum long data */ +#define MAX_BUFS_IN_STREAM 100 /* at a maximum, 100 buffers per stream */ +#define MAX_LONG 99999999 /* maximum long data */ -typedef struct { - INTS4 l_endian; - INTS4 l_version; - INTS4 l_bufsize; - INTS4 l_buffers; - INTS4 l_events; - INTS4 l_filesize; - INTS4 l_first; - INTS4 l_last; - INTS4 l_linear; +typedef struct +{ + INTS4 l_endian; + INTS4 l_version; + INTS4 l_bufsize; + INTS4 l_buffers; + INTS4 l_events; + INTS4 l_filesize; + INTS4 l_first; + INTS4 l_last; + INTS4 l_linear; } s_taghe; -typedef struct { - INTS4 l_event; - INTS4 l_offset; +typedef struct +{ + INTS4 l_event; + INTS4 l_offset; } s_tag; struct sLmdControl; - -typedef struct { - INTS4 l_server_type; /* number specifying input source */ - INTS4 l_buf_type; /* buffer type number */ - INTS4 l_buf_subtype; /* buffer subtype number */ - INTS4 l_channel_no; /* file descripter or server No. */ - INTS4 l_buf_size; /* buffer size */ - INTS4 l_buf_no; - INTS4 l_buf_posi; - INTS4 l_buf_lmt; - INTS4 l_bufs_in_stream; /* # of buffers per stream */ - INTS4 l_stream_bufs; - INTS4 l_io_buf_size; /* I/O buffer size=l_buf_size*l_bufs_in_stream */ - INTS4 l_io_buf_posi; - INTS4 l_evt_buf_size; /* internal buffer size */ - INTS4 l_evt_buf_posi; - INTS4 l_evt_size; - INTS4 l_timeout; /* -1 (default) no timeout */ - INTS4 l_events; /* events since open */ - INTS4 l_buffers; /* buffers since open */ - INTS4 l_kbytes; /* kbytes since open */ - INTS4 l_first_get; - INTS4 l_first_put; - INTS4 l_first_buf; - INTS4 l_frag_len; - CHARS* pc_io_buf; /* pointer to I/O buffer to server */ - CHARS* pc_evt_buf; /* pointer to internal event buffer */ - s_bufhe* ps_bufhe; - s_bufhe s_bufhe_1; /* keep buffer header of 1st buffer for spanned event */ - s_ve10_1* ps_ve10_1; - CHARS c_channel[128]; /* channel name */ - INTS4 l_tagfile_no; /* file descripter or server No. */ - INTS4 l_tagswap; - INTS4 l_lmdswap; - s_taghe* ps_taghe; - s_tag* ps_tag; - sLmdControl* pLmd; +typedef struct +{ + INTS4 l_server_type; /* number specifying input source */ + INTS4 l_buf_type; /* buffer type number */ + INTS4 l_buf_subtype; /* buffer subtype number */ + INTS4 l_channel_no; /* file descripter or server No. */ + INTS4 l_buf_size; /* buffer size */ + INTS4 l_buf_no; + INTS4 l_buf_posi; + INTS4 l_buf_lmt; + INTS4 l_bufs_in_stream; /* # of buffers per stream */ + INTS4 l_stream_bufs; + INTS4 l_io_buf_size; /* I/O buffer size=l_buf_size*l_bufs_in_stream */ + INTS4 l_io_buf_posi; + INTS4 l_evt_buf_size; /* internal buffer size */ + INTS4 l_evt_buf_posi; + INTS4 l_evt_size; + INTS4 l_timeout; /* -1 (default) no timeout */ + INTS4 l_events; /* events since open */ + INTS4 l_buffers; /* buffers since open */ + INTS4 l_kbytes; /* kbytes since open */ + INTS4 l_first_get; + INTS4 l_first_put; + INTS4 l_first_buf; + INTS4 l_frag_len; + CHARS* pc_io_buf; /* pointer to I/O buffer to server */ + CHARS* pc_evt_buf; /* pointer to internal event buffer */ + s_bufhe* ps_bufhe; + s_bufhe s_bufhe_1; /* keep buffer header of 1st buffer for spanned event */ + s_ve10_1* ps_ve10_1; + CHARS c_channel[128]; /* channel name */ + INTS4 l_tagfile_no; /* file descripter or server No. */ + INTS4 l_tagswap; + INTS4 l_lmdswap; + s_taghe* ps_taghe; + s_tag* ps_tag; + sLmdControl* pLmd; } s_evt_channel; -INTS4 f_evt_cre_tagfile(CHARS*,CHARS*, INTS4 (*)()); -INTS4 f_evt_get_tagopen(s_evt_channel*,CHARS*,CHARS*,CHARS**,INTS4); -INTS4 f_evt_get_tagevent(s_evt_channel*,INTS4,INTS4,INTS4**); -INTS4 f_evt_get_tagnext(s_evt_channel*,INTS4,INTS4**); +INTS4 f_evt_cre_tagfile(CHARS*, CHARS*, INTS4 (*)()); +INTS4 f_evt_get_tagopen(s_evt_channel*, CHARS*, CHARS*, CHARS**, INTS4); +INTS4 f_evt_get_tagevent(s_evt_channel*, INTS4, INTS4, INTS4**); +INTS4 f_evt_get_tagnext(s_evt_channel*, INTS4, INTS4**); INTS4 f_evt_get_tagclose(s_evt_channel*); INTS4 f_evt_get_open(INTS4, CHARS*, s_evt_channel*, CHARS**, INTS4, INTS4); INTS4 f_evt_get_event(s_evt_channel*, INTS4**, INTS4**); -INTS4 f_evt_get_subevent(s_ve10_1*,INTS4,INTS4**,INTS4**,INTS4*); +INTS4 f_evt_get_subevent(s_ve10_1*, INTS4, INTS4**, INTS4**, INTS4*); INTS4 f_evt_get_buffer(s_evt_channel*, INTS4*); INTS4 f_evt_get_close(s_evt_channel*); CHARS* f_evt_get_buffer_ptr(s_evt_channel*); INTS4 f_evt_skip_buffer(s_evt_channel*, INTS4); -INTS4 f_evt_put_open(CHARS*,INTS4,INTS4,INTS4,INTS4,s_evt_channel*,CHARS*); +INTS4 f_evt_put_open(CHARS*, INTS4, INTS4, INTS4, INTS4, s_evt_channel*, CHARS*); INTS4 f_evt_put_event(s_evt_channel*, INTS4*); INTS4 f_evt_put_buffer(s_evt_channel*, s_bufhe*); INTS4 f_evt_put_close(s_evt_channel*); -INTS4 f_evt_type(s_bufhe*,s_evhe*,INTS4,INTS4,INTS4,INTS4); -INTS4 f_evt_error( INTS4 , CHARS* , INTS4 ); -INTS4 f_evt_timeout(s_evt_channel*, INTS4 ); +INTS4 f_evt_type(s_bufhe*, s_evhe*, INTS4, INTS4, INTS4, INTS4); +INTS4 f_evt_error(INTS4, CHARS*, INTS4); +INTS4 f_evt_timeout(s_evt_channel*, INTS4); INTS4 f_evt_rev_port(INTS4); INTS4 f_evt_swap(CHARS*, INTS4); s_evt_channel* f_evt_control(); @@ -114,41 +116,41 @@ s_evt_channel* f_evt_control(); /* ******************************/ /* Input selector */ /* ******************************/ -#define GETEVT__FILE 1 -#define GETEVT__STREAM 2 -#define GETEVT__TRANS 3 -#define GETEVT__EVENT 4 -#define GETEVT__REVSERV 5 -#define GETEVT__RFIO 6 -#define GETEVT__TAGINDEX 10 +#define GETEVT__FILE 1 +#define GETEVT__STREAM 2 +#define GETEVT__TRANS 3 +#define GETEVT__EVENT 4 +#define GETEVT__REVSERV 5 +#define GETEVT__RFIO 6 +#define GETEVT__TAGINDEX 10 #define GETEVT__TAGNUMBER 11 /* ********************************************************************** */ /* error messages */ /* ********************************************************************** */ -#define GETEVT__SUCCESS 0 -#define GETEVT__FAILURE 1 -#define GETEVT__FRAGMENT 2 -#define GETEVT__NOMORE 3 -#define GETEVT__NOFILE 4 -#define GETEVT__NOSERVER 5 -#define GETEVT__RDERR 6 -#define GETEVT__CLOSE_ERR 7 -#define GETEVT__NOCHANNEL 8 -#define GETEVT__TIMEOUT 9 -#define GETEVT__NOTAGFILE 10 -#define GETEVT__NOTAG 11 -#define GETEVT__TAGRDERR 12 -#define GETEVT__TAGWRERR 13 -#define GETEVT__NOLMDFILE 14 +#define GETEVT__SUCCESS 0 +#define GETEVT__FAILURE 1 +#define GETEVT__FRAGMENT 2 +#define GETEVT__NOMORE 3 +#define GETEVT__NOFILE 4 +#define GETEVT__NOSERVER 5 +#define GETEVT__RDERR 6 +#define GETEVT__CLOSE_ERR 7 +#define GETEVT__NOCHANNEL 8 +#define GETEVT__TIMEOUT 9 +#define GETEVT__NOTAGFILE 10 +#define GETEVT__NOTAG 11 +#define GETEVT__TAGRDERR 12 +#define GETEVT__TAGWRERR 13 +#define GETEVT__NOLMDFILE 14 -#define PUTEVT__SUCCESS 0 -#define PUTEVT__FILE_EXIST 101 -#define PUTEVT__FAILURE 102 -#define PUTEVT__TOOBIG 103 -#define PUTEVT__TOO_SMALLS 104 -#define PUTEVT__CLOSE_ERR 105 -#define PUTEVT__WRERR 106 -#define PUTEVT__NOCHANNEL 107 +#define PUTEVT__SUCCESS 0 +#define PUTEVT__FILE_EXIST 101 +#define PUTEVT__FAILURE 102 +#define PUTEVT__TOOBIG 103 +#define PUTEVT__TOO_SMALLS 104 +#define PUTEVT__CLOSE_ERR 105 +#define PUTEVT__WRERR 106 +#define PUTEVT__NOCHANNEL 107 #endif /***************** End f_evt.h ******************************/ diff --git a/MbsAPI/f_stccomm.c b/MbsAPI/f_stccomm.c index 41a8e626d8..0f1e4c954d 100644 --- a/MbsAPI/f_stccomm.c +++ b/MbsAPI/f_stccomm.c @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "f_stccomm.h" @@ -120,36 +120,35 @@ CHARS c_msg[80]; /*1- PLI Main ****************+****************************************/ /* %%-HEAD: */ -INTS4 f_stc_read( p_buffer , i_buflen , i_channel , i_timeout ) -INTS1* p_buffer; -INTS4 i_buflen; -INTS4 i_channel; -INTS4 i_timeout; +INTS4 f_stc_read(p_buffer, i_buflen, i_channel, i_timeout) INTS1* p_buffer; +INTS4 i_buflen; +INTS4 i_channel; +INTS4 i_timeout; { - INTS4 retval , buflen_tmp; - INTS1* p_buffer_tmp; -// INTS4 rmask , wmask , emask; - INTS4 i_retry=0; - struct timeval read_timeout; - fd_set xrmask,xwmask,xemask; - INTS4 num_of_bytes_read = 0; - - buflen_tmp = i_buflen; - p_buffer_tmp = p_buffer; /* actual pointer to buffer */ - - FD_ZERO(&xrmask); - FD_ZERO(&xemask); - FD_ZERO(&xwmask); - FD_SET(i_channel,&xrmask); - read_timeout.tv_sec = i_timeout; - read_timeout.tv_usec = 0; + INTS4 retval, buflen_tmp; + INTS1* p_buffer_tmp; + // INTS4 rmask , wmask , emask; + INTS4 i_retry = 0; + struct timeval read_timeout; + fd_set xrmask, xwmask, xemask; + INTS4 num_of_bytes_read = 0; + + buflen_tmp = i_buflen; + p_buffer_tmp = p_buffer; /* actual pointer to buffer */ + + FD_ZERO(&xrmask); + FD_ZERO(&xemask); + FD_ZERO(&xwmask); + FD_SET(i_channel, &xrmask); + read_timeout.tv_sec = i_timeout; + read_timeout.tv_usec = 0; #ifdef DEBUG - printf("STC: read %6d bytes channel %d ",i_buflen,i_channel); - fflush(stdout); + printf("STC: read %6d bytes channel %d ", i_buflen, i_channel); + fflush(stdout); #endif - while( num_of_bytes_read < i_buflen && buflen_tmp > 0 ) { - if( i_timeout >= 0 ) { - /* + while (num_of_bytes_read < i_buflen && buflen_tmp > 0) { + if (i_timeout >= 0) { + /* #ifdef GSI__AIX retval = select(32,&xrmask,&xwmask,&xemask,&read_timeout); #else @@ -157,89 +156,90 @@ INTS4 i_timeout; #endif */ - /* Changed by S.Linev, 18.09.2007 */ -// retval = select(32,(fd_set*) &rmask, (fd_set*) &wmask, (fd_set*) &emask,&read_timeout); - retval = select(i_channel+1, &xrmask, &xwmask, &xemask, &read_timeout); - - switch( retval ) { - case -1: - switch( errno ) { - case EBADF : - return STC__INVSOCK; - case EINVAL : - return STC__INVTIME; - case EINTR : - continue; - case ECONNRESET : - return STC__ECONNRES; - default : - sprintf(c_msg,"STC select error channel %d",i_channel); - perror(c_msg); - return STC__FAILURE; + /* Changed by S.Linev, 18.09.2007 */ + // retval = select(32,(fd_set*) &rmask, (fd_set*) &wmask, (fd_set*) &emask,&read_timeout); + retval = select(i_channel + 1, &xrmask, &xwmask, &xemask, &read_timeout); + + switch (retval) { + case -1: + switch (errno) { + case EBADF: + return STC__INVSOCK; + case EINVAL: + return STC__INVTIME; + case EINTR: + continue; + case ECONNRESET: + return STC__ECONNRES; + default: + sprintf(c_msg, "STC select error channel %d", i_channel); + perror(c_msg); + return STC__FAILURE; + } + case 0: + return STC__TIMEOUT; + } } - case 0: - return STC__TIMEOUT; - } - } - /* ------------------------------------------------------- */ - /* read data from the connect socket. */ - /* ------------------------------------------------------- */ + /* ------------------------------------------------------- */ + /* read data from the connect socket. */ + /* ------------------------------------------------------- */ #ifdef DEBUG - printf("read "); - fflush(stdout); + printf("read "); + fflush(stdout); #endif #ifdef GSI__WINNT - retval = recv(i_channel ,p_buffer_tmp, buflen_tmp,0); /* Mohammad Al-Turany 31.07.00 */ + retval = recv(i_channel, p_buffer_tmp, buflen_tmp, 0); /* Mohammad Al-Turany 31.07.00 */ #else - retval = read(i_channel , p_buffer_tmp,buflen_tmp); + retval = read(i_channel, p_buffer_tmp, buflen_tmp); #endif - if( retval == -1 ) { - switch( errno ) { - case EBADF : - return STC__INVSOCK; - case EFAULT : - return STC__INVBUF; - case EINVAL : - return STC__NGBUFSIZE; - case EINTR : - return STC__EINTR; - case ECONNRESET : - return STC__ECONNRES; - default : - sprintf(c_msg,"STC read error channel %d",i_channel); - perror(c_msg); - return STC__FAILURE; - } /* switch( errno ) */ - - } /* if( retval == -1 ) */ - - /* ------------------------------------------------------- */ - /* set the num of bytes to read in the next */ - /* read statement. */ - /* ------------------------------------------------------- */ - - num_of_bytes_read += retval; - buflen_tmp -= retval; - p_buffer_tmp += retval; /* calc actual pointer */ - if( i_retry == 100000 ) { - printf("Request %d bytes, read %d, timeout after 100000 retries\n",i_buflen,num_of_bytes_read); - return STC__NODATA; - } - ++i_retry; - - read_timeout.tv_sec = 100; - read_timeout.tv_usec = 0; + if (retval == -1) { + switch (errno) { + case EBADF: + return STC__INVSOCK; + case EFAULT: + return STC__INVBUF; + case EINVAL: + return STC__NGBUFSIZE; + case EINTR: + return STC__EINTR; + case ECONNRESET: + return STC__ECONNRES; + default: + sprintf(c_msg, "STC read error channel %d", i_channel); + perror(c_msg); + return STC__FAILURE; + } /* switch( errno ) */ + + } /* if( retval == -1 ) */ + + /* ------------------------------------------------------- */ + /* set the num of bytes to read in the next */ + /* read statement. */ + /* ------------------------------------------------------- */ + + num_of_bytes_read += retval; + buflen_tmp -= retval; + p_buffer_tmp += retval; /* calc actual pointer */ + if (i_retry == 100000) { + printf("Request %d bytes, read %d, timeout after 100000 retries\n", i_buflen, num_of_bytes_read); + return STC__NODATA; + } + ++i_retry; - } /* end while */ + read_timeout.tv_sec = 100; + read_timeout.tv_usec = 0; + } /* end while */ #ifdef DEBUG - printf("done\n"); - fflush(stdout); + printf("done\n"); + fflush(stdout); #endif - if( num_of_bytes_read == i_buflen ) { return STC__SUCCESS; } + if (num_of_bytes_read == i_buflen) { + return STC__SUCCESS; + } - return STC__FAILURE; + return STC__FAILURE; } /* f_stc_read() */ /* ------------------------------------------------------------------------- */ @@ -321,53 +321,53 @@ INTS4 i_timeout; /*1- PLI Main ****************+****************************************/ /* %%-HEAD: */ -INTS4 f_stc_write( p_buffer , i_buflen , i_channel) -INTS1* p_buffer; -INTS4 i_buflen; -INTS4 i_channel; +INTS4 f_stc_write(p_buffer, i_buflen, i_channel) INTS1* p_buffer; +INTS4 i_buflen; +INTS4 i_channel; { - INTS4 l_retval; + INTS4 l_retval; - /* ---------------------------------------------------------- */ - /* send data to server. */ - /* ---------------------------------------------------------- */ + /* ---------------------------------------------------------- */ + /* send data to server. */ + /* ---------------------------------------------------------- */ #ifdef DEBUG - printf("STC: write %5d bytes channel %d ",i_buflen,i_channel); - fflush(stdout); + printf("STC: write %5d bytes channel %d ", i_buflen, i_channel); + fflush(stdout); #endif - l_retval = send(i_channel , p_buffer , i_buflen , 0); - - switch( l_retval ) { - case -1: - switch( errno ) { - case EBADF : - return STC__INVSOCK; - case ENOTSOCK : - return STC__NOTSOCK; - case EFAULT : - return STC__INVADDR; - default : - sprintf(c_msg,"STC write error channel %d",i_channel); - perror(c_msg); - return STC__FAILURE; - } /* switch( errno ) */ - - } /* switch( l_retval ) */ - - /* ---------------------------------------------------------- */ - /* send() returns the number of bytes sent. */ - /* ---------------------------------------------------------- */ + l_retval = send(i_channel, p_buffer, i_buflen, 0); + + switch (l_retval) { + case -1: + switch (errno) { + case EBADF: + return STC__INVSOCK; + case ENOTSOCK: + return STC__NOTSOCK; + case EFAULT: + return STC__INVADDR; + default: + sprintf(c_msg, "STC write error channel %d", i_channel); + perror(c_msg); + return STC__FAILURE; + } /* switch( errno ) */ + + } /* switch( l_retval ) */ + + /* ---------------------------------------------------------- */ + /* send() returns the number of bytes sent. */ + /* ---------------------------------------------------------- */ #ifdef DEBUG - printf("done\n"); - fflush(stdout); + printf("done\n"); + fflush(stdout); #endif - if(l_retval == i_buflen) { return STC__SUCCESS; } - - return STC__FAILURE; -} /* end f_stc_write() */ + if (l_retval == i_buflen) { + return STC__SUCCESS; + } + return STC__FAILURE; +} /* end f_stc_write() */ /* %%+HEAD: */ /*****************+***********+****************************************/ @@ -483,126 +483,114 @@ INTS4 i_channel; /*1- PLI Main ****************+****************************************/ /* %%-HEAD: */ -INTS4 f_stc_connectserver( c_node , l_port , pi_channel , ps_client ) -CHARS* c_node; -INTS4 l_port; -INTS4* pi_channel; +INTS4 f_stc_connectserver(c_node, l_port, pi_channel, ps_client) CHARS* c_node; +INTS4 l_port; +INTS4* pi_channel; struct s_tcpcomm* ps_client; { + INTS4 /*shut,*/ retval; + // INTS4 thirty = 30; + struct s_tcpcomm s_client; + memset(&s_client, 0, sizeof(s_client)); - INTS4 /*shut,*/ retval ; -// INTS4 thirty = 30; - struct s_tcpcomm s_client; - memset(&s_client, 0, sizeof(s_client)); - - /* ----------------------------------------------------------------------- */ - /* init communication socket. */ - /* ----------------------------------------------------------------------- */ - + /* ----------------------------------------------------------------------- */ + /* init communication socket. */ + /* ----------------------------------------------------------------------- */ #ifdef GSI__WINNT - WORD wVersionRequested; - WSADATA wsaData; - char message1[512]; - wVersionRequested = MAKEWORD( 2, 2 ); -//err = WSAStartup( wVersionRequested, &wsaData ); - if (WSAStartup( wVersionRequested, &wsaData)!=0) { - printf("WinSock NOT found"); - /* Tell the user that we could not find a usable */ - /* WinSock DLL. */ - } - - if ( LOBYTE( wsaData.wVersion ) != 2 || - HIBYTE( wsaData.wVersion ) != 2 ) { - /* Tell the user that we could not find a usable */ - /* WinSock DLL. - */ - printf("WinSock %d.%d",LOBYTE( wsaData.wVersion ),HIBYTE( wsaData.wVersion )); - WSACleanup( ); - } - -#endif - - - - - s_client.socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + WORD wVersionRequested; + WSADATA wsaData; + char message1[512]; + wVersionRequested = MAKEWORD(2, 2); + // err = WSAStartup( wVersionRequested, &wsaData ); + if (WSAStartup(wVersionRequested, &wsaData) != 0) { + printf("WinSock NOT found"); + /* Tell the user that we could not find a usable */ + /* WinSock DLL. */ + } - *ps_client = s_client; - *pi_channel = s_client.socket; /* save channel also in case of error */ - /* 17.7.95, H.G. */ - switch( s_client.socket ) { - case -1: - switch( errno ) { - case EAFNOSUPPORT : - return STC__INVADDRF; - case ESOCKTNOSUPPORT : - return STC__SOCKNSUP; - case EPROTONOSUPPORT : - return STC__INVPROTO; - case EMFILE : - return STC__SOCKTABF; - case ENOBUFS : - return STC__SOCKSPAF; - default : - return STC__FAILURE; - } /* switch( errno ) */ - } /* switch( s_client.socket) */ + if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) { + /* Tell the user that we could not find a usable */ + /* WinSock DLL. + */ + printf("WinSock %d.%d", LOBYTE(wsaData.wVersion), HIBYTE(wsaData.wVersion)); + WSACleanup(); + } +#endif - if(( s_client.hostentptr = gethostbyname(c_node)) == NULL) { + s_client.socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + + *ps_client = s_client; + *pi_channel = s_client.socket; /* save channel also in case of error */ + /* 17.7.95, H.G. */ + switch (s_client.socket) { + case -1: + switch (errno) { + case EAFNOSUPPORT: + return STC__INVADDRF; + case ESOCKTNOSUPPORT: + return STC__SOCKNSUP; + case EPROTONOSUPPORT: + return STC__INVPROTO; + case EMFILE: + return STC__SOCKTABF; + case ENOBUFS: + return STC__SOCKSPAF; + default: + return STC__FAILURE; + } /* switch( errno ) */ + } /* switch( s_client.socket) */ + + if ((s_client.hostentptr = gethostbyname(c_node)) == NULL) { #ifdef GSI__WINNT - closesocket(s_client.socket); /* Mohammad Al-Turany 31.07.00*/ + closesocket(s_client.socket); /* Mohammad Al-Turany 31.07.00*/ #else - close(s_client.socket); /* close socket here and in any case! */ - /* H.G., 17.7.95 */ + close(s_client.socket); /* close socket here and in any case! */ + /* H.G., 17.7.95 */ #endif - /* printf("--E--f_stc_connectserver(): error gethostbyname: >%s<\n",c_node);*/ - return STC__FAILURE; - } - + /* printf("--E--f_stc_connectserver(): error gethostbyname: >%s<\n",c_node);*/ + return STC__FAILURE; + } - s_client.hostentstruct = *s_client.hostentptr; - s_client.sock.sin_family = s_client.hostentstruct.h_addrtype; - s_client.sock.sin_port = htons(l_port); - s_client.sock.sin_addr = - * ((struct in_addr*) s_client.hostentstruct.h_addr); + s_client.hostentstruct = *s_client.hostentptr; + s_client.sock.sin_family = s_client.hostentstruct.h_addrtype; + s_client.sock.sin_port = htons(l_port); + s_client.sock.sin_addr = *((struct in_addr*)s_client.hostentstruct.h_addr); - retval = connect( s_client.socket, - ( struct sockaddr*) &s_client.sock, - sizeof(s_client.sock)); - if( retval == -1) { + retval = connect(s_client.socket, (struct sockaddr*)&s_client.sock, sizeof(s_client.sock)); + if (retval == -1) { #ifdef GSI__WINNT - closesocket(s_client.socket); /* Mohammad Al-Turany 31.07.00*/ + closesocket(s_client.socket); /* Mohammad Al-Turany 31.07.00*/ #else - close(s_client.socket); /* close socket here and in any case! */ - /* H.G., 17.7.95 */ + close(s_client.socket); /* close socket here and in any case! */ + /* H.G., 17.7.95 */ #endif - switch( errno ) { - case EBADF : - return STC__INVSOCK; - case ENOTSOCK : - return STC__NOTSOCK; - case EISCONN : - return STC__SOCKISC; - case ETIMEDOUT : - return STC__CONNTOUT; - case ENETUNREACH : - return STC__NETUNREA; - case EADDRINUSE : - return STC__PORTINUS; - case ECONNREFUSED : - return STC__ECONNREF; - default : - return STC__FAILURE; - } /* switch( errno ) */ - } - - *ps_client = s_client; - - return STC__SUCCESS; + switch (errno) { + case EBADF: + return STC__INVSOCK; + case ENOTSOCK: + return STC__NOTSOCK; + case EISCONN: + return STC__SOCKISC; + case ETIMEDOUT: + return STC__CONNTOUT; + case ENETUNREACH: + return STC__NETUNREA; + case EADDRINUSE: + return STC__PORTINUS; + case ECONNREFUSED: + return STC__ECONNREF; + default: + return STC__FAILURE; + } /* switch( errno ) */ + } + + *ps_client = s_client; + + return STC__SUCCESS; } /* f_stc_connectserver() */ @@ -694,34 +682,30 @@ struct s_tcpcomm* ps_client; /*1- PLI Main ****************+****************************************/ /* %%-HEAD: */ -INTS4 f_stc_acceptclient( ps_server , pi_channel) -struct s_tcpcomm* ps_server; +INTS4 f_stc_acceptclient(ps_server, pi_channel) struct s_tcpcomm* ps_server; INTS4* pi_channel; { -// INTS4 i_socket; -// struct hostent* he; + // INTS4 i_socket; + // struct hostent* he; #ifdef GSI__AIX - *pi_channel = accept( ps_server->sock_rw, - ( struct sockaddr*) &ps_server->sock_name, - (socklen_t*) &ps_server->namelength); + *pi_channel = + accept(ps_server->sock_rw, (struct sockaddr*)&ps_server->sock_name, (socklen_t*)&ps_server->namelength); #else - *pi_channel = accept( ps_server->sock_rw, - ( struct sockaddr*) &ps_server->sock_name, - (uint*)&ps_server->namelength); + *pi_channel = accept(ps_server->sock_rw, (struct sockaddr*)&ps_server->sock_name, (uint*)&ps_server->namelength); #endif - if( *pi_channel == -1) { - switch( errno ) { - case EBADF : - return STC__INVSOCK; - case ENOTSOCK : - return STC__NOTSOCK; - default : - return STC__FAILURE; - } /* switch( errno ) */ - } - - /* + if (*pi_channel == -1) { + switch (errno) { + case EBADF: + return STC__INVSOCK; + case ENOTSOCK: + return STC__NOTSOCK; + default: + return STC__FAILURE; + } /* switch( errno ) */ + } + + /* hostname of remote node. he = gethostbyaddr( ps_server->sock_name.sin_addr.s_addr, sizeof(ps_server->sock_name.sin_addr.s_addr), @@ -731,7 +715,7 @@ INTS4* pi_channel; printf("name of client: %s\n",he->h_name); */ - return STC__SUCCESS; + return STC__SUCCESS; } /* end f_stc_acceptclient() */ @@ -859,206 +843,193 @@ INTS4* pi_channel; /*1- PLI Main ****************+****************************************/ /* %%-HEAD: */ -INTS4 f_stc_createserver( pl_port , ps_server) -INTS4* pl_port; +INTS4 f_stc_createserver(pl_port, ps_server) INTS4* pl_port; struct s_tcpcomm* ps_server; { - INTS4 retval, /*i,*/ retry, on ; -// struct protoent* p; - struct s_tcpcomm s_server; - memset(&s_server, 0, sizeof(s_server)); - + INTS4 retval, /*i,*/ retry, on; + // struct protoent* p; + struct s_tcpcomm s_server; + memset(&s_server, 0, sizeof(s_server)); #ifdef GSI__WINNT - WORD wVersionRequested; - WSADATA wsaData; - char message1[512]; - wVersionRequested = MAKEWORD( 2, 2 ); -//err = WSAStartup( wVersionRequested, &wsaData ); - if (WSAStartup( wVersionRequested, &wsaData)!=0) { - printf("WinSock NOT found"); - /* Tell the user that we could not find a usable */ - /* WinSock DLL. */ - } - - if ( LOBYTE( wsaData.wVersion ) != 2 || - HIBYTE( wsaData.wVersion ) != 2 ) { - /* Tell the user that we could not find a usable */ - /* WinSock DLL. - */ - printf("WinSock %d.%d",LOBYTE( wsaData.wVersion ),HIBYTE( wsaData.wVersion )); - WSACleanup( ); - } - -#endif + WORD wVersionRequested; + WSADATA wsaData; + char message1[512]; + wVersionRequested = MAKEWORD(2, 2); + // err = WSAStartup( wVersionRequested, &wsaData ); + if (WSAStartup(wVersionRequested, &wsaData) != 0) { + printf("WinSock NOT found"); + /* Tell the user that we could not find a usable */ + /* WinSock DLL. */ + } + if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) { + /* Tell the user that we could not find a usable */ + /* WinSock DLL. + */ + printf("WinSock %d.%d", LOBYTE(wsaData.wVersion), HIBYTE(wsaData.wVersion)); + WSACleanup(); + } +#endif - on = 1; - - if( *pl_port == 0 ) { - retry = 1 ; - *pl_port = 1024; - } else { - retry = 0; - } - - s_server.sock_rw = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); - - switch( s_server.sock_rw ) { - case -1: - switch( errno ) { - case EAFNOSUPPORT : - return STC__INVADDRF; - case ESOCKTNOSUPPORT : - return STC__SOCKNSUP; - case EPROTONOSUPPORT : - return STC__INVPROTO; - case EMFILE : - return STC__SOCKTABF; - case ENOBUFS : - return STC__SOCKSPAF; - default : - return STC__FAILURE; - } /* switch( errno ) */ - } /* switch( s_server.sock_rw) */ - - - retval = gethostname(s_server.hostname,sizeof(s_server.hostname)); - if(retval) { - printf("--E--f_stc_createserver() error get local hostname\n"); - return STC__FAILURE; - } + on = 1; - if((s_server.hostentptr = gethostbyname (s_server.hostname)) == NULL) { - printf("--E--f_stc_createserver() error get local Internet address\n"); - return STC__FAILURE; - } - - bzero( (CHARS*) &s_server.sock_name , sizeof( s_server.sock_name ) ); - s_server.sock_name.sin_family = AF_INET; - s_server.sock_name.sin_addr.s_addr = htonl(INADDR_ANY); - s_server.sock_name.sin_port = htons(*pl_port); - - retval = bind( s_server.sock_rw, - (struct sockaddr*) &s_server.sock_name, - sizeof(s_server.sock_name)); - - if( retval == -1 && retry == 0 ) { - - close( s_server.sock_rw ); - - switch( errno ) { - case EBADF : - return STC__INVSOCK; - case ENOTSOCK : - return STC__NOTSOCK; - case EADDRINUSE : - return STC__PORTINUS; - case EINVAL : - return STC__SOCKISC; - case EACCES : - return STC__SOCKISP; - default : - return STC__FAILURE; + if (*pl_port == 0) { + retry = 1; + *pl_port = 1024; + } else { + retry = 0; } - } - - retval = -1; - - while ( retval == -1 && retry == 1 ) { - - s_server.sock_rw = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); - - switch( s_server.sock_rw ) { - case -1: - switch( errno ) { - case EAFNOSUPPORT : - return STC__INVADDRF; - case ESOCKTNOSUPPORT : - return STC__SOCKNSUP; - case EPROTONOSUPPORT : - return STC__INVPROTO; - case EMFILE : - return STC__SOCKTABF; - case ENOBUFS : - return STC__SOCKSPAF; - default : + + s_server.sock_rw = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + + switch (s_server.sock_rw) { + case -1: + switch (errno) { + case EAFNOSUPPORT: + return STC__INVADDRF; + case ESOCKTNOSUPPORT: + return STC__SOCKNSUP; + case EPROTONOSUPPORT: + return STC__INVPROTO; + case EMFILE: + return STC__SOCKTABF; + case ENOBUFS: + return STC__SOCKSPAF; + default: + return STC__FAILURE; + } /* switch( errno ) */ + } /* switch( s_server.sock_rw) */ + + retval = gethostname(s_server.hostname, sizeof(s_server.hostname)); + if (retval) { + printf("--E--f_stc_createserver() error get local hostname\n"); return STC__FAILURE; - } } - retval = gethostname(s_server.hostname,sizeof(s_server.hostname)); - if(retval) { - printf("--E--f_stc_createserver() error get local hostname\n"); - return STC__FAILURE; + if ((s_server.hostentptr = gethostbyname(s_server.hostname)) == NULL) { + printf("--E--f_stc_createserver() error get local Internet address\n"); + return STC__FAILURE; } - - if((s_server.hostentptr = gethostbyname (s_server.hostname)) == NULL) { - printf("--E--f_stc_createserver() error get local Internet address\n"); - return STC__FAILURE; + bzero((CHARS*)&s_server.sock_name, sizeof(s_server.sock_name)); + s_server.sock_name.sin_family = AF_INET; + s_server.sock_name.sin_addr.s_addr = htonl(INADDR_ANY); + s_server.sock_name.sin_port = htons(*pl_port); + + retval = bind(s_server.sock_rw, (struct sockaddr*)&s_server.sock_name, sizeof(s_server.sock_name)); + + if (retval == -1 && retry == 0) { + + close(s_server.sock_rw); + + switch (errno) { + case EBADF: + return STC__INVSOCK; + case ENOTSOCK: + return STC__NOTSOCK; + case EADDRINUSE: + return STC__PORTINUS; + case EINVAL: + return STC__SOCKISC; + case EACCES: + return STC__SOCKISP; + default: + return STC__FAILURE; + } } retval = -1; - bzero( (CHARS*) &s_server.sock_name , sizeof( s_server.sock_name ) ); - s_server.sock_name.sin_family = AF_INET; - s_server.sock_name.sin_addr.s_addr = htonl(INADDR_ANY); - s_server.sock_name.sin_port = htons(*pl_port); - - retval = bind( s_server.sock_rw, - (struct sockaddr*) &s_server.sock_name, - sizeof(s_server.sock_name)); - if( retval == -1 ) { - close( s_server.sock_rw ); - - *pl_port += 1; - - if( *pl_port > 65535 ) { - printf("--E--f_stc_createserver() portnumber exceeded > 655535\n"); - - switch( errno ) { - case EBADF : - return STC__INVSOCK; - case ENOTSOCK : - return STC__NOTSOCK; - case EADDRINUSE : - return STC__PORTINUS; - case EINVAL : - return STC__SOCKISC; - case EACCES : - return STC__SOCKISP; - default : - return STC__FAILURE; - } /* end switch( errno ) */ - - } /* end if *pl_port > ... ) */ - - } /* end if (retval == -1 ) */ - - - } - - retval = listen(s_server.sock_rw,5); - if( retval == -1 ) { - switch( errno ) { - case EBADF : - return STC__INVSOCK; - case ENOTSOCK : - return STC__NOTSOCK; - default : - return STC__FAILURE; + while (retval == -1 && retry == 1) { + + s_server.sock_rw = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + + switch (s_server.sock_rw) { + case -1: + switch (errno) { + case EAFNOSUPPORT: + return STC__INVADDRF; + case ESOCKTNOSUPPORT: + return STC__SOCKNSUP; + case EPROTONOSUPPORT: + return STC__INVPROTO; + case EMFILE: + return STC__SOCKTABF; + case ENOBUFS: + return STC__SOCKSPAF; + default: + return STC__FAILURE; + } + } + + retval = gethostname(s_server.hostname, sizeof(s_server.hostname)); + if (retval) { + printf("--E--f_stc_createserver() error get local hostname\n"); + return STC__FAILURE; + } + + if ((s_server.hostentptr = gethostbyname(s_server.hostname)) == NULL) { + printf("--E--f_stc_createserver() error get local Internet address\n"); + return STC__FAILURE; + } + + retval = -1; + + bzero((CHARS*)&s_server.sock_name, sizeof(s_server.sock_name)); + s_server.sock_name.sin_family = AF_INET; + s_server.sock_name.sin_addr.s_addr = htonl(INADDR_ANY); + s_server.sock_name.sin_port = htons(*pl_port); + + retval = bind(s_server.sock_rw, (struct sockaddr*)&s_server.sock_name, sizeof(s_server.sock_name)); + if (retval == -1) { + close(s_server.sock_rw); + + *pl_port += 1; + + if (*pl_port > 65535) { + printf("--E--f_stc_createserver() portnumber exceeded > 655535\n"); + + switch (errno) { + case EBADF: + return STC__INVSOCK; + case ENOTSOCK: + return STC__NOTSOCK; + case EADDRINUSE: + return STC__PORTINUS; + case EINVAL: + return STC__SOCKISC; + case EACCES: + return STC__SOCKISP; + default: + return STC__FAILURE; + } /* end switch( errno ) */ + + } /* end if *pl_port > ... ) */ + + } /* end if (retval == -1 ) */ } - } - s_server.namelength = sizeof( s_server.sock_name); + retval = listen(s_server.sock_rw, 5); + if (retval == -1) { + switch (errno) { + case EBADF: + return STC__INVSOCK; + case ENOTSOCK: + return STC__NOTSOCK; + default: + return STC__FAILURE; + } + } - *ps_server = s_server; + s_server.namelength = sizeof(s_server.sock_name); - return STC__SUCCESS; + *ps_server = s_server; + + return STC__SUCCESS; } /* end f_stc_createserver() */ /* %%+HEAD: */ @@ -1121,25 +1092,24 @@ struct s_tcpcomm* ps_server; /*1- PLI Main ****************+****************************************/ /* %%-HEAD: */ -INTS4 f_stc_close( ps_tcp) -struct s_tcpcomm* ps_tcp; +INTS4 f_stc_close(ps_tcp) struct s_tcpcomm* ps_tcp; { - INTS4 retval; + INTS4 retval; - if( ps_tcp->socket ) { - retval = shutdown( ps_tcp->socket,2); - if(retval == -1) { - return STC__FAILURE; - } - retval = close(ps_tcp->socket); - if(retval == -1) { - return STC__FAILURE; - } + if (ps_tcp->socket) { + retval = shutdown(ps_tcp->socket, 2); + if (retval == -1) { + return STC__FAILURE; + } + retval = close(ps_tcp->socket); + if (retval == -1) { + return STC__FAILURE; + } - return STC__SUCCESS; - } + return STC__SUCCESS; + } - return STC__FAILURE; + return STC__FAILURE; } /* f_stc_close() */ /* %%+HEAD: */ @@ -1202,18 +1172,17 @@ struct s_tcpcomm* ps_tcp; /*1- PLI Main ****************+****************************************/ /* %%-HEAD: */ -INTS4 f_stc_discclient( i_channel ) -INTS4 i_channel; +INTS4 f_stc_discclient(i_channel) INTS4 i_channel; { - INTS4 retval; + INTS4 retval; - /* call of shutdown removed 17.7.95, H.G. */ - retval = close( i_channel ); - if(retval == -1) { - return STC__FAILURE; - } else { - return STC__SUCCESS; - } + /* call of shutdown removed 17.7.95, H.G. */ + retval = close(i_channel); + if (retval == -1) { + return STC__FAILURE; + } else { + return STC__SUCCESS; + } } /* f_stc_discclient() */ /* %%+HEAD: */ @@ -1285,62 +1254,57 @@ INTS4 i_channel; /*1- PLI Main ****************+****************************************/ /* %%-HEAD: */ -INTS4 f_stc_listenserver( ps_server) -struct s_tcpcomm* ps_server; +INTS4 f_stc_listenserver(ps_server) struct s_tcpcomm* ps_server; { - struct timeval read_timeout; - fd_set rset , allset , wset , eset; - INTS4 listenfd , maxfd , sts; - - - read_timeout.tv_sec = 0; - read_timeout.tv_usec = 0; - - listenfd = ps_server->sock_rw; - - FD_ZERO(&rset); - FD_ZERO(&wset); - FD_ZERO(&eset); - FD_ZERO(&allset); - FD_SET(listenfd,&rset); - FD_SET(listenfd,&wset); - FD_SET(listenfd,&eset); - maxfd = listenfd; - - sts = select( maxfd + 1 , &rset , - &wset , - &eset , &read_timeout); - switch( sts ) { - case -1: - switch( errno ) { - case EBADF : - return STC__INVSOCK; - case EINVAL : - return STC__INVTIME; - default : - return STC__FAILURE; - } /* switch( errno ) */ - - case 0: - return STC__TIMEOUT; - - } /* end switch( sts ) */ - - if( FD_ISSET(listenfd,&eset)) { - return STC__SUCCESS; - } + struct timeval read_timeout; + fd_set rset, allset, wset, eset; + INTS4 listenfd, maxfd, sts; - if( FD_ISSET(listenfd,&rset)) { - return STC__SUCCESS; - } + read_timeout.tv_sec = 0; + read_timeout.tv_usec = 0; - if( FD_ISSET(listenfd,&wset)) { - return STC__SUCCESS; - } + listenfd = ps_server->sock_rw; + + FD_ZERO(&rset); + FD_ZERO(&wset); + FD_ZERO(&eset); + FD_ZERO(&allset); + FD_SET(listenfd, &rset); + FD_SET(listenfd, &wset); + FD_SET(listenfd, &eset); + maxfd = listenfd; + + sts = select(maxfd + 1, &rset, &wset, &eset, &read_timeout); + switch (sts) { + case -1: + switch (errno) { + case EBADF: + return STC__INVSOCK; + case EINVAL: + return STC__INVTIME; + default: + return STC__FAILURE; + } /* switch( errno ) */ + + case 0: + return STC__TIMEOUT; + + } /* end switch( sts ) */ + + if (FD_ISSET(listenfd, &eset)) { + return STC__SUCCESS; + } - return STC__FAILURE; -} + if (FD_ISSET(listenfd, &rset)) { + return STC__SUCCESS; + } + if (FD_ISSET(listenfd, &wset)) { + return STC__SUCCESS; + } + + return STC__FAILURE; +} /* %%+HEAD: */ /*****************+***********+****************************************/ @@ -1435,103 +1399,105 @@ struct s_tcpcomm* ps_server; /*1- PLI Main ****************+****************************************/ /* %%-HEAD: */ -INTS4 f_stc_disperror( i_error , c_dest , i_out ) -INTS4 i_error; +INTS4 f_stc_disperror(i_error, c_dest, i_out) INTS4 i_error; CHARS* c_dest; INTS4 i_out; { - CHARS c_line[80]; - - switch( i_error ) { - case STC__FAILURE : - sprintf(c_line,"-I- f_stc failure"); - break; - case STC__SUCCESS : - sprintf(c_line,"-I- f_stc failure"); - break; - case STC__INVSOCK : - sprintf(c_line,"-I- f_stc invalid socket number"); - break; - case STC__INVBUF : - sprintf(c_line,"-I- f_stc buffer points outside allocated address space"); - break; - case STC__NGBUFSIZE : - sprintf(c_line,"-I- f_stc buffer length is negative"); - break; - case STC__INVTIME : - sprintf(c_line,"-I- f_stc time limit is negativ or to long"); - break; - case STC__TIMEOUT : - sprintf(c_line,"-I- f_stc timeout read data from socket"); - break; - case STC__NOTSOCK : - sprintf(c_line,"-I- f_stc socket number points to a file not a socket"); - break; - case STC__INVADDR : - sprintf(c_line,"-I- f_stc invalid address specified in parameter"); - break; - case STC__INVADDRF : - sprintf(c_line,"-I- f_stc the specified address family is not supported"); - break; - case STC__SOCKNSUP : - sprintf(c_line,"-I- f_stc The specified socket type is not supported."); - break; - case STC__INVPROTO : - sprintf(c_line,"-I- f_stc The specified protocol is not supported."); - break; - case STC__SOCKTABF : - sprintf(c_line,"-I- f_stc The per-process descriptor table is full."); - break; - case STC__SOCKSPAF : - sprintf(c_line,"-I- f_stc No buffer space is available. The socket can't be created"); - break; - case STC__SOCKISC : - sprintf(c_line,"-I- f_stc socket is already connected."); - break; - case STC__CONNTOUT : - sprintf(c_line,"-I- f_stc connection timed out without establishing a connection."); - break; - case STC__NETUNREA : - sprintf(c_line,"-I- f_stc The network is not reachable from this host."); - break; - case STC__PORTINUS : - sprintf(c_line,"-I- f_stc The specified Internet Address and port is already in use."); - break; - case STC__SOCKISP : - sprintf(c_line,"-I- f_stc socket address is protected."); - break; - case STC__ECONNREF : /* added 17.7.95, H.G. */ - sprintf(c_line,"-I- f_stc connection refused."); - break; - case TPS__ECPORTS : - sprintf(c_line,"-I- f_stc error connect portserver"); - break; - case TPS__EREGSERV : - sprintf(c_line,"-I- f_stc error register service at portserver"); - break; - case TPS__EWTOPORTS : - sprintf(c_line,"-I- f_stc error write buffer to portserver"); - break; - case TPS__ERMFRPORTS : - sprintf(c_line,"-I- f_stc error read status message from portserver"); - break; - case TPS__EGSERVICE : - sprintf(c_line,"-I- f_stc error get spec. info from portserver"); - break; - default: - sprintf(c_line,"-I- f_stc unknown message id %d",i_error); - if(i_out==0) { printf("%s\n",c_line); } - if(i_out==1) { strcpy(c_dest,c_line); } - return STC__FAILURE; - } /* end switch( i_error ) */ - - if(i_out==0) { printf("%s\n",c_line); } - if(i_out==1) { strcpy(c_dest,c_line); } - - return STC__SUCCESS; -} /* f_stc_disperror() */ - - - - + CHARS c_line[80]; + + switch (i_error) { + case STC__FAILURE: + sprintf(c_line, "-I- f_stc failure"); + break; + case STC__SUCCESS: + sprintf(c_line, "-I- f_stc failure"); + break; + case STC__INVSOCK: + sprintf(c_line, "-I- f_stc invalid socket number"); + break; + case STC__INVBUF: + sprintf(c_line, "-I- f_stc buffer points outside allocated address space"); + break; + case STC__NGBUFSIZE: + sprintf(c_line, "-I- f_stc buffer length is negative"); + break; + case STC__INVTIME: + sprintf(c_line, "-I- f_stc time limit is negativ or to long"); + break; + case STC__TIMEOUT: + sprintf(c_line, "-I- f_stc timeout read data from socket"); + break; + case STC__NOTSOCK: + sprintf(c_line, "-I- f_stc socket number points to a file not a socket"); + break; + case STC__INVADDR: + sprintf(c_line, "-I- f_stc invalid address specified in parameter"); + break; + case STC__INVADDRF: + sprintf(c_line, "-I- f_stc the specified address family is not supported"); + break; + case STC__SOCKNSUP: + sprintf(c_line, "-I- f_stc The specified socket type is not supported."); + break; + case STC__INVPROTO: + sprintf(c_line, "-I- f_stc The specified protocol is not supported."); + break; + case STC__SOCKTABF: + sprintf(c_line, "-I- f_stc The per-process descriptor table is full."); + break; + case STC__SOCKSPAF: + sprintf(c_line, "-I- f_stc No buffer space is available. The socket can't be created"); + break; + case STC__SOCKISC: + sprintf(c_line, "-I- f_stc socket is already connected."); + break; + case STC__CONNTOUT: + sprintf(c_line, "-I- f_stc connection timed out without establishing a connection."); + break; + case STC__NETUNREA: + sprintf(c_line, "-I- f_stc The network is not reachable from this host."); + break; + case STC__PORTINUS: + sprintf(c_line, "-I- f_stc The specified Internet Address and port is already in use."); + break; + case STC__SOCKISP: + sprintf(c_line, "-I- f_stc socket address is protected."); + break; + case STC__ECONNREF: /* added 17.7.95, H.G. */ + sprintf(c_line, "-I- f_stc connection refused."); + break; + case TPS__ECPORTS: + sprintf(c_line, "-I- f_stc error connect portserver"); + break; + case TPS__EREGSERV: + sprintf(c_line, "-I- f_stc error register service at portserver"); + break; + case TPS__EWTOPORTS: + sprintf(c_line, "-I- f_stc error write buffer to portserver"); + break; + case TPS__ERMFRPORTS: + sprintf(c_line, "-I- f_stc error read status message from portserver"); + break; + case TPS__EGSERVICE: + sprintf(c_line, "-I- f_stc error get spec. info from portserver"); + break; + default: + sprintf(c_line, "-I- f_stc unknown message id %d", i_error); + if (i_out == 0) { + printf("%s\n", c_line); + } + if (i_out == 1) { + strcpy(c_dest, c_line); + } + return STC__FAILURE; + } /* end switch( i_error ) */ + + if (i_out == 0) { + printf("%s\n", c_line); + } + if (i_out == 1) { + strcpy(c_dest, c_line); + } + return STC__SUCCESS; +} /* f_stc_disperror() */ diff --git a/MbsAPI/f_stccomm.h b/MbsAPI/f_stccomm.h index 240c016288..4d37d0d457 100644 --- a/MbsAPI/f_stccomm.h +++ b/MbsAPI/f_stccomm.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef F_STCCOMM @@ -11,64 +11,63 @@ #include "typedefs.h" /* typedef INTS1, INTS2, ... */ #ifndef OSK -INTS4 f_stc_connectserver (); -INTS4 f_stc_createserver (); -INTS4 f_stc_listenserver (); -INTS4 f_stc_acceptclient (); -INTS4 f_stc_disperror (); -INTS4 f_stc_read (); -INTS4 f_stc_write (); -INTS4 f_stc_close (); -INTS4 f_stc_discclient (); - -void f_stc_swap4 (INTS4*); +INTS4 f_stc_connectserver(); +INTS4 f_stc_createserver(); +INTS4 f_stc_listenserver(); +INTS4 f_stc_acceptclient(); +INTS4 f_stc_disperror(); +INTS4 f_stc_read(); +INTS4 f_stc_write(); +INTS4 f_stc_close(); +INTS4 f_stc_discclient(); + +void f_stc_swap4(INTS4*); #endif #ifdef GSI__WINNT -#include +#include #include -#include -#include +#include #include +#include +#include #include -#include -#define bzero(a,n) memset(a,0,n) +#define bzero(a, n) memset(a, 0, n) #endif /* **************** WINDOWS_NT ********************************/ - #ifdef VMS INTS4 SYS$TRNLNM(); #endif #ifdef _HPUX_SOURCE -#include #include -#include -#include -#include -#include +#include #include +#include #include -#include +#include +#include +#include #include +#include #endif #ifdef VMS -#include -#include +#include +#include #include -#include -#include -#include -#include #include -#include +#include +#include +#include #include -#include +#include +#include +#include /* * The maximum number of file descriptors is now a configurable option * (max_nofile variable in /sys/conf/{mips|vax}/param.c). @@ -79,127 +78,127 @@ INTS4 SYS$TRNLNM(); * programs that need a static sized array for selecting. These programs * should be modified to use the getdtablesize() interface for sizing. */ -#define MAX_NOFILE 4096 /* This should not exist ! */ -#define NBBY 8 /* number of bits in a byte */ +#define MAX_NOFILE 4096 /* This should not exist ! */ +#define NBBY 8 /* number of bits in a byte */ /* * Select uses bit masks of file descriptors in longs. * These macros manipulate such bit fields (the filesystem macros use chars). * FD_SETSIZE may be defined by the user, but the default here * should be >= NOFILE (param.h). */ -#ifndef FD_SETSIZE -#define FD_SETSIZE MAX_NOFILE -#endif /* FD_SETSIZE */ +#ifndef FD_SETSIZE +#define FD_SETSIZE MAX_NOFILE +#endif /* FD_SETSIZE */ /* How many things we'll allow select to use. 0 if unlimited */ -#define MAXSELFD MAX_NOFILE +#define MAXSELFD MAX_NOFILE /*typedef INTS4 fd_mask;*/ -#define NFDBITS (sizeof(fd_mask) * NBBY) /* bits per mask (power of 2!)*/ -#define NFDSHIFT 5 /* Shift based on above */ +#define NFDBITS (sizeof(fd_mask) * NBBY) /* bits per mask (power of 2!)*/ +#define NFDSHIFT 5 /* Shift based on above */ #ifndef howmany -#define howmany(x, y) (((x)+((y)-1))/(y)) +#define howmany(x, y) (((x) + ((y)-1)) / (y)) #endif /* howmany */ -#define bzero(a,n) memset(a,0,n) -#define FD_SET(n, p) ((p)->fds_bits[(n)/NFDBITS] |= (1 << ((n) % NFDBITS))) -#define FD_CLR(n, p) ((p)->fds_bits[(n)/NFDBITS] &= ~(1 << ((n) % NFDBITS))) -#define FD_ISSET(n, p) ((p)->fds_bits[(n)/NFDBITS] & (1 << ((n) % NFDBITS))) -#define FD_ZERO(p) bzero((INTS1 *)(p), sizeof(*(p))) +#define bzero(a, n) memset(a, 0, n) +#define FD_SET(n, p) ((p)->fds_bits[(n) / NFDBITS] |= (1 << ((n) % NFDBITS))) +#define FD_CLR(n, p) ((p)->fds_bits[(n) / NFDBITS] &= ~(1 << ((n) % NFDBITS))) +#define FD_ISSET(n, p) ((p)->fds_bits[(n) / NFDBITS] & (1 << ((n) % NFDBITS))) +#define FD_ZERO(p) bzero((INTS1*)(p), sizeof(*(p))) #endif /* VMS */ #ifdef OSK -#include #include -#include -#include -#include -#include #include #include +#include +#include +#include +#include +#include -struct timeval { - INTS4 tv_sec; - INTS4 tv_usec; +struct timeval +{ + INTS4 tv_sec; + INTS4 tv_usec; }; #endif /* OSK */ #ifdef ultrix -#include +#include #include -#include -#include -#include -#include #include +#include #include -#include +#include +#include +#include #include +#include #endif #ifdef Lynx -#include +#include #include -#include -#include -#include -#include -#include #include -#include +#include +#include +#include +#include +#include +#include #include #endif #ifdef GSI__LINUX #undef unix -#include +#include #include -#include +#include +#include +#include #include -#include #include #include #include -#include -#include -#include -#include +#include #include +#include +#include #endif #ifdef GSI__SOLARIS #undef unix -#include +#include #include -#include +#include +#include +#include #include -#include #include #include #include -#include -#include -#include -#include +#include #include +#include +#include #endif - #ifdef _AIX -#include +#include #include -#include +#include +#include +#include #include #include -#include -#include -#include -#include +#include #include -#define _ALL_SOURCE /* for types.h typedef u_char... */ -#define _POSIX_SOURCE /* any include is done */ +#include +#define _ALL_SOURCE /* for types.h typedef u_char... */ +#define _POSIX_SOURCE /* any include is done */ /* * The maximum number of file descriptors is now a configurable option @@ -211,26 +210,26 @@ struct timeval { * programs that need a static sized array for selecting. These programs * should be modified to use the getdtablesize() interface for sizing. */ -#define MAX_NOFILE 4096 /* This should not exist ! */ -#define NBBY 8 /* number of bits in a byte */ +#define MAX_NOFILE 4096 /* This should not exist ! */ +#define NBBY 8 /* number of bits in a byte */ /* * Select uses bit masks of file descriptors in longs. * These macros manipulate such bit fields (the filesystem macros use chars). * FD_SETSIZE may be defined by the user, but the default here * should be >= NOFILE (param.h). */ -#ifndef FD_SETSIZE -#define FD_SETSIZE MAX_NOFILE -#endif /* FD_SETSIZE */ +#ifndef FD_SETSIZE +#define FD_SETSIZE MAX_NOFILE +#endif /* FD_SETSIZE */ /* How many things we'll allow select to use. 0 if unlimited */ -#define MAXSELFD MAX_NOFILE -typedef INTS4 fd_mask; -#define NFDBITS (sizeof(fd_mask) * NBBY) /* bits per mask (power of 2!)*/ -#define NFDSHIFT 5 /* Shift based on above */ +#define MAXSELFD MAX_NOFILE +typedef INTS4 fd_mask; +#define NFDBITS (sizeof(fd_mask) * NBBY) /* bits per mask (power of 2!)*/ +#define NFDSHIFT 5 /* Shift based on above */ #ifndef howmany -#define howmany(x, y) (((x)+((y)-1))/(y)) +#define howmany(x, y) (((x) + ((y)-1)) / (y)) #endif /* howmany */ /* fd_set and FD_x are defined in time.h typedef struct fd_set { @@ -245,20 +244,20 @@ typedef struct fd_set { */ #endif /* AIX */ -#ifdef unix /* DEC OSF/1 */ -#include +#ifdef unix /* DEC OSF/1 */ +#include #include -#include +#include +#include +#include #include #include #include -#include -#include -#include -#include +#include #include -#define _ALL_SOURCE /* for types.h typedef u_char... */ -#define _POSIX_SOURCE /* any include is done */ +#include +#define _ALL_SOURCE /* for types.h typedef u_char... */ +#define _POSIX_SOURCE /* any include is done */ /* * The maximum number of file descriptors is now a configurable option @@ -270,26 +269,26 @@ typedef struct fd_set { * programs that need a static sized array for selecting. These programs * should be modified to use the getdtablesize() interface for sizing. */ -#define MAX_NOFILE 4096 /* This should not exist ! */ -#define NBBY 8 /* number of bits in a byte */ +#define MAX_NOFILE 4096 /* This should not exist ! */ +#define NBBY 8 /* number of bits in a byte */ /* * Select uses bit masks of file descriptors in longs. * These macros manipulate such bit fields (the filesystem macros use chars). * FD_SETSIZE may be defined by the user, but the default here * should be >= NOFILE (param.h). */ -#ifndef FD_SETSIZE -#define FD_SETSIZE MAX_NOFILE -#endif /* FD_SETSIZE */ +#ifndef FD_SETSIZE +#define FD_SETSIZE MAX_NOFILE +#endif /* FD_SETSIZE */ /* How many things we'll allow select to use. 0 if unlimited */ -#define MAXSELFD MAX_NOFILE +#define MAXSELFD MAX_NOFILE /*typedef INTS4 fd_mask;*/ -#define NFDBITS (sizeof(fd_mask) * NBBY) /* bits per mask (power of 2!)*/ -#define NFDSHIFT 5 /* Shift based on above */ +#define NFDBITS (sizeof(fd_mask) * NBBY) /* bits per mask (power of 2!)*/ +#define NFDSHIFT 5 /* Shift based on above */ #ifndef howmany -#define howmany(x, y) (((x)+((y)-1))/(y)) +#define howmany(x, y) (((x) + ((y)-1)) / (y)) #endif /* howmany */ /*typedef struct fd_set { @@ -297,105 +296,104 @@ typedef struct fd_set { } fd_set;*/ /*#define bzero(a,n) memset(a,0,n)*/ -#define FD_SET(n, p) ((p)->fds_bits[(n)/NFDBITS] |= (1 << ((n) % NFDBITS))) -#define FD_CLR(n, p) ((p)->fds_bits[(n)/NFDBITS] &= ~(1 << ((n) % NFDBITS))) -#define FD_ISSET(n, p) ((p)->fds_bits[(n)/NFDBITS] & (1 << ((n) % NFDBITS))) +#define FD_SET(n, p) ((p)->fds_bits[(n) / NFDBITS] |= (1 << ((n) % NFDBITS))) +#define FD_CLR(n, p) ((p)->fds_bits[(n) / NFDBITS] &= ~(1 << ((n) % NFDBITS))) +#define FD_ISSET(n, p) ((p)->fds_bits[(n) / NFDBITS] & (1 << ((n) % NFDBITS))) /*#define FD_ZERO(p) bzero((INTS1 *)(p), sizeof(*(p)))*/ #endif /* unix */ - -struct s_tcpcomm { - INTS4 socket , sock_rw , namelength ; - INTS4 i_signals; - struct sockaddr_in sock , sock_name; - struct hostent hostentstruct; - struct hostent* hostentptr; - INTS1 hostname[256] ; -} ; +struct s_tcpcomm +{ + INTS4 socket, sock_rw, namelength; + INTS4 i_signals; + struct sockaddr_in sock, sock_name; + struct hostent hostentstruct; + struct hostent* hostentptr; + INTS1 hostname[256]; +}; #ifdef vms -#define PORTSERV_DATA "portserv.dat;1" +#define PORTSERV_DATA "portserv.dat;1" #else -#define PORTSERV_DATA "portserv.dat" +#define PORTSERV_DATA "portserv.dat" #endif -#define MAXSERVER 50 -#define PORTSERVER_PORT 1000 -#define PORTSERVER_M_DEF "VSBP" -#define PORTSERVER_S_DEF "DSAG" +#define MAXSERVER 50 +#define PORTSERVER_PORT 1000 +#define PORTSERVER_M_DEF "VSBP" +#define PORTSERVER_S_DEF "DSAG" -struct s_comm_message { - INTS1 c_message[128]; - INTS1 c_status[12]; +struct s_comm_message +{ + INTS1 c_message[128]; + INTS1 c_status[12]; }; -struct s_comm_portserv { - INTS1 c_command[32]; - INTS1 c_serv_node[32]; - INTS1 c_serv_name[32]; - INTS1 c_date[32]; - INTS1 c_data[128]; - INTS1 c_port[8]; -} ; - +struct s_comm_portserv +{ + INTS1 c_command[32]; + INTS1 c_serv_node[32]; + INTS1 c_serv_name[32]; + INTS1 c_date[32]; + INTS1 c_data[128]; + INTS1 c_port[8]; +}; #ifdef vms -#include #include #include -#include -#include #include +#include +#include +#include +#include #include +#include #include -#include -#include -#define $DSC_FXDLEN(name,string) name.dsc$w_length = strlen(string); \ - strcpy(name.dsc$a_pointer,string); +#define $DSC_FXDLEN(name, string) \ + name.dsc$w_length = strlen(string); \ + strcpy(name.dsc$a_pointer, string); #endif /* VMS */ - -#define FALSE 0 -#define TRUE 1 -#define f_stc_nosig( ps_server ) (ps_server)->i_signals = 100; +#define FALSE 0 +#define TRUE 1 +#define f_stc_nosig(ps_server) (ps_server)->i_signals = 100; /* ********************************************************************** */ /* error messages */ /* ********************************************************************** */ -#define STC__FAILURE 0 -#define STC__SUCCESS 1 -#define STC__INVSOCK 2 -#define STC__INVBUF 3 -#define STC__NGBUFSIZE 4 -#define STC__INVTIME 5 -#define STC__TIMEOUT 6 -#define STC__NOTSOCK 7 -#define STC__INVADDR 8 -#define STC__INVADDRF 9 -#define STC__SOCKNSUP 10 -#define STC__INVPROTO 11 -#define STC__SOCKTABF 12 -#define STC__SOCKSPAF 13 -#define STC__SOCKISC 14 -#define STC__CONNTOUT 15 -#define STC__NETUNREA 16 -#define STC__PORTINUS 17 -#define STC__SOCKISP 18 -#define TPS__ECPORTS 19 -#define TPS__EREGSERV 20 -#define TPS__EWTOPORTS 21 +#define STC__FAILURE 0 +#define STC__SUCCESS 1 +#define STC__INVSOCK 2 +#define STC__INVBUF 3 +#define STC__NGBUFSIZE 4 +#define STC__INVTIME 5 +#define STC__TIMEOUT 6 +#define STC__NOTSOCK 7 +#define STC__INVADDR 8 +#define STC__INVADDRF 9 +#define STC__SOCKNSUP 10 +#define STC__INVPROTO 11 +#define STC__SOCKTABF 12 +#define STC__SOCKSPAF 13 +#define STC__SOCKISC 14 +#define STC__CONNTOUT 15 +#define STC__NETUNREA 16 +#define STC__PORTINUS 17 +#define STC__SOCKISP 18 +#define TPS__ECPORTS 19 +#define TPS__EREGSERV 20 +#define TPS__EWTOPORTS 21 #define TPS__ERMFRPORTS 22 -#define TPS__EGSERVICE 23 -#define STC__BROPIPE 24 -#define STC__NODATA 25 -#define STC__ECONNREF 26 -#define STC__EINTR 27 -#define STC__ECONNRES 28 +#define TPS__EGSERVICE 23 +#define STC__BROPIPE 24 +#define STC__NODATA 25 +#define STC__ECONNREF 26 +#define STC__EINTR 27 +#define STC__ECONNRES 28 -#define TCPCOMM_INCLUDE 1 +#define TCPCOMM_INCLUDE 1 #endif - - diff --git a/MbsAPI/f_ut_utime.c b/MbsAPI/f_ut_utime.c index b24cb0c9c5..9b33e16b42 100644 --- a/MbsAPI/f_ut_utime.c +++ b/MbsAPI/f_ut_utime.c @@ -53,79 +53,81 @@ #include #include #else -#include #include +#include #endif #include -#include #include +#include INTS4 f_ut_utime(INTS4 l_sec, INTS4 l_msec, CHARS* pc_time) { -// time_t t_time; - struct timeb tp; - struct tm st_time; - CHARS c_allmon[37]="JanFebMarAprMayJunJulAugSepOctNovDec"; - CHARS c_mon[4]; - CHARS* pc_mon; + // time_t t_time; + struct timeb tp; + struct tm st_time; + CHARS c_allmon[37] = "JanFebMarAprMayJunJulAugSepOctNovDec"; + CHARS c_mon[4]; + CHARS* pc_mon; - if(l_sec == 0) { - strcpy(pc_time,"no valid date"); + if (l_sec == 0) { + strcpy(pc_time, "no valid date"); #ifdef VMS - return(1); + return (1); #else - return(0); + return (0); #endif - } - *pc_time=0; - ftime(&tp); - if(l_sec > 0) { - tp.time = l_sec; - /* + } + *pc_time = 0; + ftime(&tp); + if (l_sec > 0) { + tp.time = l_sec; + /* #ifdef VMS tp.time = l_sec + 7200; #endif */ #ifdef xxxLynx - tp.time = l_sec + 86400; /* one day */ + tp.time = l_sec + 86400; /* one day */ #endif - tp.millitm = l_msec; - } + tp.millitm = l_msec; + } #ifdef xxxLynx - localtime_r(&st_time,&tp.time); - if(st_time.tm_mon > 2 && st_time.tm_mon < 9) { /* daylight saving ? */ - tp.time+=3600; - localtime_r(&st_time,&tp.time); - } + localtime_r(&st_time, &tp.time); + if (st_time.tm_mon > 2 && st_time.tm_mon < 9) { /* daylight saving ? */ + tp.time += 3600; + localtime_r(&st_time, &tp.time); + } #else - st_time = *localtime(&tp.time); + st_time = *localtime(&tp.time); #endif - pc_mon = (CHARS*) &c_allmon; - pc_mon += (st_time.tm_mon * 3); - strncpy(c_mon,pc_mon,3); - c_mon[3]='\0'; - if(st_time.tm_year < 100) - sprintf(pc_time,"%02d-%s-19%02d %02d:%02d:%02d.%02d" - ,st_time.tm_mday - ,c_mon - ,st_time.tm_year - ,st_time.tm_hour - ,st_time.tm_min - ,st_time.tm_sec - ,l_msec/10); - else - sprintf(pc_time,"%02d-%s-20%02d %02d:%02d:%02d.%02d" - ,st_time.tm_mday - ,c_mon - ,st_time.tm_year-100 - ,st_time.tm_hour - ,st_time.tm_min - ,st_time.tm_sec - ,l_msec/10); + pc_mon = (CHARS*)&c_allmon; + pc_mon += (st_time.tm_mon * 3); + strncpy(c_mon, pc_mon, 3); + c_mon[3] = '\0'; + if (st_time.tm_year < 100) + sprintf(pc_time, + "%02d-%s-19%02d %02d:%02d:%02d.%02d", + st_time.tm_mday, + c_mon, + st_time.tm_year, + st_time.tm_hour, + st_time.tm_min, + st_time.tm_sec, + l_msec / 10); + else + sprintf(pc_time, + "%02d-%s-20%02d %02d:%02d:%02d.%02d", + st_time.tm_mday, + c_mon, + st_time.tm_year - 100, + st_time.tm_hour, + st_time.tm_min, + st_time.tm_sec, + l_msec / 10); #ifdef VMS - return(1); + return (1); #else - return(0); + return (0); #endif } diff --git a/MbsAPI/portnum_def.h b/MbsAPI/portnum_def.h index 07ab5172e3..b24f99a3d8 100644 --- a/MbsAPI/portnum_def.h +++ b/MbsAPI/portnum_def.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "typedefs.h" @@ -10,19 +10,18 @@ * definitons of the port numbers used */ -#define PORT__TRANSPORT 6000 -#define PORT__ESONE_SERV 6001 -#define PORT__STREAM_SERV 6002 -#define PORT__EVENT_SERV 6003 -#define PORT__PROMPT 6004 -#define PORT__MSG_LOG 6005 -#define PORT__PROMPT_R 6006 -#define PORT__MSG_REM 6007 -#define PORT__STAT_SERV 6008 -#define PORT__HIST_SERV 6009 -#define MO__PORT_BASE 6100 /* m_ds and m_dr processes construct their -* necessary ports from this base. It requires, -* that ports 6100 - 6256 are reserved (if max - * nr of m_ds and m_dr nodes is defined to 16.*/ - - +#define PORT__TRANSPORT 6000 +#define PORT__ESONE_SERV 6001 +#define PORT__STREAM_SERV 6002 +#define PORT__EVENT_SERV 6003 +#define PORT__PROMPT 6004 +#define PORT__MSG_LOG 6005 +#define PORT__PROMPT_R 6006 +#define PORT__MSG_REM 6007 +#define PORT__STAT_SERV 6008 +#define PORT__HIST_SERV 6009 +#define MO__PORT_BASE \ + 6100 /* m_ds and m_dr processes construct their \ + * necessary ports from this base. It requires, \ + * that ports 6100 - 6256 are reserved (if max \ + * nr of m_ds and m_dr nodes is defined to 16.*/ diff --git a/MbsAPI/sMbs.h b/MbsAPI/sMbs.h index c40170da51..8c4422270c 100644 --- a/MbsAPI/sMbs.h +++ b/MbsAPI/sMbs.h @@ -1,42 +1,42 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef MbsStruct #define MbsStruct -#define LMD__TYPE_FILE_HEADER_101_1 0x00010065 -#define LMD__TYPE_EVENT_HEADER_10_1 0x0001000a -#define LMD__TYPE_FILE_INDEX_101_2 0x00020065 -#define LMD__TYPE_BUFFER_HEADER_10_1 0x0001000a +#define LMD__TYPE_FILE_HEADER_101_1 0x00010065 +#define LMD__TYPE_EVENT_HEADER_10_1 0x0001000a +#define LMD__TYPE_FILE_INDEX_101_2 0x00020065 +#define LMD__TYPE_BUFFER_HEADER_10_1 0x0001000a #define LMD__TYPE_BUFFER_HEADER_100_1 0x00010064 -#define LMD__TYPE_TIME_STAMP_11_1 0x0001000b -#define LMD__GET_EVENTS NULL -#define LMD__STANDARD_HEADER NULL -#define LMD__INTERNAL_HEADER NULL -#define LMD__INDEX 1 -#define LMD__OVERWRITE 1 -#define LMD__LARGE_FILE 1 -#define LMD__MIN_BUFFER 0 -#define LMD__BUFFER 1 -#define LMD__VERBOSE 1 -#define LMD__NO_VERBOSE 0 -#define LMD__NO_BUFFER 0 -#define LMD__NO_INDEX 0 -#define LMD__NO_OVERWRITE 0 +#define LMD__TYPE_TIME_STAMP_11_1 0x0001000b +#define LMD__GET_EVENTS NULL +#define LMD__STANDARD_HEADER NULL +#define LMD__INTERNAL_HEADER NULL +#define LMD__INDEX 1 +#define LMD__OVERWRITE 1 +#define LMD__LARGE_FILE 1 +#define LMD__MIN_BUFFER 0 +#define LMD__BUFFER 1 +#define LMD__VERBOSE 1 +#define LMD__NO_VERBOSE 0 +#define LMD__NO_BUFFER 0 +#define LMD__NO_INDEX 0 +#define LMD__NO_OVERWRITE 0 #define LMD__NO_LARGE_FILE 0 -#define LMD__NO_VERBOSE 0 -#define LMD__VERBOSE 1 +#define LMD__NO_VERBOSE 0 +#define LMD__VERBOSE 1 #define LMD__ENDIAN_LITTLE 1 -#define LMD__ENDIAN_BIG 2 +#define LMD__ENDIAN_BIG 2 #define LMD__ENDIAN_UNKNOWN 0 #include "s_stdint.h" -typedef uint64_t lmdoff_t; +typedef uint64_t lmdoff_t; // must #include // on Lynx, define int32_t, uint32_t, int16_t @@ -45,77 +45,84 @@ typedef uint64_t lmdoff_t; //-------------------------------------------------- // Structure maps the MBS transport info buffer -typedef struct { - uint32_t iEndian; // byte order. Set to 1 by sender - uint32_t iMaxBytes; // maximum buffer size - uint32_t iBuffers; // buffers per stream - uint32_t iStreams; // number of streams +typedef struct +{ + uint32_t iEndian; // byte order. Set to 1 by sender + uint32_t iMaxBytes; // maximum buffer size + uint32_t iBuffers; // buffers per stream + uint32_t iStreams; // number of streams } sMbsTransportInfo; //-------------------------------------------------- // Buffer header, maps s_bufhe, some fields used in different way -typedef struct { - uint32_t iMaxWords; // compatible with s_bufhe (total buffer size - header) - uint32_t iType; // compatible with s_bufhe, low=type (=100), high=subtype - uint32_t iUsed; // not used for iMaxWords>MAX__DLEN (16360), low 16bits only - uint32_t iBuffer; // compatible with s_bufhe - uint32_t iElements; // compatible with s_bufhe - uint32_t iTemp; // Used volatile - uint32_t iTimeSpecSec; // compatible with s_bufhe (2*32bit) - uint32_t iTimeSpecNanoSec; // compatible with s_bufhe (2*32bit) - // struct timespec TimeSpec; - uint32_t iEndian; // compatible with s_bufhe free[0] - uint32_t iWrittenEndian;// one of LMD__ENDIAN_x - uint32_t iUsedWords; // total words without header to read for type=100, free[2] - uint32_t iFree3; // free[3] +typedef struct +{ + uint32_t iMaxWords; // compatible with s_bufhe (total buffer size - header) + uint32_t iType; // compatible with s_bufhe, low=type (=100), high=subtype + uint32_t iUsed; // not used for iMaxWords>MAX__DLEN (16360), low 16bits only + uint32_t iBuffer; // compatible with s_bufhe + uint32_t iElements; // compatible with s_bufhe + uint32_t iTemp; // Used volatile + uint32_t iTimeSpecSec; // compatible with s_bufhe (2*32bit) + uint32_t iTimeSpecNanoSec; // compatible with s_bufhe (2*32bit) + // struct timespec TimeSpec; + uint32_t iEndian; // compatible with s_bufhe free[0] + uint32_t iWrittenEndian; // one of LMD__ENDIAN_x + uint32_t iUsedWords; // total words without header to read for type=100, free[2] + uint32_t iFree3; // free[3] } sMbsBufferHeader; //-------------------------------------------------- // Buffer header, maps s_bufhe -typedef struct { - uint32_t iMaxWords; // compatible with s_bufhe (total buffer size - header) - uint32_t iType; // compatible with s_bufhe, low=type (=100), high=subtype - lmdoff_t iTableOffset; // optional offset to element offset table in file - uint32_t iElements; // compatible with s_bufhe - uint32_t iOffsetSize; // Offset size, 4 or 8 [bytes] - uint32_t iTimeSpecSec; // compatible with s_bufhe (2*32bit) - uint32_t iTimeSpecNanoSec; // compatible with s_bufhe (2*32bit) - // struct timespec TimeSpec; - uint32_t iEndian; // compatible with s_bufhe free[0] - uint32_t iWrittenEndian;// one of LMD__ENDIAN_x - uint32_t iUsedWords; // total words without header to read for type=100, free[2] - uint32_t iFree3; // free[3] +typedef struct +{ + uint32_t iMaxWords; // compatible with s_bufhe (total buffer size - header) + uint32_t iType; // compatible with s_bufhe, low=type (=100), high=subtype + lmdoff_t iTableOffset; // optional offset to element offset table in file + uint32_t iElements; // compatible with s_bufhe + uint32_t iOffsetSize; // Offset size, 4 or 8 [bytes] + uint32_t iTimeSpecSec; // compatible with s_bufhe (2*32bit) + uint32_t iTimeSpecNanoSec; // compatible with s_bufhe (2*32bit) + // struct timespec TimeSpec; + uint32_t iEndian; // compatible with s_bufhe free[0] + uint32_t iWrittenEndian; // one of LMD__ENDIAN_x + uint32_t iUsedWords; // total words without header to read for type=100, free[2] + uint32_t iFree3; // free[3] } sMbsFileHeader; //-------------------------------------------------- -typedef struct { - uint32_t iMaxWords; - uint32_t iType; - uint32_t iTimeSpecSec; - uint32_t iTimeSpecNanoSec; +typedef struct +{ + uint32_t iMaxWords; + uint32_t iType; + uint32_t iTimeSpecSec; + uint32_t iTimeSpecNanoSec; } sMbsTimeStamp; //-------------------------------------------------- // maps s_evhe -typedef struct { - uint32_t iWords; // following data words - uint32_t iType; // compatible with s_ve10_1, low=type (=10), high=subtype +typedef struct +{ + uint32_t iWords; // following data words + uint32_t iType; // compatible with s_ve10_1, low=type (=10), high=subtype } sMbsHeader; //-------------------------------------------------- // maps s_ve10_1 -typedef struct { - uint32_t iWords; // data words + 4 - uint32_t iType; // compatible with s_ve10_1, low=type (=10), high=subtype - uint32_t iTrigger; - uint32_t iEventNumber; +typedef struct +{ + uint32_t iWords; // data words + 4 + uint32_t iType; // compatible with s_ve10_1, low=type (=10), high=subtype + uint32_t iTrigger; + uint32_t iEventNumber; } sMbsEventHeader; //-------------------------------------------------- // maps s_ves10_1 -typedef struct { - uint32_t iWords; // data words + 2 - uint32_t iType; // compatible with s_ves10_1, low=type (=10), high=subtype - uint32_t iSubeventID; // 2 low bytes=procid, next byte=subcrate, high byte control +typedef struct +{ + uint32_t iWords; // data words + 2 + uint32_t iType; // compatible with s_ves10_1, low=type (=10), high=subtype + uint32_t iSubeventID; // 2 low bytes=procid, next byte=subcrate, high byte control } sMbsSubeventHeader; #endif diff --git a/MbsAPI/s_bufhe.h b/MbsAPI/s_bufhe.h index a6666769fd..e01293e919 100644 --- a/MbsAPI/s_bufhe.h +++ b/MbsAPI/s_bufhe.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ @@ -17,34 +17,36 @@ #if MBS_ENDIAN == 1 -typedef struct { - INTS4 l_dlen; /* Length of data field in words */ - INTS2 i_subtype; - INTS2 i_type; - CHARS h_begin; /* Fragment at end of buffer */ - CHARS h_end; /* Fragment at begin of buffer */ - INTS2 i_used; /* Used length of data field in words */ - INTS4 l_buf; /* Current buffer number */ - INTS4 l_evt; /* Number of fragments */ - INTS4 l_current_i; /* Index, temporarily used */ - INTS4 l_time[2]; - INTS4 l_free[4]; +typedef struct +{ + INTS4 l_dlen; /* Length of data field in words */ + INTS2 i_subtype; + INTS2 i_type; + CHARS h_begin; /* Fragment at end of buffer */ + CHARS h_end; /* Fragment at begin of buffer */ + INTS2 i_used; /* Used length of data field in words */ + INTS4 l_buf; /* Current buffer number */ + INTS4 l_evt; /* Number of fragments */ + INTS4 l_current_i; /* Index, temporarily used */ + INTS4 l_time[2]; + INTS4 l_free[4]; } s_bufhe; #else -typedef struct { - INTS4 l_dlen; /* Length of data field in words */ - INTS2 i_type; - INTS2 i_subtype; - INTS2 i_used; /* Used length of data field in words */ - CHARS h_end; /* Fragment at begin of buffer */ - CHARS h_begin; /* Fragment at end of buffer */ - INTS4 l_buf; /* Current buffer number */ - INTS4 l_evt; /* Number of fragments */ - INTS4 l_current_i; /* Index, temporarily used */ - INTS4 l_time[2]; - INTS4 l_free[4]; +typedef struct +{ + INTS4 l_dlen; /* Length of data field in words */ + INTS2 i_type; + INTS2 i_subtype; + INTS2 i_used; /* Used length of data field in words */ + CHARS h_end; /* Fragment at begin of buffer */ + CHARS h_begin; /* Fragment at end of buffer */ + INTS4 l_buf; /* Current buffer number */ + INTS4 l_evt; /* Number of fragments */ + INTS4 l_current_i; /* Index, temporarily used */ + INTS4 l_time[2]; + INTS4 l_free[4]; } s_bufhe; #endif diff --git a/MbsAPI/s_bufhe_swap.h b/MbsAPI/s_bufhe_swap.h index fd29bbf598..d17153acd0 100644 --- a/MbsAPI/s_bufhe_swap.h +++ b/MbsAPI/s_bufhe_swap.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef F_BUFHE_SWAP diff --git a/MbsAPI/s_evhe.h b/MbsAPI/s_evhe.h index c2f933a4e5..fde906fc1f 100644 --- a/MbsAPI/s_evhe.h +++ b/MbsAPI/s_evhe.h @@ -1,12 +1,11 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ - #ifndef S_EVHE #define S_EVHE @@ -15,19 +14,21 @@ #if MBS_ENDIAN == 1 /* ================= GSI VME General event header =============== */ -typedef struct { - INTS4 l_dlen; /* Length of data in words */ - INTS2 i_subtype; - INTS2 i_type; +typedef struct +{ + INTS4 l_dlen; /* Length of data in words */ + INTS2 i_subtype; + INTS2 i_type; } s_evhe; /* ------------------------------------------------------------------ */ #else -typedef struct { - INTS4 l_dlen; /* Length of data in words */ - INTS2 i_type; - INTS2 i_subtype; +typedef struct +{ + INTS4 l_dlen; /* Length of data in words */ + INTS2 i_type; + INTS2 i_subtype; } s_evhe; #endif diff --git a/MbsAPI/s_evhe_swap.h b/MbsAPI/s_evhe_swap.h index 6518e88ec4..29c6790e85 100644 --- a/MbsAPI/s_evhe_swap.h +++ b/MbsAPI/s_evhe_swap.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef S_EVHE_SWAP diff --git a/MbsAPI/s_filhe.h b/MbsAPI/s_filhe.h index 27c161f9c3..cf9da8a873 100644 --- a/MbsAPI/s_filhe.h +++ b/MbsAPI/s_filhe.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ @@ -11,66 +11,68 @@ #include "typedefs.h" -struct cv_string { - INTS2 string_l; - CHARS string[78]; -} ; - +struct cv_string +{ + INTS2 string_l; + CHARS string[78]; +}; #if MBS_ENDIAN == 1 -typedef struct { - INTS4 filhe_dlen; /* length of data in words */ - INTS2 filhe_subtype; /* = 1 */ - INTS2 filhe_type; /* = 2000 */ - INTS2 filhe_frag; - INTS2 filhe_used; - INTS4 filhe_buf; - INTS4 filhe_evt; - INTS4 filhe_current_i; - INTS4 filhe_stime[2]; - INTS4 filhe_free[4]; /* free[0] = 1 -> swap */ - INTS2 filhe_label_l; /* length of tape label string */ - CHARS filhe_label[30]; /* tape label */ - INTS2 filhe_file_l; /* length of file name */ - CHARS filhe_file[86]; /* file name */ - INTS2 filhe_user_l; /* length of user name */ - CHARS filhe_user[30]; /* user name */ - CHARS filhe_time[24]; /* date and time string */ - INTS2 filhe_run_l; /* length of run id */ - CHARS filhe_run[66]; /* run id */ - INTS2 filhe_exp_l; /* length of explanation */ - CHARS filhe_exp[66]; /* explanation */ - INTS4 filhe_lines; /* # of comment lines */ - struct cv_string s_strings[30]; /* max 30 comment lines */ +typedef struct +{ + INTS4 filhe_dlen; /* length of data in words */ + INTS2 filhe_subtype; /* = 1 */ + INTS2 filhe_type; /* = 2000 */ + INTS2 filhe_frag; + INTS2 filhe_used; + INTS4 filhe_buf; + INTS4 filhe_evt; + INTS4 filhe_current_i; + INTS4 filhe_stime[2]; + INTS4 filhe_free[4]; /* free[0] = 1 -> swap */ + INTS2 filhe_label_l; /* length of tape label string */ + CHARS filhe_label[30]; /* tape label */ + INTS2 filhe_file_l; /* length of file name */ + CHARS filhe_file[86]; /* file name */ + INTS2 filhe_user_l; /* length of user name */ + CHARS filhe_user[30]; /* user name */ + CHARS filhe_time[24]; /* date and time string */ + INTS2 filhe_run_l; /* length of run id */ + CHARS filhe_run[66]; /* run id */ + INTS2 filhe_exp_l; /* length of explanation */ + CHARS filhe_exp[66]; /* explanation */ + INTS4 filhe_lines; /* # of comment lines */ + struct cv_string s_strings[30]; /* max 30 comment lines */ } s_filhe; #else -typedef struct { - INTS4 filhe_dlen; /* length of data in words */ - INTS2 filhe_type; /* = 2000 */ - INTS2 filhe_subtype; /* = 1 */ - INTS2 filhe_used; - INTS2 filhe_frag; - INTS4 filhe_buf; - INTS4 filhe_evt; - INTS4 filhe_current_i; - INTS4 filhe_stime[2]; - INTS4 filhe_free[4]; /* free[0] = 1 -> swap */ - INTS2 filhe_label_l; /* length of tape label string */ - CHARS filhe_label[30]; /* tape label */ - INTS2 filhe_file_l; /* length of file name */ - CHARS filhe_file[86]; /* file name */ - INTS2 filhe_user_l; /* length of user name */ - CHARS filhe_user[30]; /* user name */ - CHARS filhe_time[24]; /* date and time string */ - INTS2 filhe_run_l; /* length of run id */ - CHARS filhe_run[66]; /* run id */ - INTS2 filhe_exp_l; /* length of explanation */ - CHARS filhe_exp[66]; /* explanation */ - INTS4 filhe_lines; /* # of comment lines */ - struct cv_string s_strings[30]; /* max 30 comment lines */ +typedef struct +{ + INTS4 filhe_dlen; /* length of data in words */ + INTS2 filhe_type; /* = 2000 */ + INTS2 filhe_subtype; /* = 1 */ + INTS2 filhe_used; + INTS2 filhe_frag; + INTS4 filhe_buf; + INTS4 filhe_evt; + INTS4 filhe_current_i; + INTS4 filhe_stime[2]; + INTS4 filhe_free[4]; /* free[0] = 1 -> swap */ + INTS2 filhe_label_l; /* length of tape label string */ + CHARS filhe_label[30]; /* tape label */ + INTS2 filhe_file_l; /* length of file name */ + CHARS filhe_file[86]; /* file name */ + INTS2 filhe_user_l; /* length of user name */ + CHARS filhe_user[30]; /* user name */ + CHARS filhe_time[24]; /* date and time string */ + INTS2 filhe_run_l; /* length of run id */ + CHARS filhe_run[66]; /* run id */ + INTS2 filhe_exp_l; /* length of explanation */ + CHARS filhe_exp[66]; /* explanation */ + INTS4 filhe_lines; /* # of comment lines */ + struct cv_string s_strings[30]; /* max 30 comment lines */ } s_filhe; #endif diff --git a/MbsAPI/s_filhe_swap.h b/MbsAPI/s_filhe_swap.h index 1776693de2..9235fd8194 100644 --- a/MbsAPI/s_filhe_swap.h +++ b/MbsAPI/s_filhe_swap.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ diff --git a/MbsAPI/s_stdint.h b/MbsAPI/s_stdint.h index 6457461b03..b81ffddf06 100644 --- a/MbsAPI/s_stdint.h +++ b/MbsAPI/s_stdint.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef S_STDINT_H @@ -19,27 +19,27 @@ #include #include -typedef __int8 int8_t; -typedef __int16 int16_t; -typedef __int32 int32_t; -typedef __int64 int64_t; -typedef unsigned __int8 uint8_t; -typedef unsigned __int16 uint16_t; -typedef unsigned __int32 uint32_t; -typedef unsigned __int64 uint64_t; +typedef __int8 int8_t; +typedef __int16 int16_t; +typedef __int32 int32_t; +typedef __int64 int64_t; +typedef unsigned __int8 uint8_t; +typedef unsigned __int16 uint16_t; +typedef unsigned __int32 uint32_t; +typedef unsigned __int64 uint64_t; #endif #ifdef Lynx -typedef char int8_t; -typedef unsigned char uint8_t; -typedef short int16_t; +typedef char int8_t; +typedef unsigned char uint8_t; +typedef short int16_t; typedef unsigned short uint16_t; -typedef int int32_t; -typedef unsigned int uint32_t; -typedef long int64_t; -typedef unsigned long uint64_t; +typedef int int32_t; +typedef unsigned int uint32_t; +typedef long int64_t; +typedef unsigned long uint64_t; #endif @@ -55,5 +55,4 @@ typedef unsigned long uint64_t; #include #endif - #endif diff --git a/MbsAPI/s_ve10_1.h b/MbsAPI/s_ve10_1.h index c329b3d1f3..21718fa5f5 100644 --- a/MbsAPI/s_ve10_1.h +++ b/MbsAPI/s_ve10_1.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef S_VE10_1 @@ -13,25 +13,27 @@ #if MBS_ENDIAN == 1 -typedef struct { - INTS4 l_dlen; /* Data length + 4 in words */ - INTS2 i_subtype; - INTS2 i_type; - INTS2 i_trigger; /* Trigger number */ - INTS2 i_dummy; /* Not used yet */ - INTS4 l_count; /* Current event number */ +typedef struct +{ + INTS4 l_dlen; /* Data length + 4 in words */ + INTS2 i_subtype; + INTS2 i_type; + INTS2 i_trigger; /* Trigger number */ + INTS2 i_dummy; /* Not used yet */ + INTS4 l_count; /* Current event number */ } s_ve10_1; /* ------------------------------------------------------------------ */ #else -typedef struct { - INTS4 l_dlen; /* Data length + 4 in words */ - INTS2 i_type; - INTS2 i_subtype; - INTS2 i_dummy; /* Not used yet */ - INTS2 i_trigger; /* Trigger number */ - INTS4 l_count; /* Current event number */ +typedef struct +{ + INTS4 l_dlen; /* Data length + 4 in words */ + INTS2 i_type; + INTS2 i_subtype; + INTS2 i_dummy; /* Not used yet */ + INTS2 i_trigger; /* Trigger number */ + INTS4 l_count; /* Current event number */ } s_ve10_1; #endif diff --git a/MbsAPI/s_ve10_1_swap.h b/MbsAPI/s_ve10_1_swap.h index 9b2b40873b..5d743ee17d 100644 --- a/MbsAPI/s_ve10_1_swap.h +++ b/MbsAPI/s_ve10_1_swap.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef S_VE10_1_SWAP diff --git a/MbsAPI/s_ves10_1.h b/MbsAPI/s_ves10_1.h index c0f3b3ca96..cb402e55a6 100644 --- a/MbsAPI/s_ves10_1.h +++ b/MbsAPI/s_ves10_1.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef S_VES10_1 @@ -13,26 +13,28 @@ #if MBS_ENDIAN == 1 -typedef struct { - INTS4 l_dlen; /* Data length +2 in words */ - INTS2 i_subtype; - INTS2 i_type; - CHARS h_control; /* Processor type code */ - CHARS h_subcrate; /* Subcrate number */ - INTS2 i_procid; /* Processor ID [as loaded from VAX] */ -} s_ves10_1 ; +typedef struct +{ + INTS4 l_dlen; /* Data length +2 in words */ + INTS2 i_subtype; + INTS2 i_type; + CHARS h_control; /* Processor type code */ + CHARS h_subcrate; /* Subcrate number */ + INTS2 i_procid; /* Processor ID [as loaded from VAX] */ +} s_ves10_1; /* ------------------------------------------------------------------ */ #else -typedef struct { - INTS4 l_dlen; /* Data length +2 in words */ - INTS2 i_type; - INTS2 i_subtype; - INTS2 i_procid; /* Processor ID [as loaded from VAX] */ - CHARS h_subcrate; /* Subcrate number */ - CHARS h_control; /* Processor type code */ -} s_ves10_1 ; +typedef struct +{ + INTS4 l_dlen; /* Data length +2 in words */ + INTS2 i_type; + INTS2 i_subtype; + INTS2 i_procid; /* Processor ID [as loaded from VAX] */ + CHARS h_subcrate; /* Subcrate number */ + CHARS h_control; /* Processor type code */ +} s_ves10_1; #endif diff --git a/MbsAPI/s_ves10_1_swap.h b/MbsAPI/s_ves10_1_swap.h index aad04f7c3d..7fde4ac7ff 100644 --- a/MbsAPI/s_ves10_1_swap.h +++ b/MbsAPI/s_ves10_1_swap.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef S_VES10_1_SWAP diff --git a/MbsAPI/typedefs.h b/MbsAPI/typedefs.h index 50811f989a..cb2dae3fe6 100644 --- a/MbsAPI/typedefs.h +++ b/MbsAPI/typedefs.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* This central include file defines data types for all platforms */ @@ -12,16 +12,16 @@ /* Platform independent definitions */ -typedef char CHARS; -typedef unsigned char CHARU; -typedef char INTS1; -typedef unsigned char INTU1; -typedef short INTS2; -typedef unsigned short INTU2; -typedef int INTS4; -typedef unsigned int INTU4; -typedef float REAL4; -typedef double REAL8; +typedef char CHARS; +typedef unsigned char CHARU; +typedef char INTS1; +typedef unsigned char INTU1; +typedef short INTS2; +typedef unsigned short INTU2; +typedef int INTS4; +typedef unsigned int INTU4; +typedef float REAL4; +typedef double REAL8; /* Platform specific definitions */ @@ -32,7 +32,6 @@ typedef double REAL8; typedef unsigned long ADDRS; #endif - #ifdef Linux #define MBS_ENDIAN 0 /* little endian */ #define GSI__LINUX @@ -47,7 +46,6 @@ typedef unsigned long ADDRS; typedef unsigned long ADDRS; #endif - #ifdef Darwin #define MBS_ENDIAN 0 /* little endian */ #define GSI__LINUX @@ -55,12 +53,11 @@ typedef unsigned long ADDRS; typedef unsigned long ADDRS; #endif - #ifdef _AIX #define MBS_ENDIAN 1 /* big endian */ #define GSI__AIX #define GSI__UNIX -typedef long long INTS8; +typedef long long INTS8; typedef unsigned long long INTU8; typedef unsigned long ADDRS; #endif @@ -71,34 +68,34 @@ typedef unsigned long ADDRS; #define AXP #define GSI__UNIX_AXP #define GSI__UNIX -typedef long INTS8; +typedef long INTS8; typedef unsigned long INTU8; typedef unsigned long ADDRS; #endif #endif #ifdef _HPUX_SOURCE -#define MBS_ENDIAN 1 /* big endian */ +#define MBS_ENDIAN 1 /* big endian */ #define GSI__HPUX #define GSI__UNIX -typedef long INTS8; +typedef long INTS8; typedef unsigned long INTU8; typedef unsigned long ADDRS; #endif #ifdef Lynx -#define MBS_ENDIAN 1 /* big endian */ +#define MBS_ENDIAN 1 /* big endian */ #define GSI__LYNX #define GSI__UNIX -typedef long INTS8; +typedef long INTS8; typedef unsigned long INTU8; typedef unsigned long ADDRS; #endif #ifdef VMS -#define MBS_ENDIAN 0 /* little endian */ +#define MBS_ENDIAN 0 /* little endian */ #define GSI__VMS -typedef long INTS8; +typedef long INTS8; typedef unsigned long INTU8; typedef unsigned long ADDRS; #ifdef __alpha @@ -110,5 +107,4 @@ typedef unsigned long ADDRS; #endif #endif - #endif diff --git a/alignment/FairAlignmentHandler.cxx b/alignment/FairAlignmentHandler.cxx index 611ef5f85f..5e8bf25403 100644 --- a/alignment/FairAlignmentHandler.cxx +++ b/alignment/FairAlignmentHandler.cxx @@ -5,88 +5,91 @@ #include #include -FairAlignmentHandler::FairAlignmentHandler() { -} +FairAlignmentHandler::FairAlignmentHandler() {} -FairAlignmentHandler::~FairAlignmentHandler() { -} +FairAlignmentHandler::~FairAlignmentHandler() {} -void FairAlignmentHandler::AlignGeometry() const { - if (fAlignmentMatrices.size() > 0) { - LOG(info) << "aligning the geometry..."; +void FairAlignmentHandler::AlignGeometry() const +{ + if (fAlignmentMatrices.size() > 0) { + LOG(info) << "aligning the geometry..."; - LOG(info) << "aligning in total " << fAlignmentMatrices.size() << " volumes."; - if (gGeoManager->GetNAlignable() > 0) { - AlignGeometryBySymlink(); - } else { - AlignGeometryByFullPath(); - } + LOG(info) << "aligning in total " << fAlignmentMatrices.size() << " volumes."; + if (gGeoManager->GetNAlignable() > 0) { + AlignGeometryBySymlink(); + } else { + AlignGeometryByFullPath(); + } - LOG(info) << "alignment finished!"; - } + LOG(info) << "alignment finished!"; + } } -void FairAlignmentHandler::AlignGeometryByFullPath() const { - TString volume_path; - - LOG(info)<< "aligning using full path."; - for (auto const& alignment_entry : fAlignmentMatrices) { - volume_path = alignment_entry.first; +void FairAlignmentHandler::AlignGeometryByFullPath() const +{ + TString volume_path; - gGeoManager->cd(volume_path); + LOG(info) << "aligning using full path."; + for (auto const& alignment_entry : fAlignmentMatrices) { + volume_path = alignment_entry.first; - TGeoNode* volume_node = gGeoManager->GetCurrentNode(); - TGeoMatrix* volume_matrix = volume_node->GetMatrix(); - // Need to do this as since ROOT 6.14 TGeoMatrix has no multiplication operator anymore - // it is implimnted now in TGeoHMatrix + gGeoManager->cd(volume_path); - TGeoHMatrix local_volume_matrix = TGeoHMatrix(*volume_matrix); + TGeoNode* volume_node = gGeoManager->GetCurrentNode(); + TGeoMatrix* volume_matrix = volume_node->GetMatrix(); + // Need to do this as since ROOT 6.14 TGeoMatrix has no multiplication operator anymore + // it is implimnted now in TGeoHMatrix - TGeoHMatrix* new_volume_matrix = new TGeoHMatrix(local_volume_matrix * alignment_entry.second); - // new matrix, representing real position (from new local mis RS to the global one) + TGeoHMatrix local_volume_matrix = TGeoHMatrix(*volume_matrix); - TGeoPhysicalNode* pn = gGeoManager->MakePhysicalNode(volume_path); + TGeoHMatrix* new_volume_matrix = new TGeoHMatrix(local_volume_matrix * alignment_entry.second); + // new matrix, representing real position (from new local mis RS to the global one) - pn->Align(new_volume_matrix); - } - LOG(info)<< "alignments applied!"; -} - -void FairAlignmentHandler::AlignGeometryBySymlink() const { - TString volume_path; - - LOG(info)<< "aligning using symlinks"; - for (auto const& alignment_entry : fAlignmentMatrices) { - volume_path = alignment_entry.first; + TGeoPhysicalNode* pn = gGeoManager->MakePhysicalNode(volume_path); - TGeoPhysicalNode* node = NULL; - TGeoPNEntry* entry = gGeoManager->GetAlignableEntry(volume_path); - if (entry) { - node = gGeoManager->MakeAlignablePN(entry); + pn->Align(new_volume_matrix); } + LOG(info) << "alignments applied!"; +} - TGeoMatrix* volume_matrix = NULL; - if (node) { - volume_matrix = node->GetMatrix(); - } else { - continue; +void FairAlignmentHandler::AlignGeometryBySymlink() const +{ + TString volume_path; + + LOG(info) << "aligning using symlinks"; + for (auto const& alignment_entry : fAlignmentMatrices) { + volume_path = alignment_entry.first; + + TGeoPhysicalNode* node = NULL; + TGeoPNEntry* entry = gGeoManager->GetAlignableEntry(volume_path); + if (entry) { + node = gGeoManager->MakeAlignablePN(entry); + } + + TGeoMatrix* volume_matrix = NULL; + if (node) { + volume_matrix = node->GetMatrix(); + } else { + continue; + } + // Need to do this as since ROOT 6.14 TGeoMatrix has no multiplication operator anymore + // it is implimnted now in TGeoHMatrix + TGeoHMatrix local_volume_matrix = TGeoHMatrix(*volume_matrix); + + TGeoHMatrix* new_volume_matrix = new TGeoHMatrix(local_volume_matrix * alignment_entry.second); + // new matrix, representing real position (from new local mis RS to the global one) + node->Align(new_volume_matrix); } - // Need to do this as since ROOT 6.14 TGeoMatrix has no multiplication operator anymore - // it is implimnted now in TGeoHMatrix - TGeoHMatrix local_volume_matrix = TGeoHMatrix(*volume_matrix); - - TGeoHMatrix* new_volume_matrix = new TGeoHMatrix(local_volume_matrix * alignment_entry.second); - // new matrix, representing real position (from new local mis RS to the global one) - node->Align(new_volume_matrix); - } } -void FairAlignmentHandler::AddAlignmentMatrices(const std::map& alignmentMatrices, bool invertMatrices) { - LOG(info) << "adding inverting matrices..."; - for (auto const& m : alignmentMatrices) { - if (invertMatrices) - fAlignmentMatrices[m.first] *= m.second.Inverse(); - else - fAlignmentMatrices[m.first] *= m.second; - } +void FairAlignmentHandler::AddAlignmentMatrices(const std::map& alignmentMatrices, + bool invertMatrices) +{ + LOG(info) << "adding inverting matrices..."; + for (auto const& m : alignmentMatrices) { + if (invertMatrices) + fAlignmentMatrices[m.first] *= m.second.Inverse(); + else + fAlignmentMatrices[m.first] *= m.second; + } } diff --git a/alignment/FairAlignmentHandler.h b/alignment/FairAlignmentHandler.h index 184726e38c..1bae25bd78 100644 --- a/alignment/FairAlignmentHandler.h +++ b/alignment/FairAlignmentHandler.h @@ -1,11 +1,11 @@ #ifndef FAIR_ALIGNMENTHANDLER_H #define FAIR_ALIGNMENTHANDLER_H -#include - #include +#include -class FairAlignmentHandler { +class FairAlignmentHandler +{ friend class FairRun; std::map fAlignmentMatrices; diff --git a/apply-format.sh b/apply-format.sh new file mode 100755 index 0000000000..12f7369609 --- /dev/null +++ b/apply-format.sh @@ -0,0 +1,7 @@ +#!/bin/bash + +CLANG_FORMAT_BIN=${FAIRROOT_CLANG_FORMAT_BIN:-clang-format} + +FILES=$(find . -type f \( -iname "*.h" ! -iname "*.pb.h" ! -iname "*LinkDef.h" -o -iname "*.hpp" -o -iname "*.cxx" -o -iname "*.cpp" -o -iname "*.tpl" -o -iname "*.c" -o -iname "*.C" \) -not \( -path "./build/*" -o -path "./cmake/*" -prune \)) + +$CLANG_FORMAT_BIN -i $FILES --verbose diff --git a/base/MQ/baseMQtools/baseMQtools.h b/base/MQ/baseMQtools/baseMQtools.h index adc26601a1..c1629f57e1 100644 --- a/base/MQ/baseMQtools/baseMQtools.h +++ b/base/MQ/baseMQtools/baseMQtools.h @@ -1,4 +1,4 @@ -/* +/* * File: baseMQtools.h * Author: winckler * @@ -10,9 +10,9 @@ // std #include -#include -#include #include +#include +#include // boost #include @@ -20,29 +20,28 @@ // FairRoot - FairMQ #include "FairLogger.h" -namespace baseMQ -{ -namespace tools -{ +namespace baseMQ { +namespace tools { /// ///////////////////////// to print tuple elements //////////////////////////////////////////// /// Define a type which holds an unsigned integer value template -struct int_{}; +struct int_ +{}; -template -std::ostream& print_tuple(std::ostream& out, const Tuple& t, int_ ) +template +std::ostream& print_tuple(std::ostream& out, const Tuple& t, int_) { - out << std::get< std::tuple_size::value-Pos >(t) << ','; - return print_tuple(out, t, int_()); + out << std::get::value - Pos>(t) << ','; + return print_tuple(out, t, int_()); } -template -std::ostream& print_tuple(std::ostream& out, const Tuple& t, int_<1> ) +template +std::ostream& print_tuple(std::ostream& out, const Tuple& t, int_<1>) { - return out << std::get::value-1>(t); + return out << std::get::value - 1>(t); } -template +template std::ostream& operator<<(std::ostream& out, const std::tuple& t) { out << '('; @@ -50,40 +49,46 @@ std::ostream& operator<<(std::ostream& out, const std::tuple& t) return out << ')'; } -namespace resolve -{ +namespace resolve { /// test function member signature in given class -namespace details -{ +namespace details { // test whether T has SetFileProperties member function template -struct has_SetFileProperties : std::false_type{}; +struct has_SetFileProperties : std::false_type +{}; template -struct has_SetFileProperties().SetFileProperties(std::declval()...)), R>::value - || std::is_same::value // all return types are compatible with void - // and, due to SFINAE, we can invoke T.foo(Args...) (otherwise previous clause fails) - >::type - >:std::true_type{}; + || std::is_same::value // all return types are compatible with void + // and, due to SFINAE, we can invoke T.foo(Args...) (otherwise previous clause + // fails) + >::type> : std::true_type +{}; // test whether T has InitTClonesArray member function template -struct has_InitTClonesArray : std::false_type{}; +struct has_InitTClonesArray : std::false_type +{}; template -struct has_InitTClonesArray().InitTClonesArray(std::declval()...)), R>::value - || std::is_same::value // all return types are compatible with void - // and, due to SFINAE, we can invoke T.foo(Args...) (otherwise previous clause fails) - >::type - >:std::true_type{}; + || std::is_same::value // all return types are compatible with void + // and, due to SFINAE, we can invoke T.foo(Args...) (otherwise previous clause + // fails) + >::type> : std::true_type +{}; -} // end namespace details +} // end namespace details template using has_SetFileProperties = std::integral_constant::value>; @@ -91,81 +96,58 @@ using has_SetFileProperties = std::integral_constant using has_InitTClonesArray = std::integral_constant::value>; -} // end namespace resolve +} // end namespace resolve -namespace typeinfo -{ -template +namespace typeinfo { +template void DataTypeInfo(std::string classname) { LOG(info) << "Info on type " << classname; - if (std::is_class::value) - { + if (std::is_class::value) { - if (std::is_pod::value) - { - LOG(info) << classname << " is POD" ; - } - else - { - LOG(info) << classname << " is not POD" ; + if (std::is_pod::value) { + LOG(info) << classname << " is POD"; + } else { + LOG(info) << classname << " is not POD"; } - - if (std::is_trivial::value) - { - LOG(info) << classname << " is trivial" ; - } - else - { - LOG(info) << classname << " is not trivial" ; + if (std::is_trivial::value) { + LOG(info) << classname << " is trivial"; + } else { + LOG(info) << classname << " is not trivial"; } - // below commented because not yet implemented in gcc - //if(std::is_trivially_copyable::value) not implemented yet in gcc 4.8.2 + // if(std::is_trivially_copyable::value) not implemented yet in gcc 4.8.2 // LOG(info) << classname << " is trivially copyable" ; - //else + // else // LOG(info) << classname << " is not trivially copyable" ; - - if (std::is_standard_layout::value) - { - LOG(info) << classname << " is standard layout" ; - } - else - { - LOG(info) << classname << " is not standard layout" ; + if (std::is_standard_layout::value) { + LOG(info) << classname << " is standard layout"; + } else { + LOG(info) << classname << " is not standard layout"; } - - if (resolve::has_BoostSerialization::value) - { - LOG(info) << classname << " is boost serializable" ; - } - else - { - if (resolve::has_BoostSerialization::value) - { - LOG(info) << classname << " is boost serializable" ; - } - else - { - LOG(info) << classname << " has no void serialize(BoostArchive&) member" ; + if (resolve::has_BoostSerialization::value) { + LOG(info) << classname << " is boost serializable"; + } else { + if (resolve::has_BoostSerialization::value) { + LOG(info) << classname << " is boost serializable"; + } else { + LOG(info) << classname << " has no void serialize(BoostArchive&) member"; } } - } - else - { - LOG(info) << classname << " is not a class" ; + } else { + LOG(info) << classname << " is not a class"; } }; -} // end namespace TypeInfo +} // namespace typeinfo -} // end namespace tools +} // end namespace tools -} // end namespace BaseMQ +} // namespace baseMQ #endif /* FAIRMQTEMPLATE_H */ diff --git a/base/MQ/devices/BaseMQFileSink.h b/base/MQ/devices/BaseMQFileSink.h index aa00294a71..824f228dbb 100644 --- a/base/MQ/devices/BaseMQFileSink.h +++ b/base/MQ/devices/BaseMQFileSink.h @@ -19,8 +19,11 @@ #include #include -template -class BaseMQFileSink : public FairMQDevice, public InputPolicy, public OutputPolicy +template +class BaseMQFileSink + : public FairMQDevice + , public InputPolicy + , public OutputPolicy { public: BaseMQFileSink() @@ -29,8 +32,7 @@ class BaseMQFileSink : public FairMQDevice, public InputPolicy, public OutputPol , fInputChanName() {} - virtual ~BaseMQFileSink() - {} + virtual ~BaseMQFileSink() {} template void InitInputData(Args&&... args) @@ -49,13 +51,12 @@ class BaseMQFileSink : public FairMQDevice, public InputPolicy, public OutputPol virtual void Run() { int receivedMsg = 0; - while (!NewStatePending()) - { + while (!NewStatePending()) { std::unique_ptr msg(NewMessage()); - if (Receive(msg, fInputChanName) > 0) - { - FairMQDevice::Deserialize(*msg, InputPolicy::fInput); // get data from message. - OutputPolicy::Serialize(InputPolicy::fInput); // put data into output. + if (Receive(msg, fInputChanName) > 0) { + FairMQDevice::Deserialize( + *msg, InputPolicy::fInput); // get data from message. + OutputPolicy::Serialize(InputPolicy::fInput); // put data into output. receivedMsg++; } } diff --git a/base/MQ/devices/FairMQLmdSampler.h b/base/MQ/devices/FairMQLmdSampler.h index ddd63e928e..1f89ed15d2 100644 --- a/base/MQ/devices/FairMQLmdSampler.h +++ b/base/MQ/devices/FairMQLmdSampler.h @@ -1,11 +1,11 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ - /* +/* * File: FairMQLmdSampler.h * Author: winckler * @@ -18,20 +18,18 @@ extern "C" { #include "f_evt.h" -#include "s_filhe_swap.h" #include "s_bufhe_swap.h" +#include "s_filhe_swap.h" } -#include -#include -#include -#include - -#include - -#include #include +#include #include +#include +#include +#include +#include +#include class FairMQLmdSampler : public FairMQDevice { @@ -62,16 +60,20 @@ class FairMQLmdSampler : public FairMQDevice FairMQLmdSampler(const FairMQLmdSampler&) = delete; FairMQLmdSampler operator=(const FairMQLmdSampler&) = delete; - virtual ~FairMQLmdSampler() - {} + virtual ~FairMQLmdSampler() {} - void AddSubEvtKey(short type, short subType, short procid, short subCrate, short control, const std::string& channelName) + void AddSubEvtKey(short type, + short subType, + short procid, + short subCrate, + short control, + const std::string& channelName) { SubEvtKey key(type, subType, procid, subCrate, control); - if (fSubEventChanMap.count(key)) - { - LOG(warn) << "FairMQLmdSampler : subevent header key '(" - << type << "," << subType << "," << procid << "," << subCrate << "," << control << ")' has already been defined with channel name '" << fSubEventChanMap.at(key) + if (fSubEventChanMap.count(key)) { + LOG(warn) << "FairMQLmdSampler : subevent header key '(" << type << "," << subType << "," << procid << "," + << subCrate << "," << control << ")' has already been defined with channel name '" + << fSubEventChanMap.at(key) << "'. it will be overwritten with new channel name = " << channelName; } fSubEventChanMap[key] = channelName; @@ -81,33 +83,25 @@ class FairMQLmdSampler : public FairMQDevice { boost::filesystem::path directory = dir; - if (boost::filesystem::exists(directory)) - { + if (boost::filesystem::exists(directory)) { boost::filesystem::directory_iterator end_itr; - for (boost::filesystem::directory_iterator itr(directory); itr != end_itr; ++itr) - { - if (boost::filesystem::is_regular_file(itr->path())) - { + for (boost::filesystem::directory_iterator itr(directory); itr != end_itr; ++itr) { + if (boost::filesystem::is_regular_file(itr->path())) { std::string currentFile = itr->path().string(); AddFile(currentFile); } } - } - else - { + } else { LOG(warn) << "FairMQLmdSampler: directory '" << directory.string() << "' not found"; } } void AddFile(const std::string& fileName) { boost::filesystem::path filepath = fileName; - if (boost::filesystem::exists(filepath)) - { + if (boost::filesystem::exists(filepath)) { fFileNames.push_back(fileName); - } - else - { + } else { LOG(warn) << "FairMQLmdSampler: file '" << fileName << "' not found"; } } @@ -128,14 +122,12 @@ class FairMQLmdSampler : public FairMQDevice // this channel MUST be defined in the json file for the MQ configuration AddSubEvtKey(fType, fSubType, fProcId, fSubCrate, fControl, fChanName); - if (fFileNames.empty()) - { + if (fFileNames.empty()) { throw std::runtime_error(std::string("FairMQLmdSampler::InitTask: No files provided")); } std::string name = fFileNames.at(fCurrentFile); - if (!OpenNextFile(name)) - { + if (!OpenNextFile(name)) { throw std::runtime_error(std::string("FairMQLmdSampler::InitTask: cannot open file ") + name); } @@ -146,10 +138,9 @@ class FairMQLmdSampler : public FairMQDevice } void Run() { - while (!NewStatePending())//&& !fStop) + while (!NewStatePending()) //&& !fStop) { - if (1 == ReadEvent()) - { + if (1 == ReadEvent()) { break; } } @@ -161,55 +152,51 @@ class FairMQLmdSampler : public FairMQDevice void* evtptr = &fEvent; void* buffptr = &fBuffer; - //INTS4 f_evt_get_event(s_evt_channel*, INTS4**, INTS4**); // -> in f_evt.h + // INTS4 f_evt_get_event(s_evt_channel*, INTS4**, INTS4**); // -> in f_evt.h /*- GETEVT__SUCCESS=0 : success. */ /*- GETEVT__FRAGMENT=1: Event fragment found. */ /*- GETEVT__NOMORE=3 : No more events. */ /*- GETEVT__RDERR=6 : read server or file error */ /*- GETEVT__TIMEOUT=9 : when enabled by f_evt_timeout */ int status = f_evt_get_event(&fInputChannel, static_cast(evtptr), static_cast(buffptr)); - //int fuEventCounter = fEvent->l_count; - //int fCurrentMbsEventNo = fuEventCounter; + // int fuEventCounter = fEvent->l_count; + // int fCurrentMbsEventNo = fuEventCounter; // LOG(debug) << "STATUS = " << status; - if (GETEVT__SUCCESS != status) // if f_evt_get_event not successfull close if nomore evt or look to another file and start again + if (GETEVT__SUCCESS != status) // if f_evt_get_event not successfull close if nomore evt or look to another + // file and start again { // LOG(debug) << "FairMQLmdSampler::ReadEvent()"; CHARS* sErrorString = NULL; f_evt_error(status, sErrorString, 0); - if (GETEVT__NOMORE == status) - { + if (GETEVT__NOMORE == status) { Close(); } // fCurrentFile incremented in InitTask once - if (fCurrentFile >= static_cast(fFileNames.size())) - { + if (fCurrentFile >= static_cast(fFileNames.size())) { fStop = true; return 1; } std::string name = fFileNames.at(fCurrentFile); - if (!OpenNextFile(name)) - { + if (!OpenNextFile(name)) { return 1; - } - else - { + } else { fCurrentFile += 1; return ReadEvent(); } } - //Store Start Times - //if (fCurrentEvent==0 ) + // Store Start Times + // if (fCurrentEvent==0 ) // Unpack((int*)fBuffer, sizeof(s_bufhe), -4, -4, -4, -4, -4); // Decode event header - //bool result = false; + // bool result = false; /*bool result = */ - //Unpack((int*)fEvent, sizeof(s_ve10_1), -2, -2, -2, -2, -2); + // Unpack((int*)fEvent, sizeof(s_ve10_1), -2, -2, -2, -2, -2); int nrSubEvts = f_evt_get_subevent(fEvent, 0, NULL, NULL, NULL); int sebuflength; @@ -220,18 +207,18 @@ class FairMQLmdSampler : public FairMQDevice short secontrol; // LOG(debug) << "FairMQLmdSampler::ReadEvent => Found " << nrSubEvts << " Sub-event "; - //if (fCurrentEvent%10000==0) - //cout << " -I- LMD_ANA: evt# " << fCurrentEvent << " n_subevt# " << nrSubEvts << " evt processed# " << fNEvent << " : " << fEvent->l_count << endl; + // if (fCurrentEvent%10000==0) + // cout << " -I- LMD_ANA: evt# " << fCurrentEvent << " n_subevt# " << nrSubEvts << " evt processed# " << + // fNEvent << " : " << fEvent->l_count << endl; - for (int i = 1; i <= nrSubEvts; i++) - { + for (int i = 1; i <= nrSubEvts; i++) { void* SubEvtptr = &fSubEvent; void* EvtDataptr = &fEventData; int nrlongwords; - status = f_evt_get_subevent(fEvent, i, static_cast(SubEvtptr), static_cast(EvtDataptr), &nrlongwords); + status = f_evt_get_subevent( + fEvent, i, static_cast(SubEvtptr), static_cast(EvtDataptr), &nrlongwords); - if (status) - { + if (status) { return 1; } @@ -242,17 +229,15 @@ class FairMQLmdSampler : public FairMQDevice sesubcrate = fSubEvent->h_subcrate; secontrol = fSubEvent->h_control; - //cout << setype << " " << sesubtype << " " << seprocid << " " << sesubcrate << " " << secontrol << endl; + // cout << setype << " " << sesubtype << " " << seprocid << " " << sesubcrate << " " << secontrol << + // endl; // Data to send : fEventData SubEvtKey key(setype, sesubtype, seprocid, sesubcrate, secontrol); - if (!fSubEventChanMap.count(key)) - { + if (!fSubEventChanMap.count(key)) { // LOG(debug) << "FairMQLmdSampler::ReadEvent: sub-event key not registered"; - } - else - { + } else { // LOG(debug) << "array size = " << sebuflength; // LOG(debug) << "fEventData = " << *fEventData; @@ -262,19 +247,27 @@ class FairMQLmdSampler : public FairMQDevice FairMQParts parts; // send header - //std::unique_ptr header(fTransportFactory->CreateMessage(fSubEvent, sizeof(fSubEvent), free_buffer, nullptr)); - //fChannels.at(chanName).at(0).SendPart(header); + // std::unique_ptr header(fTransportFactory->CreateMessage(fSubEvent, sizeof(fSubEvent), + // free_buffer, nullptr)); fChannels.at(chanName).at(0).SendPart(header); int* arraySize = new int(sebuflength); - parts.AddPart(NewMessage(arraySize, sizeof(int), [](void* /*data*/, void* hint) { delete static_cast(hint); }, arraySize)); - parts.AddPart(NewMessage(fEventData, sebuflength, [](void* /*data*/, void* /*hint*/) { /*LOG(debug) << "empty deleter";*/ }, nullptr)); + parts.AddPart(NewMessage( + arraySize, + sizeof(int), + [](void* /*data*/, void* hint) { delete static_cast(hint); }, + arraySize)); + parts.AddPart(NewMessage( + fEventData, + sebuflength, + [](void* /*data*/, void* /*hint*/) { /*LOG(debug) << "empty deleter";*/ }, + nullptr)); Send(parts, chanName); fMsgCounter++; /* if (Unpack(fEventData, sebuflength, setype, sesubtype, - seprocid, sesubcrate, secontrol)) + seprocid, sesubcrate, secontrol)) { result = true; } @@ -301,10 +294,10 @@ class FairMQLmdSampler : public FairMQDevice LOG(info) << "File " << fileName << " will be opened."; - status = f_evt_get_open(inputMode, const_cast(fileName.c_str()), &fInputChannel, static_cast(headptr), 1, 1); + status = f_evt_get_open( + inputMode, const_cast(fileName.c_str()), &fInputChannel, static_cast(headptr), 1, 1); - if (status) - { + if (status) { LOG(error) << "File " << fileName << " opening failed."; return false; } @@ -320,7 +313,7 @@ class FairMQLmdSampler : public FairMQDevice void Close() { f_evt_get_close(&fInputChannel); - // Unpack((Int_t*)fBuffer, sizeof(s_bufhe), -4, -4, -4, -4, -4); + // Unpack((Int_t*)fBuffer, sizeof(s_bufhe), -4, -4, -4, -4, -4); fCurrentEvent = 0; } @@ -349,4 +342,4 @@ class FairMQLmdSampler : public FairMQDevice std::string fChanName; }; -#endif /* !FAIRMQLMDSAMPLER_H */ +#endif /* !FAIRMQLMDSAMPLER_H */ diff --git a/base/MQ/devices/FairMQProcessor.h b/base/MQ/devices/FairMQProcessor.h index dc75112eff..0e7312cb28 100644 --- a/base/MQ/devices/FairMQProcessor.h +++ b/base/MQ/devices/FairMQProcessor.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /** @@ -15,11 +15,12 @@ #ifndef FAIRMQPROCESSOR_H_ #define FAIRMQPROCESSOR_H_ -#include #include "FairMQProcessorTask.h" + +#include #include -template +template class FairMQProcessor : public FairMQDevice { public: @@ -43,18 +44,15 @@ class FairMQProcessor : public FairMQDevice std::string inChannelName = fConfig->GetValue("in-channel"); std::string outChannelName = fConfig->GetValue("out-channel"); // check if the returned value actually exists, for the compatibility with old devices. - if (inChannelName != "") - { + if (inChannelName != "") { fInChannelName = inChannelName; } - if (outChannelName != "") - { + if (outChannelName != "") { fOutChannelName = outChannelName; } fProcessorTask->InitTask(); - OnData(fInChannelName, [this](FairMQMessagePtr& msg, int /*index*/) - { + OnData(fInChannelName, [this](FairMQMessagePtr& msg, int /*index*/) { ++fReceivedMsgs; fProcessorTask->SetPayload(msg); fProcessorTask->Exec(); @@ -67,10 +65,7 @@ class FairMQProcessor : public FairMQDevice }); } - virtual void PostRun() - { - LOG(info) << "Received " << fReceivedMsgs << " and sent " << fSentMsgs << " messages!"; - } + virtual void PostRun() { LOG(info) << "Received " << fReceivedMsgs << " and sent " << fSentMsgs << " messages!"; } private: std::unique_ptr fProcessorTask; diff --git a/base/MQ/devices/FairMQSampler.h b/base/MQ/devices/FairMQSampler.h index 6823686dc3..c07809c937 100644 --- a/base/MQ/devices/FairMQSampler.h +++ b/base/MQ/devices/FairMQSampler.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /** @@ -15,18 +15,17 @@ #ifndef FAIRMQSAMPLER_H_ #define FAIRMQSAMPLER_H_ -#include -#include - +#include "FairFileSource.h" +#include "FairMQSamplerTask.h" #include "FairParRootFileIo.h" -#include "FairRuntimeDb.h" -#include "FairRunAna.h" #include "FairRootFileSink.h" -#include "FairFileSource.h" +#include "FairRunAna.h" +#include "FairRuntimeDb.h" #include -#include "FairMQSamplerTask.h" #include +#include +#include /** * Reads simulated digis from a root file and samples the digi as a time-series UDP stream. @@ -40,7 +39,7 @@ * feasibility and quality of the various possible online analysis features. */ -template +template class FairMQSampler : public FairMQDevice { public: @@ -63,8 +62,7 @@ class FairMQSampler : public FairMQDevice FairMQSampler(const FairMQSampler&) = delete; FairMQSampler operator=(const FairMQSampler&) = delete; - virtual ~FairMQSampler() - {} + virtual ~FairMQSampler() {} protected: virtual void InitTask() @@ -82,12 +80,10 @@ class FairMQSampler : public FairMQDevice std::string outChannelName = fConfig->GetValue("out-channel"); std::string ackChannelName = fConfig->GetValue("ack-channel"); // check if the returned value actually exists, for the compatibility with old devices. - if (outChannelName != "") - { + if (outChannelName != "") { fOutChannelName = outChannelName; } - if (ackChannelName != "") - { + if (ackChannelName != "") { fAckChannelName = ackChannelName; } @@ -96,8 +92,7 @@ class FairMQSampler : public FairMQDevice FairFileSource* source = new FairFileSource(TString(fInputFile)); // Adds the same file to the input. The output will still be a single file. - for (int i = 0; i < fChainInput; ++i) - { + for (int i = 0; i < fChainInput; ++i) { source->AddFile(fInputFile); } @@ -109,16 +104,13 @@ class FairMQSampler : public FairMQDevice fFairRunAna->AddTask(fSamplerTask); - if (fParFile != "") - { + if (fParFile != "") { FairRuntimeDb* rtdb = fFairRunAna->GetRuntimeDb(); FairParRootFileIo* parInput = new FairParRootFileIo(); parInput->open(TString(fParFile).Data()); rtdb->setFirstInput(parInput); rtdb->print(); - } - else - { + } else { LOG(warn) << "Parameter file not provided. Starting without RuntimeDB."; } @@ -144,11 +136,9 @@ class FairMQSampler : public FairMQDevice fFairRunAna->RunMQ(fSentMsgs); fSamplerTask->GetPayload(msg); - if (Send(msg, fOutChannelName) >= 0) - { + if (Send(msg, fOutChannelName) >= 0) { ++fSentMsgs; - if (fSentMsgs == fNumEvents) - { + if (fSentMsgs == fNumEvents) { return false; } } @@ -158,12 +148,9 @@ class FairMQSampler : public FairMQDevice virtual void PostRun() { - try - { + try { fAckListener.join(); - } - catch (std::exception& e) - { + } catch (std::exception& e) { LOG(error) << "Exception when ending AckListener thread: " << e.what(); exit(EXIT_FAILURE); } @@ -171,8 +158,7 @@ class FairMQSampler : public FairMQDevice virtual void ResetTask() { - if (fFairRunAna) - { + if (fFairRunAna) { fFairRunAna->TerminateRun(); } delete fSamplerTask; @@ -181,22 +167,20 @@ class FairMQSampler : public FairMQDevice void ListenForAcks() { uint64_t numAcks = 0; - for (Long64_t eventNr = 0; eventNr < fNumEvents; ++eventNr) - { + for (Long64_t eventNr = 0; eventNr < fNumEvents; ++eventNr) { FairMQMessagePtr ack(NewMessage()); - if (Receive(ack, fAckChannelName) >= 0) - { + if (Receive(ack, fAckChannelName) >= 0) { ++numAcks; } - if (NewStatePending()) - { + if (NewStatePending()) { break; } } fEnd = std::chrono::high_resolution_clock::now(); - LOG(info) << "Acknowledged " << numAcks << " messages in: " << std::chrono::duration(fEnd - fStart).count() << "ms."; + LOG(info) << "Acknowledged " << numAcks + << " messages in: " << std::chrono::duration(fEnd - fStart).count() << "ms."; } private: @@ -204,9 +188,9 @@ class FairMQSampler : public FairMQDevice FairMQSamplerTask* fSamplerTask; std::chrono::high_resolution_clock::time_point fStart; std::chrono::high_resolution_clock::time_point fEnd; - std::string fInputFile; // Filename of a root file containing the simulated digis. + std::string fInputFile; // Filename of a root file containing the simulated digis. std::string fParFile; - std::string fBranch; // The name of the sub-detector branch to stream the digis from. + std::string fBranch; // The name of the sub-detector branch to stream the digis from. std::string fOutChannelName; std::string fAckChannelName; int fNumEvents; diff --git a/base/MQ/devices/FairMQUnpacker.h b/base/MQ/devices/FairMQUnpacker.h index 5961145554..692baba78d 100644 --- a/base/MQ/devices/FairMQUnpacker.h +++ b/base/MQ/devices/FairMQUnpacker.h @@ -5,7 +5,7 @@ * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ - /* +/* * File: FairMQUnpacker.h * Author: winckler * @@ -15,13 +15,13 @@ #ifndef FAIRMQUNPACKER_H #define FAIRMQUNPACKER_H -#include #include "RootSerializer.h" +#include +#include #include #include #include -#include template class FairMQUnpacker : public FairMQDevice @@ -43,26 +43,24 @@ class FairMQUnpacker : public FairMQDevice FairMQUnpacker(const FairMQUnpacker&) = delete; FairMQUnpacker operator=(const FairMQUnpacker&) = delete; - virtual ~FairMQUnpacker() - { - delete fUnpacker; - } + virtual ~FairMQUnpacker() { delete fUnpacker; } - void AddSubEvtKey(short type, short subType, short procid, short subCrate, short control, const std::string& channelName) + void AddSubEvtKey(short type, + short subType, + short procid, + short subCrate, + short control, + const std::string& channelName) { - if (fSubEventChanMap.size() > 0) - { + if (fSubEventChanMap.size() > 0) { LOG(error) << "Only one input channel allowed for this device"; - } - else - { - SubEvtKey key(type, subType, procid, subCrate, control); - fInputChannelName = channelName; - - if (fSubEventChanMap.count(fInputChannelName)) - { - LOG(warn) << "FairMQLmdSampler : subevent header key '(" - << type << "," << subType << "," << procid << "," << subCrate << "," << control << ")' has already been defined. " + } else { + SubEvtKey key(type, subType, procid, subCrate, control); + fInputChannelName = channelName; + + if (fSubEventChanMap.count(fInputChannelName)) { + LOG(warn) << "FairMQLmdSampler : subevent header key '(" << type << "," << subType << "," << procid + << "," << subCrate << "," << control << ")' has already been defined. " << "It will be overwritten with new channel name = " << fInputChannelName; } fSubEventChanMap[fInputChannelName] = key; @@ -85,15 +83,14 @@ class FairMQUnpacker : public FairMQDevice AddSubEvtKey(fType, fSubType, fProcId, fSubCrate, fControl, fInputChanName); // check if subevt map is configured - if (fInputChannelName.empty() || fSubEventChanMap.size() == 0) - { + if (fInputChannelName.empty() || fSubEventChanMap.size() == 0) { throw std::runtime_error(std::string("Sub-event map not configured.")); } // check if given channel exist - if (!fChannels.count(fInputChannelName)) - { - throw std::runtime_error(std::string("MQ-channel name '") + fInputChannelName + "' does not exist. Check the MQ-channel configuration"); + if (!fChannels.count(fInputChannelName)) { + throw std::runtime_error(std::string("MQ-channel name '") + fInputChannelName + + "' does not exist. Check the MQ-channel configuration"); } short setype; @@ -110,15 +107,12 @@ class FairMQUnpacker : public FairMQDevice { FairMQChannel& inputChannel = fChannels.at(fInputChannelName).at(0); - while (!NewStatePending()) - { + while (!NewStatePending()) { FairMQMessagePtr msgSize(NewMessage()); FairMQMessagePtr msg(NewMessage()); - if (inputChannel.Receive(msgSize) >= 0) - { - if (inputChannel.Receive(msg) >= 0) - { + if (inputChannel.Receive(msgSize) >= 0) { + if (inputChannel.Receive(msg) >= 0) { int dataSize = *(static_cast(msgSize->GetData())); int* subEvtPtr = static_cast(msg->GetData()); diff --git a/base/MQ/policies/Sampler/FairMQFileSource.h b/base/MQ/policies/Sampler/FairMQFileSource.h index b5aa6d1386..c14459985f 100644 --- a/base/MQ/policies/Sampler/FairMQFileSource.h +++ b/base/MQ/policies/Sampler/FairMQFileSource.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ diff --git a/base/MQ/policies/Sampler/FairSourceMQInterface.h b/base/MQ/policies/Sampler/FairSourceMQInterface.h index 65f55f2aa2..da13ef5a34 100644 --- a/base/MQ/policies/Sampler/FairSourceMQInterface.h +++ b/base/MQ/policies/Sampler/FairSourceMQInterface.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ @@ -10,12 +10,12 @@ #define FAIRSOURCEMQINTERFACE_H #include "BaseSourcePolicy.h" -#include - -#include "FairRunAna.h" #include "FairFileSource.h" -#include +#include "FairRunAna.h" + +#include #include +#include template using enable_if_match = typename std::enable_if::value, int>::type; @@ -24,26 +24,24 @@ template class FairSourceMQInterface : public BaseSourcePolicy> { typedef DataType* DataType_ptr; - typedef FairSourceMQInterface this_type; + typedef FairSourceMQInterface this_type; public: - FairSourceMQInterface() : - BaseSourcePolicy>(), - fSource(nullptr), - fInput(nullptr), - fIndex(0), - fMaxIndex(-1), - fClassName(""), - fBranchName(""), - fSourceName(""), - fRunAna(nullptr) - { - } + FairSourceMQInterface() + : BaseSourcePolicy>() + , fSource(nullptr) + , fInput(nullptr) + , fIndex(0) + , fMaxIndex(-1) + , fClassName("") + , fBranchName("") + , fSourceName("") + , fRunAna(nullptr) + {} FairSourceMQInterface(const FairSourceMQInterface&) = delete; FairSourceMQInterface operator=(const FairSourceMQInterface&) = delete; - virtual ~FairSourceMQInterface() { delete fInput; @@ -56,39 +54,35 @@ class FairSourceMQInterface : public BaseSourcePolicy = 0> + template = 0> void InitSource() { fRunAna = new FairRunAna(); fSource = new FairSourceType(fSourceName.c_str()); fSource->Init(); - fSource->ActivateObject(reinterpret_cast(&fInput),fBranchName.c_str()); -// fSource->ActivateObject(dynamic_cast(fData),fBranchName.c_str()); + fSource->ActivateObject(reinterpret_cast(&fInput), fBranchName.c_str()); + // fSource->ActivateObject(dynamic_cast(fData),fBranchName.c_str()); fMaxIndex = fSource->CheckMaxEventNo(); } - template = 0> + template = 0> void SetIndex(int64_t eventIdx) { fIndex = eventIdx; } - template = 0> + template = 0> DataType_ptr GetOutData() { fSource->ReadEvent(fIndex); @@ -98,14 +92,11 @@ class FairSourceMQInterface : public BaseSourcePolicyReadEvent(evtIdx); - data=fInput; + data = fInput; } /*required for MQ*/ - void deserialize_impl(int64_t evtIdx) - { - fSource->ReadEvent(evtIdx); - } + void deserialize_impl(int64_t evtIdx) { fSource->ReadEvent(evtIdx); } protected: FairSourceType* fSource; @@ -119,5 +110,4 @@ class FairSourceMQInterface : public BaseSourcePolicy -#include #include #include +#include +#include // ROOT #include +#include #include #include -#include // FairRoot #include #include -template +template class BaseSimpleTreeReader { public: @@ -48,8 +47,7 @@ class BaseSimpleTreeReader virtual ~BaseSimpleTreeReader() { - if (fInputFile) - { + if (fInputFile) { fInputFile->Close(); delete fInputFile; } @@ -66,40 +64,28 @@ class BaseSimpleTreeReader void InitSource() { fInputFile = TFile::Open(fFileName.c_str(), "READ"); - if (fInputFile) - { + if (fInputFile) { fTree = static_cast(fInputFile->Get(fTreeName.c_str())); - if (fTree) - { + if (fTree) { fTree->SetBranchAddress(fBranchName.c_str(), &fInput); fIndexMax = fTree->GetEntries(); - } - else - { + } else { LOG(error) << "Could not find tree " << fTreeName; } - } - else - { + } else { LOG(error) << "Could not open file " << fFileName << " in SimpleTreeReader::InitSource()"; } - } void SendMultiPart() { - fSendHeader(0);// callback that does the zmq multipart AND increment the current index (Event number) in generic sampler + fSendHeader(0); // callback that does the zmq multipart AND increment the current index (Event number) in + // generic sampler } - void SetIndex(int64_t Event) - { - fIndex = Event; - } + void SetIndex(int64_t Event) { fIndex = Event; } - DataType* GetOutData() - { - return GetOutData(fIndex); - } + DataType* GetOutData() { return GetOutData(fIndex); } DataType* GetOutData(int64_t Event) { @@ -125,44 +111,34 @@ class BaseSimpleTreeReader int64_t GetNumberOfEvent() { - if (fTree) - { + if (fTree) { return fIndexMax; - } - else - { + } else { return 0; } } template - std::vector< std::vector> GetDataVector() + std::vector> GetDataVector() { std::vector> allObj; std::vector tempObj; - if (std::is_same::value) - { - for (int64_t i = 0; i < fTree->GetEntries(); i++) - { + if (std::is_same::value) { + for (int64_t i = 0; i < fTree->GetEntries(); i++) { tempObj.clear(); fTree->GetEntry(i); - for (int64_t iobj = 0; iobj < fInput->GetEntriesFast(); ++iobj) - { + for (int64_t iobj = 0; iobj < fInput->GetEntriesFast(); ++iobj) { T* data = reinterpret_cast(fInput->At(iobj)); - if (!data) - { + if (!data) { continue; } tempObj.push_back(*data); } allObj.push_back(tempObj); } - } - else - { - for (int64_t i = 0; i < fTree->GetEntries(); i++) - { + } else { + for (int64_t i = 0; i < fTree->GetEntries(); i++) { tempObj.clear(); fTree->GetEntry(i); T data = *fInput; @@ -174,28 +150,19 @@ class BaseSimpleTreeReader } // provides a callback to the Sampler. - void BindSendHeader(std::function callback) - { - fSendHeader = callback; - } + void BindSendHeader(std::function callback) { fSendHeader = callback; } - void BindGetSocketNumber(std::function callback) - { - fGetSocketNumber = callback; - } + void BindGetSocketNumber(std::function callback) { fGetSocketNumber = callback; } - void BindGetCurrentIndex(std::function callback) - { - fGetCurrentIndex = callback; - } + void BindGetCurrentIndex(std::function callback) { fGetCurrentIndex = callback; } protected: - DataType* fInput;// data type of the branch you want to extract + DataType* fInput; // data type of the branch you want to extract private: - std::function fSendHeader; // function pointer for the Sampler callback. - std::function fGetSocketNumber; // function pointer for the Sampler callback. - std::function fGetCurrentIndex; // function pointer for the Sampler callback. + std::function fSendHeader; // function pointer for the Sampler callback. + std::function fGetSocketNumber; // function pointer for the Sampler callback. + std::function fGetCurrentIndex; // function pointer for the Sampler callback. std::string fFileName; std::string fTreeName; diff --git a/base/MQ/policies/Serialization/BinaryBaseClassSerializer.h b/base/MQ/policies/Serialization/BinaryBaseClassSerializer.h index 8c19c7eb72..a8da5bc198 100644 --- a/base/MQ/policies/Serialization/BinaryBaseClassSerializer.h +++ b/base/MQ/policies/Serialization/BinaryBaseClassSerializer.h @@ -1,4 +1,4 @@ -/* +/* * File: BinaryBaseClassSerializer.h * Author: winckler * @@ -10,7 +10,7 @@ #include -template +template class BinaryBaseClassSerializer { public: @@ -23,28 +23,20 @@ class BinaryBaseClassSerializer BinaryBaseClassSerializer(const BinaryBaseClassSerializer&) = delete; BinaryBaseClassSerializer operator=(const BinaryBaseClassSerializer&) = delete; - virtual ~BinaryBaseClassSerializer() - {} + virtual ~BinaryBaseClassSerializer() {} void GetPayload(FairMQMessage* msg) { int inputSize = msg->GetSize(); - if (inputSize > 0) - { + if (inputSize > 0) { fNumInput = inputSize / sizeof(TPayload); } fPayload = static_cast(msg->GetData()); } - void SetMessage(FairMQMessage* msg) - { - fMessage = msg; - } + void SetMessage(FairMQMessage* msg) { fMessage = msg; } - FairMQMessage* GetMessage() - { - return fMessage; - } + FairMQMessage* GetMessage() { return fMessage; } protected: TPayload* fPayload; @@ -53,4 +45,3 @@ class BinaryBaseClassSerializer }; #endif /* BINARYBASECLASSSERIALIZER_H */ - diff --git a/base/MQ/policies/Serialization/BoostSerializer.h b/base/MQ/policies/Serialization/BoostSerializer.h index 4bf718750a..9576c9a14a 100644 --- a/base/MQ/policies/Serialization/BoostSerializer.h +++ b/base/MQ/policies/Serialization/BoostSerializer.h @@ -1,62 +1,61 @@ /* -* File: BoostSerializer.h -* Author: winckler -* -* Created on October 7, 2014, 8:07 PM -*/ + * File: BoostSerializer.h + * Author: winckler + * + * Created on October 7, 2014, 8:07 PM + */ #ifndef BOOSTSERIALIZER_H #define BOOSTSERIALIZER_H #include #include - #include -namespace boost { namespace serialization { class access; } } +namespace boost { +namespace serialization { +class access; +} +} // namespace boost +#include // input: a non-portable native binary archive +#include // output: a non-portable native binary archive #include -#include // input: a non-portable native binary archive -#include // output: a non-portable native binary archive - -#include -#include -#include #include +#include +#include #include +#include -namespace fair -{ -namespace base -{ -namespace serialization -{ +namespace fair { +namespace base { +namespace serialization { -template +template struct has_BoostSerialization { static_assert(std::integral_constant::value, "Second template parameter needs to be of function type."); }; -template +template struct has_BoostSerialization { private: - template - static constexpr auto check(T*) // attempt to call it and see if the return type is correct + template + static constexpr auto check(T*) // attempt to call it and see if the return type is correct -> std::is_same().serialize(std::declval()...)), Ret>; - template + template static constexpr std::false_type check(...); public: static constexpr bool value = decltype(check(0))::value; }; -} // namespace serialization -} // namespace base -} // namespace fair +} // namespace serialization +} // namespace base +} // namespace fair -template +template class BoostSerializer { public: @@ -103,10 +102,7 @@ class BoostSerializer Serialize(msg, dataVec); } - void Serialize(FairMQMessage& msg, std::unique_ptr input) - { - Serialize(msg, input.get()); - } + void Serialize(FairMQMessage& msg, std::unique_ptr input) { Serialize(msg, input.get()); } void Deserialize(FairMQMessage& msg, DataType& input) { @@ -145,10 +141,7 @@ class BoostSerializer } } - void Deserialize(FairMQMessage& msg, std::unique_ptr& input) - { - Deserialize(msg, input.get()); - } + void Deserialize(FairMQMessage& msg, std::unique_ptr& input) { Deserialize(msg, input.get()); } }; #endif /* BOOSTSERIALIZER_H */ diff --git a/base/MQ/policies/Serialization/IOPolicy.h b/base/MQ/policies/Serialization/IOPolicy.h index a30b744f37..a75490333d 100644 --- a/base/MQ/policies/Serialization/IOPolicy.h +++ b/base/MQ/policies/Serialization/IOPolicy.h @@ -3,19 +3,21 @@ #include -namespace fair -{ -namespace mq -{ -namespace policy -{ +namespace fair { +namespace mq { +namespace policy { // PassTypes -struct PointerType {}; -struct ReferenceType {}; -struct ValueType {}; -struct UniquePtrType {}; -struct SharedPtrType {}; +struct PointerType +{}; +struct ReferenceType +{}; +struct ValueType +{}; +struct UniquePtrType +{}; +struct SharedPtrType +{}; // PassType template @@ -56,7 +58,6 @@ struct SelectPassType using Type = std::shared_ptr; }; - // AllocatorType struct OpNewCreator { @@ -102,7 +103,6 @@ struct SmartPtrCreator } }; - // InitializerType struct NullptrInitializer { @@ -131,7 +131,6 @@ struct EmptyInitializer {} }; - // DeleterType struct EmptyDeleter { @@ -152,7 +151,12 @@ struct RawPtrDeleter }; // Input Policy -template +template class InputPolicy : public Deserializer { public: @@ -176,17 +180,18 @@ class InputPolicy : public Deserializer } protected: - virtual ~InputPolicy() - { - DeleterType::DestroyImpl(fInput); - } + virtual ~InputPolicy() { DeleterType::DestroyImpl(fInput); } DataType fInput; }; - // Output Policy -template +template class OutputPolicy : public Serializer { public: @@ -206,16 +211,13 @@ class OutputPolicy : public Serializer } protected: - ~OutputPolicy() - { - DeleterType::DestroyImpl(fOutput); - } + ~OutputPolicy() { DeleterType::DestroyImpl(fOutput); } DataType fOutput; }; -} // namespace policy -} // namespace mq -} // namespace fair +} // namespace policy +} // namespace mq +} // namespace fair -#endif // IOPOLICY_H +#endif // IOPOLICY_H diff --git a/base/MQ/policies/Serialization/RootSerializer.h b/base/MQ/policies/Serialization/RootSerializer.h index 3d0f77f927..e0ad0eb937 100644 --- a/base/MQ/policies/Serialization/RootSerializer.h +++ b/base/MQ/policies/Serialization/RootSerializer.h @@ -1,4 +1,4 @@ -/* +/* * File: RootSerializer.h * Author: winckler * @@ -8,12 +8,10 @@ #ifndef ROOTSERIALIZER_H #define ROOTSERIALIZER_H -#include - +#include #include #include - -#include +#include // special class to expose protected TMessage constructor class FairTMessage : public TMessage @@ -36,10 +34,8 @@ struct RootSerializer { TMessage* tm = new TMessage(kMESS_OBJECT); tm->WriteObject(input); - msg.Rebuild(tm->Buffer(), - tm->BufferSize(), - [](void*, void* tmsg){ delete static_cast(tmsg); }, - tm); + msg.Rebuild( + tm->Buffer(), tm->BufferSize(), [](void*, void* tmsg) { delete static_cast(tmsg); }, tm); } template @@ -47,10 +43,8 @@ struct RootSerializer { TMessage* tm = new TMessage(kMESS_OBJECT); tm->WriteObject(input.get()); - msg.Rebuild(tm->Buffer(), - tm->BufferSize(), - [](void*, void* tmsg){ delete static_cast(tmsg); }, - tm); + msg.Rebuild( + tm->Buffer(), tm->BufferSize(), [](void*, void* tmsg) { delete static_cast(tmsg); }, tm); } template diff --git a/base/MQ/policies/Storage/BinaryOutFileManager.h b/base/MQ/policies/Storage/BinaryOutFileManager.h index 396ae54517..7d36f4a0e7 100644 --- a/base/MQ/policies/Storage/BinaryOutFileManager.h +++ b/base/MQ/policies/Storage/BinaryOutFileManager.h @@ -1,4 +1,4 @@ -/* +/* * File: BinaryOutFileManager.h * Author: winckler * @@ -6,46 +6,53 @@ */ #ifndef BINARYOUTFILEMANAGER_H -#define BINARYOUTFILEMANAGER_H +#define BINARYOUTFILEMANAGER_H // std -#include -#include #include +#include #include +#include // boost -namespace boost { namespace serialization { class access; } } +namespace boost { +namespace serialization { +class access; +} +} // namespace boost #include #include #include // FairRoot -#include -#include -#include "TriviallyCopyableDataSaver.h" #include "BoostDataSaver.h" +#include "TriviallyCopyableDataSaver.h" #include "baseMQtools.h" +#include +#include + #define GET_POLICY_ID(Policy) #Policy using BinArchive = boost::archive::binary_oarchive; -template +template using BoostSerializable = baseMQ::tools::resolve::has_BoostSerialization; -template > +template> class BinaryOutFileManager : public TStoragePolicy { public: - using TStoragePolicy::Write; using TStoragePolicy::Read; + using TStoragePolicy::Write; - BinaryOutFileManager() : TStoragePolicy(), fFileName("test.dat") {;} - virtual ~BinaryOutFileManager() + BinaryOutFileManager() + : TStoragePolicy() + , fFileName("test.dat") { - fOutfile.close(); + ; } + virtual ~BinaryOutFileManager() { fOutfile.close(); } std::string GetPolicyID() { @@ -53,20 +60,11 @@ class BinaryOutFileManager : public TStoragePolicy return str; } - void SetFileProperties(const std::string &filename) - { - fFileName = filename; - } + void SetFileProperties(const std::string& filename) { fFileName = filename; } - void AddToFile(FairMQMessage* msg) - { - TStoragePolicy::Write(fOutfile, msg); - } + void AddToFile(FairMQMessage* msg) { TStoragePolicy::Write(fOutfile, msg); } - void AddToFile(TPayload* objArr, long size) - { - AppendObjArray(fOutfile, objArr, size); - } + void AddToFile(TPayload* objArr, long size) { AppendObjArray(fOutfile, objArr, size); } template void AppendObjArray(std::ofstream& outfile, T* objArr, long size) @@ -74,7 +72,7 @@ class BinaryOutFileManager : public TStoragePolicy TStoragePolicy::Write(outfile, objArr, size); } - std::vector > GetAllObj(const std::string &filename) + std::vector> GetAllObj(const std::string& filename) { std::ifstream infile; infile = std::ifstream(filename); diff --git a/base/MQ/policies/Storage/BoostDataSaver.h b/base/MQ/policies/Storage/BoostDataSaver.h index ebc1e10509..f4cdad40d2 100644 --- a/base/MQ/policies/Storage/BoostDataSaver.h +++ b/base/MQ/policies/Storage/BoostDataSaver.h @@ -1,4 +1,4 @@ -/* +/* * File: BoostDataSaver.h * Author: winckler * @@ -6,17 +6,21 @@ */ #ifndef BOOSTDATASAVER_H -#define BOOSTDATASAVER_H +#define BOOSTDATASAVER_H // std +#include #include -#include #include -#include #include +#include // boost -namespace boost { namespace serialization { class access; } } +namespace boost { +namespace serialization { +class access; +} +} // namespace boost #include #include #include @@ -24,7 +28,9 @@ namespace boost { namespace serialization { class access; } } // FairRoot #include -template +template class BoostDataSaver { public: @@ -52,12 +58,9 @@ class BoostDataSaver std::string msgStr(static_cast(msg->GetData()), msg->GetSize()); std::istringstream ibuffer(msgStr); TArchiveIn inputArchive(ibuffer); - try - { + try { inputArchive >> objArr; - } - catch (boost::archive::archive_exception& e) - { + } catch (boost::archive::archive_exception& e) { LOG(error) << e.what(); } TArchiveOut outArchive(outfile); @@ -67,8 +70,7 @@ class BoostDataSaver std::vector> Read(std::ifstream& infile) { std::vector> dataContainer; - while (infile.peek()!= EOF && !infile.eof()) - { + while (infile.peek() != EOF && !infile.eof()) { TArchiveIn inArchive(infile); std::vector temp; inArchive >> temp; diff --git a/base/MQ/policies/Storage/RootOutFileManager.h b/base/MQ/policies/Storage/RootOutFileManager.h index 1a85d52ccc..18403692ac 100644 --- a/base/MQ/policies/Storage/RootOutFileManager.h +++ b/base/MQ/policies/Storage/RootOutFileManager.h @@ -1,4 +1,4 @@ -/* +/* * File: RootOutFileManager.h * Author: winckler * @@ -10,25 +10,26 @@ // std #include -#include #include +#include // ROOT #include -#include -#include #include -#include +#include #include -#include +#include #include +#include +#include // FairRoot #include "FairLogger.h" + #include #include -template +template class RootOutFileManager { public: @@ -48,7 +49,11 @@ class RootOutFileManager , fFolder(nullptr) {} - RootOutFileManager(const std::string& filename, const std::string& treeName, const std::string& branchName, const std::string& className, const std::string& fileOption) + RootOutFileManager(const std::string& filename, + const std::string& treeName, + const std::string& branchName, + const std::string& className, + const std::string& fileOption) : fFilename(filename) , fTreeName(treeName) , fBranchName(branchName) @@ -69,17 +74,14 @@ class RootOutFileManager virtual ~RootOutFileManager() { - if (fFlowMode && fWrite) - { + if (fFlowMode && fWrite) { fTree->Write("", TObject::kOverwrite); } delete fTree; - if (fOutFile) - { - if (fOutFile->IsOpen()) - { + if (fOutFile) { + if (fOutFile->IsOpen()) { fOutFile->Close(); } delete fOutFile; @@ -88,7 +90,13 @@ class RootOutFileManager delete fFolder; } - void SetFileProperties(const std::string& filename, const std::string& treeName, const std::string& branchName, const std::string& className = "", const std::string& fileOption = "RECREATE", bool useClonesArray = false, bool flowMode = true) + void SetFileProperties(const std::string& filename, + const std::string& treeName, + const std::string& branchName, + const std::string& className = "", + const std::string& fileOption = "RECREATE", + bool useClonesArray = false, + bool flowMode = true) { fFilename = filename; fTreeName = treeName; @@ -97,8 +105,7 @@ class RootOutFileManager fFileOption = fileOption; fUseClonesArray = useClonesArray; fFlowMode = flowMode; - if (!std::is_base_of::value && fUseClonesArray) - { + if (!std::is_base_of::value && fUseClonesArray) { fUseClonesArray = false; LOG(warn) << "Deactivate TClonesArray method: the data class must inherit from TObject."; } @@ -114,8 +121,7 @@ class RootOutFileManager fUseClonesArray = config.GetValue("use-clones-array"); fFlowMode = config.GetValue("flow-mode"); - if (!std::is_base_of::value && fUseClonesArray) - { + if (!std::is_base_of::value && fUseClonesArray) { fUseClonesArray = false; LOG(warn) << "Deactivate TClonesArray method: the data class must inherit from TObject."; } @@ -123,61 +129,48 @@ class RootOutFileManager void AddToFile(std::vector& inputData) { - if (fUseClonesArray) - { + if (fUseClonesArray) { fOutput->Delete(); - for (unsigned int i = 0; i < inputData.size(); ++i) - { + for (unsigned int i = 0; i < inputData.size(); ++i) { new ((*fOutput)[i]) DataType(inputData.at(i)); } - if (fOutput->IsEmpty()) - { + if (fOutput->IsEmpty()) { LOG(debug) << "RootOutFileManager::AddToFile(vector&): No Output array!"; } fTree->Fill(); - } - else - { - for (unsigned int i = 0; i < inputData.size(); ++i) - { + } else { + for (unsigned int i = 0; i < inputData.size(); ++i) { fOutputData = &inputData.at(i); fTree->Fill(); } } - if (!fFlowMode) - { + if (!fFlowMode) { fTree->Write("", TObject::kOverwrite); } } void AddToFile(DataType* objArr, long size) { - //todo : check if fine when update option - if (fUseClonesArray) - { + // todo : check if fine when update option + if (fUseClonesArray) { fOutput->Delete(); - for (unsigned int i = 0; i < size; ++i) - { + for (unsigned int i = 0; i < size; ++i) { new ((*fOutput)[i]) DataType(objArr[i]); } - if (fOutput->IsEmpty()) - { + if (fOutput->IsEmpty()) { LOG(debug) << "RootOutFileManager::AddToFile(vector&): No Output array!"; } fTree->Fill(); - if (!fFlowMode) - { + if (!fFlowMode) { fTree->Write("", TObject::kOverwrite); } - } - else - { + } else { std::vector dataVector(objArr, objArr + size); AddToFile(dataVector); } @@ -185,23 +178,18 @@ class RootOutFileManager void AddToFile(TClonesArray* inputData) { - if (fUseClonesArray) - { + if (fUseClonesArray) { fOutput = inputData; fTree->SetBranchAddress(fBranchName.c_str(), &fOutput); - if (fOutput->IsEmpty()) - { + if (fOutput->IsEmpty()) { LOG(debug) << "RootOutFileManager::AddToFile(TClonesArray*): No Output array!"; } fTree->Fill(); - if (!fFlowMode) - { + if (!fFlowMode) { fTree->Write("", TObject::kOverwrite); } - } - else - { + } else { LOG(debug) << "RootOutFileManager::AddToFile(TClonesArray*): TClonesArray not set as output container"; } } @@ -210,18 +198,14 @@ class RootOutFileManager { int inputSize = msg->GetSize(); int numInput = 0; - if (inputSize > 0) - { + if (inputSize > 0) { numInput = inputSize / sizeof(DataType); } fOutputData = static_cast(msg->GetData()); AddToFile(fOutputData, numInput); } - void AddToFile(std::unique_ptr& input) - { - AddToFile(input.get()); - } + void AddToFile(std::unique_ptr& input) { AddToFile(input.get()); } void InitOutputFile() { @@ -231,53 +215,39 @@ class RootOutFileManager bool updateTree = false; // if given option is update attempt to get tree from file - if (fFileOption == "UPDATE") - { + if (fFileOption == "UPDATE") { fTree = static_cast(fOutFile->Get(fTreeName.c_str())); - if (fTree) - { + if (fTree) { updateTree = true; LOG(info) << "Update tree"; - } - else - { + } else { updateTree = false; LOG(info) << "Create new tree"; } } // if tree not found or option is not UPDATE, create a new tree - if (!updateTree) - { + if (!updateTree) { fTree = new TTree(fTreeName.c_str(), "Test output"); } // direct storage or TClonesArray - if (fUseClonesArray) - { + if (fUseClonesArray) { fOutput = new TClonesArray(fClassName.c_str()); - if (updateTree) - { + if (updateTree) { fTree->SetBranchAddress(fBranchName.c_str(), &fOutput); + } else { + fTree->Branch(fBranchName.c_str(), "TClonesArray", &fOutput); } - else - { - fTree->Branch(fBranchName.c_str(),"TClonesArray", &fOutput); - } - } - else - { - if (updateTree) - { + } else { + if (updateTree) { fTree->SetBranchAddress(fBranchName.c_str(), &fOutputData); - } - else - { + } else { fTree->Branch(fBranchName.c_str(), fClassName.c_str(), &fOutputData); } } - fFolder = new TFolder("cbmroot","/cbmroot"); + fFolder = new TFolder("cbmroot", "/cbmroot"); TList* branchNameList = new TList(); branchNameList->AddLast(new TObjString(fBranchName.c_str())); branchNameList->Write("BranchList", TObject::kSingleKey); @@ -287,7 +257,9 @@ class RootOutFileManager } void InitTCA(const std::string& classname); - std::vector> GetAllObj(const std::string& filename, const std::string& treename, const std::string& branchname) + std::vector> GetAllObj(const std::string& filename, + const std::string& treename, + const std::string& branchname) { fWrite = false; @@ -296,57 +268,43 @@ class RootOutFileManager std::vector> allObj; std::vector tempObj; - if (file) - { + if (file) { fTree = static_cast(file->Get(fTreeName.c_str())); - } - else - { + } else { LOG(error) << "Could not open file" << fTreeName.c_str(); } - if (fTree) - { - if (fUseClonesArray) - { + if (fTree) { + if (fUseClonesArray) { fOutput = new TClonesArray(fClassName.c_str()); fTree->SetBranchAddress(fBranchName.c_str(), &fOutput); - for (Long64_t i = 0; i < fTree->GetEntries(); i++) - { + for (Long64_t i = 0; i < fTree->GetEntries(); i++) { tempObj.clear(); fTree->GetEntry(i); - for (Int_t iobj = 0; iobj < fOutput->GetEntriesFast(); ++iobj) - { + for (Int_t iobj = 0; iobj < fOutput->GetEntriesFast(); ++iobj) { DataType* data = reinterpret_cast(fOutput->At(iobj)); - if (!data) - { + if (!data) { continue; } tempObj.push_back(*data); } allObj.push_back(tempObj); } - } - else - { + } else { fTree->SetBranchAddress(branchname.c_str(), &fOutputData); - for (Long64_t i = 0; i < fTree->GetEntries(); i++) - { + for (Long64_t i = 0; i < fTree->GetEntries(); i++) { fTree->GetEntry(i); DataType data = *fOutputData; tempObj.push_back(data); } allObj.push_back(tempObj); } - } - else - { + } else { LOG(error) << "Could not find tree " << treename.c_str(); } - if (file) - { + if (file) { file->Close(); } return allObj; @@ -367,49 +325,35 @@ class RootOutFileManager bool updateTree = false; // if given option is update attempt to get tree from file - if (fFileOption == "UPDATE") - { + if (fFileOption == "UPDATE") { fTree = static_cast(fOutFile->Get(fTreeName.c_str())); - if (fTree) - { + if (fTree) { updateTree = true; LOG(info) << "Update tree"; - } - else - { + } else { updateTree = false; LOG(info) << "Create new tree"; } } // if tree not found or option is not UPDATE, create a new tree - if (!updateTree) - { + if (!updateTree) { fTree = new TTree(fTreeName.c_str(), "Test output"); } // direct storage or TClonesArray - if (fUseClonesArray) - { + if (fUseClonesArray) { fOutput = new TClonesArray(fClassName.c_str()); - if (updateTree) - { + if (updateTree) { fTree->SetBranchAddress(fBranchName.c_str(), &fOutput); + } else { + fTree->Branch(fBranchName.c_str(), "TClonesArray", &fOutput); } - else - { - fTree->Branch(fBranchName.c_str(),"TClonesArray", &fOutput); - } - } - else - { - if (updateTree) - { + } else { + if (updateTree) { fTree->SetBranchAddress(fBranchName.c_str(), &fOutputData); - } - else - { - fTree->Branch(fBranchName.c_str(),fClassName.c_str(), &fOutputData); + } else { + fTree->Branch(fBranchName.c_str(), fClassName.c_str(), &fOutputData); } } } diff --git a/base/MQ/policies/Storage/TriviallyCopyableDataSaver.h b/base/MQ/policies/Storage/TriviallyCopyableDataSaver.h index 0ae8543be8..dfc6b31444 100644 --- a/base/MQ/policies/Storage/TriviallyCopyableDataSaver.h +++ b/base/MQ/policies/Storage/TriviallyCopyableDataSaver.h @@ -1,4 +1,4 @@ -/* +/* * File: TriviallyCopyableDataSaver.h * Author: winckler * @@ -6,24 +6,23 @@ */ #ifndef TRIVIALLYCOPYABLEDATASAVER_H -#define TRIVIALLYCOPYABLEDATASAVER_H +#define TRIVIALLYCOPYABLEDATASAVER_H #include -template +template class TriviallyCopyableDataSaver { public: TriviallyCopyableDataSaver() {} - virtual ~TriviallyCopyableDataSaver(){} + virtual ~TriviallyCopyableDataSaver() {} - virtual void InitOutputFile(){} + virtual void InitOutputFile() {} void Write(std::ofstream& outfile, TPayload* ObjArr, long sizeArr = 1) { // if (std::is_trivially_copyable::value) not implemented yet in gcc 4.8.2 - if (std::is_trivial::value) - { + if (std::is_trivial::value) { write_pod_array(outfile, ObjArr, sizeArr); outfile.close(); } @@ -33,55 +32,47 @@ class TriviallyCopyableDataSaver { int inputSize = msg->GetSize(); long sizeArr = 0; - if (inputSize > 0) - { + if (inputSize > 0) { sizeArr = inputSize / sizeof(TPayload); } TPayload* ObjArr = static_cast(msg->GetData()); // if (std::is_trivially_copyable::value) - if (std::is_trivial::value) - { + if (std::is_trivial::value) { write_pod_array(outfile, ObjArr, sizeArr); outfile.close(); } } - std::vector > Read(std::ifstream& infile) + std::vector> Read(std::ifstream& infile) { - std::vector > DataContainer; - ReadArr(infile,DataContainer); + std::vector> DataContainer; + ReadArr(infile, DataContainer); return DataContainer; } - void ReadArr(std::ifstream& infile,std::vector >& DataContainer) + void ReadArr(std::ifstream& infile, std::vector>& DataContainer) { // if (std::is_trivially_copyable::value) - if (std::is_trivial::value) - { + if (std::is_trivial::value) { int c = infile.peek(); - if (c == EOF) - { - if (infile.eof()) - { - infile.close(); + if (c == EOF) { + if (infile.eof()) { + infile.close(); } - } - else - { + } else { long sizeArr; read_pod(infile, sizeArr); TPayload* ObjArr = new TPayload[sizeArr]; infile.read(reinterpret_cast(ObjArr), sizeArr * sizeof(TPayload)); - std::vector DataVector(ObjArr, ObjArr + sizeArr); + std::vector DataVector(ObjArr, ObjArr + sizeArr); delete[] ObjArr; DataContainer.push_back(DataVector); ReadArr(infile, DataContainer); } - } - else - { + } else { LOG(error) << "In ReadArr(std::ifstream& , std::vector >& ) :"; - LOG(error) << "(de)serialization of object is not supported (Object must be a 'trivially copyable' data class)."; + LOG(error) + << "(de)serialization of object is not supported (Object must be a 'trivially copyable' data class)."; } } @@ -89,26 +80,20 @@ class TriviallyCopyableDataSaver void ReadArr(std::ifstream& infile, T* ObjArr, long posArr = 0) { // if(std::is_trivially_copyable::value) - if (std::is_trivial::value) - { + if (std::is_trivial::value) { int c = infile.peek(); - if (c == EOF) - { - if (infile.eof()) - { - infile.close(); + if (c == EOF) { + if (infile.eof()) { + infile.close(); } - } - else - { + } else { posArr += read_pod_array(infile, ObjArr, posArr); ReadArr(infile, ObjArr, posArr); } - } - else - { + } else { LOG(error) << "In ReadArr(std::ifstream& infile, T* ObjArr, long posArr = 0):"; - LOG(error) << "(de)serialization of object is not supported (Object must be a 'trivially copyable' data class)."; + LOG(error) + << "(de)serialization of object is not supported (Object must be a 'trivially copyable' data class)."; } } @@ -153,23 +138,18 @@ class TriviallyCopyableDataSaver { int count = 0; // if (std::is_trivially_copyable::value) - if (std::is_trivial::value) - { + if (std::is_trivial::value) { int c = in.peek(); - if (c == EOF) - { - if (in.eof()) - { - in.close(); + if (c == EOF) { + if (in.eof()) { + in.close(); } - } - else - { + } else { long size; read_pod(in, size); count += size; - in.seekg (size * sizeof(T), std::ios::cur); - count+=count_podObj_inFile(in); + in.seekg(size * sizeof(T), std::ios::cur); + count += count_podObj_inFile(in); } } return count; @@ -180,7 +160,7 @@ class TriviallyCopyableDataSaver { long size; read_pod(in, size); - in.read(reinterpret_cast(objarr+posArr), size * sizeof(T)); + in.read(reinterpret_cast(objarr + posArr), size * sizeof(T)); return size; } }; diff --git a/base/MQ/tasks/FairMQProcessorTask.cxx b/base/MQ/tasks/FairMQProcessorTask.cxx index d3e455816b..6836a4b880 100644 --- a/base/MQ/tasks/FairMQProcessorTask.cxx +++ b/base/MQ/tasks/FairMQProcessorTask.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /** @@ -14,26 +14,14 @@ #include "FairMQProcessorTask.h" - FairMQProcessorTask::FairMQProcessorTask() : fPayload() -{ -} +{} -FairMQProcessorTask::~FairMQProcessorTask() -{ -} +FairMQProcessorTask::~FairMQProcessorTask() {} -void FairMQProcessorTask::Exec(Option_t* /*opt*/) -{ -} +void FairMQProcessorTask::Exec(Option_t* /*opt*/) {} -void FairMQProcessorTask::SetPayload(std::unique_ptr& msg) -{ - fPayload = std::move(msg); -} +void FairMQProcessorTask::SetPayload(std::unique_ptr& msg) { fPayload = std::move(msg); } -void FairMQProcessorTask::GetPayload(std::unique_ptr& msg) -{ - msg = std::move(fPayload); -} +void FairMQProcessorTask::GetPayload(std::unique_ptr& msg) { msg = std::move(fPayload); } diff --git a/base/MQ/tasks/FairMQProcessorTask.h b/base/MQ/tasks/FairMQProcessorTask.h index 6078ffd409..3e0be24358 100644 --- a/base/MQ/tasks/FairMQProcessorTask.h +++ b/base/MQ/tasks/FairMQProcessorTask.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /** diff --git a/base/MQ/tasks/FairMQSamplerTask.cxx b/base/MQ/tasks/FairMQSamplerTask.cxx index 5bbf7560f5..5e4721819c 100644 --- a/base/MQ/tasks/FairMQSamplerTask.cxx +++ b/base/MQ/tasks/FairMQSamplerTask.cxx @@ -24,8 +24,7 @@ FairMQSamplerTask::FairMQSamplerTask() , fEventIndex(0) , fEvtHeader(nullptr) , fTransportFactory(nullptr) -{ -} +{} FairMQSamplerTask::FairMQSamplerTask(const Text_t* name, int iVerbose) : FairTask(name, iVerbose) @@ -35,13 +34,9 @@ FairMQSamplerTask::FairMQSamplerTask(const Text_t* name, int iVerbose) , fEventIndex(0) , fEvtHeader(nullptr) , fTransportFactory(nullptr) -{ -} +{} -FairMQSamplerTask::~FairMQSamplerTask() -{ - delete fInput; -} +FairMQSamplerTask::~FairMQSamplerTask() { delete fInput; } InitStatus FairMQSamplerTask::Init() { @@ -52,26 +47,12 @@ InitStatus FairMQSamplerTask::Init() return kSUCCESS; } -void FairMQSamplerTask::Exec(Option_t* /*opt*/) -{ -} +void FairMQSamplerTask::Exec(Option_t* /*opt*/) {} -void FairMQSamplerTask::SetBranch(const string& branch) -{ - fBranch = branch; -} +void FairMQSamplerTask::SetBranch(const string& branch) { fBranch = branch; } -void FairMQSamplerTask::SetEventIndex(Long64_t eventIndex) -{ - fEventIndex = eventIndex; -} +void FairMQSamplerTask::SetEventIndex(Long64_t eventIndex) { fEventIndex = eventIndex; } -void FairMQSamplerTask::GetPayload(FairMQMessagePtr& msg) -{ - msg = move(fPayload); -} +void FairMQSamplerTask::GetPayload(FairMQMessagePtr& msg) { msg = move(fPayload); } -void FairMQSamplerTask::SetTransport(shared_ptr factory) -{ - fTransportFactory = factory; -} +void FairMQSamplerTask::SetTransport(shared_ptr factory) { fTransportFactory = factory; } diff --git a/base/MQ/tasks/FairMQSamplerTask.h b/base/MQ/tasks/FairMQSamplerTask.h index 6ca51d7557..229754c201 100644 --- a/base/MQ/tasks/FairMQSamplerTask.h +++ b/base/MQ/tasks/FairMQSamplerTask.h @@ -15,15 +15,14 @@ #ifndef FAIRMQSAMPLERTASK_H_ #define FAIRMQSAMPLERTASK_H_ -#include -#include - -#include +#include "FairEventHeader.h" #include "FairMQTransportFactory.h" +#include "FairTask.h" +#include #include -#include "FairTask.h" -#include "FairEventHeader.h" +#include +#include class FairMQSamplerTask : public FairTask { @@ -36,7 +35,7 @@ class FairMQSamplerTask : public FairTask virtual ~FairMQSamplerTask(); virtual InitStatus Init(); - virtual void Exec(Option_t *opt); + virtual void Exec(Option_t* opt); void SetEventIndex(Long64_t eventIndex); void SetBranch(const std::string& branch); diff --git a/base/event/FairEventBuilder.cxx b/base/event/FairEventBuilder.cxx index f6a5a7063f..f6504e5d60 100644 --- a/base/event/FairEventBuilder.cxx +++ b/base/event/FairEventBuilder.cxx @@ -34,74 +34,70 @@ #include "FairTimeStamp.h" #include - #include FairEventBuilder::FairEventBuilder() - : FairWriteoutBuffer(), - fBuilderName (""), - fTimer (), - fExecTime (0.), - fIdentifier (0), - fMaxAllowedEventCreationTime(0.) -{ -} + : FairWriteoutBuffer() + , fBuilderName("") + , fTimer() + , fExecTime(0.) + , fIdentifier(0) + , fMaxAllowedEventCreationTime(0.) +{} FairEventBuilder::FairEventBuilder(TString branchName, TString className, TString folderName, Bool_t persistance) - : FairWriteoutBuffer(branchName,className,folderName,persistance), - fBuilderName (""), - fTimer (), - fExecTime (0.), - fIdentifier (0), - fMaxAllowedEventCreationTime(0.) -{ -} + : FairWriteoutBuffer(branchName, className, folderName, persistance) + , fBuilderName("") + , fTimer() + , fExecTime(0.) + , fIdentifier(0) + , fMaxAllowedEventCreationTime(0.) +{} -FairEventBuilder::~FairEventBuilder() -{ -} +FairEventBuilder::~FairEventBuilder() {} void FairEventBuilder::WriteOutAllDeadTimeData() { - if (fBranchName.Length() < 1) { - return; - } - - FairRootManager* ioman = FairRootManager::Instance(); - std::vector data; - if (fActivateBuffering) { - if (fVerbose > 0) { - std::cout << "-I- FairEventBuilder::WriteOutAllDeadTimeData" << std::endl; + if (fBranchName.Length() < 1) { + return; } - data = GetAllData(); - if (fTreeSave && data.size() > 0) { - TClonesArray* myArray = ioman->GetTClonesArray(fBranchName); - if (!myArray) { - std::cout << "-E- FairEventBuilder::WriteOutData " << fBranchName << " array is not available!" << std::endl; - } - if (fVerbose > 0) { - std::cout << "-I- FairEventBuilder::WriteOutData size: " << data.size() << std::endl; - } - for (unsigned int i = 0; i < data.size(); i++) { - AddNewDataToTClonesArray(data[i]); - if (fVerbose > 1) { - std::cout << i << " : "; - data[i]->Print(); - std::cout << std::endl; + + FairRootManager* ioman = FairRootManager::Instance(); + std::vector data; + if (fActivateBuffering) { + if (fVerbose > 0) { + std::cout << "-I- FairEventBuilder::WriteOutAllDeadTimeData" << std::endl; + } + data = GetAllData(); + if (fTreeSave && data.size() > 0) { + TClonesArray* myArray = ioman->GetTClonesArray(fBranchName); + if (!myArray) { + std::cout << "-E- FairEventBuilder::WriteOutData " << fBranchName << " array is not available!" + << std::endl; + } + if (fVerbose > 0) { + std::cout << "-I- FairEventBuilder::WriteOutData size: " << data.size() << std::endl; + } + for (unsigned int i = 0; i < data.size(); i++) { + AddNewDataToTClonesArray(data[i]); + if (fVerbose > 1) { + std::cout << i << " : "; + data[i]->Print(); + std::cout << std::endl; + } + delete data[i]; + } } - delete data[i]; - } + } else { + ioman->GetTClonesArray(fBranchName); } - } else { - ioman->GetTClonesArray(fBranchName); - } } void FairEventBuilder::Finish() { - std::cout << "-------------------- " << GetBuilderName() << " : Summary -----------------------" << std::endl; - std::cout << " Should be implemented by the user" << std::endl; - std::cout << "---------------------------------------------------------------------" << std::endl; + std::cout << "-------------------- " << GetBuilderName() << " : Summary -----------------------" << std::endl; + std::cout << " Should be implemented by the user" << std::endl; + std::cout << "---------------------------------------------------------------------" << std::endl; } -ClassImp(FairEventBuilder) +ClassImp(FairEventBuilder); diff --git a/base/event/FairEventBuilder.h b/base/event/FairEventBuilder.h index 48b70136a5..714d09f042 100644 --- a/base/event/FairEventBuilder.h +++ b/base/event/FairEventBuilder.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ //* $Id: */ @@ -12,7 +12,6 @@ // ----- Created 23/09/2013 by R. Karabowicz ----- // ------------------------------------------------------------------------- - /** FairEventBuilder *@author Radoslaw Karabowicz *@since 23/09/2013 @@ -32,18 +31,17 @@ #ifndef FAIREVENTBUILDER_H #define FAIREVENTBUILDER_H 1 -#include "FairWriteoutBuffer.h" #include "FairRecoEventHeader.h" +#include "FairWriteoutBuffer.h" +#include #include #include -#include - +#include // pair #include -#include // pair class TClonesArray; -//class FairRecoEventHeader; +// class FairRecoEventHeader; class FairEventBuilder : public FairWriteoutBuffer { @@ -79,15 +77,15 @@ class FairEventBuilder : public FairWriteoutBuffer TString GetBuilderName() { return fBuilderName; } private: - TString fBuilderName; + TString fBuilderName; TStopwatch fTimer; - Double_t fExecTime; + Double_t fExecTime; - Int_t fIdentifier; - Double_t fMaxAllowedEventCreationTime; + Int_t fIdentifier; + Double_t fMaxAllowedEventCreationTime; - ClassDef(FairEventBuilder,1); + ClassDef(FairEventBuilder, 1); }; #endif diff --git a/base/event/FairEventBuilderManager.cxx b/base/event/FairEventBuilderManager.cxx index f8b38bf8cd..06ca953953 100644 --- a/base/event/FairEventBuilderManager.cxx +++ b/base/event/FairEventBuilderManager.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* $Id: */ @@ -35,148 +35,148 @@ #include "FairRunAna.h" #include - #include using std::cout; using std::endl; FairEventBuilderManager::FairEventBuilderManager() - : FairTask("FairEventBuilderManager", 0), - fEventBuilders(), - fPossibleEvents() -{ -} + : FairTask("FairEventBuilderManager", 0) + , fEventBuilders() + , fPossibleEvents() +{} FairEventBuilderManager::FairEventBuilderManager(const char* name, Int_t iVerbose) - : FairTask(name, iVerbose), - fEventBuilders(), - fPossibleEvents() -{ -} + : FairTask(name, iVerbose) + , fEventBuilders() + , fPossibleEvents() +{} -FairEventBuilderManager::~FairEventBuilderManager() -{ -} +FairEventBuilderManager::~FairEventBuilderManager() {} void FairEventBuilderManager::Exec(Option_t*) { - if (fVerbose) { - cout << "FairEventBuilderManager::Exec() begin" << endl; - } + if (fVerbose) { + cout << "FairEventBuilderManager::Exec() begin" << endl; + } - Double_t maxEventTimeAllowed = FillEventVectors(); + Double_t maxEventTimeAllowed = FillEventVectors(); - if (fVerbose) { - cout << "++ CAN CREATE EVENTS THAT ARE SMALLER THAN " << maxEventTimeAllowed << " ns" << endl; - } + if (fVerbose) { + cout << "++ CAN CREATE EVENTS THAT ARE SMALLER THAN " << maxEventTimeAllowed << " ns" << endl; + } - // AnalyzeAndExtractEvents function: - // - works on fEventBuilders[ieb] - // - should extract possible events - // - is implemented by different experiments - AnalyzeAndExtractEvents(maxEventTimeAllowed); + // AnalyzeAndExtractEvents function: + // - works on fEventBuilders[ieb] + // - should extract possible events + // - is implemented by different experiments + AnalyzeAndExtractEvents(maxEventTimeAllowed); - return; + return; } Double_t FairEventBuilderManager::FillEventVectors() { - // for (std::vector::iterator it = fEventBuilders.begin() ; it != fEventBuilders.end() ; ++it) { - // *it.FindEvents(); - // } - Double_t maxEventTimeAllowed = 10.e6; - for (UInt_t ieb = 0 ; ieb < fEventBuilders.size() ; ieb++) { - if (fVerbose) { cout << "***** " << fEventBuilders[ieb]->GetName() << " *****" << endl; } - if (fVerbose) { cout << " there are " << fPossibleEvents[ieb].size() << " possible events" << endl; } - std::vector> tempBuilder = fEventBuilders[ieb]->FindEvents(); - if (fVerbose) { - cout << " event buffer " << fEventBuilders[ieb]->GetName() << " found " << tempBuilder.size() << " events" << endl; - } - std::pair tempPair; - for (UInt_t ipair = 0 ; ipair < tempBuilder.size() ; ipair++) { - fPossibleEvents[ieb].push_back(tempBuilder[ipair]); - if (fVerbose) - cout << " added event " << fPossibleEvents[ieb][fPossibleEvents[ieb].size()-1].second - << " at " << fPossibleEvents[ieb][fPossibleEvents[ieb].size()-1].second->GetEventTime() << " ns." << endl; + // for (std::vector::iterator it = fEventBuilders.begin() ; it != fEventBuilders.end() ; ++it) { + // *it.FindEvents(); + // } + Double_t maxEventTimeAllowed = 10.e6; + for (UInt_t ieb = 0; ieb < fEventBuilders.size(); ieb++) { + if (fVerbose) { + cout << "***** " << fEventBuilders[ieb]->GetName() << " *****" << endl; + } + if (fVerbose) { + cout << " there are " << fPossibleEvents[ieb].size() << " possible events" << endl; + } + std::vector> tempBuilder = fEventBuilders[ieb]->FindEvents(); + if (fVerbose) { + cout << " event buffer " << fEventBuilders[ieb]->GetName() << " found " << tempBuilder.size() << " events" + << endl; + } + std::pair tempPair; + for (UInt_t ipair = 0; ipair < tempBuilder.size(); ipair++) { + fPossibleEvents[ieb].push_back(tempBuilder[ipair]); + if (fVerbose) + cout << " added event " << fPossibleEvents[ieb][fPossibleEvents[ieb].size() - 1].second << " at " + << fPossibleEvents[ieb][fPossibleEvents[ieb].size() - 1].second->GetEventTime() << " ns." << endl; + } + if (fVerbose) { + cout << " and now " << fPossibleEvents[ieb].size() << " possible events" << endl; + } + + if (fEventBuilders[ieb]->AllowedTime() < maxEventTimeAllowed) { + maxEventTimeAllowed = fEventBuilders[ieb]->AllowedTime(); + } } - if (fVerbose) { - cout << " and now " << fPossibleEvents[ieb].size() << " possible events" << endl; - } - - if (fEventBuilders[ieb]->AllowedTime() < maxEventTimeAllowed) { - maxEventTimeAllowed = fEventBuilders[ieb]->AllowedTime(); - } - } - return maxEventTimeAllowed; + return maxEventTimeAllowed; } void FairEventBuilderManager::CreateAndFillEvent(FairRecoEventHeader* recoEvent) { - for (UInt_t ieb = 0 ; ieb < fEventBuilders.size() ; ieb++) { - fEventBuilders[ieb]->StoreEventData(recoEvent); - fEventBuilders[ieb]->WriteOutAllDeadTimeData(); - } + for (UInt_t ieb = 0; ieb < fEventBuilders.size(); ieb++) { + fEventBuilders[ieb]->StoreEventData(recoEvent); + fEventBuilders[ieb]->WriteOutAllDeadTimeData(); + } - FairRootManager::Instance()->Fill(); + FairRootManager::Instance()->Fill(); - for (UInt_t ieb = 0 ; ieb < fEventBuilders.size() ; ieb++) { - fEventBuilders[ieb]->DeleteOldData(); - } + for (UInt_t ieb = 0; ieb < fEventBuilders.size(); ieb++) { + fEventBuilders[ieb]->DeleteOldData(); + } } void FairEventBuilderManager::AddEventBuilder(FairEventBuilder* eventBuilder) { - fEventBuilders .push_back(eventBuilder); - std::vector> tcArray; - fPossibleEvents.push_back(tcArray); - // if (fVerbose) - cout << "*** FairEventBuilderManager. Registered " << eventBuilder->GetName() << endl; + fEventBuilders.push_back(eventBuilder); + std::vector> tcArray; + fPossibleEvents.push_back(tcArray); + // if (fVerbose) + cout << "*** FairEventBuilderManager. Registered " << eventBuilder->GetName() << endl; } void FairEventBuilderManager::SetParContainers() { - // Get run and runtime database - FairRunAna* run = FairRunAna::Instance(); - if (! run) { - Fatal("SetParContainers", "No analysis run"); - } else { - FairRuntimeDb* db = run->GetRuntimeDb(); - if (! db) { Fatal("SetParContainers", "No runtime database"); } - } + // Get run and runtime database + FairRunAna* run = FairRunAna::Instance(); + if (!run) { + Fatal("SetParContainers", "No analysis run"); + } else { + FairRuntimeDb* db = run->GetRuntimeDb(); + if (!db) { + Fatal("SetParContainers", "No runtime database"); + } + } } InitStatus FairEventBuilderManager::Init() { - // Get input array - FairRootManager* ioman = FairRootManager::Instance(); - if (! ioman) { Fatal("Init", "No FairRootManager"); } + // Get input array + FairRootManager* ioman = FairRootManager::Instance(); + if (!ioman) { + Fatal("Init", "No FairRootManager"); + } - cout << "*** FairEventBuilderManager. " << fEventBuilders.size() << " event builders registered." << endl; + cout << "*** FairEventBuilderManager. " << fEventBuilders.size() << " event builders registered." << endl; - for (UInt_t ieb = 0 ; ieb < fEventBuilders.size() ; ieb++) { - fEventBuilders[ieb]->SetIdentifier(TMath::Power(2,static_cast(ieb))); - fEventBuilders[ieb]->Init(); - } + for (UInt_t ieb = 0; ieb < fEventBuilders.size(); ieb++) { + fEventBuilders[ieb]->SetIdentifier(TMath::Power(2, static_cast(ieb))); + fEventBuilders[ieb]->Init(); + } - return kSUCCESS; + return kSUCCESS; } -InitStatus FairEventBuilderManager::ReInit() -{ - - return kSUCCESS; -} +InitStatus FairEventBuilderManager::ReInit() { return kSUCCESS; } void FairEventBuilderManager::Finish() { - AnalyzeAndExtractEvents(-1.); + AnalyzeAndExtractEvents(-1.); - cout << "==================== " << fName.Data() << " : Summary ========================" << endl; - for (UInt_t ieb = 0 ; ieb < fEventBuilders.size() ; ieb++) { - fEventBuilders[ieb]->Finish(); - } - cout << "=====================================================================" << endl; + cout << "==================== " << fName.Data() << " : Summary ========================" << endl; + for (UInt_t ieb = 0; ieb < fEventBuilders.size(); ieb++) { + fEventBuilders[ieb]->Finish(); + } + cout << "=====================================================================" << endl; } -ClassImp(FairEventBuilderManager) +ClassImp(FairEventBuilderManager); diff --git a/base/event/FairEventBuilderManager.h b/base/event/FairEventBuilderManager.h index 7051f6839b..6ed99707b6 100644 --- a/base/event/FairEventBuilderManager.h +++ b/base/event/FairEventBuilderManager.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ //* $Id: */ @@ -12,7 +12,6 @@ // ----- Created 20/09/2013 by R. Karabowicz ----- // ------------------------------------------------------------------------- - /** FairEventBuilderManager *@author Radoslaw Karabowicz *@since 20/09/2013 @@ -32,11 +31,10 @@ #ifndef FAIREVENTBUILDERMANAGER_H #define FAIREVENTBUILDERMANAGER_H 1 -#include "FairTask.h" #include "FairEventBuilder.h" +#include "FairTask.h" -#include // ClassDef - +#include // ClassDef #include class TClonesArray; @@ -48,7 +46,7 @@ class FairEventBuilderManager : public FairTask FairEventBuilderManager(); /** Constructor with task name **/ - FairEventBuilderManager(const char* name, Int_t iVerbose=1); + FairEventBuilderManager(const char* name, Int_t iVerbose = 1); /** Destructor **/ virtual ~FairEventBuilderManager(); @@ -61,7 +59,7 @@ class FairEventBuilderManager : public FairTask protected: std::vector fEventBuilders; - std::vector>> fPossibleEvents; + std::vector>> fPossibleEvents; /** Fill events from various builders **/ virtual Double_t FillEventVectors(); @@ -85,7 +83,7 @@ class FairEventBuilderManager : public FairTask /** Finish at the end of each event **/ virtual void Finish(); - ClassDef(FairEventBuilderManager,1); + ClassDef(FairEventBuilderManager, 1); }; #endif diff --git a/base/event/FairEventHeader.cxx b/base/event/FairEventHeader.cxx index 300f2db547..8692197eac 100644 --- a/base/event/FairEventHeader.cxx +++ b/base/event/FairEventHeader.cxx @@ -11,21 +11,21 @@ // ------------------------------------------------------------------------- #include "FairEventHeader.h" + #include "FairRootManager.h" FairEventHeader::FairEventHeader() - :fRunId(0), - fEventTime(-1.), - fInputFileId(0), - fMCEntryNo(0) -{ -} + : fRunId(0) + , fEventTime(-1.) + , fInputFileId(0) + , fMCEntryNo(0) +{} -FairEventHeader::~FairEventHeader() { } +FairEventHeader::~FairEventHeader() {} void FairEventHeader::Register(Bool_t Persistence) { - FairRootManager::Instance()->Register("EventHeader.", "EvtHeader", this, Persistence); + FairRootManager::Instance()->Register("EventHeader.", "EvtHeader", this, Persistence); } -ClassImp(FairEventHeader) +ClassImp(FairEventHeader); diff --git a/base/event/FairEventHeader.h b/base/event/FairEventHeader.h index 2f42b34b9f..93a19bd206 100644 --- a/base/event/FairEventHeader.h +++ b/base/event/FairEventHeader.h @@ -13,13 +13,13 @@ #ifndef FAIREVENTHEADER_H #define FAIREVENTHEADER_H -#include // for TNamed -#include // for Int_t, Double_t, UInt_t, ClassDef, etc +#include // for Int_t, Double_t, UInt_t, ClassDef, etc +#include // for TNamed /** * Event Header Class - **@author D.Bertini - **@author M.Al-Turany + **@author D.Bertini + **@author M.Al-Turany */ class FairEventHeader : public TNamed { @@ -40,8 +40,8 @@ class FairEventHeader : public TNamed Int_t GetMCEntryNumber() { return fMCEntryNo; } /** Set the run ID for this run - * @param runid : unique run id - */ + * @param runid : unique run id + */ void SetRunId(UInt_t runid) { fRunId = runid; } /** Set the MC time for this event @@ -65,13 +65,13 @@ class FairEventHeader : public TNamed /** Run Id */ UInt_t fRunId; /** Event Time **/ - Double_t fEventTime; + Double_t fEventTime; /** Input file identifier, the file description is in the File header*/ - Int_t fInputFileId; + Int_t fInputFileId; /**MC entry number from input chain*/ - Int_t fMCEntryNo; + Int_t fMCEntryNo; - ClassDef(FairEventHeader,3) + ClassDef(FairEventHeader, 3) }; #endif diff --git a/base/event/FairFileHeader.cxx b/base/event/FairFileHeader.cxx index 82c66ebf8c..8f5a88a47f 100644 --- a/base/event/FairFileHeader.cxx +++ b/base/event/FairFileHeader.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -12,50 +12,44 @@ #include "FairFileHeader.h" -#include "FairFileInfo.h" // for FairFileInfo +#include "FairFileInfo.h" // for FairFileInfo -#include // for TIterator -#include // for TList -#include // for TObjString -#include // for TObject +#include // for TIterator +#include // for TList +#include // for TObjString +#include // for TObject class TFile; FairFileHeader::FairFileHeader() - :TNamed(), - fRunId(0), - fTaskList(new TList()), - fFileList(new TList()) -{ -} + : TNamed() + , fRunId(0) + , fTaskList(new TList()) + , fFileList(new TList()) +{} -void FairFileHeader::AddTaskClassName(TString taskname) -{ - fTaskList->AddLast(new TObjString(taskname)); -} +void FairFileHeader::AddTaskClassName(TString taskname) { fTaskList->AddLast(new TObjString(taskname)); } -void FairFileHeader::AddInputFile(TFile* f, UInt_t id, UInt_t ChId) +void FairFileHeader::AddInputFile(TFile* f, UInt_t id, UInt_t ChId) { - fFileList->AddLast(new FairFileInfo(f,id, ChId)); + fFileList->AddLast(new FairFileInfo(f, id, ChId)); } FairFileInfo* FairFileHeader::GetFileInfo(UInt_t id, UInt_t ChId) { - TIterator* Iter=fFileList->MakeIterator(); - Iter->Reset(); - TObject* obj = 0; - FairFileInfo* info = 0; - while ((obj = Iter->Next())) { - info = dynamic_cast (obj); - if (info && info->GetIdentifier() == id && info->GetOrderInChain() == ChId) { - return info; + TIterator* Iter = fFileList->MakeIterator(); + Iter->Reset(); + TObject* obj = 0; + FairFileInfo* info = 0; + while ((obj = Iter->Next())) { + info = dynamic_cast(obj); + if (info && info->GetIdentifier() == id && info->GetOrderInChain() == ChId) { + return info; + } } - } - delete Iter; - return 0; + delete Iter; + return 0; } -FairFileHeader::~FairFileHeader() -{ -} +FairFileHeader::~FairFileHeader() {} -ClassImp(FairFileHeader) +ClassImp(FairFileHeader); diff --git a/base/event/FairFileHeader.h b/base/event/FairFileHeader.h index 5e35d7fafb..ecfde53e8c 100644 --- a/base/event/FairFileHeader.h +++ b/base/event/FairFileHeader.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -13,10 +13,9 @@ #ifndef FAIRFILEHEADER_H #define FAIRFILEHEADER_H -#include // for TNamed - -#include // for UInt_t, etc -#include // for TString +#include // for UInt_t, etc +#include // for TNamed +#include // for TString class FairFileInfo; class TFile; @@ -24,7 +23,7 @@ class TList; /** * File Header Class - **@author M.Al-Turany + **@author M.Al-Turany */ class FairFileHeader : public TNamed { @@ -36,8 +35,8 @@ class FairFileHeader : public TNamed void AddTaskClassName(TString taskname); /** Set the run ID for this run - * @param runid : unique run id - */ + * @param runid : unique run id + */ void SetRunId(UInt_t runid) { fRunId = runid; } /** Get the run ID for this run*/ @@ -69,7 +68,7 @@ class FairFileHeader : public TNamed FairFileHeader(const FairFileHeader&); FairFileHeader& operator=(const FairFileHeader&); - ClassDef(FairFileHeader,2) + ClassDef(FairFileHeader, 2) }; #endif diff --git a/base/event/FairFileInfo.cxx b/base/event/FairFileInfo.cxx index 732ff7c6a1..ed1e0605da 100644 --- a/base/event/FairFileInfo.cxx +++ b/base/event/FairFileInfo.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // FairFileInfo.cxx @@ -10,43 +10,39 @@ // #include "FairFileInfo.h" -#include // for TFile -#include // for TSystem, gSystem - -#include // for printf +#include // for TFile +#include // for TSystem, gSystem +#include // for printf //__________________________________________________________________________ FairFileInfo::FairFileInfo() - :TNamed(), - fPath(""), - fSize(0), - fIdentifier(0), - fInChainId(0) -{ -} + : TNamed() + , fPath("") + , fSize(0) + , fIdentifier(0) + , fInChainId(0) +{} //__________________________________________________________________________ -FairFileInfo::FairFileInfo(TFile* file, UInt_t id, UInt_t ChId) - :TNamed(file->GetName(), "Inputfile"), - fPath(""), - fSize(file->GetSize()), - fIdentifier(id), - fInChainId(ChId) +FairFileInfo::FairFileInfo(TFile* file, UInt_t id, UInt_t ChId) + : TNamed(file->GetName(), "Inputfile") + , fPath("") + , fSize(file->GetSize()) + , fIdentifier(id) + , fInChainId(ChId) { - fPath += gSystem->WorkingDirectory(); - fPath += fName; + fPath += gSystem->WorkingDirectory(); + fPath += fName; } //__________________________________________________________________________ -FairFileInfo::~FairFileInfo() -{ -} +FairFileInfo::~FairFileInfo() {} //__________________________________________________________________________ void FairFileInfo::Print(Option_t*) const { - printf("Printing FairFileInfo for : %s \n", fName.Data()); - printf("File full path : %s \n", fPath.Data()); - printf("File Size in Byte : %i \n", fSize); - printf("File Identifier : %i \n", fIdentifier); - printf("File order in input chain : %i \n", fInChainId); + printf("Printing FairFileInfo for : %s \n", fName.Data()); + printf("File full path : %s \n", fPath.Data()); + printf("File Size in Byte : %i \n", fSize); + printf("File Identifier : %i \n", fIdentifier); + printf("File order in input chain : %i \n", fInChainId); } //__________________________________________________________________________ -ClassImp(FairFileInfo) +ClassImp(FairFileInfo); diff --git a/base/event/FairFileInfo.h b/base/event/FairFileInfo.h index 3a1d329860..58d9be0ea0 100644 --- a/base/event/FairFileInfo.h +++ b/base/event/FairFileInfo.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // FairFileInfo.h @@ -11,9 +11,9 @@ #ifndef FAIRFILEINFO_H #define FAIRFILEINFO_H -#include // for TNamed -#include // for UInt_t, FairFileInfo::Class, etc -#include // for TString +#include // for UInt_t, FairFileInfo::Class, etc +#include // for TNamed +#include // for TString class TFile; @@ -21,36 +21,36 @@ class FairFileInfo : public TNamed { public: FairFileInfo(); - FairFileInfo(TFile* file, UInt_t id, UInt_t ChId); - virtual ~FairFileInfo(); + FairFileInfo(TFile* file, UInt_t id, UInt_t ChId); + virtual ~FairFileInfo(); - TString GetPath() { return fPath; } - UInt_t GetSize() { return fSize; } - UInt_t GetIdentifier() { return fIdentifier; } - UInt_t GetOrderInChain() { return fInChainId; } + TString GetPath() { return fPath; } + UInt_t GetSize() { return fSize; } + UInt_t GetIdentifier() { return fIdentifier; } + UInt_t GetOrderInChain() { return fInChainId; } - void Print(Option_t* option="") const; + void Print(Option_t* option = "") const; - void SetPath(TString path) {fPath = path;} - void SetSize(UInt_t size) {fSize =size;} - void SetIdentifier(UInt_t id) {fIdentifier =id;} - void SetOrderInChain(UInt_t id) {fInChainId =id;} + void SetPath(TString path) { fPath = path; } + void SetSize(UInt_t size) { fSize = size; } + void SetIdentifier(UInt_t id) { fIdentifier = id; } + void SetOrderInChain(UInt_t id) { fInChainId = id; } protected: /** Full path of file*/ TString fPath; /** size of file in bytes*/ - UInt_t fSize; + UInt_t fSize; /** Signal file identifier used*/ - UInt_t fIdentifier; + UInt_t fIdentifier; /** file order in the chain*/ - UInt_t fInChainId; + UInt_t fInChainId; private: FairFileInfo(const FairFileInfo&); FairFileInfo& operator=(const FairFileInfo&); - ClassDef(FairFileInfo,1) + ClassDef(FairFileInfo, 1) }; -#endif //FAIRFILEINFO_H +#endif // FAIRFILEINFO_H diff --git a/base/event/FairHit.cxx b/base/event/FairHit.cxx index 1ab58f03a4..d1c61696d2 100644 --- a/base/event/FairHit.cxx +++ b/base/event/FairHit.cxx @@ -1,38 +1,36 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "FairHit.h" FairHit::FairHit() - : FairTimeStamp(), - fDx(0), - fDy(0), - fDz(0), - fRefIndex(-1), - fDetectorID(-1), - fX(0), - fY(0), - fZ(0) -{ -} + : FairTimeStamp() + , fDx(0) + , fDy(0) + , fDz(0) + , fRefIndex(-1) + , fDetectorID(-1) + , fX(0) + , fY(0) + , fZ(0) +{} FairHit::FairHit(Int_t detID, const TVector3& pos, const TVector3& dpos, Int_t index) - :FairTimeStamp(), - fDx (dpos.X()), - fDy (dpos.Y()), - fDz (dpos.Z()), - fRefIndex (index), - fDetectorID (detID), - fX (pos.X()), - fY (pos.Y()), - fZ (pos.Z()) -{ -} + : FairTimeStamp() + , fDx(dpos.X()) + , fDy(dpos.Y()) + , fDz(dpos.Z()) + , fRefIndex(index) + , fDetectorID(detID) + , fX(pos.X()) + , fY(pos.Y()) + , fZ(pos.Z()) +{} -FairHit::~FairHit() { } +FairHit::~FairHit() {} -ClassImp(FairHit) +ClassImp(FairHit); diff --git a/base/event/FairHit.h b/base/event/FairHit.h index 6e9a0f15d7..c5f60414d4 100644 --- a/base/event/FairHit.h +++ b/base/event/FairHit.h @@ -1,26 +1,30 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRHIT_H #define FAIRHIT_H -#include "FairTimeStamp.h" // for FairTimeStamp +#include "FairTimeStamp.h" // for FairTimeStamp -#include // for Double_t, Int_t, Double32_t, etc -#include // for TVector3 +#include // for Double_t, Int_t, Double32_t, etc +#include // for TVector3 -namespace boost { namespace serialization { class access; } } +namespace boost { +namespace serialization { +class access; +} +} // namespace boost #include /** * Abstract base class for reconstructed hits in the FAIR detectors. - **@author V.Friese - **@author D.Bertini - **@author M.Al-Turany + **@author V.Friese + **@author D.Bertini + **@author M.Al-Turany */ class FairHit : public FairTimeStamp { @@ -52,7 +56,7 @@ class FairHit : public FairTimeStamp void SetDz(Double_t dz) { fDz = dz; } void SetDxyz(Double_t dx, Double_t dy, Double_t dz); void SetPositionError(const TVector3& dpos); - void SetRefIndex(Int_t index) { fRefIndex = index; } + void SetRefIndex(Int_t index) { fRefIndex = index; } void SetDetectorID(Int_t detID) { fDetectorID = detID; } void SetX(Double_t x) { fX = x; } void SetY(Double_t y) { fY = y; } @@ -61,7 +65,7 @@ class FairHit : public FairTimeStamp void SetPosition(const TVector3& pos); /*** Output to screen */ - virtual void Print(const Option_t*) const {;} + virtual void Print(const Option_t*) const { ; } template void serialize(Archive& ar, const unsigned int) @@ -81,49 +85,43 @@ class FairHit : public FairTimeStamp friend class boost::serialization::access; Double32_t fDx, fDy, fDz; ///< Errors of position [cm] - Int_t fRefIndex; ///< Index of FairMCPoint for this hit - Int_t fDetectorID; ///< Detector unique identifier + Int_t fRefIndex; ///< Index of FairMCPoint for this hit + Int_t fDetectorID; ///< Detector unique identifier Double32_t fX, fY, fZ; ///< Position of hit [cm] - ClassDef(FairHit,3); + ClassDef(FairHit, 3); }; -inline void FairHit::PositionError(TVector3& dpos) const -{ - dpos.SetXYZ(fDx, fDy, fDz); -} +inline void FairHit::PositionError(TVector3& dpos) const { dpos.SetXYZ(fDx, fDy, fDz); } inline void FairHit::SetDxyz(Double_t dx, Double_t dy, Double_t dz) { - fDx = dx; - fDy = dy; - fDz = dz; + fDx = dx; + fDy = dy; + fDz = dz; } inline void FairHit::SetPositionError(const TVector3& dpos) { - fDx = dpos.X(); - fDy = dpos.Y(); - fDz = dpos.Z(); + fDx = dpos.X(); + fDy = dpos.Y(); + fDz = dpos.Z(); } -inline void FairHit::Position(TVector3& pos) const -{ - pos.SetXYZ(fX, fY, fZ); -} +inline void FairHit::Position(TVector3& pos) const { pos.SetXYZ(fX, fY, fZ); } inline void FairHit::SetXYZ(Double_t x, Double_t y, Double_t z) { - fX = x; - fY = y; - fZ = z; + fX = x; + fY = y; + fZ = z; } inline void FairHit::SetPosition(const TVector3& pos) { - fX = pos.X(); - fY = pos.Y(); - fZ = pos.Z(); + fX = pos.X(); + fY = pos.Y(); + fZ = pos.Z(); } #endif diff --git a/base/event/FairLink.cxx b/base/event/FairLink.cxx index f3264e7c19..364026880c 100644 --- a/base/event/FairLink.cxx +++ b/base/event/FairLink.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* @@ -13,33 +13,34 @@ */ #include "FairLink.h" + #include "FairRootManager.h" ClassImp(FairLink); FairLink::FairLink(TString branchName, Int_t index, Float_t weight) - :fFile(0), - fType(0), - fEntry(-1), - fIndex(index), - fWeight(weight) + : fFile(0) + , fType(0) + , fEntry(-1) + , fIndex(index) + , fWeight(weight) { - SetType(FairRootManager::Instance()->GetBranchId(branchName)); + SetType(FairRootManager::Instance()->GetBranchId(branchName)); } FairLink::FairLink(Int_t file, Int_t entry, TString branchName, Int_t index, Float_t weight) - :fFile(0), - fType(0), - fEntry(entry), - fIndex(index), - fWeight(weight) + : fFile(0) + , fType(0) + , fEntry(entry) + , fIndex(index) + , fWeight(weight) { - SetFile(file); - SetType(FairRootManager::Instance()->GetBranchId(branchName)); + SetFile(file); + SetType(FairRootManager::Instance()->GetBranchId(branchName)); } void FairLink::PrintLinkInfo(std::ostream& out) const { - out << "(" << GetFile() << "/" << GetEntry() << "/"; - out << GetType() << "/" << GetIndex() << "/" << GetWeight() << ")"; + out << "(" << GetFile() << "/" << GetEntry() << "/"; + out << GetType() << "/" << GetIndex() << "/" << GetWeight() << ")"; } diff --git a/base/event/FairLink.h b/base/event/FairLink.h index b47051b9b7..78ad91fe91 100644 --- a/base/event/FairLink.h +++ b/base/event/FairLink.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* @@ -23,9 +23,8 @@ #ifndef FAIRLINK_H_ #define FAIRLINK_H_ -#include // for Int_t, Float_t, etc, ClassDefNV - -#include // for ostream, cout +#include // for Int_t, Float_t, etc, ClassDefNV +#include // for ostream, cout class FairLink { @@ -35,21 +34,23 @@ class FairLink FairLink(TString branchName, Int_t index, Float_t weight = 1.); FairLink(Int_t file, Int_t entry, Int_t type, Int_t index, Float_t weight = 1.); FairLink(Int_t file, Int_t entry, TString branchName, Int_t index, Float_t weight = 1.); - ~FairLink() {}; - - void SetLink(Int_t file, Int_t entry, Int_t type, Int_t index, Float_t weight = 1.) { - SetFile(file); - SetEntry(entry); - SetType(type); - SetIndex(index); - SetWeight(weight); + ~FairLink(){}; + + void SetLink(Int_t file, Int_t entry, Int_t type, Int_t index, Float_t weight = 1.) + { + SetFile(file); + SetEntry(entry); + SetType(type); + SetIndex(index); + SetWeight(weight); }; - void SetLink(Int_t type, Int_t index, Float_t weight = 1.) { - SetFile(-1); - SetEntry(-1); - SetType(type); - SetIndex(index); - SetWeight(weight); + void SetLink(Int_t type, Int_t index, Float_t weight = 1.) + { + SetFile(-1); + SetEntry(-1); + SetType(type); + SetIndex(index); + SetWeight(weight); }; int GetFile() const; int GetEntry() const { return fEntry; } @@ -58,45 +59,56 @@ class FairLink float GetWeight() const { return fWeight; } void SetFile(int file); - void SetEntry(int entry){ fEntry = entry; }; + void SetEntry(int entry) { fEntry = entry; }; void SetType(int type); - void SetIndex(int index){ fIndex = index; }; + void SetIndex(int index) { fIndex = index; }; void SetWeight(Float_t weight) { fWeight = weight; } void AddWeight(Float_t weight) { fWeight += weight; } void PrintLinkInfo(std::ostream& out = std::cout) const; - bool operator==(const FairLink& link) const { - if ((GetFile() == link.GetFile() || link.GetFile() == -1) && - (GetEntry() == link.GetEntry() || link.GetEntry() == -1) && - GetType() == link.GetType() && GetIndex() == link.GetIndex()) { - return true; - } else { - return false; - } + bool operator==(const FairLink& link) const + { + if ((GetFile() == link.GetFile() || link.GetFile() == -1) + && (GetEntry() == link.GetEntry() || link.GetEntry() == -1) && GetType() == link.GetType() + && GetIndex() == link.GetIndex()) { + return true; + } else { + return false; + } } - bool operator<(const FairLink& link) const { - if (GetFile() != -1 && link.GetFile() != -1) { - if (GetFile() < link.GetFile()) return true; - else if (link.GetFile() < GetFile()) return false; - } - if (GetEntry() != -1 && link.GetEntry() != -1) { - if (GetEntry() < link.GetEntry()) return true; - else if (link.GetEntry() < GetEntry()) return false; - } - if (GetType() < link.GetType()) return true; - else if (link.GetType() < GetType()) return false; - if (GetIndex() < link.GetIndex()) return true; - else if (link.GetIndex() < GetIndex()) return false; - - return false; + bool operator<(const FairLink& link) const + { + if (GetFile() != -1 && link.GetFile() != -1) { + if (GetFile() < link.GetFile()) + return true; + else if (link.GetFile() < GetFile()) + return false; + } + if (GetEntry() != -1 && link.GetEntry() != -1) { + if (GetEntry() < link.GetEntry()) + return true; + else if (link.GetEntry() < GetEntry()) + return false; + } + if (GetType() < link.GetType()) + return true; + else if (link.GetType() < GetType()) + return false; + if (GetIndex() < link.GetIndex()) + return true; + else if (link.GetIndex() < GetIndex()) + return false; + + return false; } - friend std::ostream& operator<< (std::ostream& out, const FairLink& link) { - link.PrintLinkInfo(out); - return out; + friend std::ostream& operator<<(std::ostream& out, const FairLink& link) + { + link.PrintLinkInfo(out); + return out; } ClassDefNV(FairLink, 5); @@ -119,58 +131,59 @@ class FairLink float fWeight; }; -inline FairLink::FairLink() : - fFile(0), - fType(0), - fEntry(-1), - fIndex(-1), - fWeight(1.0) -{ -} +inline FairLink::FairLink() + : fFile(0) + , fType(0) + , fEntry(-1) + , fIndex(-1) + , fWeight(1.0) +{} inline FairLink::FairLink(Int_t type, Int_t index, Float_t weight) - :fFile(0), - fType(0), - fEntry(-1), - fIndex(index), - fWeight(weight) + : fFile(0) + , fType(0) + , fEntry(-1) + , fIndex(index) + , fWeight(weight) { - SetType(type); + SetType(type); } inline FairLink::FairLink(Int_t file, Int_t entry, Int_t type, Int_t index, Float_t weight) - :fFile(0), - fType(0), - fEntry(entry), - fIndex(index), - fWeight(weight) + : fFile(0) + , fType(0) + , fEntry(entry) + , fIndex(index) + , fWeight(weight) { - SetFile(file); - SetType(type); + SetFile(file); + SetType(type); } inline void FairLink::SetType(int type) { - if (type < -1) return; - fType = type + 1; + if (type < -1) + return; + fType = type + 1; } inline int FairLink::GetType() const { - int type = fType; - return type - 1; + int type = fType; + return type - 1; } inline void FairLink::SetFile(int file) { - if (file < -1) return; - fFile = file + 1; + if (file < -1) + return; + fFile = file + 1; } inline int FairLink::GetFile() const { - int file = fFile; - return file - 1; + int file = fFile; + return file - 1; } #endif /* FAIRLINK_H_ */ diff --git a/base/event/FairMCEventHeader.cxx b/base/event/FairMCEventHeader.cxx index e9523152cd..3709c98aa1 100644 --- a/base/event/FairMCEventHeader.cxx +++ b/base/event/FairMCEventHeader.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ @@ -13,78 +13,78 @@ // ------------------------------------------------------------------------ #include "FairMCEventHeader.h" + #include "FairRootManager.h" FairMCEventHeader::FairMCEventHeader() - : TNamed("MCEvent", "MC"), - fRunId(0), - fEventId(-1), - fX (0.), - fY (0.), - fZ (0.), - fT (0.), - fB (0.), - fNPrim(0), - fIsSet(kFALSE), - fRotX (0.), - fRotY (0.), - fRotZ (0.) -{ -} + : TNamed("MCEvent", "MC") + , fRunId(0) + , fEventId(-1) + , fX(0.) + , fY(0.) + , fZ(0.) + , fT(0.) + , fB(0.) + , fNPrim(0) + , fIsSet(kFALSE) + , fRotX(0.) + , fRotY(0.) + , fRotZ(0.) +{} FairMCEventHeader::FairMCEventHeader(UInt_t runId) - : TNamed("MCEvent", "MC"), - fRunId(runId), - fEventId(-1), - fX (0.), - fY (0.), - fZ (0.), - fT (0.), - fB (0.), - fNPrim(0), - fIsSet(kFALSE), - fRotX (0.), - fRotY (0.), - fRotZ (0.) -{ -} + : TNamed("MCEvent", "MC") + , fRunId(runId) + , fEventId(-1) + , fX(0.) + , fY(0.) + , fZ(0.) + , fT(0.) + , fB(0.) + , fNPrim(0) + , fIsSet(kFALSE) + , fRotX(0.) + , fRotY(0.) + , fRotZ(0.) +{} -FairMCEventHeader::FairMCEventHeader(Int_t iEvent, Double_t x, Double_t y, - Double_t z, Double_t t,Double_t b, +FairMCEventHeader::FairMCEventHeader(Int_t iEvent, + Double_t x, + Double_t y, + Double_t z, + Double_t t, + Double_t b, Int_t nPrim) - : TNamed("MCEvent", "MC"), - fRunId(0), - fEventId(iEvent), - fX (x), - fY (y), - fZ (z), - fT (t), - fB (b), - fNPrim(nPrim), - fIsSet(kFALSE), - fRotX (0.), - fRotY (0.), - fRotZ (0.) -{ -} + : TNamed("MCEvent", "MC") + , fRunId(0) + , fEventId(iEvent) + , fX(x) + , fY(y) + , fZ(z) + , fT(t) + , fB(b) + , fNPrim(nPrim) + , fIsSet(kFALSE) + , fRotX(0.) + , fRotY(0.) + , fRotZ(0.) +{} -FairMCEventHeader::~FairMCEventHeader() -{ -} +FairMCEventHeader::~FairMCEventHeader() {} void FairMCEventHeader::Reset() { - fEventId = -1; - fNPrim = 0; - fX = fY = fZ = fT = fB = 0.; - fIsSet = kFALSE; - fRotX = fRotY = fRotZ = 0.; + fEventId = -1; + fNPrim = 0; + fX = fY = fZ = fT = fB = 0.; + fIsSet = kFALSE; + fRotX = fRotY = fRotZ = 0.; } void FairMCEventHeader::Register() { - // Dot at the end of the name is needed for splitting!! - FairRootManager::Instance()->Register("MCEventHeader.", "Event", this, kTRUE); + // Dot at the end of the name is needed for splitting!! + FairRootManager::Instance()->Register("MCEventHeader.", "Event", this, kTRUE); } -ClassImp(FairMCEventHeader) +ClassImp(FairMCEventHeader); diff --git a/base/event/FairMCEventHeader.h b/base/event/FairMCEventHeader.h index 9f75e33ae7..3b071a755c 100644 --- a/base/event/FairMCEventHeader.h +++ b/base/event/FairMCEventHeader.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /** FairMCEventHeader.h @@ -11,14 +11,12 @@ ** 15.05.2008 change the event time to ns (M. Al-Turany) **/ - #ifndef FAIRMCEVENTHEADER_H #define FAIRMCEVENTHEADER_H 1 -#include // for TNamed - -#include // for Double_t, UInt_t, etc -#include // for TVector3 +#include // for Double_t, UInt_t, etc +#include // for TNamed +#include // for TVector3 class FairMCEventHeader : public TNamed { @@ -34,8 +32,7 @@ class FairMCEventHeader : public TNamed *@param b impact parameter [fm] (if relevant) *@param nPrim number of input tracks **/ - FairMCEventHeader(Int_t iEvent, Double_t x, Double_t y, Double_t z, - Double_t t, Double_t b, Int_t nPrim); + FairMCEventHeader(Int_t iEvent, Double_t x, Double_t y, Double_t z, Double_t t, Double_t b, Int_t nPrim); /** Standard constructor with run identifier **/ FairMCEventHeader(UInt_t runId); @@ -44,28 +41,28 @@ class FairMCEventHeader : public TNamed virtual ~FairMCEventHeader(); /** Accessors **/ - UInt_t GetRunID() const { return fRunId; } /// run identifier - UInt_t GetEventID() const { return fEventId; } /// event identifier - Double_t GetX() const { return fX; } /// vertex x [cm] - Double_t GetY() const { return fY; } /// vertex y [cm] - Double_t GetZ() const { return fZ; } /// vertex z [cm] - Double_t GetT() const { return fT; } /// event time [ns] - Double_t GetB() const { return fB; } /// impact parameter [fm] - Int_t GetNPrim() const { return fNPrim; } /// number of input tracks - Bool_t IsSet() const { return fIsSet; } /// Flag - Double_t GetRotX() const { return fRotX; } /// rot. around x-axis [rad] - Double_t GetRotY() const { return fRotY; } /// rot. around y-axis [rad] - Double_t GetRotZ() const { return fRotZ; } /// rot. around z-axis [rad] + UInt_t GetRunID() const { return fRunId; } /// run identifier + UInt_t GetEventID() const { return fEventId; } /// event identifier + Double_t GetX() const { return fX; } /// vertex x [cm] + Double_t GetY() const { return fY; } /// vertex y [cm] + Double_t GetZ() const { return fZ; } /// vertex z [cm] + Double_t GetT() const { return fT; } /// event time [ns] + Double_t GetB() const { return fB; } /// impact parameter [fm] + Int_t GetNPrim() const { return fNPrim; } /// number of input tracks + Bool_t IsSet() const { return fIsSet; } /// Flag + Double_t GetRotX() const { return fRotX; } /// rot. around x-axis [rad] + Double_t GetRotY() const { return fRotY; } /// rot. around y-axis [rad] + Double_t GetRotZ() const { return fRotZ; } /// rot. around z-axis [rad] void GetVertex(TVector3& vertex) { vertex.SetXYZ(fX, fY, fZ); } /** Modifiers **/ void SetEventID(UInt_t eventId) { fEventId = eventId; } void SetRunID(UInt_t runId) { fRunId = runId; } - void SetTime(Double_t t) { fT = t; } - void SetB(Double_t b) { fB = b; } - void SetNPrim(Int_t nPrim) { fNPrim = nPrim; } - void MarkSet(Bool_t isSet) { fIsSet = isSet; } + void SetTime(Double_t t) { fT = t; } + void SetB(Double_t b) { fB = b; } + void SetNPrim(Int_t nPrim) { fNPrim = nPrim; } + void MarkSet(Bool_t isSet) { fIsSet = isSet; } void SetVertex(Double_t x, Double_t y, Double_t z); void SetVertex(const TVector3& vertex); void SetRotX(Double_t rotx) { fRotX = rotx; } @@ -79,34 +76,34 @@ class FairMCEventHeader : public TNamed virtual void Register(); protected: - UInt_t fRunId; /// Run identifier - UInt_t fEventId; /// Event identifier - Double32_t fX; /// Primary vertex x [cm] - Double32_t fY; /// Primary vertex y [cm] - Double32_t fZ; /// Primary vertex z [cm] - Double32_t fT; /// Event time [s] - Double32_t fB; /// Impact parameter [fm] (if relevant) - Int_t fNPrim; /// Number of input tracks - Bool_t fIsSet; /// Flag whether variables are filled - Double32_t fRotX; /// Rotation around x-axis (beam tilt) [rad] - Double32_t fRotY; /// Rotation around y-axis (beam tilt) [rad] - Double32_t fRotZ; /// Rotation around z-axis (event plane) [rad] - - ClassDef(FairMCEventHeader,2); + UInt_t fRunId; /// Run identifier + UInt_t fEventId; /// Event identifier + Double32_t fX; /// Primary vertex x [cm] + Double32_t fY; /// Primary vertex y [cm] + Double32_t fZ; /// Primary vertex z [cm] + Double32_t fT; /// Event time [s] + Double32_t fB; /// Impact parameter [fm] (if relevant) + Int_t fNPrim; /// Number of input tracks + Bool_t fIsSet; /// Flag whether variables are filled + Double32_t fRotX; /// Rotation around x-axis (beam tilt) [rad] + Double32_t fRotY; /// Rotation around y-axis (beam tilt) [rad] + Double32_t fRotZ; /// Rotation around z-axis (event plane) [rad] + + ClassDef(FairMCEventHeader, 2); }; inline void FairMCEventHeader::SetVertex(Double_t x, Double_t y, Double_t z) { - fX = x; - fY = y; - fZ = z; + fX = x; + fY = y; + fZ = z; } inline void FairMCEventHeader::SetVertex(const TVector3& vertex) { - fX = vertex.X(); - fY = vertex.Y(); - fZ = vertex.Z(); + fX = vertex.X(); + fY = vertex.Y(); + fZ = vertex.Z(); } #endif diff --git a/base/event/FairMCPoint.cxx b/base/event/FairMCPoint.cxx index 51ea7a7889..77b086b615 100644 --- a/base/event/FairMCPoint.cxx +++ b/base/event/FairMCPoint.cxx @@ -1,57 +1,62 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "FairMCPoint.h" + #include "FairLogger.h" FairMCPoint::FairMCPoint() - : FairMultiLinkedData_Interface(), - fTrackID(-1), - fEventId(0), - fPx(0.), - fPy(0.), - fPz(0.), - fTime (0.), - fLength(0.), - fELoss(0.), - fDetectorID (-1), - fX(0), - fY (0), - fZ(0) -{ -} + : FairMultiLinkedData_Interface() + , fTrackID(-1) + , fEventId(0) + , fPx(0.) + , fPy(0.) + , fPz(0.) + , fTime(0.) + , fLength(0.) + , fELoss(0.) + , fDetectorID(-1) + , fX(0) + , fY(0) + , fZ(0) +{} -FairMCPoint::FairMCPoint(Int_t trackID, Int_t detID, TVector3 pos, - TVector3 mom, Double_t tof, Double_t length, - Double_t eLoss, UInt_t EventId) - :FairMultiLinkedData_Interface(), - fTrackID ( trackID), - fEventId (EventId), - fPx ( mom.Px()), - fPy ( mom.Py()), - fPz ( mom.Pz()), - fTime ( tof), - fLength ( length), - fELoss ( eLoss), - fDetectorID (detID), - fX(pos.X()), - fY(pos.Y()), - fZ(pos.Z()) -{ -} +FairMCPoint::FairMCPoint(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t tof, + Double_t length, + Double_t eLoss, + UInt_t EventId) + : FairMultiLinkedData_Interface() + , fTrackID(trackID) + , fEventId(EventId) + , fPx(mom.Px()) + , fPy(mom.Py()) + , fPz(mom.Pz()) + , fTime(tof) + , fLength(length) + , fELoss(eLoss) + , fDetectorID(detID) + , fX(pos.X()) + , fY(pos.Y()) + , fZ(pos.Z()) +{} FairMCPoint::~FairMCPoint() {} void FairMCPoint::Print(const Option_t*) const { - LOG(debug) << "FairMC point for track " << fTrackID << " in detector " << fDetectorID; - LOG(debug) << "Position (" << fX << ", " << fY << ", " << fZ << ") cm"; - LOG(debug) << " Momentum (" << fPx << ", " << fPy << ", " << fPz << ") GeV"; - LOG(debug) << " Time " << fTime << " ns, Length " << fLength << " cm, Energy loss " << fELoss * 1.0e06 << " keV"; + LOG(debug) << "FairMC point for track " << fTrackID << " in detector " << fDetectorID; + LOG(debug) << "Position (" << fX << ", " << fY << ", " << fZ << ") cm"; + LOG(debug) << " Momentum (" << fPx << ", " << fPy << ", " << fPz << ") GeV"; + LOG(debug) << " Time " << fTime << " ns, Length " << fLength << " cm, Energy loss " << fELoss * 1.0e06 + << " keV"; } -ClassImp(FairMCPoint) +ClassImp(FairMCPoint); diff --git a/base/event/FairMCPoint.h b/base/event/FairMCPoint.h index 8ea0cf4485..e7571b55c2 100644 --- a/base/event/FairMCPoint.h +++ b/base/event/FairMCPoint.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /** FairMCPoint.h @@ -13,12 +13,16 @@ #ifndef FAIRMCPOINT_H #define FAIRMCPOINT_H -#include "FairMultiLinkedData_Interface.h" // for FairMultiLinkedData +#include "FairMultiLinkedData_Interface.h" // for FairMultiLinkedData -#include // for Double_t, Double32_t, Int_t, etc -#include // for TVector3 +#include // for Double_t, Double32_t, Int_t, etc +#include // for TVector3 -namespace boost { namespace serialization { class access; } } +namespace boost { +namespace serialization { +class access; +} +} // namespace boost #include class FairMCPoint : public FairMultiLinkedData_Interface @@ -37,14 +41,20 @@ class FairMCPoint : public FairMultiLinkedData_Interface *@param eLoss Energy deposit [GeV] *@param EventId MC event id **/ - FairMCPoint(Int_t trackID, Int_t detID, TVector3 pos, TVector3 mom, - Double_t tof, Double_t length, Double_t eLoss, UInt_t EventId=0); + FairMCPoint(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t tof, + Double_t length, + Double_t eLoss, + UInt_t EventId = 0); /** Destructor **/ virtual ~FairMCPoint(); /** Accessors */ - UInt_t GetEventID() const { return fEventId; } /// event identifier + UInt_t GetEventID() const { return fEventId; } /// event identifier Int_t GetTrackID() const { return fTrackID; } Double_t GetPx() const { return fPx; } Double_t GetPy() const { return fPy; } @@ -61,7 +71,7 @@ class FairMCPoint : public FairMultiLinkedData_Interface /** Modifiers **/ void SetEventID(UInt_t eventId) { fEventId = eventId; } - virtual void SetTrackID(Int_t id) { fTrackID = id;} + virtual void SetTrackID(Int_t id) { fTrackID = id; } void SetTime(Double_t time) { fTime = time; } void SetLength(Double_t length) { fLength = length; } void SetEnergyLoss(Double_t eLoss) { fELoss = eLoss; } @@ -77,57 +87,57 @@ class FairMCPoint : public FairMultiLinkedData_Interface virtual void Print(const Option_t* opt = 0) const; template - void serialize(Archive & ar, const unsigned int) + void serialize(Archive& ar, const unsigned int) { - //ar & boost::serialization::base_object(*this); - ar & fTrackID; - ar & fEventId; - ar & fDetectorID; - ar & fX; - ar & fY; - ar & fZ; - ar & fPx; - ar & fPy; - ar & fPz; - ar & fTime; - ar & fLength; - ar & fELoss; + // ar & boost::serialization::base_object(*this); + ar& fTrackID; + ar& fEventId; + ar& fDetectorID; + ar& fX; + ar& fY; + ar& fZ; + ar& fPx; + ar& fPy; + ar& fPz; + ar& fTime; + ar& fLength; + ar& fELoss; } protected: friend class boost::serialization::access; - Int_t fTrackID; ///< Track index - UInt_t fEventId; ///< MC Event id - Double32_t fPx, fPy, fPz; ///< Momentum components [GeV] - Double32_t fTime; ///< Time since event start [ns] - Double32_t fLength; ///< Track length since creation [cm] - Double32_t fELoss; ///< Energy loss at this point [GeV] - Int_t fDetectorID; ///< Detector unique identifier - Double32_t fX, fY, fZ; ///< Position of hit [cm] + Int_t fTrackID; ///< Track index + UInt_t fEventId; ///< MC Event id + Double32_t fPx, fPy, fPz; ///< Momentum components [GeV] + Double32_t fTime; ///< Time since event start [ns] + Double32_t fLength; ///< Track length since creation [cm] + Double32_t fELoss; ///< Energy loss at this point [GeV] + Int_t fDetectorID; ///< Detector unique identifier + Double32_t fX, fY, fZ; ///< Position of hit [cm] - ClassDef(FairMCPoint,5) + ClassDef(FairMCPoint, 5) }; inline void FairMCPoint::SetMomentum(const TVector3& mom) { - fPx = mom.Px(); - fPy = mom.Py(); - fPz = mom.Pz(); + fPx = mom.Px(); + fPy = mom.Py(); + fPz = mom.Pz(); } inline void FairMCPoint::SetXYZ(Double_t x, Double_t y, Double_t z) { - fX = x; - fY = y; - fZ = z; + fX = x; + fY = y; + fZ = z; } inline void FairMCPoint::SetPosition(const TVector3& pos) { - fX = pos.X(); - fY = pos.Y(); - fZ = pos.Z(); + fX = pos.X(); + fY = pos.Y(); + fZ = pos.Z(); } #endif diff --git a/base/event/FairMesh.cxx b/base/event/FairMesh.cxx index 5de83b0403..1218e48163 100644 --- a/base/event/FairMesh.cxx +++ b/base/event/FairMesh.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -13,93 +13,88 @@ #include "FairMesh.h" -#include // for Sqrt -#include // for TString, operator+ - -#include // for operator<<, basic_ostream, etc +#include // for Sqrt +#include // for TString, operator+ +#include // for operator<<, basic_ostream, etc using namespace std; FairMesh::FairMesh() - : TObject(), - fXmin (0.0), - fYmin(0.), - fZmin (0.), - fXmax(0.), - fYmax(0.), - fZmax(0.), - NXbin(0), - NYbin(0), - NZbin(0), - fBinVolume(0.), - fDiag(0.), - fMeshTid(nullptr), - fMeshFlu(nullptr), - fMeshSEU(nullptr), - fhname("") -{ -} + : TObject() + , fXmin(0.0) + , fYmin(0.) + , fZmin(0.) + , fXmax(0.) + , fYmax(0.) + , fZmax(0.) + , NXbin(0) + , NYbin(0) + , NZbin(0) + , fBinVolume(0.) + , fDiag(0.) + , fMeshTid(nullptr) + , fMeshFlu(nullptr) + , fMeshSEU(nullptr) + , fhname("") +{} FairMesh::FairMesh(const char* fname) - : TObject(), - fXmin (0.0), - fYmin(0.), - fZmin (0.), - fXmax(0.), - fYmax(0.), - fZmax(0.), - NXbin(0), - NYbin(0), - NZbin(0), - fBinVolume(0.), - fDiag(0.), - fMeshTid(nullptr), - fMeshFlu(nullptr), - fMeshSEU(nullptr), - fhname(fname) + : TObject() + , fXmin(0.0) + , fYmin(0.) + , fZmin(0.) + , fXmax(0.) + , fYmax(0.) + , fZmax(0.) + , NXbin(0) + , NYbin(0) + , NZbin(0) + , fBinVolume(0.) + , fDiag(0.) + , fMeshTid(nullptr) + , fMeshFlu(nullptr) + , fMeshSEU(nullptr) + , fhname(fname) { - // fhname = fname; + // fhname = fname; } void FairMesh::calculate() { - // compute numbers + // compute numbers - TString tid = fhname + "TID"; - fMeshTid = new TH2D(tid.Data(), "TID", NXbin, fXmin, fXmax, NYbin, fYmin, fYmax); - fMeshTid->Sumw2(); + TString tid = fhname + "TID"; + fMeshTid = new TH2D(tid.Data(), "TID", NXbin, fXmin, fXmax, NYbin, fYmin, fYmax); + fMeshTid->Sumw2(); - TString flu = fhname + "FLU"; - fMeshFlu = new TH2D(flu.Data(), "Fluence", NXbin, fXmin, fXmax, NYbin, fYmin, fYmax); - fMeshFlu->Sumw2(); + TString flu = fhname + "FLU"; + fMeshFlu = new TH2D(flu.Data(), "Fluence", NXbin, fXmin, fXmax, NYbin, fYmin, fYmax); + fMeshFlu->Sumw2(); - TString seu = fhname + "SEU"; - fMeshSEU = new TH2D(seu.Data(), "SEU", NXbin, fXmin, fXmax, NYbin, fYmin, fYmax); - fMeshSEU->Sumw2(); + TString seu = fhname + "SEU"; + fMeshSEU = new TH2D(seu.Data(), "SEU", NXbin, fXmin, fXmax, NYbin, fYmin, fYmax); + fMeshSEU->Sumw2(); - // reseting - fMeshTid->Reset(); - fMeshFlu->Reset(); - fMeshSEU->Reset(); + // reseting + fMeshTid->Reset(); + fMeshFlu->Reset(); + fMeshSEU->Reset(); - fBinVolume = ((fXmax - fXmin) / NXbin) * - ((fYmax - fYmin) / NYbin) * - ((fZmax - fZmin) / NZbin); + fBinVolume = ((fXmax - fXmin) / NXbin) * ((fYmax - fYmin) / NYbin) * ((fZmax - fZmin) / NZbin); - fDiag = TMath::Sqrt( - ((fXmax - fXmin) / NXbin)*((fXmax - fXmin) / NXbin) + - ((fYmax - fYmin) / NYbin)*((fYmax - fYmin) / NYbin) + - ((fZmax - fZmin) / NZbin)*((fZmax - fZmin) / NZbin)); + fDiag = TMath::Sqrt(((fXmax - fXmin) / NXbin) * ((fXmax - fXmin) / NXbin) + + ((fYmax - fYmin) / NYbin) * ((fYmax - fYmin) / NYbin) + + ((fZmax - fZmin) / NZbin) * ((fZmax - fZmin) / NZbin)); } -FairMesh::~FairMesh() { } +FairMesh::~FairMesh() {} void FairMesh::print() { - cout << " Xmin " << fXmin << " Xmax " << fXmax << endl; - cout << " Ymin " << fYmin << " Ymax " << fYmax << endl; - cout << " Zmin " << fZmin << " Zmax " << fZmax << endl; - cout << " NX " << NXbin << " NY " << NXbin << endl; + cout << " Xmin " << fXmin << " Xmax " << fXmax << endl; + cout << " Ymin " << fYmin << " Ymax " << fYmax << endl; + cout << " Zmin " << fZmin << " Zmax " << fZmax << endl; + cout << " NX " << NXbin << " NY " << NXbin << endl; } -ClassImp(FairMesh) +ClassImp(FairMesh); diff --git a/base/event/FairMesh.h b/base/event/FairMesh.h index 133a3671ff..21b33cc147 100644 --- a/base/event/FairMesh.h +++ b/base/event/FairMesh.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -14,15 +14,14 @@ #ifndef FAIRMESH_H #define FAIRMESH_H -#include // for TObject - -#include // for Double_t, Int_t, etc -#include // for TH2D -#include // for TString +#include // for Double_t, Int_t, etc +#include // for TH2D +#include // for TObject +#include // for TString /** * Abstract base class for Mesh Objects. - **@author D.Bertini + **@author D.Bertini */ class FairMesh : public TObject { @@ -35,55 +34,51 @@ class FairMesh : public TObject virtual ~FairMesh(); /** Accessors **/ - Double_t GetXmin() const { return fXmin; }; - Double_t GetYmin() const { return fYmin; }; - Double_t GetZmin() const { return fZmin; }; + Double_t GetXmin() const { return fXmin; }; + Double_t GetYmin() const { return fYmin; }; + Double_t GetZmin() const { return fZmin; }; - Double_t GetXmax() const { return fXmax; }; - Double_t GetYmax() const { return fYmax; }; - Double_t GetZmax() const { return fZmax; }; + Double_t GetXmax() const { return fXmax; }; + Double_t GetYmax() const { return fYmax; }; + Double_t GetZmax() const { return fZmax; }; /** Modifiers **/ - void SetX(Double_t xmin,Double_t xmax, Int_t nbin ) { - fXmin = xmin; - fXmax = xmax; - NXbin = nbin; + void SetX(Double_t xmin, Double_t xmax, Int_t nbin) + { + fXmin = xmin; + fXmax = xmax; + NXbin = nbin; } - void SetY(Double_t ymin,Double_t ymax, Int_t nbin ) { - fYmin = ymin; - fYmax = ymax; - NYbin = nbin; + void SetY(Double_t ymin, Double_t ymax, Int_t nbin) + { + fYmin = ymin; + fYmax = ymax; + NYbin = nbin; } - void SetZ(Double_t zmin,Double_t zmax, Int_t nbin ) { - fZmin = zmin; - fZmax = zmax; - NZbin = nbin; + void SetZ(Double_t zmin, Double_t zmax, Int_t nbin) + { + fZmin = zmin; + fZmax = zmax; + NZbin = nbin; } TH2D* GetMeshTid() { return fMeshTid; } TH2D* GetMeshFlu() { return fMeshFlu; } TH2D* GetMeshSEU() { return fMeshSEU; } /*** Output to screen */ -// virtual void Print(const Option_t* opt = 0) const {;} + // virtual void Print(const Option_t* opt = 0) const {;} Double_t GetDiag() { return fDiag; } Double_t GetBinVolume() { return fBinVolume; } - void fillTID(Double_t x , Double_t y , Double_t we ) { - fMeshTid->Fill(x,y,we); - } - void fillFluence(Double_t x , Double_t y , Double_t we ) { - fMeshFlu->Fill(x,y,we); - - } - void fillSEU(Double_t x , Double_t y , Double_t we ) { - fMeshSEU->Fill(x,y,we); - - } - void Scale(Double_t fac ) { - fMeshTid->Scale(fac); - fMeshFlu->Scale(fac); - fMeshSEU->Scale(fac); + void fillTID(Double_t x, Double_t y, Double_t we) { fMeshTid->Fill(x, y, we); } + void fillFluence(Double_t x, Double_t y, Double_t we) { fMeshFlu->Fill(x, y, we); } + void fillSEU(Double_t x, Double_t y, Double_t we) { fMeshSEU->Fill(x, y, we); } + void Scale(Double_t fac) + { + fMeshTid->Scale(fac); + fMeshFlu->Scale(fac); + fMeshSEU->Scale(fac); } void calculate(); @@ -91,21 +86,21 @@ class FairMesh : public TObject void print(); protected: - Double_t fXmin, fYmin, fZmin; - Double_t fXmax, fYmax, fZmax; - Int_t NXbin, NYbin, NZbin; + Double_t fXmin, fYmin, fZmin; + Double_t fXmax, fYmax, fZmax; + Int_t NXbin, NYbin, NZbin; Double_t fBinVolume; Double_t fDiag; - TH2D* fMeshTid; // !mesh - TH2D* fMeshFlu; // !mesh - TH2D* fMeshSEU; // !mesh - TString fhname; // !mesh + TH2D* fMeshTid; // !mesh + TH2D* fMeshFlu; // !mesh + TH2D* fMeshSEU; // !mesh + TString fhname; // !mesh private: FairMesh(const FairMesh&); FairMesh& operator=(const FairMesh&); - ClassDef(FairMesh,1); + ClassDef(FairMesh, 1); }; #endif diff --git a/base/event/FairMultiLinkedData.cxx b/base/event/FairMultiLinkedData.cxx index f1533f2e2c..4212f3f3bb 100644 --- a/base/event/FairMultiLinkedData.cxx +++ b/base/event/FairMultiLinkedData.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* @@ -13,179 +13,191 @@ */ #include "FairMultiLinkedData.h" -#include "FairMultiLinkedData_Interface.h" - -#include "FairRootManager.h" // for FairRootManager -#include "FairLinkManager.h" // for FairLinkManager -#include // for TClonesArray +#include "FairLinkManager.h" // for FairLinkManager +#include "FairMultiLinkedData_Interface.h" +#include "FairRootManager.h" // for FairRootManager -#include // for find -#include // for distance +#include // for TClonesArray +#include // for find +#include // for distance ClassImp(FairMultiLinkedData); FairMultiLinkedData::FairMultiLinkedData() - :TObject(), - fLinks(), - fEntryNr(), - fPersistanceCheck(kTRUE), - fInsertHistory(kTRUE), - fVerbose(0), - fDefaultType(0) -{ -} + : TObject() + , fLinks() + , fEntryNr() + , fPersistanceCheck(kTRUE) + , fInsertHistory(kTRUE) + , fVerbose(0) + , fDefaultType(0) +{} FairMultiLinkedData::FairMultiLinkedData(const std::set& links, Bool_t persistanceCheck) - :TObject(), - fLinks(links), - fEntryNr(), - fPersistanceCheck(persistanceCheck), - fInsertHistory(kTRUE), - fVerbose(0), - fDefaultType(0) + : TObject() + , fLinks(links) + , fEntryNr() + , fPersistanceCheck(persistanceCheck) + , fInsertHistory(kTRUE) + , fVerbose(0) + , fDefaultType(0) +{} + +FairMultiLinkedData::FairMultiLinkedData(TString dataType, + const std::vector& links, + Int_t fileId, + Int_t evtId, + Bool_t persistanceCheck, + Bool_t bypass, + Float_t mult) + : TObject() + , fLinks() + , fEntryNr() + , fPersistanceCheck(persistanceCheck) + , fInsertHistory(kTRUE) + , fVerbose(0) + , fDefaultType(0) { + SimpleAddLinks(fileId, evtId, FairRootManager::Instance()->GetBranchId(dataType), links, bypass, mult); + // FairMultiLinkedData(ioman->GetBranchId(dataType), links, persistanceCheck, bypass, addup, mult); } -FairMultiLinkedData::FairMultiLinkedData(TString dataType, const std::vector& links, Int_t fileId, Int_t evtId, Bool_t persistanceCheck, Bool_t bypass, Float_t mult) - :TObject(), - fLinks(), - fEntryNr(), - fPersistanceCheck(persistanceCheck), - fInsertHistory(kTRUE), - fVerbose(0), - fDefaultType(0) +FairMultiLinkedData::FairMultiLinkedData(Int_t dataType, + const std::vector& links, + Int_t fileId, + Int_t evtId, + Bool_t persistanceCheck, + Bool_t bypass, + Float_t mult) + : TObject() + , fLinks() + , fEntryNr() + , fPersistanceCheck(persistanceCheck) + , fInsertHistory(kTRUE) + , fVerbose(0) + , fDefaultType(0) { - SimpleAddLinks(fileId, evtId, FairRootManager::Instance()->GetBranchId(dataType), links, bypass, mult); -// FairMultiLinkedData(ioman->GetBranchId(dataType), links, persistanceCheck, bypass, addup, mult); -} - -FairMultiLinkedData::FairMultiLinkedData(Int_t dataType, const std::vector& links, Int_t fileId, Int_t evtId, Bool_t persistanceCheck, Bool_t bypass, Float_t mult) - :TObject(), - fLinks(), - fEntryNr(), - fPersistanceCheck(persistanceCheck), - fInsertHistory(kTRUE), - fVerbose(0), - fDefaultType(0) -{ - SimpleAddLinks(fileId, evtId, dataType, links, bypass, mult); + SimpleAddLinks(fileId, evtId, dataType, links, bypass, mult); } FairLink FairMultiLinkedData::GetLink(Int_t pos) const { - if (pos < static_cast(fLinks.size())) { - // return value at iterator+pos - return *(std::next(fLinks.begin(), pos)); - } else { - std::cout << "-E- FairMultiLinkedData:GetLink(pos) pos " << pos << " outside range " << fLinks.size() << std::endl; - return FairLink(); - } + if (pos < static_cast(fLinks.size())) { + // return value at iterator+pos + return *(std::next(fLinks.begin(), pos)); + } else { + std::cout << "-E- FairMultiLinkedData:GetLink(pos) pos " << pos << " outside range " << fLinks.size() + << std::endl; + return FairLink(); + } } void FairMultiLinkedData::SetLinks(FairMultiLinkedData links, Float_t mult) { - fLinks.clear(); - AddLinks(links, mult); + fLinks.clear(); + AddLinks(links, mult); } void FairMultiLinkedData::SetLink(FairLink link, Bool_t bypass, Float_t mult) { - fLinks.clear(); - Float_t weight = link.GetWeight() * mult; - link.SetWeight(weight); - AddLink(link, bypass); + fLinks.clear(); + Float_t weight = link.GetWeight() * mult; + link.SetWeight(weight); + AddLink(link, bypass); } void FairMultiLinkedData::AddLinks(FairMultiLinkedData links, Float_t mult) { - std::set myLinks = links.GetLinks(); - for (auto link : myLinks) { - link.SetWeight(link.GetWeight()*mult); - AddLink(link); - } + std::set myLinks = links.GetLinks(); + for (auto link : myLinks) { + link.SetWeight(link.GetWeight() * mult); + AddLink(link); + } } void FairMultiLinkedData::AddLink(FairLink link, Bool_t bypass, Float_t mult) { - Float_t weight = link.GetWeight() * mult; - link.SetWeight(weight); - //std::cout << fVerbose << std::endl; - - FairRootManager* ioman = FairRootManager::Instance(); - - if (ioman == 0) { - std::cout << "-W- no IOManager present!" << std::endl; - fPersistanceCheck = kFALSE; - } - if (fVerbose > 1) { - std::cout << "Add FairLink: " << link << std::endl; - } - - if (fPersistanceCheck == kFALSE || - link.GetIndex() < 0 || - ( link.GetType() != ioman->GetMCTrackBranchId() && - ioman->CheckBranch(ioman->GetBranchName(link.GetType())) == 0) ) { - InsertLink(link); - if (fInsertHistory == kTRUE) - InsertHistory(link); - return; - } + Float_t weight = link.GetWeight() * mult; + link.SetWeight(weight); + // std::cout << fVerbose << std::endl; + + FairRootManager* ioman = FairRootManager::Instance(); - if (bypass == kFALSE) { + if (ioman == 0) { + std::cout << "-W- no IOManager present!" << std::endl; + fPersistanceCheck = kFALSE; + } if (fVerbose > 1) { - std::cout << "BranchName " << ioman->GetBranchName(link.GetType()) << " checkStatus: " << ioman->CheckBranch(ioman->GetBranchName(link.GetType())) << std::endl; + std::cout << "Add FairLink: " << link << std::endl; } - if (link.GetType() > ioman->GetMCTrackBranchId() && ioman->CheckBranch(ioman->GetBranchName(link.GetType())) != 1) { - if (fVerbose > 1) { - std::cout << "BYPASS!" << std::endl; - } -// bypass = kTRUE; + + if (fPersistanceCheck == kFALSE || link.GetIndex() < 0 + || (link.GetType() != ioman->GetMCTrackBranchId() + && ioman->CheckBranch(ioman->GetBranchName(link.GetType())) == 0)) { + InsertLink(link); + if (fInsertHistory == kTRUE) + InsertHistory(link); + return; } - } - - if (bypass == kTRUE) { - //FairRootManager* ioman = FairRootManager::Instance(); - if (link.GetType() > ioman->GetMCTrackBranchId()) { - TClonesArray* array = static_cast(ioman->GetObject(ioman->GetBranchName(link.GetType()))); - if (fVerbose > 1) { - std::cout << "Entries in " << ioman->GetBranchName(link.GetType()) << " Array: " << array->GetEntries() << std::endl; - } - FairMultiLinkedData* links = static_cast(array->At(link.GetIndex())); - if (fVerbose > 1) { - std::cout << "FairMultiLinkedData has " << links->GetNLinks() << " Entries: " << std::endl; - std::cout << *links << std::endl; - } - AddLinks(*links, mult); - return; + + if (bypass == kFALSE) { + if (fVerbose > 1) { + std::cout << "BranchName " << ioman->GetBranchName(link.GetType()) + << " checkStatus: " << ioman->CheckBranch(ioman->GetBranchName(link.GetType())) << std::endl; + } + if (link.GetType() > ioman->GetMCTrackBranchId() + && ioman->CheckBranch(ioman->GetBranchName(link.GetType())) != 1) { + if (fVerbose > 1) { + std::cout << "BYPASS!" << std::endl; + } + // bypass = kTRUE; + } + } + + if (bypass == kTRUE) { + // FairRootManager* ioman = FairRootManager::Instance(); + if (link.GetType() > ioman->GetMCTrackBranchId()) { + TClonesArray* array = static_cast(ioman->GetObject(ioman->GetBranchName(link.GetType()))); + if (fVerbose > 1) { + std::cout << "Entries in " << ioman->GetBranchName(link.GetType()) << " Array: " << array->GetEntries() + << std::endl; + } + FairMultiLinkedData* links = static_cast(array->At(link.GetIndex())); + if (fVerbose > 1) { + std::cout << "FairMultiLinkedData has " << links->GetNLinks() << " Entries: " << std::endl; + std::cout << *links << std::endl; + } + AddLinks(*links, mult); + return; + } else { + InsertLink(link); + if (fInsertHistory == kTRUE) + InsertHistory(link); + } } else { - InsertLink(link); - if (fInsertHistory == kTRUE) - InsertHistory(link); + InsertLink(link); + if (fInsertHistory == kTRUE) + InsertHistory(link); } - } else { - InsertLink(link); - if (fInsertHistory == kTRUE) - InsertHistory(link); - } } void FairMultiLinkedData::InsertLink(FairLink link) { - if (FairLinkManager::Instance()->IsIgnoreType(link.GetType())){ + if (FairLinkManager::Instance()->IsIgnoreType(link.GetType())) { + return; + } + + std::set::iterator it = fLinks.find(link); + if (it != fLinks.end()) { + FairLink myTempLink = *it; + myTempLink.AddWeight(link.GetWeight()); + fLinks.erase(it); + fLinks.insert(myTempLink); + } else { + fLinks.insert(link); + } return; - } - - std::set::iterator it = fLinks.find(link); - if (it != fLinks.end()) { - FairLink myTempLink = *it; - myTempLink.AddWeight(link.GetWeight()); - fLinks.erase(it); - fLinks.insert(myTempLink); - } else { - fLinks.insert(link); - } - return; } void FairMultiLinkedData::InsertHistory(FairLink link) @@ -194,7 +206,8 @@ void FairMultiLinkedData::InsertHistory(FairLink link) FairMultiLinkedData* pointerToLinks = 0; if (fVerbose > 1) { - std::cout << "FairMultiLinkedData::InsertHistory for Link " << link << " Type: " << ioman->GetBranchName(link.GetType()) << std::endl; + std::cout << "FairMultiLinkedData::InsertHistory for Link " << link + << " Type: " << ioman->GetBranchName(link.GetType()) << std::endl; } if (link.GetType() < 0) @@ -206,24 +219,26 @@ void FairMultiLinkedData::InsertHistory(FairLink link) if (link.GetEntry() != -1 && link.GetEntry() != ioman->GetEntryNr()) return; - if (link.GetIndex() < 0) { //if index is -1 then this is not a TClonesArray so only the Object is returned + if (link.GetIndex() < 0) { // if index is -1 then this is not a TClonesArray so only the Object is returned TObject* myObject = ioman->GetObject(ioman->GetBranchName(link.GetType())); if (myObject->InheritsFrom("FairMultiLinkedData_Interface")) { FairMultiLinkedData_Interface* interface = static_cast(myObject); pointerToLinks = interface->GetPointerToLinks(); } else { - std::cout << "FairMultiLinkedData::InsertHistory Link to wrong Class: " << ioman->GetBranchName(link.GetType()) << std::endl; + std::cout << "FairMultiLinkedData::InsertHistory Link to wrong Class: " + << ioman->GetBranchName(link.GetType()) << std::endl; return; } } else { - TClonesArray* dataArray = static_cast( ioman->GetObject(ioman->GetBranchName(link.GetType()))); + TClonesArray* dataArray = static_cast(ioman->GetObject(ioman->GetBranchName(link.GetType()))); if (dataArray != 0 && link.GetIndex() < dataArray->GetEntriesFast()) { TObject* myObject = dataArray->At(link.GetIndex()); if (myObject->InheritsFrom("FairMultiLinkedData_Interface")) { FairMultiLinkedData_Interface* interface = static_cast(myObject); pointerToLinks = interface->GetPointerToLinks(); } else { - std::cout << "FairMultiLinkedData::InsertHistory Link to wrong Class: " << ioman->GetBranchName(link.GetType()) << std::endl; + std::cout << "FairMultiLinkedData::InsertHistory Link to wrong Class: " + << ioman->GetBranchName(link.GetType()) << std::endl; return; } } @@ -240,24 +255,24 @@ void FairMultiLinkedData::InsertHistory(FairLink link) Bool_t FairMultiLinkedData::IsLinkInList(Int_t type, Int_t index) { - if (LinkPosInList(type, index) > -1) { - return kTRUE; - } - return kFALSE; + if (LinkPosInList(type, index) > -1) { + return kTRUE; + } + return kFALSE; } Int_t FairMultiLinkedData::LinkPosInList(Int_t type, Int_t index) { - std::set::iterator it = std::find(fLinks.begin(), fLinks.end(), FairLink(type, index)); - if (it != fLinks.end()) { - return std::distance(fLinks.begin(), it); - } - return -1; + std::set::iterator it = std::find(fLinks.begin(), fLinks.end(), FairLink(type, index)); + if (it != fLinks.end()) { + return std::distance(fLinks.begin(), it); + } + return -1; } void FairMultiLinkedData::DeleteLink(Int_t /*type*/, Int_t /*index*/) { - /* Int_t pos = LinkPosInList(type, index); + /* Int_t pos = LinkPosInList(type, index); if (pos < 0) return; else{ fLinks.erase(fLinks.begin()+pos); @@ -266,70 +281,76 @@ void FairMultiLinkedData::DeleteLink(Int_t /*type*/, Int_t /*index*/) FairMultiLinkedData FairMultiLinkedData::GetLinksWithType(Int_t type) const { - FairMultiLinkedData result; - for (auto link : fLinks) { - if (link.GetType() == type) { - result.InsertLink(link); + FairMultiLinkedData result; + for (auto link : fLinks) { + if (link.GetType() == type) { + result.InsertLink(link); + } } - } - return result; + return result; } -bool LargerWeight(FairLink val1, FairLink val2){ - return val1.GetWeight() > val2.GetWeight(); -} +bool LargerWeight(FairLink val1, FairLink val2) { return val1.GetWeight() > val2.GetWeight(); } -std::vector FairMultiLinkedData::GetSortedMCTracks(){ +std::vector FairMultiLinkedData::GetSortedMCTracks() +{ FairMultiLinkedData mcLinks = GetLinksWithType(FairRootManager::Instance()->GetMCTrackBranchId()); std::set mcSet = mcLinks.GetLinks(); std::vector mcVector(mcSet.begin(), mcSet.end()); - //std::sort(begin(mcVector), end(mcVector), [](FairLink& val1, FairLink& val2){ return val1.GetWeight() > val2.GetWeight();}); + // std::sort(begin(mcVector), end(mcVector), [](FairLink& val1, FairLink& val2){ return val1.GetWeight() > + // val2.GetWeight();}); std::sort(begin(mcVector), end(mcVector), LargerWeight); return mcVector; } TObject* FairMultiLinkedData::GetData(FairLink& myLink) { - FairRootManager* ioman = FairRootManager::Instance(); - TString branchName = ioman->GetBranchName(myLink.GetType()); - if (ioman->CheckBranch(branchName) > 0) { - TClonesArray* myArray = static_cast(ioman->GetObject(branchName)); - if (myArray != 0) { - if (myArray->GetEntries() > myLink.GetIndex()) { - return myArray->At(myLink.GetIndex()); - } else { std::cout << "-E- FairMultiLinkedData::GetData index out of bounds" << std::endl; } - } else { std::cout << "-E- FairMultiLinkedData::GetData no TClonesArray" << std::endl; } - } else { std::cout << "-E- FairMultiLinkedData::GetData Branch does not exist in Memory" << std::endl; } - - return 0; + FairRootManager* ioman = FairRootManager::Instance(); + TString branchName = ioman->GetBranchName(myLink.GetType()); + if (ioman->CheckBranch(branchName) > 0) { + TClonesArray* myArray = static_cast(ioman->GetObject(branchName)); + if (myArray != 0) { + if (myArray->GetEntries() > myLink.GetIndex()) { + return myArray->At(myLink.GetIndex()); + } else { + std::cout << "-E- FairMultiLinkedData::GetData index out of bounds" << std::endl; + } + } else { + std::cout << "-E- FairMultiLinkedData::GetData no TClonesArray" << std::endl; + } + } else { + std::cout << "-E- FairMultiLinkedData::GetData Branch does not exist in Memory" << std::endl; + } + + return 0; } void FairMultiLinkedData::SetAllWeights(Double_t weight) { - std::set tempLinks; - for (auto link : fLinks) { - link.SetWeight(weight); - tempLinks.insert(link); - } - fLinks = tempLinks; + std::set tempLinks; + for (auto link : fLinks) { + link.SetWeight(weight); + tempLinks.insert(link); + } + fLinks = tempLinks; } void FairMultiLinkedData::AddAllWeights(Double_t weight) { - std::set tempLinks; - for (auto link : fLinks) { - link.SetWeight(weight + link.GetWeight()); - tempLinks.insert(link); - } - fLinks = tempLinks; + std::set tempLinks; + for (auto link : fLinks) { + link.SetWeight(weight + link.GetWeight()); + tempLinks.insert(link); + } + fLinks = tempLinks; } void FairMultiLinkedData::MultiplyAllWeights(Double_t weight) { - std::set tempLinks; - for (auto link : fLinks) { - link.SetWeight(weight * link.GetWeight()); - tempLinks.insert(link); - } - fLinks = tempLinks; + std::set tempLinks; + for (auto link : fLinks) { + link.SetWeight(weight * link.GetWeight()); + tempLinks.insert(link); + } + fLinks = tempLinks; } diff --git a/base/event/FairMultiLinkedData.h b/base/event/FairMultiLinkedData.h index dc8a9b2a9b..7735abfdb0 100644 --- a/base/event/FairMultiLinkedData.h +++ b/base/event/FairMultiLinkedData.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /** @@ -15,95 +15,139 @@ #ifndef FAIRMULTILINKEDDATA_H_ #define FAIRMULTILINKEDDATA_H_ -#include "FairLink.h" // for FairLink +#include "FairLink.h" // for FairLink -#include // for TObject -#include // for Int_t, Bool_t, kFALSE, etc -#include // for TString +#include // for Int_t, Bool_t, kFALSE, etc +#include // for TObject +#include // for TString +#include // for ostream +#include // for operator<<, ostream, cout +#include // for set +#include // for vector -#include // for ostream -#include // for operator<<, ostream, cout -#include // for set -#include // for vector - -class FairMultiLinkedData : public TObject +class FairMultiLinkedData : public TObject { public: - FairMultiLinkedData(); ///< Default constructor - FairMultiLinkedData(const std::set& links, Bool_t persistanceCheck = kTRUE); ///< Constructor - FairMultiLinkedData(TString dataType, const std::vector& links, Int_t fileId = -1, Int_t evtId = -1,Bool_t persistanceCheck = kTRUE, Bool_t bypass = kFALSE, Float_t mult = 1.0); ///< Constructor - FairMultiLinkedData(Int_t dataType, const std::vector& links, Int_t fileId = -1, Int_t evtId = -1, Bool_t persistanceCheck = kTRUE, Bool_t bypass = kFALSE, Float_t mult = 1.0); ///< Constructor - - virtual ~FairMultiLinkedData() {}; - - virtual std::set GetLinks() const { return fLinks; } ///< returns stored links as FairLinks - virtual FairLink GetEntryNr() const { return fEntryNr; } ///< gives back the entryNr - virtual Int_t GetNLinks() const { return fLinks.size(); } ///< returns the number of stored links - virtual FairLink GetLink(Int_t pos) const; ///< returns the FairLink at the given position - virtual FairMultiLinkedData GetLinksWithType(Int_t type) const; ///< Gives you a list of links which contain the given type - virtual std::vector GetSortedMCTracks(); ///< Gives you a list of all FairLinks pointing to a "MCTrack" sorted by their weight - TObject* GetData(FairLink& myLink); ///< Get the TObject the Link is pointing to - virtual Int_t GetDefaultType() { return fDefaultType;} - Bool_t GetPersistanceCheck() {return fPersistanceCheck; } ///< Returns the value of PersistanceCheck - Int_t GetVerbose() {return fVerbose; } ///< Returns the verbosity level - virtual void SetDefaultType(Int_t type) { fDefaultType = type;} - virtual void SetPersistanceCheck(Bool_t check) {fPersistanceCheck = check; } ///< Controls if a persistance check of a link is done or not - virtual void SetVerbose(Int_t level) {fVerbose = level; } ///< Sets the verbosity level - virtual void SetInsertHistory(Bool_t val){ fInsertHistory = val; } ///< Toggles if history of a link is inserted or not - Bool_t GetInsertHistory() const {return fInsertHistory;} - - virtual void SetEntryNr(FairLink entry){ fEntryNr = entry;} - virtual void SetLinks(FairMultiLinkedData links, Float_t mult = 1.0); ///< Sets the links as vector of FairLink - virtual void SetLink(FairLink link, Bool_t bypass = kFALSE, Float_t mult = 1.0); ///< Sets the Links with a single FairLink - - virtual void AddLinks(FairMultiLinkedData links, Float_t mult = 1.0); ///< Adds a List of FairLinks (FairMultiLinkedData) to fLinks - virtual void AddLink(FairLink link, Bool_t bypass = kFALSE, Float_t mult = 1.0); ///< Adds a FairLink link at the end of fLinks. If multi is kTRUE a link is allowed more than once otherwise it is stored only once - - virtual void InsertLink(FairLink link); ///< Inserts a link into the list of links without persistance checking - virtual void InsertHistory(FairLink link); ///< Adds the FairLinks of the inserted link to the set of links of this object - - virtual void AddAllWeights(Double_t weight); ///< Adds weight to all Links - virtual void SetAllWeights(Double_t weight); ///< Sets a common weight for Links - virtual void MultiplyAllWeights(Double_t weight); ///& links, Bool_t persistanceCheck = kTRUE); ///< Constructor + FairMultiLinkedData(TString dataType, + const std::vector& links, + Int_t fileId = -1, + Int_t evtId = -1, + Bool_t persistanceCheck = kTRUE, + Bool_t bypass = kFALSE, + Float_t mult = 1.0); ///< Constructor + FairMultiLinkedData(Int_t dataType, + const std::vector& links, + Int_t fileId = -1, + Int_t evtId = -1, + Bool_t persistanceCheck = kTRUE, + Bool_t bypass = kFALSE, + Float_t mult = 1.0); ///< Constructor + + virtual ~FairMultiLinkedData(){}; + + virtual std::set GetLinks() const { return fLinks; } ///< returns stored links as FairLinks + virtual FairLink GetEntryNr() const { return fEntryNr; } ///< gives back the entryNr + virtual Int_t GetNLinks() const { return fLinks.size(); } ///< returns the number of stored links + virtual FairLink GetLink(Int_t pos) const; ///< returns the FairLink at the given position + virtual FairMultiLinkedData GetLinksWithType( + Int_t type) const; ///< Gives you a list of links which contain the given type + virtual std::vector + GetSortedMCTracks(); ///< Gives you a list of all FairLinks pointing to a "MCTrack" sorted by their weight + TObject* GetData(FairLink& myLink); ///< Get the TObject the Link is pointing to + virtual Int_t GetDefaultType() { return fDefaultType; } + Bool_t GetPersistanceCheck() { return fPersistanceCheck; } ///< Returns the value of PersistanceCheck + Int_t GetVerbose() { return fVerbose; } ///< Returns the verbosity level + virtual void SetDefaultType(Int_t type) { fDefaultType = type; } + virtual void SetPersistanceCheck(Bool_t check) + { + fPersistanceCheck = check; + } ///< Controls if a persistance check of a link is done or not + virtual void SetVerbose(Int_t level) { fVerbose = level; } ///< Sets the verbosity level + virtual void SetInsertHistory(Bool_t val) + { + fInsertHistory = val; + } ///< Toggles if history of a link is inserted or not + Bool_t GetInsertHistory() const { return fInsertHistory; } + + virtual void SetEntryNr(FairLink entry) { fEntryNr = entry; } + virtual void SetLinks(FairMultiLinkedData links, Float_t mult = 1.0); ///< Sets the links as vector of FairLink + virtual void SetLink(FairLink link, + Bool_t bypass = kFALSE, + Float_t mult = 1.0); ///< Sets the Links with a single FairLink + + virtual void AddLinks(FairMultiLinkedData links, + Float_t mult = 1.0); ///< Adds a List of FairLinks (FairMultiLinkedData) to fLinks + virtual void AddLink(FairLink link, + Bool_t bypass = kFALSE, + Float_t mult = 1.0); ///< Adds a FairLink link at the end of fLinks. If multi is kTRUE a link + ///< is allowed more than once otherwise it is stored only once + + virtual void InsertLink(FairLink link); ///< Inserts a link into the list of links without persistance checking + virtual void InsertHistory( + FairLink link); ///< Adds the FairLinks of the inserted link to the set of links of this object + + virtual void AddAllWeights(Double_t weight); ///< Adds weight to all Links + virtual void SetAllWeights(Double_t weight); ///< Sets a common weight for Links + virtual void MultiplyAllWeights(Double_t weight); ///< Multiplies all Links with weight + + virtual Bool_t IsLinkInList(FairLink link) + { + return IsLinkInList(link.GetType(), link.GetIndex()); + } ///< Test if a given link is in fLinks + virtual Bool_t IsLinkInList( + Int_t type, + Int_t index); ///< Same as IsLinkInList(FairLink) just with type and index given separately + virtual Int_t LinkPosInList(FairLink link) + { + return LinkPosInList(link.GetType(), link.GetIndex()); + } ///< returns position of link in fLinks. If it is not in the list -1 is returned + virtual Int_t LinkPosInList(Int_t type, Int_t index); ///< Same as LinkPosInList(FairLink) + + virtual void DeleteLink(FairLink link) + { + DeleteLink(link.GetType(), link.GetIndex()); + } ///< Deletes a link ouf of fLinks + virtual void DeleteLink(Int_t type, Int_t index); ///< Deletes a link ouf of fLinks + + virtual void Reset() { ResetLinks(); } + virtual void ResetLinks() { fLinks.clear(); } ///< Clears fLinks std::ostream& PrintLinkInfo(std::ostream& out = std::cout) const { - out << GetEntryNr() << " -> ["; - for (Int_t i = 0; i < GetNLinks(); i++) { - GetLink(i).PrintLinkInfo(out); - out << " "; - } - out << "]"; - return out; - } ///< Output - - friend std::ostream& operator<< (std::ostream& out, const FairMultiLinkedData& data) { - data.PrintLinkInfo(out); - return out; - } ///< Output + out << GetEntryNr() << " -> ["; + for (Int_t i = 0; i < GetNLinks(); i++) { + GetLink(i).PrintLinkInfo(out); + out << " "; + } + out << "]"; + return out; + } ///< Output + + friend std::ostream& operator<<(std::ostream& out, const FairMultiLinkedData& data) + { + data.PrintLinkInfo(out); + return out; + } ///< Output protected: std::set fLinks; FairLink fEntryNr; - Bool_t fPersistanceCheck; //! - Bool_t fInsertHistory; //! - Int_t fVerbose; //! - - virtual void SimpleAddLinks(Int_t fileId, Int_t evtId, Int_t dataType, const std::vector& links, Bool_t, Float_t) { - for (UInt_t i = 0; i < links.size(); i++) { - fLinks.insert(FairLink(fileId, evtId, dataType, links[i])); - } + Bool_t fPersistanceCheck; //! + Bool_t fInsertHistory; //! + Int_t fVerbose; //! + + virtual void SimpleAddLinks(Int_t fileId, + Int_t evtId, + Int_t dataType, + const std::vector& links, + Bool_t, + Float_t) + { + for (UInt_t i = 0; i < links.size(); i++) { + fLinks.insert(FairLink(fileId, evtId, dataType, links[i])); + } } Int_t fDefaultType; @@ -112,12 +156,14 @@ class FairMultiLinkedData : public TObject /**\fn virtual void FairMultiLinkedData::SetLinks(Int_t type, std::vector links) * \param type as Int_t gives one type of source data for all indices - * \param links as vector gives the vector of indices at which position in the TClonesArray the source data is stored + * \param links as vector gives the vector of indices at which position in the TClonesArray the source data is + * stored */ /**\fn virtual void FairMultiLinkedData::SetLinks(std::vector type, std::vector links) * \param type as vector gives the type of source data (TClonesArray) - * \param links as vector gives the vector of indices at which position in the TClonesArray the source data is stored + * \param links as vector gives the vector of indices at which position in the TClonesArray the source data is + * stored */ #endif /* FAIRMULTILinkedData_H_ */ diff --git a/base/event/FairMultiLinkedData_Interface.cxx b/base/event/FairMultiLinkedData_Interface.cxx index 0d675c95fb..5b39b6b74d 100644 --- a/base/event/FairMultiLinkedData_Interface.cxx +++ b/base/event/FairMultiLinkedData_Interface.cxx @@ -6,32 +6,49 @@ */ #include "FairMultiLinkedData_Interface.h" -#include "FairRootManager.h" // for FairRootManager + +#include "FairRootManager.h" // for FairRootManager ClassImp(FairMultiLinkedData_Interface); FairMultiLinkedData_Interface::FairMultiLinkedData_Interface(FairMultiLinkedData& links, Bool_t) - :TObject(), fLink(nullptr) + : TObject() + , fLink(nullptr) { SetLinks(links); } -FairMultiLinkedData_Interface::FairMultiLinkedData_Interface(TString dataType, std::vector links, Int_t fileId, Int_t evtId, Bool_t persistanceCheck, Bool_t bypass, Float_t mult) - :TObject(), fLink(nullptr) +FairMultiLinkedData_Interface::FairMultiLinkedData_Interface(TString dataType, + std::vector links, + Int_t fileId, + Int_t evtId, + Bool_t persistanceCheck, + Bool_t bypass, + Float_t mult) + : TObject() + , fLink(nullptr) { FairMultiLinkedData data(dataType, links, fileId, evtId, persistanceCheck, bypass, mult); SetLinks(data); } -FairMultiLinkedData_Interface::FairMultiLinkedData_Interface( Int_t dataType, std::vector links, Int_t fileId, Int_t evtId, Bool_t persistanceCheck, Bool_t bypass, Float_t mult) - :TObject(), fLink(nullptr) +FairMultiLinkedData_Interface::FairMultiLinkedData_Interface(Int_t dataType, + std::vector links, + Int_t fileId, + Int_t evtId, + Bool_t persistanceCheck, + Bool_t bypass, + Float_t mult) + : TObject() + , fLink(nullptr) { FairMultiLinkedData data(dataType, links, fileId, evtId, persistanceCheck, bypass, mult); SetLinks(data); } FairMultiLinkedData_Interface::FairMultiLinkedData_Interface(const FairMultiLinkedData_Interface& toCopy) - :TObject(toCopy), fLink(nullptr) + : TObject(toCopy) + , fLink(nullptr) { if (toCopy.GetPointerToLinks() != 0) { SetInsertHistory(kFALSE); @@ -57,7 +74,7 @@ FairMultiLinkedData* FairMultiLinkedData_Interface::CreateFairMultiLinkedData() { if (FairRootManager::Instance() != 0) { if (FairRootManager::Instance()->GetUseFairLinks()) { - if (fLink == 0){ + if (fLink == 0) { fLink = new FairMultiLinkedData(); } return fLink; @@ -68,7 +85,7 @@ FairMultiLinkedData* FairMultiLinkedData_Interface::CreateFairMultiLinkedData() std::set FairMultiLinkedData_Interface::GetLinks() const { - if (GetPointerToLinks() != 0){ + if (GetPointerToLinks() != 0) { return GetPointerToLinks()->GetLinks(); } else { std::set emptySet; @@ -78,7 +95,7 @@ std::set FairMultiLinkedData_Interface::GetLinks() const Int_t FairMultiLinkedData_Interface::GetNLinks() const { - if (GetPointerToLinks() != 0){ + if (GetPointerToLinks() != 0) { return GetPointerToLinks()->GetNLinks(); } else { return 0; @@ -87,7 +104,7 @@ Int_t FairMultiLinkedData_Interface::GetNLinks() const FairLink FairMultiLinkedData_Interface::GetLink(Int_t pos) const { - if (GetPointerToLinks() != 0){ + if (GetPointerToLinks() != 0) { return GetPointerToLinks()->GetLink(pos); } else { FairLink emptyLink; @@ -107,7 +124,7 @@ FairLink FairMultiLinkedData_Interface::GetEntryNr() const FairMultiLinkedData FairMultiLinkedData_Interface::GetLinksWithType(Int_t type) const { - if (GetPointerToLinks() != 0){ + if (GetPointerToLinks() != 0) { return GetPointerToLinks()->GetLinksWithType(type); } else { FairMultiLinkedData emptyLinks; @@ -117,7 +134,7 @@ FairMultiLinkedData FairMultiLinkedData_Interface::GetLinksWithType(Int_t type) std::vector FairMultiLinkedData_Interface::GetSortedMCTracks() { - if (GetPointerToLinks() != 0){ + if (GetPointerToLinks() != 0) { return GetPointerToLinks()->GetSortedMCTracks(); } else { std::vector empty; @@ -128,7 +145,7 @@ std::vector FairMultiLinkedData_Interface::GetSortedMCTracks() void FairMultiLinkedData_Interface::SetLinks(FairMultiLinkedData links) { CreateFairMultiLinkedData(); - if (GetPointerToLinks() != 0){ + if (GetPointerToLinks() != 0) { GetPointerToLinks()->SetLinks(links); } } @@ -136,7 +153,7 @@ void FairMultiLinkedData_Interface::SetLinks(FairMultiLinkedData links) void FairMultiLinkedData_Interface::SetLink(FairLink link) { CreateFairMultiLinkedData(); - if (GetPointerToLinks() != 0){ + if (GetPointerToLinks() != 0) { GetPointerToLinks()->SetLink(link); } } @@ -152,7 +169,7 @@ void FairMultiLinkedData_Interface::SetEntryNr(FairLink val) void FairMultiLinkedData_Interface::AddLinks(FairMultiLinkedData links, Float_t mult) { CreateFairMultiLinkedData(); - if (GetPointerToLinks() != 0){ + if (GetPointerToLinks() != 0) { GetPointerToLinks()->AddLinks(links, mult); } } @@ -160,18 +177,19 @@ void FairMultiLinkedData_Interface::AddLinks(FairMultiLinkedData links, Float_t void FairMultiLinkedData_Interface::AddLink(FairLink link) { CreateFairMultiLinkedData(); - if (GetPointerToLinks() != 0){ + if (GetPointerToLinks() != 0) { GetPointerToLinks()->AddLink(link); } } void FairMultiLinkedData_Interface::AddInterfaceData(FairMultiLinkedData_Interface* data) { - SetInsertHistory(kFALSE); //todo add previous history value + SetInsertHistory(kFALSE); // todo add previous history value if (data->GetEntryNr().GetType() != -1) AddLink(data->GetEntryNr()); else - std::cout << "-E- FairMultiLinkedData_Interface::AddInterfaceData EntryNr == " << data->GetEntryNr() << std::endl; + std::cout << "-E- FairMultiLinkedData_Interface::AddInterfaceData EntryNr == " << data->GetEntryNr() + << std::endl; if (data->GetPointerToLinks() != 0) { AddLinks(*data->GetPointerToLinks()); @@ -189,7 +207,7 @@ void FairMultiLinkedData_Interface::SetInsertHistory(Bool_t val) void FairMultiLinkedData_Interface::ResetLinks() { - if (GetPointerToLinks() != 0){ + if (GetPointerToLinks() != 0) { GetPointerToLinks()->ResetLinks(); } } diff --git a/base/event/FairMultiLinkedData_Interface.h b/base/event/FairMultiLinkedData_Interface.h index 9ba9df5cf3..b63efb771b 100644 --- a/base/event/FairMultiLinkedData_Interface.h +++ b/base/event/FairMultiLinkedData_Interface.h @@ -8,63 +8,76 @@ #ifndef FairMultiLinkedData_Interface_H_ #define FairMultiLinkedData_Interface_H_ -#include "FairLink.h" // for FairLink +#include "FairLink.h" // for FairLink #include "FairMultiLinkedData.h" -#include // for TObject -#include // for Int_t, Bool_t, kFALSE, etc -#include // for TString +#include // for Int_t, Bool_t, kFALSE, etc +#include // for TObject +#include // for TString +#include // for operator<<, ostream, cout +#include // for set +#include // for vector -#include // for operator<<, ostream, cout -#include // for set -#include // for vector - -class FairMultiLinkedData_Interface : public TObject +class FairMultiLinkedData_Interface : public TObject { public: - FairMultiLinkedData_Interface(); ///< Default constructor - FairMultiLinkedData_Interface(FairMultiLinkedData& links, Bool_t persistanceCheck = kTRUE); ///< Constructor - FairMultiLinkedData_Interface(TString dataType, std::vector links, Int_t fileId = -1, Int_t evtId = -1,Bool_t persistanceCheck = kTRUE, Bool_t bypass = kFALSE, Float_t mult = 1.0); ///< Constructor - FairMultiLinkedData_Interface(Int_t dataType, std::vector links, Int_t fileId = -1, Int_t evtId = -1, Bool_t persistanceCheck = kTRUE, Bool_t bypass = kFALSE, Float_t mult = 1.0); ///< Constructor + FairMultiLinkedData_Interface(); ///< Default constructor + FairMultiLinkedData_Interface(FairMultiLinkedData& links, Bool_t persistanceCheck = kTRUE); ///< Constructor + FairMultiLinkedData_Interface(TString dataType, + std::vector links, + Int_t fileId = -1, + Int_t evtId = -1, + Bool_t persistanceCheck = kTRUE, + Bool_t bypass = kFALSE, + Float_t mult = 1.0); ///< Constructor + FairMultiLinkedData_Interface(Int_t dataType, + std::vector links, + Int_t fileId = -1, + Int_t evtId = -1, + Bool_t persistanceCheck = kTRUE, + Bool_t bypass = kFALSE, + Float_t mult = 1.0); ///< Constructor FairMultiLinkedData_Interface(const FairMultiLinkedData_Interface& toCopy); - ~FairMultiLinkedData_Interface() { - delete(fLink); - }; + ~FairMultiLinkedData_Interface() { delete (fLink); }; FairMultiLinkedData_Interface& operator=(const FairMultiLinkedData_Interface& rhs); - std::set GetLinks() const; ///< returns stored links as FairLinks - Int_t GetNLinks() const; ///< returns the number of stored links - FairLink GetLink(Int_t pos) const; ///< returns the FairLink at the given position - FairMultiLinkedData GetLinksWithType(Int_t type) const; ///< returns all FairLinks with the corresponding type + std::set GetLinks() const; ///< returns stored links as FairLinks + Int_t GetNLinks() const; ///< returns the number of stored links + FairLink GetLink(Int_t pos) const; ///< returns the FairLink at the given position + FairMultiLinkedData GetLinksWithType(Int_t type) const; ///< returns all FairLinks with the corresponding type FairLink GetEntryNr() const; - FairMultiLinkedData* GetPointerToLinks() const { return fLink;} + FairMultiLinkedData* GetPointerToLinks() const { return fLink; } std::vector GetSortedMCTracks(); - void SetLinks(FairMultiLinkedData links); ///< Sets the links as vector of FairLink - void SetLink(FairLink link); ///< Sets the Links with a single FairLink + void SetLinks(FairMultiLinkedData links); ///< Sets the links as vector of FairLink + void SetLink(FairLink link); ///< Sets the Links with a single FairLink void SetInsertHistory(Bool_t val); void SetEntryNr(FairLink val); - void SetPointerToLinks(FairMultiLinkedData* links) {fLink = links;} + void SetPointerToLinks(FairMultiLinkedData* links) { fLink = links; } - void AddLinks(FairMultiLinkedData links, Float_t mult = 1.0); ///< Adds a List of FairLinks (FairMultiLinkedData_Interface) to fLinks - void AddLink(FairLink link); ///< Adds a FairLink link at the end of fLinks. If multi is kTRUE a link is allowed more than once otherwise + void AddLinks(FairMultiLinkedData links, + Float_t mult = 1.0); ///< Adds a List of FairLinks (FairMultiLinkedData_Interface) to fLinks + void AddLink(FairLink link); ///< Adds a FairLink link at the end of fLinks. If multi is kTRUE a link is allowed + ///< more than once otherwise void AddInterfaceData(FairMultiLinkedData_Interface* data); void ResetLinks(); - std::ostream& PrintLinkInfo(std::ostream& out = std::cout) const { - if (GetPointerToLinks() != 0) - GetPointerToLinks()->PrintLinkInfo(out); - return out; - } ///< Output + std::ostream& PrintLinkInfo(std::ostream& out = std::cout) const + { + if (GetPointerToLinks() != 0) + GetPointerToLinks()->PrintLinkInfo(out); + return out; + } ///< Output - friend std::ostream& operator<< (std::ostream& out, const FairMultiLinkedData_Interface& data) { - data.PrintLinkInfo(out); - return out; - } ///< Output + friend std::ostream& operator<<(std::ostream& out, const FairMultiLinkedData_Interface& data) + { + data.PrintLinkInfo(out); + return out; + } ///< Output protected: FairMultiLinkedData* fLink; @@ -74,18 +87,20 @@ class FairMultiLinkedData_Interface : public TObject }; inline FairMultiLinkedData_Interface::FairMultiLinkedData_Interface() - :TObject(), fLink(nullptr) -{ -} + : TObject() + , fLink(nullptr) +{} /**\fn virtual void FairMultiLinkedData_Interface::SetLinks(Int_t type, std::vector links) * \param type as Int_t gives one type of source data for all indices - * \param links as vector gives the vector of indices at which position in the TClonesArray the source data is stored + * \param links as vector gives the vector of indices at which position in the TClonesArray the source data is + * stored */ /**\fn virtual void FairMultiLinkedData_Interface::SetLinks(std::vector type, std::vector links) * \param type as vector gives the type of source data (TClonesArray) - * \param links as vector gives the vector of indices at which position in the TClonesArray the source data is stored + * \param links as vector gives the vector of indices at which position in the TClonesArray the source data is + * stored */ #endif /* FairMultiLinkedData_Interface_H_ */ diff --git a/base/event/FairPrintFairLinks.cxx b/base/event/FairPrintFairLinks.cxx index 48e63d0c98..85bb892676 100644 --- a/base/event/FairPrintFairLinks.cxx +++ b/base/event/FairPrintFairLinks.cxx @@ -9,28 +9,28 @@ #include // framework includes -#include "FairRootManager.h" -#include "FairMultiLinkedData_Interface.h" #include "FairLogger.h" +#include "FairMultiLinkedData_Interface.h" +#include "FairRootManager.h" -FairPrintFairLinks::FairPrintFairLinks() : FairTask("Creates PndMCMatch"), fSelectedBranches(new TList()) -{ -} +FairPrintFairLinks::FairPrintFairLinks() + : FairTask("Creates PndMCMatch") + , fSelectedBranches(new TList()) +{} -FairPrintFairLinks::~FairPrintFairLinks() -{ -} +FairPrintFairLinks::~FairPrintFairLinks() {} InitStatus FairPrintFairLinks::Init() { FairRootManager* ioman = FairRootManager::Instance(); if (!ioman) { - LOG(error) << "-E- FairPrintFairLinks::Init: " << "RootManager not instantiated!"; + LOG(error) << "-E- FairPrintFairLinks::Init: " + << "RootManager not instantiated!"; return kFATAL; } TList* branchNames; - if (fSelectedBranches->GetEntries() > 0){ + if (fSelectedBranches->GetEntries() > 0) { branchNames = fSelectedBranches; } else { branchNames = ioman->GetBranchNameList(); @@ -46,20 +46,30 @@ InitStatus FairPrintFairLinks::Init() void FairPrintFairLinks::InitBranchList(TList* branches) { FairRootManager* ioman = FairRootManager::Instance(); - for (int i = 0; i < branches->GetEntries(); i++) { //removes branches which do not contain objects derived from FairMultiLinkedData_Interface - TObjString* branchName = (TObjString*) branches->At(i); - if (branchName->String().Contains("_link")) continue; - if (branchName->String().Contains("MCTrack")) continue; - if (branchName->String().Contains(".")) continue; - if (branchName->String().Contains("GeoTracks")) continue; - if (branchName->String().Contains("Header")) continue; - if (branchName->String().Contains("Info")) continue; - if (branchName->String().Contains("ID")) continue; - if (branchName->String().Contains("PidAlgo")) continue; - if (branchName->String().Contains("Riemann")) continue; + for (int i = 0; i < branches->GetEntries(); + i++) { // removes branches which do not contain objects derived from FairMultiLinkedData_Interface + TObjString* branchName = (TObjString*)branches->At(i); + if (branchName->String().Contains("_link")) + continue; + if (branchName->String().Contains("MCTrack")) + continue; + if (branchName->String().Contains(".")) + continue; + if (branchName->String().Contains("GeoTracks")) + continue; + if (branchName->String().Contains("Header")) + continue; + if (branchName->String().Contains("Info")) + continue; + if (branchName->String().Contains("ID")) + continue; + if (branchName->String().Contains("PidAlgo")) + continue; + if (branchName->String().Contains("Riemann")) + continue; LOG(debug) << "FairPrintFairLinks::Init() branches: " << branchName->String(); - if ((TClonesArray*)ioman->GetObject(branchName->String()) != 0){ + if ((TClonesArray*)ioman->GetObject(branchName->String()) != 0) { fBranches[ioman->GetBranchId(branchName->String())] = (TClonesArray*)ioman->GetObject(branchName->String()); } else { LOG(warning) << "-E- FairPrintFairLinks " << branchName->String().Data() << " is not a valid branch name!"; @@ -72,7 +82,7 @@ void FairPrintFairLinks::PrintBranchNameList(TList* branches) LOG(info) << "-I- FairPrintFairLinks Branches:"; for (int i = 0; i < branches->GetEntries(); i++) { - TObjString* branchName = (TObjString*) branches->At(i); + TObjString* branchName = (TObjString*)branches->At(i); LOG(info) << i << " : " << branchName->String().Data() << "\n"; } LOG(info) << "\n"; @@ -87,20 +97,21 @@ void FairPrintFairLinks::SetParContainers() void FairPrintFairLinks::Exec(Option_t*) { - LOG(info) << "\n--------------------- Event " << FairRootManager::Instance()->GetEntryNr() << " at " << FairRootManager::Instance()->GetEventTime() << " ns ----------------------"; - for (std::map::iterator iter = fBranches.begin(); iter != fBranches.end(); iter++){ - LOG(info) << "\n" << iter->first << " : " << FairRootManager::Instance()->GetBranchName(iter->first) << " Entries: " << iter->second->GetEntriesFast(); - for (int i = 0; i < iter->second->GetEntriesFast(); i++){ + LOG(info) << "\n--------------------- Event " << FairRootManager::Instance()->GetEntryNr() << " at " + << FairRootManager::Instance()->GetEventTime() << " ns ----------------------"; + for (std::map::iterator iter = fBranches.begin(); iter != fBranches.end(); iter++) { + LOG(info) << "\n" + << iter->first << " : " << FairRootManager::Instance()->GetBranchName(iter->first) + << " Entries: " << iter->second->GetEntriesFast(); + for (int i = 0; i < iter->second->GetEntriesFast(); i++) { FairMultiLinkedData_Interface* myLinks = (FairMultiLinkedData_Interface*)iter->second->At(i); - if (myLinks->GetPointerToLinks() != 0){ + if (myLinks->GetPointerToLinks() != 0) { LOG(info) << i << " : " << *myLinks << "\n"; } } } } -void FairPrintFairLinks::Finish() -{ -} +void FairPrintFairLinks::Finish() {} ClassImp(FairPrintFairLinks); diff --git a/base/event/FairPrintFairLinks.h b/base/event/FairPrintFairLinks.h index a9af311fc2..1fabb0fcd7 100644 --- a/base/event/FairPrintFairLinks.h +++ b/base/event/FairPrintFairLinks.h @@ -31,9 +31,7 @@ class FairPrintFairLinks : public FairTask /** Virtual method Init **/ virtual void SetParContainers(); - virtual void AddBranchName(const TString& name){ - fSelectedBranches->AddLast(new TObjString(name.Data())); - } + virtual void AddBranchName(const TString& name) { fSelectedBranches->AddLast(new TObjString(name.Data())); } virtual void PrintBranchNameList(TList* branches); @@ -44,7 +42,7 @@ class FairPrintFairLinks : public FairTask virtual void Finish(); - protected: + protected: void InitBranchList(TList* branches); private: @@ -55,7 +53,7 @@ class FairPrintFairLinks : public FairTask void Reset(); void ProduceHits(); - ClassDef(FairPrintFairLinks,1); + ClassDef(FairPrintFairLinks, 1); }; #endif diff --git a/base/event/FairRadLenPoint.cxx b/base/event/FairRadLenPoint.cxx index d45deb1947..30878697fe 100644 --- a/base/event/FairRadLenPoint.cxx +++ b/base/event/FairRadLenPoint.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -13,44 +13,51 @@ #include "FairRadLenPoint.h" FairRadLenPoint::FairRadLenPoint() - : FairMCPoint(), - fA(0), - fZmat(0), - fDensity(0), - fRadLen(0), - fXOut(0), - fYOut(0), - fZOut(0), - fPxOut(0), - fPyOut(0), - fPzOut(0) + : FairMCPoint() + , fA(0) + , fZmat(0) + , fDensity(0) + , fRadLen(0) + , fXOut(0) + , fYOut(0) + , fZOut(0) + , fPxOut(0) + , fPyOut(0) + , fPzOut(0) { - /**default ctor*/ + /**default ctor*/ } -FairRadLenPoint::FairRadLenPoint(Int_t trackID, Int_t detID, TVector3 pos, - TVector3 mom, Double_t tof, Double_t length, Double_t eLoss, - TVector3 posOut, TVector3 momOut, - Float_t A, Float_t Z, Float_t Density, Float_t RadLen) - : FairMCPoint(trackID, detID, pos, mom, tof, length, eLoss), - fA(A), - fZmat(Z), - fDensity(Density), - fRadLen(RadLen), - fXOut(posOut.X()), - fYOut(posOut.Y()), - fZOut(posOut.Z()), - fPxOut(momOut.Px()), - fPyOut(momOut.Py()), - fPzOut(momOut.Pz()) -{ -} +FairRadLenPoint::FairRadLenPoint(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t tof, + Double_t length, + Double_t eLoss, + TVector3 posOut, + TVector3 momOut, + Float_t A, + Float_t Z, + Float_t Density, + Float_t RadLen) + : FairMCPoint(trackID, detID, pos, mom, tof, length, eLoss) + , fA(A) + , fZmat(Z) + , fDensity(Density) + , fRadLen(RadLen) + , fXOut(posOut.X()) + , fYOut(posOut.Y()) + , fZOut(posOut.Z()) + , fPxOut(momOut.Px()) + , fPyOut(momOut.Py()) + , fPzOut(momOut.Pz()) +{} -FairRadLenPoint::~FairRadLenPoint() { } +FairRadLenPoint::~FairRadLenPoint() {} -void FairRadLenPoint::Print(const Option_t*) const -{ - /**to be implimented*/ +void FairRadLenPoint::Print(const Option_t*) const +{ /**to be implimented*/ } -ClassImp(FairRadLenPoint) +ClassImp(FairRadLenPoint); diff --git a/base/event/FairRadLenPoint.h b/base/event/FairRadLenPoint.h index d905d3a3e6..00af66acc7 100644 --- a/base/event/FairRadLenPoint.h +++ b/base/event/FairRadLenPoint.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -18,10 +18,10 @@ #ifndef FAIRRADLENPOINT_H #define FAIRRADLENPOINT_H -#include "FairMCPoint.h" // for FairMCPoint +#include "FairMCPoint.h" // for FairMCPoint -#include // for Double_t, Float_t, etc -#include // for TVector3 +#include // for Double_t, Float_t, etc +#include // for TVector3 class FairRadLenPoint : public FairMCPoint { @@ -29,9 +29,19 @@ class FairRadLenPoint : public FairMCPoint /** Default constructor **/ FairRadLenPoint(); - FairRadLenPoint(Int_t trackID, Int_t detID, TVector3 pos, TVector3 mom, - Double_t tof, Double_t length, Double_t eLoss, TVector3 posOut, TVector3 momOut, - Float_t fA, Float_t fZ, Float_t fDensity, Float_t fRadLen); + FairRadLenPoint(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t tof, + Double_t length, + Double_t eLoss, + TVector3 posOut, + TVector3 momOut, + Float_t fA, + Float_t fZ, + Float_t fDensity, + Float_t fRadLen); /** Destructor **/ virtual ~FairRadLenPoint(); @@ -39,42 +49,42 @@ class FairRadLenPoint : public FairMCPoint /** Accessors **/ Float_t GetA() { return fA; } Float_t GetZm() { return fZmat; } - Float_t GetRadLength() { return fRadLen;} - Float_t GetDensity() { return fDensity ; } + Float_t GetRadLength() { return fRadLen; } + Float_t GetDensity() { return fDensity; } /** Modifiers **/ void SetA(Double_t A) { fA = A; } void SetZm(Double_t Z) { fZmat = Z; } - void SetRadLength(Double_t length) { fRadLen = length;} - void SetDensity (Double_t Density) { fDensity = Density; } + void SetRadLength(Double_t length) { fRadLen = length; } + void SetDensity(Double_t Density) { fDensity = Density; } /** Output to screen **/ virtual void Print(const Option_t* opt) const; - Double_t GetXOut() const { return fXOut;}; - Double_t GetYOut() const { return fYOut;}; - Double_t GetZOut() const { return fZOut;}; + Double_t GetXOut() const { return fXOut; }; + Double_t GetYOut() const { return fYOut; }; + Double_t GetZOut() const { return fZOut; }; Double_t GetPxOut() const { return fPxOut; } Double_t GetPyOut() const { return fPyOut; } Double_t GetPzOut() const { return fPzOut; } - TVector3 GetPosition() const { return TVector3(fX, fY, fZ);} - TVector3 GetPositionOut() const { return TVector3(fXOut, fYOut, fZOut);} + TVector3 GetPosition() const { return TVector3(fX, fY, fZ); } + TVector3 GetPositionOut() const { return TVector3(fXOut, fYOut, fZOut); } - void PositionOut(TVector3& pos) const { pos.SetXYZ(fXOut, fYOut, fZOut);}; - void MomentumOut(TVector3& mom) const { mom.SetXYZ(fPxOut,fPyOut,fPzOut); } + void PositionOut(TVector3& pos) const { pos.SetXYZ(fXOut, fYOut, fZOut); }; + void MomentumOut(TVector3& mom) const { mom.SetXYZ(fPxOut, fPyOut, fPzOut); } protected: - Float_t fA; // A of material - Float_t fZmat; // Z of material - Float_t fDensity; // density of material - Float_t fRadLen; // radiation length + Float_t fA; // A of material + Float_t fZmat; // Z of material + Float_t fDensity; // density of material + Float_t fRadLen; // radiation length Double_t fXOut, fYOut, fZOut; Double_t fPxOut, fPyOut, fPzOut; - ClassDef(FairRadLenPoint,1) + ClassDef(FairRadLenPoint, 1) }; #endif diff --git a/base/event/FairRadMapPoint.cxx b/base/event/FairRadMapPoint.cxx index ca48f404f9..0bdc6eafde 100644 --- a/base/event/FairRadMapPoint.cxx +++ b/base/event/FairRadMapPoint.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -12,53 +12,62 @@ #include "FairRadMapPoint.h" FairRadMapPoint::FairRadMapPoint() - : FairMCPoint(), - fPdg(0), - fA(0), - fZmat(0), - fDensity(0), - fVolMass(0), - fStep(0), - fDose(0), - fDoseSL(0), - fXOut(0), - fYOut(0), - fZOut(0), - fPxOut(0), - fPyOut(0), - fPzOut(0) -{ -} + : FairMCPoint() + , fPdg(0) + , fA(0) + , fZmat(0) + , fDensity(0) + , fVolMass(0) + , fStep(0) + , fDose(0) + , fDoseSL(0) + , fXOut(0) + , fYOut(0) + , fZOut(0) + , fPxOut(0) + , fPyOut(0) + , fPzOut(0) +{} -FairRadMapPoint::FairRadMapPoint(Int_t trackID, Int_t detID, TVector3 pos, - TVector3 mom, Double_t tof, Double_t length, - Double_t eLoss, TVector3 posOut, TVector3 momOut, - Float_t A, Float_t Z, Float_t Density, Double_t VolMass, - Double_t Step, Double_t Dose, Double_t DoseSL, Int_t Pdg) - : FairMCPoint(trackID, detID, pos, mom, tof, length, eLoss), - fPdg(Pdg), - fA(A), - fZmat(Z), - fDensity(Density), - fVolMass(VolMass), - fStep(Step), - fDose(Dose), - fDoseSL(DoseSL), - fXOut ( posOut.X()), - fYOut ( posOut.Y()), - fZOut ( posOut.Z()), - fPxOut ( momOut.Px()), - fPyOut ( momOut.Py()), - fPzOut ( momOut.Pz()) +FairRadMapPoint::FairRadMapPoint(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t tof, + Double_t length, + Double_t eLoss, + TVector3 posOut, + TVector3 momOut, + Float_t A, + Float_t Z, + Float_t Density, + Double_t VolMass, + Double_t Step, + Double_t Dose, + Double_t DoseSL, + Int_t Pdg) + : FairMCPoint(trackID, detID, pos, mom, tof, length, eLoss) + , fPdg(Pdg) + , fA(A) + , fZmat(Z) + , fDensity(Density) + , fVolMass(VolMass) + , fStep(Step) + , fDose(Dose) + , fDoseSL(DoseSL) + , fXOut(posOut.X()) + , fYOut(posOut.Y()) + , fZOut(posOut.Z()) + , fPxOut(momOut.Px()) + , fPyOut(momOut.Py()) + , fPzOut(momOut.Pz()) -{ -} +{} -FairRadMapPoint::~FairRadMapPoint() { } +FairRadMapPoint::~FairRadMapPoint() {} -void FairRadMapPoint::Print(const Option_t*) const -{ - /**to be implimented*/ +void FairRadMapPoint::Print(const Option_t*) const +{ /**to be implimented*/ } -ClassImp(FairRadMapPoint) +ClassImp(FairRadMapPoint); diff --git a/base/event/FairRadMapPoint.h b/base/event/FairRadMapPoint.h index b5d5e8c68d..c127408be7 100644 --- a/base/event/FairRadMapPoint.h +++ b/base/event/FairRadMapPoint.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -17,10 +17,10 @@ #ifndef FAIRRADMAPPOINT_H #define FAIRRADMAPPOINT_H -#include "FairMCPoint.h" // for FairMCPoint +#include "FairMCPoint.h" // for FairMCPoint -#include // for Double_t, Float_t, Int_t, etc -#include // for TVector3 +#include // for Double_t, Float_t, Int_t, etc +#include // for TVector3 class FairRadMapPoint : public FairMCPoint { @@ -28,26 +28,38 @@ class FairRadMapPoint : public FairMCPoint /** Default constructor **/ FairRadMapPoint(); - FairRadMapPoint(Int_t trackID, Int_t detID, TVector3 pos, TVector3 mom, - Double_t tof, Double_t length, Double_t eLoss, - TVector3 posOut, TVector3 momOut, - Float_t fA, Float_t fZ, Float_t fDensity, Double_t fVolMass, - Double_t fStep, Double_t fDose, Double_t fDoseSL, Int_t fPdg ); + FairRadMapPoint(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t tof, + Double_t length, + Double_t eLoss, + TVector3 posOut, + TVector3 momOut, + Float_t fA, + Float_t fZ, + Float_t fDensity, + Double_t fVolMass, + Double_t fStep, + Double_t fDose, + Double_t fDoseSL, + Int_t fPdg); /** Destructor **/ virtual ~FairRadMapPoint(); /** Accessors **/ - Float_t GetA() { return fA; } - Float_t GetZm() { return fZmat; } - Float_t GetMass() { return fVolMass; } - Float_t GetDensity() { return fDensity ; } + Float_t GetA() { return fA; } + Float_t GetZm() { return fZmat; } + Float_t GetMass() { return fVolMass; } + Float_t GetDensity() { return fDensity; } /** Modifiers **/ - void SetA(Double_t A) { fA = A; } - void SetZm(Double_t Z) { fZmat = Z; } - void SetMass(Double_t vmass) { fVolMass = vmass; } - void SetDensity (Double_t Density) { fDensity = Density; } + void SetA(Double_t A) { fA = A; } + void SetZm(Double_t Z) { fZmat = Z; } + void SetMass(Double_t vmass) { fVolMass = vmass; } + void SetDensity(Double_t Density) { fDensity = Density; } /** Output to screen **/ virtual void Print(const Option_t* opt) const; @@ -69,21 +81,21 @@ class FairRadMapPoint : public FairMCPoint TVector3 GetPositionOut() const { return TVector3(fXOut, fYOut, fZOut); } void PositionOut(TVector3& pos) const { pos.SetXYZ(fXOut, fYOut, fZOut); }; - void MomentumOut(TVector3& mom) const { mom.SetXYZ(fPxOut,fPyOut,fPzOut); } + void MomentumOut(TVector3& mom) const { mom.SetXYZ(fPxOut, fPyOut, fPzOut); } protected: // Int_t detID; // detector ID or volume ID - Int_t fPdg; // track PID - Float_t fA; // A of material - Float_t fZmat; // Z of material - Float_t fDensity; // density of material - Double_t fVolMass; // radiation length + Int_t fPdg; // track PID + Float_t fA; // A of material + Float_t fZmat; // Z of material + Float_t fDensity; // density of material + Double_t fVolMass; // radiation length Double_t fStep, fDose, fDoseSL; Double_t fXOut, fYOut, fZOut; Double_t fPxOut, fPyOut, fPzOut; - ClassDef(FairRadMapPoint,3) + ClassDef(FairRadMapPoint, 3) }; #endif diff --git a/base/event/FairRecoEventHeader.cxx b/base/event/FairRecoEventHeader.cxx index 1a44602e54..ff688c82cd 100644 --- a/base/event/FairRecoEventHeader.cxx +++ b/base/event/FairRecoEventHeader.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -13,13 +13,12 @@ #include "FairRecoEventHeader.h" FairRecoEventHeader::FairRecoEventHeader() - :fRunId(0), - fIdentifier(0), - fEventTime(-1.), - fEventTimeError(-1.) -{ -} + : fRunId(0) + , fIdentifier(0) + , fEventTime(-1.) + , fEventTimeError(-1.) +{} -FairRecoEventHeader::~FairRecoEventHeader() { } +FairRecoEventHeader::~FairRecoEventHeader() {} -ClassImp(FairRecoEventHeader) +ClassImp(FairRecoEventHeader); diff --git a/base/event/FairRecoEventHeader.h b/base/event/FairRecoEventHeader.h index 1761749306..25b26686d3 100644 --- a/base/event/FairRecoEventHeader.h +++ b/base/event/FairRecoEventHeader.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -17,9 +17,9 @@ /** * Event Header Class - **@author D.Bertini - **@author M.Al-Turany - **@author R.Karabowicz + **@author D.Bertini + **@author M.Al-Turany + **@author R.Karabowicz */ class FairRecoEventHeader : public TNamed { @@ -28,65 +28,63 @@ class FairRecoEventHeader : public TNamed FairRecoEventHeader(); /** Get the run ID for this run*/ - UInt_t GetRunId() const { - return fRunId; - } + UInt_t GetRunId() const { return fRunId; } /** Get the MC time for this event*/ - Double_t GetEventTime() const { - return fEventTime; - } + Double_t GetEventTime() const { return fEventTime; } /** Get the error of MC time for this event*/ - Double_t GetEventTimeError() const { - return fEventTimeError; - } + Double_t GetEventTimeError() const { return fEventTimeError; } /** Get identifier*/ - Int_t GetIdentifier() const { - return fIdentifier; - } + Int_t GetIdentifier() const { return fIdentifier; } /** Set the run ID for this run - * @param runid : unique run id - */ - void SetRunId(UInt_t runid) { - fRunId=runid; - } + * @param runid : unique run id + */ + void SetRunId(UInt_t runid) { fRunId = runid; } /** Set the MC time for this event * @param time : time in ns * @param terr : time error in ns */ - void SetEventTime(Double_t time, Double_t terr) { - fEventTime=time; - fEventTimeError=terr; + void SetEventTime(Double_t time, Double_t terr) + { + fEventTime = time; + fEventTimeError = terr; } /** Set the run ID for this run - * @param ident : identifier - */ - void SetIdentifier(Int_t ident) { - fIdentifier=ident; - } - - virtual bool operator<(const FairRecoEventHeader& tempObj) const { - if (fEventTime < tempObj.GetEventTime()) { return true; } - else if (fEventTime > tempObj.GetEventTime()) { return false; } - return false; + * @param ident : identifier + */ + void SetIdentifier(Int_t ident) { fIdentifier = ident; } + + virtual bool operator<(const FairRecoEventHeader& tempObj) const + { + if (fEventTime < tempObj.GetEventTime()) { + return true; + } else if (fEventTime > tempObj.GetEventTime()) { + return false; + } + return false; } - virtual bool operator>(const FairRecoEventHeader& tempObj) const { - if (fEventTime > tempObj.GetEventTime()) { return true; } - else if (fEventTime < tempObj.GetEventTime()) { return false; } - return false; + virtual bool operator>(const FairRecoEventHeader& tempObj) const + { + if (fEventTime > tempObj.GetEventTime()) { + return true; + } else if (fEventTime < tempObj.GetEventTime()) { + return false; + } + return false; } - virtual bool operator==(const FairRecoEventHeader& tempObj) const { - if (fEventTime == tempObj.GetEventTime() ) { - return true; - } - return false; + virtual bool operator==(const FairRecoEventHeader& tempObj) const + { + if (fEventTime == tempObj.GetEventTime()) { + return true; + } + return false; } /** @@ -98,13 +96,13 @@ class FairRecoEventHeader : public TNamed /** Run Id */ UInt_t fRunId; /** Identifier */ - Int_t fIdentifier; + Int_t fIdentifier; /** Event Time **/ - Double_t fEventTime; + Double_t fEventTime; /** Event Time Error **/ - Double_t fEventTimeError; + Double_t fEventTimeError; - ClassDef(FairRecoEventHeader,1) + ClassDef(FairRecoEventHeader, 1) }; #endif diff --git a/base/event/FairRunInfo.cxx b/base/event/FairRunInfo.cxx index ae4a7d129a..7ac7b73301 100644 --- a/base/event/FairRunInfo.cxx +++ b/base/event/FairRunInfo.cxx @@ -7,192 +7,193 @@ ********************************************************************************/ #include "FairRunInfo.h" -#include "FairLogger.h" // for FairLogger +#include "FairLogger.h" // for FairLogger -#include // for TFile, gFile -#include // for TH1F -#include // for TIterator -#include // for TList -#include // for TString -#include // for ProcInfo_t, TSystem, etc +#include // for TFile, gFile +#include // for TH1F +#include // for TIterator +#include // for TList +#include // for TString +#include // for ProcInfo_t, TSystem, etc +#include // for sort -#include // for sort - -ClassImp(FairRunInfo) +ClassImp(FairRunInfo); FairRunInfo::FairRunInfo() - :TObject(), - fTimeStamp(), - fCpuInfo(), - fMemInfo(), - fProcInfo(), - fTimeDiff(), - fTime(), - fResidentMemory(), - fVirtualMemory() -{ -} - -FairRunInfo::~FairRunInfo() -{ -} + : TObject() + , fTimeStamp() + , fCpuInfo() + , fMemInfo() + , fProcInfo() + , fTimeDiff() + , fTime() + , fResidentMemory() + , fVirtualMemory() +{} + +FairRunInfo::~FairRunInfo() {} void FairRunInfo::StoreInfo() { - // Extract the Information about the used memory from the system. - // Stores this info together with the timedifference between now - // and the last call in container arrays for later usage. - // gSystem->GetCpuInfo(&cpuInfo, 10); - // gSystem->GetMemInfo(&memInfo); + // Extract the Information about the used memory from the system. + // Stores this info together with the timedifference between now + // and the last call in container arrays for later usage. + // gSystem->GetCpuInfo(&cpuInfo, 10); + // gSystem->GetMemInfo(&memInfo); - GetInfo(); + GetInfo(); - CalculateTimeDifference(); + CalculateTimeDifference(); - PrintInfo(); + PrintInfo(); } void FairRunInfo::GetInfo() { - // Set the TimeStamp to the actual time and store it - fTimeStamp.Set(); - // fTime.push_back(fTimeStamp.GetSec()); - fTime.push_back(fTimeStamp.AsDouble()); - - gSystem->GetProcInfo(&fProcInfo); - fResidentMemory.push_back(fProcInfo.fMemResident/1024); - fVirtualMemory.push_back(fProcInfo.fMemVirtual/1024); + // Set the TimeStamp to the actual time and store it + fTimeStamp.Set(); + // fTime.push_back(fTimeStamp.GetSec()); + fTime.push_back(fTimeStamp.AsDouble()); + + gSystem->GetProcInfo(&fProcInfo); + fResidentMemory.push_back(fProcInfo.fMemResident / 1024); + fVirtualMemory.push_back(fProcInfo.fMemVirtual / 1024); } void FairRunInfo::CalculateTimeDifference() { - // Calculates the time difference between now and the last call + // Calculates the time difference between now and the last call - Int_t lastElement = fTime.size()-1; - fTimeDiff.push_back( fTime.at(lastElement) - - fTime.at(lastElement-1) ); + Int_t lastElement = fTime.size() - 1; + fTimeDiff.push_back(fTime.at(lastElement) - fTime.at(lastElement - 1)); } void FairRunInfo::PrintInfo() { - LOG(debug) << "Time to execute 1 event: " << fTimeDiff.back() << "s"; - LOG(debug) << "Used resident memory: " << fResidentMemory.back() << " MB"; - LOG(debug) << "Used virtual memory: " << fVirtualMemory.back() << " MB"; + LOG(debug) << "Time to execute 1 event: " << fTimeDiff.back() << "s"; + LOG(debug) << "Used resident memory: " << fResidentMemory.back() << " MB"; + LOG(debug) << "Used virtual memory: " << fVirtualMemory.back() << " MB"; } void FairRunInfo::WriteInfo() { - TList* histoList = new TList(); - CreateAndFillHistograms(histoList); - // CreateAndFillHistograms(histoList); - WriteHistosToFile(histoList); + TList* histoList = new TList(); + CreateAndFillHistograms(histoList); + // CreateAndFillHistograms(histoList); + WriteHistosToFile(histoList); } void FairRunInfo::CreateAndFillHistograms(TList* histoList) { - Int_t entries = fTime.size(); - Double_t timePeriod = fTime.back()-fTime.front(); - Int_t timeBins = static_cast(timePeriod*10); - if ( 0 == timeBins ) timeBins=1; - - TH1F* ResidentMemoryVsEvent = new TH1F("ResidentMemoryVsEvent","Resident Memory as function of Eventnumber;Event;Memory [MB]",entries, 0, entries); - TH1F* VirtualMemoryVsEvent = new TH1F("VirtualMemoryVsEvent","Virtual Memory as function of Eventnumber;Event;Memory [MB]",entries, 0, entries); - TH1F* ResidentMemoryVsTime = new TH1F("ResidentMemoryVsTime","Resident memory as function of Runtime;Time [s];Memory [MB]", timeBins, 0, timeBins); - TH1F* VirtualMemoryVsTime = new TH1F("VirtualMemoryVsTime","Virtual memory as function of Runtime;Time [s];Memory [MB]", timeBins, 0, timeBins); - TH1F* EventtimeVsEvent = new TH1F("EventtimeVsEvent","Runtime per Event as function of Event number;Event;Time [s]",entries-1, 1, entries); - - std::vector timeDiffSorted(fTimeDiff); - std::vector::iterator it; - std::sort(timeDiffSorted.begin(), timeDiffSorted.end()); - - Double_t minTime = timeDiffSorted.front(); - Double_t maxTime = timeDiffSorted.back(); - timePeriod = maxTime - minTime; - - TH1F* TimePerEvent = new TH1F("TimePerEvent","Runtime;Time [s];Events",static_cast((timePeriod+20)*10), static_cast(minTime-10), static_cast(maxTime+10)); - - Int_t counter = 0; - std::vector::iterator lit; - Double_t timeOffset = fTime.front()+1.; - for(lit=fResidentMemory.begin(); litFill(counter, *lit); - ResidentMemoryVsTime->Fill(fTime.at(counter)-timeOffset, *lit); - counter++; - } - histoList->AddLast(ResidentMemoryVsEvent); - histoList->AddLast(ResidentMemoryVsTime); - - counter = 0; - for(lit=fVirtualMemory.begin(); litFill(counter, *lit); - VirtualMemoryVsTime->Fill(fTime.at(counter)-timeOffset, *lit); - counter++; - } - histoList->AddLast(VirtualMemoryVsEvent); - histoList->AddLast(VirtualMemoryVsTime); - - counter = 1; - for(it=fTimeDiff.begin(); itFill(*it); - EventtimeVsEvent->Fill(counter, *it); - counter++; - } - histoList->AddLast(TimePerEvent); - histoList->AddLast(EventtimeVsEvent); + Int_t entries = fTime.size(); + Double_t timePeriod = fTime.back() - fTime.front(); + Int_t timeBins = static_cast(timePeriod * 10); + if (0 == timeBins) + timeBins = 1; + + TH1F* ResidentMemoryVsEvent = new TH1F( + "ResidentMemoryVsEvent", "Resident Memory as function of Eventnumber;Event;Memory [MB]", entries, 0, entries); + TH1F* VirtualMemoryVsEvent = new TH1F( + "VirtualMemoryVsEvent", "Virtual Memory as function of Eventnumber;Event;Memory [MB]", entries, 0, entries); + TH1F* ResidentMemoryVsTime = new TH1F( + "ResidentMemoryVsTime", "Resident memory as function of Runtime;Time [s];Memory [MB]", timeBins, 0, timeBins); + TH1F* VirtualMemoryVsTime = new TH1F( + "VirtualMemoryVsTime", "Virtual memory as function of Runtime;Time [s];Memory [MB]", timeBins, 0, timeBins); + TH1F* EventtimeVsEvent = new TH1F( + "EventtimeVsEvent", "Runtime per Event as function of Event number;Event;Time [s]", entries - 1, 1, entries); + + std::vector timeDiffSorted(fTimeDiff); + std::vector::iterator it; + std::sort(timeDiffSorted.begin(), timeDiffSorted.end()); + + Double_t minTime = timeDiffSorted.front(); + Double_t maxTime = timeDiffSorted.back(); + timePeriod = maxTime - minTime; + + TH1F* TimePerEvent = new TH1F("TimePerEvent", + "Runtime;Time [s];Events", + static_cast((timePeriod + 20) * 10), + static_cast(minTime - 10), + static_cast(maxTime + 10)); + + Int_t counter = 0; + std::vector::iterator lit; + Double_t timeOffset = fTime.front() + 1.; + for (lit = fResidentMemory.begin(); lit < fResidentMemory.end(); lit++) { + ResidentMemoryVsEvent->Fill(counter, *lit); + ResidentMemoryVsTime->Fill(fTime.at(counter) - timeOffset, *lit); + counter++; + } + histoList->AddLast(ResidentMemoryVsEvent); + histoList->AddLast(ResidentMemoryVsTime); + + counter = 0; + for (lit = fVirtualMemory.begin(); lit < fVirtualMemory.end(); lit++) { + VirtualMemoryVsEvent->Fill(counter, *lit); + VirtualMemoryVsTime->Fill(fTime.at(counter) - timeOffset, *lit); + counter++; + } + histoList->AddLast(VirtualMemoryVsEvent); + histoList->AddLast(VirtualMemoryVsTime); + + counter = 1; + for (it = fTimeDiff.begin(); it < fTimeDiff.end(); it++) { + TimePerEvent->Fill(*it); + EventtimeVsEvent->Fill(counter, *it); + counter++; + } + histoList->AddLast(TimePerEvent); + histoList->AddLast(EventtimeVsEvent); } void FairRunInfo::WriteHistosToFile(TList* histoList) { - // If the file size is larger then approx. 2GB then the histos - // can't be read any longer. Because of this problem the histos - // are written to a separate file instead - - TFile* oldfile = gFile; - - TString directory = gFile->GetName(); - LOG(debug) << "Name: " << gFile->GetName(); - Ssiz_t posLastSlash = directory.Last('/'); - directory.Remove(posLastSlash+1, directory.Length()-posLastSlash-1); - TString filename = ""; - if ( directory.EndsWith("/") ) { + // If the file size is larger then approx. 2GB then the histos + // can't be read any longer. Because of this problem the histos + // are written to a separate file instead + + TFile* oldfile = gFile; + + TString directory = gFile->GetName(); + LOG(debug) << "Name: " << gFile->GetName(); + Ssiz_t posLastSlash = directory.Last('/'); + directory.Remove(posLastSlash + 1, directory.Length() - posLastSlash - 1); + TString filename = ""; + if (directory.EndsWith("/")) { + filename += directory; + } + + directory = gFile->GetName(); + LOG(debug) << "Name: " << directory.Data(); + posLastSlash = directory.Last('/'); + directory.Remove(0, posLastSlash + 1); + directory.ReplaceAll(".root", ""); + LOG(debug) << "Name: " << directory.Data(); + + // Int_t pid = gSystem->GetPid(); + filename += "FairRunInfo_"; filename += directory; - } - - directory = gFile->GetName(); - LOG(debug) << "Name: " << directory.Data(); - posLastSlash = directory.Last('/'); - directory.Remove(0, posLastSlash+1); - directory.ReplaceAll(".root",""); - LOG(debug) << "Name: " << directory.Data(); - -// Int_t pid = gSystem->GetPid(); - filename += "FairRunInfo_"; - filename += directory; - filename += ".root"; - LOG(debug) << "Filename: " << filename.Data(); - - TFile* f1 = TFile::Open(filename, "recreate"); - f1->cd(); - - TIterator* listIter=histoList->MakeIterator(); - listIter->Reset(); - TObject* obj = nullptr; - while((obj=listIter->Next())) { - obj->Write(); - } - - delete listIter; - histoList->Delete(); - delete histoList; - - f1->Close(); - f1->Delete(); - gFile=oldfile; - + filename += ".root"; + LOG(debug) << "Filename: " << filename.Data(); + + TFile* f1 = TFile::Open(filename, "recreate"); + f1->cd(); + + TIterator* listIter = histoList->MakeIterator(); + listIter->Reset(); + TObject* obj = nullptr; + while ((obj = listIter->Next())) { + obj->Write(); + } + + delete listIter; + histoList->Delete(); + delete histoList; + + f1->Close(); + f1->Delete(); + gFile = oldfile; } -void FairRunInfo::Reset() -{ - GetInfo(); -} +void FairRunInfo::Reset() { GetInfo(); } diff --git a/base/event/FairRunInfo.h b/base/event/FairRunInfo.h index e07ae44d7d..aff9b7cfa2 100644 --- a/base/event/FairRunInfo.h +++ b/base/event/FairRunInfo.h @@ -1,20 +1,18 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRRUNINFO_H #define FAIRRUNINFO_H -#include // for TObject - -#include // for Double_t, Long_t, etc -#include // for CpuInfo_t, MemInfo_t, etc -#include // for TTimeStamp - -#include // for vector +#include // for Double_t, Long_t, etc +#include // for TObject +#include // for CpuInfo_t, MemInfo_t, etc +#include // for TTimeStamp +#include // for vector class TList; @@ -29,14 +27,14 @@ class FairRunInfo : public TObject void Reset(); private: - TTimeStamp fTimeStamp;//! - CpuInfo_t fCpuInfo;//! - MemInfo_t fMemInfo;//! - ProcInfo_t fProcInfo;//! - std::vector fTimeDiff;//! - std::vector fTime;//! - std::vector fResidentMemory;//! - std::vector fVirtualMemory;//! + TTimeStamp fTimeStamp; //! + CpuInfo_t fCpuInfo; //! + MemInfo_t fMemInfo; //! + ProcInfo_t fProcInfo; //! + std::vector fTimeDiff; //! + std::vector fTime; //! + std::vector fResidentMemory; //! + std::vector fVirtualMemory; //! void CalculateTimeDifference(); void PrintInfo(); @@ -47,7 +45,7 @@ class FairRunInfo : public TObject FairRunInfo(const FairRunInfo&); FairRunInfo& operator=(const FairRunInfo&); - ClassDef(FairRunInfo,2) + ClassDef(FairRunInfo, 2) }; #endif diff --git a/base/event/FairTimeStamp.cxx b/base/event/FairTimeStamp.cxx index 2bbdb3b492..784da78984 100644 --- a/base/event/FairTimeStamp.cxx +++ b/base/event/FairTimeStamp.cxx @@ -2,7 +2,7 @@ * 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, * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "FairTimeStamp.h" @@ -14,4 +14,4 @@ std::ostream& FairTimeStamp::PrintTimeInfo(std::ostream& out) const return out; } -ClassImp(FairTimeStamp) +ClassImp(FairTimeStamp); diff --git a/base/event/FairTimeStamp.h b/base/event/FairTimeStamp.h index 272d4bf4c3..257d5ce5ea 100644 --- a/base/event/FairTimeStamp.h +++ b/base/event/FairTimeStamp.h @@ -1,21 +1,24 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRTIMESTAMP_H #define FAIRTIMESTAMP_H -#include "FairMultiLinkedData_Interface.h" // for FairMultiLinkedData +#include "FairMultiLinkedData_Interface.h" // for FairMultiLinkedData -#include // for ostream -#include // for Double_t, etc +#include // for Double_t, etc +#include // for ostream +#include // for ostream, cout -#include // for ostream, cout - -namespace boost { namespace serialization { class access; } } +namespace boost { +namespace serialization { +class access; +} +} // namespace boost #include class TObject; @@ -38,39 +41,50 @@ class FairTimeStamp : public FairMultiLinkedData_Interface /** Destructor **/ virtual ~FairTimeStamp(){}; /** Accessors **/ - Double_t GetTimeStamp() const { return fTimeStamp; } - Double_t GetTimeStampError() const { return fTimeStampError; } + Double_t GetTimeStamp() const { return fTimeStamp; } + Double_t GetTimeStampError() const { return fTimeStampError; } /** Modifiers **/ void SetTimeStamp(Double_t t) { fTimeStamp = t; } - void SetTimeStampError(Double_t t) {fTimeStampError = t; } - virtual Int_t Compare(const TObject* obj) const { - if (this == obj) { return 0; } - FairTimeStamp* tsobj = static_cast(const_cast(obj)); - Double_t ts = tsobj->GetTimeStamp(); - Double_t tserror = tsobj->GetTimeStampError(); - if (fTimeStamp < ts) { return -1; } - else if (fTimeStamp == ts && fTimeStampError < tserror) { return -1; } - else if (fTimeStamp == ts && fTimeStampError == tserror) { return 0; } - else { return 1; } + void SetTimeStampError(Double_t t) { fTimeStampError = t; } + virtual Int_t Compare(const TObject* obj) const + { + if (this == obj) { + return 0; + } + FairTimeStamp* tsobj = static_cast(const_cast(obj)); + Double_t ts = tsobj->GetTimeStamp(); + Double_t tserror = tsobj->GetTimeStampError(); + if (fTimeStamp < ts) { + return -1; + } else if (fTimeStamp == ts && fTimeStampError < tserror) { + return -1; + } else if (fTimeStamp == ts && fTimeStampError == tserror) { + return 0; + } else { + return 1; + } } virtual std::ostream& PrintTimeInfo(std::ostream& out = std::cout) const; - virtual Bool_t IsSortable() const { return kTRUE;}; + virtual Bool_t IsSortable() const { return kTRUE; }; - virtual bool equal(FairTimeStamp* data) { - return (fTimeStamp == data->GetTimeStamp() && fTimeStampError == data->GetTimeStampError()); + virtual bool equal(FairTimeStamp* data) + { + return (fTimeStamp == data->GetTimeStamp() && fTimeStampError == data->GetTimeStampError()); } - friend std::ostream& operator<< (std::ostream& out, const FairTimeStamp& link) { - link.PrintTimeInfo(out); - return out; + friend std::ostream& operator<<(std::ostream& out, const FairTimeStamp& link) + { + link.PrintTimeInfo(out); + return out; } - virtual bool operator< (const FairTimeStamp* rValue) const { - if (GetTimeStamp() < rValue->GetTimeStamp()) - return true; - else - return false; + virtual bool operator<(const FairTimeStamp* rValue) const + { + if (GetTimeStamp() < rValue->GetTimeStamp()) + return true; + else + return false; } template @@ -84,33 +98,30 @@ class FairTimeStamp : public FairMultiLinkedData_Interface protected: friend class boost::serialization::access; - Double_t fTimeStamp; /** Time of digit or Hit [ns] */ - Double_t fTimeStampError; /** Error on time stamp */ + Double_t fTimeStamp; /** Time of digit or Hit [ns] */ + Double_t fTimeStampError; /** Error on time stamp */ - ClassDef(FairTimeStamp,4); + ClassDef(FairTimeStamp, 4); }; // ----- Default constructor ------------------------------------------- inline FairTimeStamp::FairTimeStamp() - : FairMultiLinkedData_Interface(), - fTimeStamp(-1), - fTimeStampError(-1) -{ -} + : FairMultiLinkedData_Interface() + , fTimeStamp(-1) + , fTimeStampError(-1) +{} // ----- Standard constructor ------------------------------------------ inline FairTimeStamp::FairTimeStamp(Double_t time) - : FairMultiLinkedData_Interface(), - fTimeStamp(time), - fTimeStampError(-1) -{ -} + : FairMultiLinkedData_Interface() + , fTimeStamp(time) + , fTimeStampError(-1) +{} inline FairTimeStamp::FairTimeStamp(Double_t time, Double_t timeerror) - : FairMultiLinkedData_Interface(), - fTimeStamp(time), - fTimeStampError(timeerror) -{ -} + : FairMultiLinkedData_Interface() + , fTimeStamp(time) + , fTimeStampError(timeerror) +{} #endif diff --git a/base/event/FairTrackParam.cxx b/base/event/FairTrackParam.cxx index 3a584dc5ef..6e43e96d71 100644 --- a/base/event/FairTrackParam.cxx +++ b/base/event/FairTrackParam.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -14,168 +14,194 @@ #include "FairLogger.h" -#include // for Sqrt -#include // for Abs -#include // for TMatrixTSym -#include // for TMatrixTRow, etc - +#include // for Sqrt +#include // for Abs +#include // for TMatrixTSym +#include // for TMatrixTRow, etc #include FairTrackParam::FairTrackParam() - : TObject(), - fX(0), - fY(0), - fZ(0), - fTx(0), - fTy(0), - fQp(0) + : TObject() + , fX(0) + , fY(0) + , fZ(0) + , fTx(0) + , fTy(0) + , fQp(0) { - // fX = fY = fZ = fTx = fTy = fQp = 0.; - for (int i=0; i<15; i++) { fCovMatrix[i] = 0; } + // fX = fY = fZ = fTx = fTy = fQp = 0.; + for (int i = 0; i < 15; i++) { + fCovMatrix[i] = 0; + } } -FairTrackParam::FairTrackParam(Double_t x, Double_t y, Double_t z, - Double_t tx, Double_t ty, Double_t qp, +FairTrackParam::FairTrackParam(Double_t x, + Double_t y, + Double_t z, + Double_t tx, + Double_t ty, + Double_t qp, const TMatrixFSym& covMat) - : TObject(), - fX(x), - fY(y), - fZ(z), - fTx(tx), - fTy(ty), - fQp(qp) + : TObject() + , fX(x) + , fY(y) + , fZ(z) + , fTx(tx) + , fTy(ty) + , fQp(qp) { - int index = 0; - for (int i=0; i<5; i++) { - for (int j=i; j<5; j++) { fCovMatrix[index++] = covMat[i][j]; } - } + int index = 0; + for (int i = 0; i < 5; i++) { + for (int j = i; j < 5; j++) { + fCovMatrix[index++] = covMat[i][j]; + } + } } FairTrackParam::FairTrackParam(const FairTrackParam& param) - : TObject(param), - fX(param.GetX()), - fY(param.GetY()), - fZ(param.GetZ()), - fTx(param.GetTx()), - fTy(param.GetTy()), - fQp(param.GetQp()) + : TObject(param) + , fX(param.GetX()) + , fY(param.GetY()) + , fZ(param.GetZ()) + , fTx(param.GetTx()) + , fTy(param.GetTy()) + , fQp(param.GetQp()) { - *this = param; + *this = param; } FairTrackParam::~FairTrackParam() {} void FairTrackParam::Print(Option_t*) const { - LOG(info) << "Position : (" << std::setprecision(2) << fX << ", " << fY << ", " << fZ << ")"; - LOG(info) << "Slopes : dx/dz = " << fTx << ", dy/dz = " << fTy; - LOG(info) << "q/p = " << fQp; + LOG(info) << "Position : (" << std::setprecision(2) << fX << ", " << fY << ", " << fZ << ")"; + LOG(info) << "Slopes : dx/dz = " << fTx << ", dy/dz = " << fTy; + LOG(info) << "q/p = " << fQp; } void FairTrackParam::Momentum(TVector3& mom) const { - Double_t p = ( TMath::Abs(fQp)>1.e-4 ) ?1./TMath::Abs(fQp) :1.e4; - Double_t pz = TMath::Sqrt( p*p / ( fTx*fTx + fTy*fTy + 1 ) ); - Double_t px = fTx * pz; - Double_t py = fTy * pz; - mom.SetXYZ(px, py, pz); - + Double_t p = (TMath::Abs(fQp) > 1.e-4) ? 1. / TMath::Abs(fQp) : 1.e4; + Double_t pz = TMath::Sqrt(p * p / (fTx * fTx + fTy * fTy + 1)); + Double_t px = fTx * pz; + Double_t py = fTy * pz; + mom.SetXYZ(px, py, pz); } void FairTrackParam::CovMatrix(Double_t cov[]) const { - for (Int_t i=0; i<15; i++) { cov[i] = fCovMatrix[i]; } + for (Int_t i = 0; i < 15; i++) { + cov[i] = fCovMatrix[i]; + } } void FairTrackParam::CovMatrix(TMatrixFSym& covMat) const { - Int_t index = 0; - for (int i=0; i<5; i++) { - for (int j=i; j<5; j++) { - covMat[i][j] = fCovMatrix[index]; - covMat[j][i] = fCovMatrix[index]; - index++; + Int_t index = 0; + for (int i = 0; i < 5; i++) { + for (int j = i; j < 5; j++) { + covMat[i][j] = fCovMatrix[index]; + covMat[j][i] = fCovMatrix[index]; + index++; + } } - } } Double_t FairTrackParam::GetCovariance(Int_t i, Int_t j) const { - if ( i<0 || j<0 || i>4 || j>4 ) { - LOG(error) << "FairTrackParam::GetCovariance: Invalid index pair (" << i << "," << j << ") !"; - return 0; - } - if (i>j) { - Int_t k = i; - i = j; - j = k; - } - Int_t index = 0; - if (i==0) { index = j; } - else if (i==1) { index = 4 + j; } - else if (i==2) { index = 7 + j; } - else if (i==3) { index = 9 + j; } - else if (i==4) { index = 10 + j; } - return fCovMatrix[index]; + if (i < 0 || j < 0 || i > 4 || j > 4) { + LOG(error) << "FairTrackParam::GetCovariance: Invalid index pair (" << i << "," << j << ") !"; + return 0; + } + if (i > j) { + Int_t k = i; + i = j; + j = k; + } + Int_t index = 0; + if (i == 0) { + index = j; + } else if (i == 1) { + index = 4 + j; + } else if (i == 2) { + index = 7 + j; + } else if (i == 3) { + index = 9 + j; + } else if (i == 4) { + index = 10 + j; + } + return fCovMatrix[index]; } void FairTrackParam::SetPosition(const TVector3& pos) { - fX = pos.X(); - fY = pos.Y(); - fZ = pos.Z(); + fX = pos.X(); + fY = pos.Y(); + fZ = pos.Z(); } void FairTrackParam::SetCovMatrix(Double_t cov[]) { - for (Int_t i=0; i<15; i++) { fCovMatrix[i] = cov[i]; } + for (Int_t i = 0; i < 15; i++) { + fCovMatrix[i] = cov[i]; + } } void FairTrackParam::SetCovMatrix(const TMatrixFSym& covMat) { - Int_t index = 0; - for (int i=0; i<5; i++) { - for (int j=i; j<5; j++) { fCovMatrix[index++] = covMat[i][j]; } - } + Int_t index = 0; + for (int i = 0; i < 5; i++) { + for (int j = i; j < 5; j++) { + fCovMatrix[index++] = covMat[i][j]; + } + } } void FairTrackParam::SetCovariance(Int_t i, Int_t j, Double_t val) { - if (i < 0 || i > 4) { - LOG(warn) << "FairTrackParam::SetCovariance: " << "First index out of range! " << i; - return; - } - if (j < 0 || j > 4) { - LOG(warn) << "FairTrackParam::SetCovariance: " << "Second index out of range! " << j; + if (i < 0 || i > 4) { + LOG(warn) << "FairTrackParam::SetCovariance: " + << "First index out of range! " << i; + return; + } + if (j < 0 || j > 4) { + LOG(warn) << "FairTrackParam::SetCovariance: " + << "Second index out of range! " << j; + return; + } + if (i > j) { + Int_t k = i; + i = j; + j = k; + } + Int_t index = 0; + if (i == 0) { + index = j; + } else if (i == 1) { + index = 4 + j; + } else if (i == 2) { + index = 7 + j; + } else if (i == 3) { + index = 9 + j; + } else if (i == 4) { + index = 10 + j; + } + fCovMatrix[index] = val; return; - } - if (i>j) { - Int_t k = i; - i = j; - j = k; - } - Int_t index = 0; - if (i==0) { index = j; } - else if (i==1) { index = 4 + j; } - else if (i==2) { index = 7 + j; } - else if (i==3) { index = 9 + j; } - else if (i==4) { index = 10 + j; } - fCovMatrix[index] = val; - return; } FairTrackParam& FairTrackParam::operator=(const FairTrackParam& par) { - fX = par.GetX(); - fY = par.GetY(); - fZ = par.GetZ(); - fTx = par.GetTx(); - fTy = par.GetTy(); - fQp = par.GetQp(); - Double_t cov[15]; - par.CovMatrix(cov); - SetCovMatrix(cov); - return *this; + fX = par.GetX(); + fY = par.GetY(); + fZ = par.GetZ(); + fTx = par.GetTx(); + fTy = par.GetTy(); + fQp = par.GetQp(); + Double_t cov[15]; + par.CovMatrix(cov); + SetCovMatrix(cov); + return *this; } -ClassImp(FairTrackParam) +ClassImp(FairTrackParam); diff --git a/base/event/FairTrackParam.h b/base/event/FairTrackParam.h index 1193c65a07..d6fafd4a95 100644 --- a/base/event/FairTrackParam.h +++ b/base/event/FairTrackParam.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -10,7 +10,6 @@ // ----- Created 27/01/05 by V. Friese ----- // ------------------------------------------------------------------------- - /** FairTrackParam.h *@author V.Friese ** @@ -23,14 +22,13 @@ ** an array of double. **/ - #ifndef FAIRSTSTRACKPARAM #define FAIRSTSTRACKPARAM 1 -#include // for TObject -#include // for Double_t, Double32_t, Int_t, etc -#include // for TMatrixFSym -#include // for TVector3 +#include // for Double_t, Double32_t, Int_t, etc +#include // for TMatrixFSym +#include // for TObject +#include // for TVector3 class FairTrackParam : public TObject { @@ -39,8 +37,12 @@ class FairTrackParam : public TObject FairTrackParam(); /** Constructor with all variables **/ - FairTrackParam(Double_t x, Double_t y, Double_t z, - Double_t tx, Double_t ty, Double_t qp, + FairTrackParam(Double_t x, + Double_t y, + Double_t z, + Double_t tx, + Double_t ty, + Double_t qp, const TMatrixFSym& covMat); /** Copy constructor **/ @@ -50,12 +52,12 @@ class FairTrackParam : public TObject virtual ~FairTrackParam(); /** Output to screen **/ - void Print(Option_t* option = "") const; + void Print(Option_t* option = "") const; /** Accessors **/ - Double_t GetX() const { return fX; }; - Double_t GetY() const { return fY; }; - Double_t GetZ() const { return fZ; }; + Double_t GetX() const { return fX; }; + Double_t GetY() const { return fY; }; + Double_t GetZ() const { return fZ; }; Double_t GetTx() const { return fTx; }; Double_t GetTy() const { return fTy; }; Double_t GetQp() const { return fQp; }; @@ -66,9 +68,9 @@ class FairTrackParam : public TObject Double_t GetCovariance(Int_t i, Int_t j) const; /** Modifiers **/ - void SetX(Double_t x) { fX = x; }; - void SetY(Double_t y) { fY = y; }; - void SetZ(Double_t z) { fZ = z; }; + void SetX(Double_t x) { fX = x; }; + void SetY(Double_t y) { fY = y; }; + void SetZ(Double_t z) { fZ = z; }; void SetTx(Double_t tx) { fTx = tx; }; void SetTy(Double_t ty) { fTy = ty; }; void SetQp(Double_t qp) { fQp = qp; }; @@ -78,7 +80,7 @@ class FairTrackParam : public TObject void SetCovariance(Int_t i, Int_t j, Double_t val); /** Assignment operator **/ - FairTrackParam& operator=(const FairTrackParam& par ); + FairTrackParam& operator=(const FairTrackParam& par); private: /** Position of track at given z [cm] **/ @@ -98,7 +100,7 @@ class FairTrackParam : public TObject Double32_t fCovMatrix[15]; - ClassDef(FairTrackParam,1); + ClassDef(FairTrackParam, 1); }; #endif diff --git a/base/field/FairField.cxx b/base/field/FairField.cxx index 3f577e160e..97a05250f5 100644 --- a/base/field/FairField.cxx +++ b/base/field/FairField.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -14,36 +14,38 @@ #include "FairField.h" FairField::FairField() - : TVirtualMagField("FAIR Magnetic Field"), - fType(0) -{ -} + : TVirtualMagField("FAIR Magnetic Field") + , fType(0) +{} FairField::FairField(const char* name, const char*) - : TVirtualMagField(name), - fType(0) -{ -} + : TVirtualMagField(name) + , fType(0) +{} -FairField::~FairField() { } +FairField::~FairField() {} Bool_t FairField::IsConst() { - if ( fType == 1 ) { return kTRUE; } - return kFALSE; + if (fType == 1) { + return kTRUE; + } + return kFALSE; } Bool_t FairField::IsMap() { - if ( fType == 2 ) { return kTRUE; } - return kFALSE; + if (fType == 2) { + return kTRUE; + } + return kFALSE; } void FairField::GetFieldValue(const Double_t point[3], Double_t* bField) { - bField[0] = GetBx(point[0], point[1], point[2]); - bField[1] = GetBy(point[0], point[1], point[2]); - bField[2] = GetBz(point[0], point[1], point[2]); + bField[0] = GetBx(point[0], point[1], point[2]); + bField[1] = GetBy(point[0], point[1], point[2]); + bField[2] = GetBz(point[0], point[1], point[2]); } -ClassImp(FairField) +ClassImp(FairField); diff --git a/base/field/FairField.h b/base/field/FairField.h index 2aed3d0e33..40d2398074 100644 --- a/base/field/FairField.h +++ b/base/field/FairField.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -28,11 +28,11 @@ #ifndef FAIRFIELD_H #define FAIRFIELD_H 1 -#include // for Double_t, Bool_t, etc -#include - #include "FairLogger.h" +#include // for Double_t, Bool_t, etc +#include + class FairField : public TVirtualMagField { public: @@ -42,7 +42,7 @@ class FairField : public TVirtualMagField /** Constructor with name and title **/ FairField(const char* name, const char* title = "FAIR Magnetic Field"); - FairField& operator=(const FairField&) {return *this;} + FairField& operator=(const FairField&) { return *this; } /** Destructor **/ virtual ~FairField(); @@ -50,7 +50,7 @@ class FairField : public TVirtualMagField /** Intialisation. E.g. read in the field map. If needed, to be ** implemented in the concrete class. **/ - virtual void Init() { }; + virtual void Init(){}; /** Test whether field type is Constant **/ Bool_t IsConst(); @@ -64,17 +64,29 @@ class FairField : public TVirtualMagField /** Get x component of magnetic field [kG] ** @param x,y,z Position [cm] **/ - virtual Double_t GetBx(Double_t, Double_t, Double_t) { LOG(warn) << "FairField::GetBx Should be implemented in User class"; return 0; } + virtual Double_t GetBx(Double_t, Double_t, Double_t) + { + LOG(warn) << "FairField::GetBx Should be implemented in User class"; + return 0; + } /** Get y component of magnetic field [kG] ** @param x,y,z Position [cm] **/ - virtual Double_t GetBy(Double_t, Double_t, Double_t) { LOG(warn) << "FairField::GetBy Should be implemented in User class"; return 0; } + virtual Double_t GetBy(Double_t, Double_t, Double_t) + { + LOG(warn) << "FairField::GetBy Should be implemented in User class"; + return 0; + } /** Get z component of magnetic field [kG] ** @param x,y,z Position [cm] **/ - virtual Double_t GetBz(Double_t, Double_t, Double_t) { LOG(warn) << "FairField::GetBz Should be implemented in User class"; return 0; } + virtual Double_t GetBz(Double_t, Double_t, Double_t) + { + LOG(warn) << "FairField::GetBz Should be implemented in User class"; + return 0; + } /** Get magnetic field. For use of Geant3 ** @param point Coordinates [cm] @@ -82,11 +94,14 @@ class FairField : public TVirtualMagField **/ virtual void GetFieldValue(const Double_t point[3], Double_t* bField); - void Field(const Double_t point[3], Double_t* B) {GetFieldValue(point,B);} + void Field(const Double_t point[3], Double_t* B) { GetFieldValue(point, B); } /** Screen output. To be implemented in the concrete class. **/ - virtual void Print(Option_t*) const {;} - virtual void GetBxyz(const Double_t[3], Double_t*) { LOG(warn) << "FairField::GetBxyz Should be implemented in User class"; } + virtual void Print(Option_t*) const { ; } + virtual void GetBxyz(const Double_t[3], Double_t*) + { + LOG(warn) << "FairField::GetBxyz Should be implemented in User class"; + } /**Fill Paramater*/ virtual void FillParContainer() { LOG(warn) << "FairField::FillParContainer Should be implemented in User class"; } @@ -98,9 +113,9 @@ class FairField : public TVirtualMagField private: FairField(const FairField&); // FairField& operator=(const FairField&); - //TODO: Check why the htrack needs this + // TODO: Check why the htrack needs this - ClassDef(FairField,4); + ClassDef(FairField, 4); }; #endif diff --git a/base/field/FairFieldFactory.cxx b/base/field/FairFieldFactory.cxx index 857a192349..b9f5b38530 100644 --- a/base/field/FairFieldFactory.cxx +++ b/base/field/FairFieldFactory.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -15,18 +15,13 @@ FairFieldFactory* FairFieldFactory::fgRinstance = 0; FairFieldFactory::FairFieldFactory() - :fCreator(0) + : fCreator(0) { - fgRinstance = this; + fgRinstance = this; } -FairFieldFactory::~FairFieldFactory() -{ -} +FairFieldFactory::~FairFieldFactory() {} -FairFieldFactory* FairFieldFactory::Instance() -{ - return fgRinstance; -} +FairFieldFactory* FairFieldFactory::Instance() { return fgRinstance; } -ClassImp(FairFieldFactory) +ClassImp(FairFieldFactory); diff --git a/base/field/FairFieldFactory.h b/base/field/FairFieldFactory.h index ad2801006f..3ae5d76281 100644 --- a/base/field/FairFieldFactory.h +++ b/base/field/FairFieldFactory.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -13,7 +13,7 @@ #ifndef FAIRFIELDFACTORY_H #define FAIRFIELDFACTORY_H -#include // for FairFieldFactory::Class, etc +#include // for FairFieldFactory::Class, etc class FairField; @@ -23,24 +23,29 @@ class FairFieldFactory static FairFieldFactory* Instance(); FairFieldFactory(); virtual ~FairFieldFactory(); - virtual FairField* createFairField() { - FairField* field=0; - if(fCreator) { field= fCreator->createFairField(); } - return field; + virtual FairField* createFairField() + { + FairField* field = 0; + if (fCreator) { + field = fCreator->createFairField(); + } + return field; }; - virtual void SetParm() { - if(fCreator) { fCreator->SetParm(); } + virtual void SetParm() + { + if (fCreator) { + fCreator->SetParm(); + } } protected: FairFieldFactory* fCreator; - static FairFieldFactory* fgRinstance; + static FairFieldFactory* fgRinstance; - ClassDef(FairFieldFactory,1) + ClassDef(FairFieldFactory, 1) - private: - FairFieldFactory(const FairFieldFactory& M); - FairFieldFactory& operator= (const FairFieldFactory&) {return *this;} + private : FairFieldFactory(const FairFieldFactory& M); + FairFieldFactory& operator=(const FairFieldFactory&) { return *this; } }; -#endif //FAIRFIELDFACTORY_H +#endif // FAIRFIELDFACTORY_H diff --git a/base/sim/FairBaseContFact.cxx b/base/sim/FairBaseContFact.cxx index 1486826e09..9b25eee58f 100644 --- a/base/sim/FairBaseContFact.cxx +++ b/base/sim/FairBaseContFact.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -10,64 +10,59 @@ // ----- Created 25/10/04 by Ilse Koenig ----- // ------------------------------------------------------------------------- - // Factory for the parameter containers in Base -#include - #include "FairBaseContFact.h" + #include "FairBaseParSet.h" #include "FairGeoParSet.h" #include "FairRuntimeDb.h" + #include #include +#include class FairParSet; -ClassImp(FairBaseContFact) +ClassImp(FairBaseContFact); static FairBaseContFact gFairBaseContFact; FairBaseContFact::FairBaseContFact() - :FairContFact() + : FairContFact() { - // Constructor (called when the library is loaded) - fName="FairBaseContFact"; - fTitle="Factory for parameter containers in libSts"; - setAllContainers(); - FairRuntimeDb::instance()->addContFactory(this); + // Constructor (called when the library is loaded) + fName = "FairBaseContFact"; + fTitle = "Factory for parameter containers in libSts"; + setAllContainers(); + FairRuntimeDb::instance()->addContFactory(this); } void FairBaseContFact::setAllContainers() { - /** Creates the Container objects with all accepted contexts and adds them to - * the list of containers for the base library.*/ - FairContainer* pTest= new FairContainer("FairBaseParSet", - "class for parameter io", - "DefaultContext"); - pTest->addContext("TestNonDefaultContext"); - containers->Add(pTest); + /** Creates the Container objects with all accepted contexts and adds them to + * the list of containers for the base library.*/ + FairContainer* pTest = new FairContainer("FairBaseParSet", "class for parameter io", "DefaultContext"); + pTest->addContext("TestNonDefaultContext"); + containers->Add(pTest); - FairContainer* pGeo= new FairContainer("FairGeoParSet", - "class for Geo parameter", - "DefaultContext"); - pTest->addContext("TestNonDefaultContext"); - containers->Add(pGeo); + FairContainer* pGeo = new FairContainer("FairGeoParSet", "class for Geo parameter", "DefaultContext"); + pTest->addContext("TestNonDefaultContext"); + containers->Add(pGeo); } FairParSet* FairBaseContFact::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=0; - if (strcmp(name,"FairBaseParSet")==0) { - p=new FairBaseParSet(c->getConcatName().Data(),c->GetTitle(),c->getContext()); - } else if (strcmp(name,"FairGeoParSet")==0) { - p=new FairGeoParSet(c->getConcatName().Data(),c->GetTitle(),c->getContext()); - } + /** 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 = 0; + if (strcmp(name, "FairBaseParSet") == 0) { + p = new FairBaseParSet(c->getConcatName().Data(), c->GetTitle(), c->getContext()); + } else if (strcmp(name, "FairGeoParSet") == 0) { + p = new FairGeoParSet(c->getConcatName().Data(), c->GetTitle(), c->getContext()); + } - return p; + return p; } - diff --git a/base/sim/FairBaseContFact.h b/base/sim/FairBaseContFact.h index 2e5d5679eb..c2d20b469d 100644 --- a/base/sim/FairBaseContFact.h +++ b/base/sim/FairBaseContFact.h @@ -1,16 +1,16 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRBASECONTFACT_H #define FAIRBASECONTFACT_H -#include "FairContFact.h" // for FairContFact, etc +#include "FairContFact.h" // for FairContFact, etc -#include // for FairBaseContFact::Class, etc +#include // for FairBaseContFact::Class, etc class FairParSet; @@ -19,6 +19,7 @@ class FairBaseContFact : public FairContFact /** Factory for all Base parameter containers */ private: void setAllContainers(); + public: /**default ctor*/ FairBaseContFact(); @@ -28,7 +29,7 @@ class FairBaseContFact : public FairContFact * 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. */ FairParSet* createContainer(FairContainer*); - ClassDef( FairBaseContFact,0) + ClassDef(FairBaseContFact, 0) }; -#endif /* !FAIRBASECONTFACT_H */ +#endif /* !FAIRBASECONTFACT_H */ diff --git a/base/sim/FairBaseParSet.cxx b/base/sim/FairBaseParSet.cxx index 2e647d9e64..20a8e29f97 100644 --- a/base/sim/FairBaseParSet.cxx +++ b/base/sim/FairBaseParSet.cxx @@ -12,53 +12,63 @@ #include "FairBaseParSet.h" -#include "FairParamList.h" // for FairParamList -#include "FairPrimaryGenerator.h" // for FairPrimaryGenerator +#include "FairParamList.h" // for FairParamList +#include "FairPrimaryGenerator.h" // for FairPrimaryGenerator #include -ClassImp(FairBaseParSet) +ClassImp(FairBaseParSet); -FairBaseParSet::FairBaseParSet(const char* name,const char* title,const char* context) - : FairParGenericSet(name,title,context), - fDetList(0), - fPriGen(0), - fBeamMom(15), - fContNameList(new TObjArray()), - fRandomSeed(99999999) -{ -} +FairBaseParSet::FairBaseParSet(const char* name, const char* title, const char* context) + : FairParGenericSet(name, title, context) + , fDetList(0) + , fPriGen(0) + , fBeamMom(15) + , fContNameList(new TObjArray()) + , fRandomSeed(99999999) +{} FairBaseParSet::~FairBaseParSet(void) { - if(fContNameList) { - fContNameList->Delete(); - delete fContNameList; - } + if (fContNameList) { + fContNameList->Delete(); + delete fContNameList; + } } -void FairBaseParSet::clear(void) -{ - fContNameList->Delete(); -} +void FairBaseParSet::clear(void) { fContNameList->Delete(); } void FairBaseParSet::putParams(FairParamList* l) { - if (!l) { return; } - l->addObject("Detector List", fDetList); - l->addObject("Event Generator", fPriGen); - l->add("Beam Momentum Gev/c", fBeamMom); - l->addObject("Parameter containers list", fContNameList); - l->add("Random Seed", fRandomSeed); + if (!l) { + return; + } + l->addObject("Detector List", fDetList); + l->addObject("Event Generator", fPriGen); + l->add("Beam Momentum Gev/c", fBeamMom); + l->addObject("Parameter containers list", fContNameList); + l->add("Random Seed", fRandomSeed); } Bool_t FairBaseParSet::getParams(FairParamList* l) { - if (!l) { return kFALSE; } - if (!l->fillObject("Detector List", fDetList)) { return kFALSE; } - if (!l->fillObject("Event Generator", fPriGen)) { return kFALSE; } - if (!l->fill("Beam Momentum Gev/c", &fBeamMom)) { return kFALSE; } - if (!l->fillObject("Parameter containers list", fContNameList)) { return kFALSE; } - if (!l->fill("Random Seed", &fRandomSeed)) { return kFALSE; } - return kTRUE; + if (!l) { + return kFALSE; + } + if (!l->fillObject("Detector List", fDetList)) { + return kFALSE; + } + if (!l->fillObject("Event Generator", fPriGen)) { + return kFALSE; + } + if (!l->fill("Beam Momentum Gev/c", &fBeamMom)) { + return kFALSE; + } + if (!l->fillObject("Parameter containers list", fContNameList)) { + return kFALSE; + } + if (!l->fill("Random Seed", &fRandomSeed)) { + return kFALSE; + } + return kTRUE; } diff --git a/base/sim/FairBaseParSet.h b/base/sim/FairBaseParSet.h index e45cf8be01..d734e0e1f6 100644 --- a/base/sim/FairBaseParSet.h +++ b/base/sim/FairBaseParSet.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRBASEPARSET_H @@ -14,10 +14,10 @@ * @version 1 * @since 12.10.04 */ -#include "FairParGenericSet.h" // for FairParGenericSet +#include "FairParGenericSet.h" // for FairParGenericSet -#include // for Double_t, etc -#include // IWYU pragma: keep needed by cint +#include // for Double_t, etc +#include // IWYU pragma: keep needed by cint class FairParamList; class FairPrimaryGenerator; @@ -29,14 +29,13 @@ class FairBaseParSet : public FairParGenericSet /** * constructor * @param name : Parameter set name - * @param title: Parameter set title - * @param context: Parameter set context - */ - + * @param title: Parameter set title + * @param context: Parameter set context + */ - FairBaseParSet(const char* name="FairBaseParSet", - const char* title="Class for base parameter io", - const char* context="BaseDefaultContext"); + FairBaseParSet(const char* name = "FairBaseParSet", + const char* title = "Class for base parameter io", + const char* context = "BaseDefaultContext"); /** dtor*/ ~FairBaseParSet(void); /** clear*/ @@ -44,7 +43,7 @@ class FairBaseParSet : public FairParGenericSet /** * Fills all persistent data members into the list for write. * @param FairParamList : Parameter list to be filled - */ + */ void putParams(FairParamList*); /** * Fills all persistent data members from the list after reading. The function @@ -57,65 +56,64 @@ class FairBaseParSet : public FairParGenericSet * Set the detector list used in the simulation * @param array: TObjArray of detector */ - void SetDetList(TObjArray* array) {fDetList=array;} + void SetDetList(TObjArray* array) { fDetList = array; } /** * Set the Generator used in the simulation * @param gen: Primary generator used in simulation */ - void SetGen(FairPrimaryGenerator* gen) {fPriGen=gen;} + void SetGen(FairPrimaryGenerator* gen) { fPriGen = gen; } /** * Set the beam momentum (if any) used in the simulation * @param BMom: Beam Momentum in GeV/c */ - void SetBeamMom(Double_t BMom) {fBeamMom = BMom;} + void SetBeamMom(Double_t BMom) { fBeamMom = BMom; } /** * Set the list of parameter containers used in a run * @param array: TObjArray of containers */ - void SetContListStr(TObjArray* list) {fContNameList= list;} - /** - * Set the random seed used in a run - * @param RndSeed: Random Seed - */ - void SetRndSeed(UInt_t RndSeed) {fRandomSeed= RndSeed;} + void SetContListStr(TObjArray* list) { fContNameList = list; } + /** + * Set the random seed used in a run + * @param RndSeed: Random Seed + */ + void SetRndSeed(UInt_t RndSeed) { fRandomSeed = RndSeed; } /** * Get the detector list used in the simulation */ - TObjArray* GetDetList() {return fDetList;} + TObjArray* GetDetList() { return fDetList; } /** * Get the Primery generator used in the simulation */ - FairPrimaryGenerator* GetPriGen() {return fPriGen; } + FairPrimaryGenerator* GetPriGen() { return fPriGen; } /** * Get the Beam Momentum used in the simulation (GeV/c) */ - Double_t GetBeamMom() {return fBeamMom; } + Double_t GetBeamMom() { return fBeamMom; } /** * Get the parameter container list used in this run */ - TObjArray* GetContList() {return fContNameList;} - /** - * Get the Random Seed used in this run - */ - UInt_t GetRndSeed() {return fRandomSeed;} + TObjArray* GetContList() { return fContNameList; } + /** + * Get the Random Seed used in this run + */ + UInt_t GetRndSeed() { return fRandomSeed; } protected: /// Detectors used in the simulation - TObjArray* fDetList; - ///Generator used for simulation - FairPrimaryGenerator* fPriGen; - ///Beam momentum (GeV/c) - Double_t fBeamMom; + TObjArray* fDetList; + /// Generator used for simulation + FairPrimaryGenerator* fPriGen; + /// Beam momentum (GeV/c) + Double_t fBeamMom; /// List of parameter container names in the RUN - TObjArray* fContNameList; + TObjArray* fContNameList; /// Random Seed from gRandom - UInt_t fRandomSeed; + UInt_t fRandomSeed; - ClassDef(FairBaseParSet,6) + ClassDef(FairBaseParSet, 6) - private: - FairBaseParSet(const FairBaseParSet& L); - FairBaseParSet& operator= (const FairBaseParSet&) {return *this;} + private : FairBaseParSet(const FairBaseParSet& L); + FairBaseParSet& operator=(const FairBaseParSet&) { return *this; } }; #endif /* !FAIRBASEPARSET_H */ diff --git a/base/sim/FairDetector.cxx b/base/sim/FairDetector.cxx index ae5185ccc8..71542f29ac 100644 --- a/base/sim/FairDetector.cxx +++ b/base/sim/FairDetector.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -12,131 +12,133 @@ #include "FairDetector.h" -#include "FairGeoNode.h" // for FairGeoNode -#include "FairLogger.h" // for FairLogger, MESSAGE_ORIGIN -#include "FairModule.h" // for FairModule::svList, etc -#include "FairVolume.h" // for FairVolume +#include "FairGeoNode.h" // for FairGeoNode +#include "FairLogger.h" // for FairLogger, MESSAGE_ORIGIN +#include "FairModule.h" // for FairModule::svList, etc #include "FairRootManager.h" - -#include // for TFolder -#include // for TList -#include // for TObject -#include // for TROOT, gROOT -#include // for TRefArray -#include // for TString -#include // for gGeoManager -#include // for TVirtualMC - -FairDetector::FairDetector(const char* Name, Bool_t Active, Int_t DetId ) - :FairModule(Name, "FAIR Detector", Active), - fDetId(DetId), - fLogger(FairLogger::GetLogger()) +#include "FairVolume.h" // for FairVolume + +#include // for TFolder +#include // for gGeoManager +#include // for TList +#include // for TObject +#include // for TROOT, gROOT +#include // for TRefArray +#include // for TString +#include // for TVirtualMC + +FairDetector::FairDetector(const char* Name, Bool_t Active, Int_t DetId) + : FairModule(Name, "FAIR Detector", Active) + , fDetId(DetId) + , fLogger(FairLogger::GetLogger()) { - flGeoPar = new TList(); - TString lname( GetName()); - lname += "GeoPar"; - flGeoPar->SetName(lname.Data()); - fGeoSaved = kFALSE; + flGeoPar = new TList(); + TString lname(GetName()); + lname += "GeoPar"; + flGeoPar->SetName(lname.Data()); + fGeoSaved = kFALSE; } FairDetector::FairDetector(const FairDetector& rhs) - :FairModule(rhs), - fDetId(rhs.fDetId), - fLogger(rhs.fLogger) -{ -} + : FairModule(rhs) + , fDetId(rhs.fDetId) + , fLogger(rhs.fLogger) +{} -FairDetector::~FairDetector() -{ - delete flGeoPar; -} +FairDetector::~FairDetector() { delete flGeoPar; } -FairDetector& FairDetector::operator= (const FairDetector& rhs) +FairDetector& FairDetector::operator=(const FairDetector& rhs) { - // check assignment to self - if (this == &rhs) return *this; + // check assignment to self + if (this == &rhs) + return *this; - // base class assignment - FairModule::operator=(rhs); + // base class assignment + FairModule::operator=(rhs); - // assignment operator - fDetId = rhs.fDetId; - fLogger = rhs.fLogger; + // assignment operator + fDetId = rhs.fDetId; + fLogger = rhs.fLogger; - return *this; + return *this; } FairDetector::FairDetector() - :fDetId(0), - fLogger(FairLogger::GetLogger()) -{ -} + : fDetId(0) + , fLogger(FairLogger::GetLogger()) +{} // ------------------------------------------------------------------------- void FairDetector::DefineSensitiveVolumes() { - LOG(info) << "FairDetector::DefineSensitiveVolumes"; - TObjArray* volumes = gGeoManager->GetListOfVolumes(); - TIter next(volumes); - TGeoVolume* volume; - while ( ( volume = static_cast(next()) ) ) { - if ( IsSensitive(volume->GetName()) ) { - LOG(debug)<<"Sensitive Volume "<< volume->GetName(); - AddSensitiveVolume(volume); + LOG(info) << "FairDetector::DefineSensitiveVolumes"; + TObjArray* volumes = gGeoManager->GetListOfVolumes(); + TIter next(volumes); + TGeoVolume* volume; + while ((volume = static_cast(next()))) { + if (IsSensitive(volume->GetName())) { + LOG(debug) << "Sensitive Volume " << volume->GetName(); + AddSensitiveVolume(volume); + } } - } } // ------------------------------------------------------------------------- -void FairDetector::Initialize() +void FairDetector::Initialize() { -// Registers hits collection in Root manager; -// sets sensitive volumes. -// --- - - // Define sensitive volumes if in MT - if ( gMC->IsMT() ) { - std::cout << "Define sensitive volume " << std::endl; - DefineSensitiveVolumes(); - } - - Int_t NoOfEntries=svList->GetEntries(); - Int_t fMCid; - FairGeoNode* fN; - TString cutName; - TString copysign="#"; - for (Int_t i = 0 ; i < NoOfEntries ; i++ ) { - FairVolume* aVol = static_cast(svList->At(i)); - cutName = aVol->GetName(); - Ssiz_t pos = cutName.Index (copysign, 1); - if(pos>1) { cutName.Resize(pos); } - if ( aVol->getModId() == GetModId() ) { - fMCid = TVirtualMC::GetMC()->VolId(cutName.Data()); - aVol->setMCid(fMCid); - fN=aVol->getGeoNode(); - if (fN) { fN->setMCid(fMCid); } + // Registers hits collection in Root manager; + // sets sensitive volumes. + // --- + + // Define sensitive volumes if in MT + if (gMC->IsMT()) { + std::cout << "Define sensitive volume " << std::endl; + DefineSensitiveVolumes(); + } + + Int_t NoOfEntries = svList->GetEntries(); + Int_t fMCid; + FairGeoNode* fN; + TString cutName; + TString copysign = "#"; + for (Int_t i = 0; i < NoOfEntries; i++) { + FairVolume* aVol = static_cast(svList->At(i)); + cutName = aVol->GetName(); + Ssiz_t pos = cutName.Index(copysign, 1); + if (pos > 1) { + cutName.Resize(pos); + } + if (aVol->getModId() == GetModId()) { + fMCid = TVirtualMC::GetMC()->VolId(cutName.Data()); + aVol->setMCid(fMCid); + fN = aVol->getGeoNode(); + if (fN) { + fN->setMCid(fMCid); + } + } } - } - // Initialize cached pointer to MC (on master in sequential mode) - fMC = TVirtualMC::GetMC(); + // Initialize cached pointer to MC (on master in sequential mode) + fMC = TVirtualMC::GetMC(); } void FairDetector::SaveGeoParams() { - if ( ! fGeoSaved ) { - LOG(info) << "Detector: " << GetName() << " Geometry parameters saved ... "; - TFolder* mf = dynamic_cast(gROOT->FindObjectAny(FairRootManager::GetFolderName())) ; - TFolder* stsf = nullptr; - if (mf ) { stsf = dynamic_cast (mf->FindObjectAny(GetName())); } - if (stsf) { - TFolder* newf = stsf->AddFolder("Parameters","Detector parameters", nullptr); - newf->Add( flGeoPar ) ; + if (!fGeoSaved) { + LOG(info) << "Detector: " << GetName() << " Geometry parameters saved ... "; + TFolder* mf = dynamic_cast(gROOT->FindObjectAny(FairRootManager::GetFolderName())); + TFolder* stsf = nullptr; + if (mf) { + stsf = dynamic_cast(mf->FindObjectAny(GetName())); + } + if (stsf) { + TFolder* newf = stsf->AddFolder("Parameters", "Detector parameters", nullptr); + newf->Add(flGeoPar); + } + fGeoSaved = kTRUE; } - fGeoSaved = kTRUE; - } } -ClassImp(FairDetector) +ClassImp(FairDetector); diff --git a/base/sim/FairDetector.h b/base/sim/FairDetector.h index f161ce364a..b1e837def2 100644 --- a/base/sim/FairDetector.h +++ b/base/sim/FairDetector.h @@ -8,9 +8,9 @@ #ifndef FAIRDETECTOR_H #define FAIRDETECTOR_H -#include "FairModule.h" // for FairModule +#include "FairModule.h" // for FairModule -#include // for Int_t, Bool_t, etc +#include // for Int_t, Bool_t, etc class FairLogger; class FairVolume; @@ -31,7 +31,7 @@ class FairDetector : public FairModule Active: kTRUE for active detectors (ProcessHits() will be called) kFALSE for inactive detectors */ - FairDetector(const char* Name, Bool_t Active, Int_t DetId=0); + FairDetector(const char* Name, Bool_t Active, Int_t DetId = 0); /** default constructor */ @@ -47,7 +47,7 @@ class FairDetector : public FairModule /** this method is called for each step during simulation (see FairMCApplication::Stepping()) */ - virtual Bool_t ProcessHits( FairVolume* v=0)=0; + virtual Bool_t ProcessHits(FairVolume* v = 0) = 0; /** this is called at the end of an event after the call to tree fill in the FairRootManager */ @@ -55,7 +55,7 @@ class FairDetector : public FairModule /** Registers the produced collections in FAIRRootManager. */ - virtual void Register()=0; + virtual void Register() = 0; /** Gets the produced collections @@ -64,9 +64,9 @@ class FairDetector : public FairModule /** has to be called after each event to reset the containers */ - virtual void Reset()=0; + virtual void Reset() = 0; - virtual void CopyClones( TClonesArray*, TClonesArray*, Int_t) {} + virtual void CopyClones(TClonesArray*, TClonesArray*, Int_t) {} /** User actions after finishing of a primary track */ @@ -97,22 +97,19 @@ class FairDetector : public FairModule virtual void FinishEvent() {} void SaveGeoParams(); - Int_t GetDetId() { - return fDetId; - } + Int_t GetDetId() { return fDetId; } protected: /** Copy constructor */ FairDetector(const FairDetector&); /** Assignment operator */ - FairDetector& operator= (const FairDetector&); + FairDetector& operator=(const FairDetector&); void DefineSensitiveVolumes(); - Int_t fDetId; // Detector Id has to be set from ctr. - FairLogger* fLogger; //! /// FairLogger - - ClassDef(FairDetector,1) + Int_t fDetId; // Detector Id has to be set from ctr. + FairLogger* fLogger; //! /// FairLogger + ClassDef(FairDetector, 1) }; -#endif //FAIRDETECTOR_H +#endif // FAIRDETECTOR_H diff --git a/base/sim/FairDoubleHit.cxx b/base/sim/FairDoubleHit.cxx index 2d845e83db..f3e8f7e4d0 100644 --- a/base/sim/FairDoubleHit.cxx +++ b/base/sim/FairDoubleHit.cxx @@ -1,30 +1,23 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* Generated by Together */ #include "FairDoubleHit.h" -FairDoubleHit::FairDoubleHit(): - fRefIndex(-1), - fDetectorID(-1), - fPosition_in(), - fPositionError_in(), - fPosition_out(), - fPositionError_out() -{ - -} - -FairDoubleHit::~FairDoubleHit() -{ - -} - -ClassImp(FairDoubleHit) +FairDoubleHit::FairDoubleHit() + : fRefIndex(-1) + , fDetectorID(-1) + , fPosition_in() + , fPositionError_in() + , fPosition_out() + , fPositionError_out() +{} +FairDoubleHit::~FairDoubleHit() {} +ClassImp(FairDoubleHit); diff --git a/base/sim/FairDoubleHit.h b/base/sim/FairDoubleHit.h index df152c399d..64081f1120 100644 --- a/base/sim/FairDoubleHit.h +++ b/base/sim/FairDoubleHit.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* Generated by Together */ @@ -10,14 +10,14 @@ #ifndef FAIRDOUBLEHIT_H #define FAIRDOUBLEHIT_H - #include "FairMultiLinkedData.h" + #include class FairDoubleHit : public FairMultiLinkedData { protected: - Int_t fRefIndex; + Int_t fRefIndex; Int_t fDetectorID; TVector3 fPosition_in; TVector3 fPositionError_in; @@ -25,49 +25,44 @@ class FairDoubleHit : public FairMultiLinkedData TVector3 fPositionError_out; public: - FairDoubleHit(); virtual ~FairDoubleHit(); // methods - virtual void Print(const Option_t* opt = 0) const =0; + virtual void Print(const Option_t* opt = 0) const = 0; // set methods - virtual void SetDetectorID(Int_t chamb)=0; - virtual void SetPos_in (TVector3 xyz)=0; - virtual void SetDPos_in (TVector3 xyz)=0; - virtual void SetPos_out (TVector3 xyz)=0; - virtual void SetDPos_out (TVector3 xyz)=0; - virtual void SetRefIndex (Int_t index)=0; + virtual void SetDetectorID(Int_t chamb) = 0; + virtual void SetPos_in(TVector3 xyz) = 0; + virtual void SetDPos_in(TVector3 xyz) = 0; + virtual void SetPos_out(TVector3 xyz) = 0; + virtual void SetDPos_out(TVector3 xyz) = 0; + virtual void SetRefIndex(Int_t index) = 0; // get methods - virtual Int_t GetDetectorID()=0; - virtual Int_t GetRefIndex()=0; - - virtual TVector3 GetPos_in()=0; - virtual TVector3 GetDPos_in()=0; - virtual TVector3 GetPos_out()=0; - virtual TVector3 GetDPos_out()=0; - - virtual Double_t x_in() =0; - virtual Double_t y_in() =0; - virtual Double_t z_in() =0; - virtual Double_t dx_in()=0; - virtual Double_t dy_in()=0; - virtual Double_t dz_in()=0; - - virtual Double_t x_out() =0; - virtual Double_t y_out() =0; - virtual Double_t z_out() =0; - virtual Double_t dx_out()=0; - virtual Double_t dy_out()=0; - virtual Double_t dz_out()=0; - - ClassDef(FairDoubleHit,1) //FAIRDoubleHit + virtual Int_t GetDetectorID() = 0; + virtual Int_t GetRefIndex() = 0; + + virtual TVector3 GetPos_in() = 0; + virtual TVector3 GetDPos_in() = 0; + virtual TVector3 GetPos_out() = 0; + virtual TVector3 GetDPos_out() = 0; + + virtual Double_t x_in() = 0; + virtual Double_t y_in() = 0; + virtual Double_t z_in() = 0; + virtual Double_t dx_in() = 0; + virtual Double_t dy_in() = 0; + virtual Double_t dz_in() = 0; + + virtual Double_t x_out() = 0; + virtual Double_t y_out() = 0; + virtual Double_t z_out() = 0; + virtual Double_t dx_out() = 0; + virtual Double_t dy_out() = 0; + virtual Double_t dz_out() = 0; + + ClassDef(FairDoubleHit, 1) // FAIRDoubleHit }; -#endif //FAIRDOUBLEHIT_H - - - - +#endif // FAIRDOUBLEHIT_H diff --git a/base/sim/FairGeaneApplication.cxx b/base/sim/FairGeaneApplication.cxx index d0a506dffd..025fdd4670 100644 --- a/base/sim/FairGeaneApplication.cxx +++ b/base/sim/FairGeaneApplication.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -12,69 +12,62 @@ #include "FairGeaneApplication.h" -#include "FairField.h" // for FairField +#include "FairField.h" // for FairField -#include // for TVirtualMC - -#include // for printf +#include // for TVirtualMC +#include // for printf FairGeaneApplication::FairGeaneApplication() - : TVirtualMCApplication(), - fxField(0), - fMcVersion(-1), - fDebug(kFALSE), - fTrkPos(TLorentzVector(0,0,0,0)) -{ -} + : TVirtualMCApplication() + , fxField(0) + , fMcVersion(-1) + , fDebug(kFALSE) + , fTrkPos(TLorentzVector(0, 0, 0, 0)) +{} FairGeaneApplication::FairGeaneApplication(Bool_t Debug) - : TVirtualMCApplication(), - fxField(0), - fMcVersion(-1), - fDebug(Debug), - fTrkPos(TLorentzVector(0,0,0,0)) + : TVirtualMCApplication() + , fxField(0) + , fMcVersion(-1) + , fDebug(Debug) + , fTrkPos(TLorentzVector(0, 0, 0, 0)) { - //constructur used by Geane track propagation + // constructur used by Geane track propagation } -FairGeaneApplication::~FairGeaneApplication() -{ -} +FairGeaneApplication::~FairGeaneApplication() {} void FairGeaneApplication::ConstructGeometry() { - TVirtualMC::GetMC()->SetRootGeometry(); // notify VMC about Root geometry + TVirtualMC::GetMC()->SetRootGeometry(); // notify VMC about Root geometry } void FairGeaneApplication::InitMC(const char*, const char*) { -// Initialize MC. + // Initialize MC. - TVirtualMC::GetMC()->Init(); - TVirtualMC::GetMC()->BuildPhysics(); - fMcVersion = 3; //Geane + TVirtualMC::GetMC()->Init(); + TVirtualMC::GetMC()->BuildPhysics(); + fMcVersion = 3; // Geane - TVirtualMC::GetMC()->SetMagField(fxField); + TVirtualMC::GetMC()->SetMagField(fxField); } void FairGeaneApplication::GeaneStepping() { -// User actions at each step -// --- - if (fDebug) { - printf(" FairGeaneApplication::GeaneStepping() \n"); - TVirtualMC::GetMC()->TrackPosition(fTrkPos); - printf(" Track Position: x = %f y= %f z= %f \n ", fTrkPos.X(), fTrkPos.Y(), fTrkPos.Z()); - printf(" Current Volume name: %s \n", TVirtualMC::GetMC()->CurrentVolName()); - Int_t copyNo; - Int_t id = TVirtualMC::GetMC()->CurrentVolID(copyNo); - printf(" Current Volume id = %i , CopyNo = %i \n", id, copyNo); - } + // User actions at each step + // --- + if (fDebug) { + printf(" FairGeaneApplication::GeaneStepping() \n"); + TVirtualMC::GetMC()->TrackPosition(fTrkPos); + printf(" Track Position: x = %f y= %f z= %f \n ", fTrkPos.X(), fTrkPos.Y(), fTrkPos.Z()); + printf(" Current Volume name: %s \n", TVirtualMC::GetMC()->CurrentVolName()); + Int_t copyNo; + Int_t id = TVirtualMC::GetMC()->CurrentVolID(copyNo); + printf(" Current Volume id = %i , CopyNo = %i \n", id, copyNo); + } } -void FairGeaneApplication::SetField(FairField* field) -{ - fxField=field; -} +void FairGeaneApplication::SetField(FairField* field) { fxField = field; } -ClassImp(FairGeaneApplication) +ClassImp(FairGeaneApplication); diff --git a/base/sim/FairGeaneApplication.h b/base/sim/FairGeaneApplication.h index 2024d11de1..b92c5e7a16 100644 --- a/base/sim/FairGeaneApplication.h +++ b/base/sim/FairGeaneApplication.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -13,10 +13,9 @@ #ifndef FAIR_GEANE_APPLICATION_H #define FAIR_GEANE_APPLICATION_H -#include // for TVirtualMCApplication - -#include // for Bool_t, etc -#include // for TLorentzVector +#include // for Bool_t, etc +#include // for TLorentzVector +#include // for TVirtualMCApplication class FairField; @@ -33,21 +32,21 @@ class FairGeaneApplication : public TVirtualMCApplication /** default constructor */ FairGeaneApplication(); /** Special constructor, used for initializing G3 for Geane track propagation - *@param Debug true to print step info*/ + *@param Debug true to print step info*/ FairGeaneApplication(Bool_t Debug); /** default destructor */ virtual ~FairGeaneApplication(); /** Return Field used in simulation*/ - FairField* GetField() {return fxField;} + FairField* GetField() { return fxField; } /** Initialize MC engine */ - void InitMC(const char* setup, const char* cuts); + void InitMC(const char* setup, const char* cuts); /** - * Set the magnetic field for simulation or Geane - * @param field: magnetic field - */ + * Set the magnetic field for simulation or Geane + * @param field: magnetic field + */ void SetField(FairField* field); /** Define action at each step, dispatch the action to the corresponding detectors */ - void GeaneStepping(); // MC Application + void GeaneStepping(); // MC Application void ConstructGeometry(); /** Singelton instance */ @@ -55,31 +54,29 @@ class FairGeaneApplication : public TVirtualMCApplication /**pure virtual functions that hasve to be implimented */ - void InitGeometry() {;} - void GeneratePrimaries() {;} - void BeginEvent() {;} - void BeginPrimary() {;} - void PreTrack() {;} - void PostTrack() {;} - void FinishPrimary() {;} - void FinishEvent() {;} - void Stepping() {;} - void StopRun() {;} - + void InitGeometry() { ; } + void GeneratePrimaries() { ; } + void BeginEvent() { ; } + void BeginPrimary() { ; } + void PreTrack() { ; } + void PostTrack() { ; } + void FinishPrimary() { ; } + void FinishEvent() { ; } + void Stepping() { ; } + void StopRun() { ; } private: // data members /**Magnetic Field Pointer*/ - FairField* fxField; // + FairField* fxField; // /**MC Engine 1= Geant3, 2 = Geant4*/ - Int_t fMcVersion; // mc Version + Int_t fMcVersion; // mc Version /** Debug flag*/ - Bool_t fDebug;//! - TLorentzVector fTrkPos; //! + Bool_t fDebug; //! + TLorentzVector fTrkPos; //! - ClassDef(FairGeaneApplication,1) //Interface to MonteCarlo application - private: - FairGeaneApplication(const FairGeaneApplication&); + ClassDef(FairGeaneApplication, 1) // Interface to MonteCarlo application + private : FairGeaneApplication(const FairGeaneApplication&); FairGeaneApplication& operator=(const FairGeaneApplication&); }; @@ -87,7 +84,7 @@ class FairGeaneApplication : public TVirtualMCApplication inline FairGeaneApplication* FairGeaneApplication::Instance() { - return static_cast(TVirtualMCApplication::Instance()); + return static_cast(TVirtualMCApplication::Instance()); } #endif diff --git a/base/sim/FairGenerator.cxx b/base/sim/FairGenerator.cxx index 4d2a316721..046fdf97f3 100644 --- a/base/sim/FairGenerator.cxx +++ b/base/sim/FairGenerator.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -12,31 +12,35 @@ #include "FairGenerator.h" FairGenerator::FairGenerator() - : TNamed() {} + : TNamed() +{} FairGenerator::FairGenerator(const char* name, const char* title) - : TNamed(name, title) {} + : TNamed(name, title) +{} FairGenerator::FairGenerator(const FairGenerator& rhs) - : TNamed(rhs) {} + : TNamed(rhs) +{} -FairGenerator::~FairGenerator() { } +FairGenerator::~FairGenerator() {} -FairGenerator& FairGenerator::operator= (const FairGenerator& rhs) +FairGenerator& FairGenerator::operator=(const FairGenerator& rhs) { - // check assignment to self - if (this == &rhs) return *this; + // check assignment to self + if (this == &rhs) + return *this; - // base class assignment - TNamed::operator=(rhs); + // base class assignment + TNamed::operator=(rhs); - return *this; + return *this; } FairGenerator* FairGenerator::CloneGenerator() const { - Fatal("CloneGenerator","Has to be overriden in multi-threading applications."); - return 0; + Fatal("CloneGenerator", "Has to be overriden in multi-threading applications."); + return 0; } -ClassImp(FairGenerator) +ClassImp(FairGenerator); diff --git a/base/sim/FairGenerator.h b/base/sim/FairGenerator.h index 4d3957f326..ba824ed1df 100644 --- a/base/sim/FairGenerator.h +++ b/base/sim/FairGenerator.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -10,7 +10,6 @@ // ----- Created 09/06/04 by D. Bertini / V. Friese ----- // ------------------------------------------------------------------------- - /** FairGenerator.h *@author D.Bertini *@author V.Friese @@ -21,13 +20,11 @@ derived from this one must implement the abtract method ReadEvent, which has to use the method FairPrimaryGenerator::AddTrack. **/ - #ifndef FAIRGENERATOR_H #define FAIRGENERATOR_H -#include // for TNamed - -#include // for Bool_t, etc +#include // for Bool_t, etc +#include // for TNamed class FairPrimaryGenerator; @@ -38,7 +35,7 @@ class FairGenerator : public TNamed FairGenerator(); /** Constructor with name and title **/ - FairGenerator(const char* name, const char* title="FAIR Generator"); + FairGenerator(const char* name, const char* title = "FAIR Generator"); /** Destructor. **/ virtual ~FairGenerator(); @@ -53,7 +50,7 @@ class FairGenerator : public TNamed virtual Bool_t ReadEvent(FairPrimaryGenerator* primGen) = 0; /**Initialize the generator if needed */ - virtual Bool_t Init() { return kTRUE;} + virtual Bool_t Init() { return kTRUE; } /** Clone this object (used in MT mode only) */ virtual FairGenerator* CloneGenerator() const; @@ -62,9 +59,9 @@ class FairGenerator : public TNamed /** Copy constructor */ FairGenerator(const FairGenerator&); /** Assignment operator */ - FairGenerator& operator= (const FairGenerator&); + FairGenerator& operator=(const FairGenerator&); - ClassDef(FairGenerator,1); + ClassDef(FairGenerator, 1); }; #endif diff --git a/base/sim/FairGenericStack.cxx b/base/sim/FairGenericStack.cxx index a9a0c68666..3015d8bef2 100644 --- a/base/sim/FairGenericStack.cxx +++ b/base/sim/FairGenericStack.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -10,160 +10,167 @@ // ----- Created 10/08/04 by D. Bertini ----- // ------------------------------------------------------------------------- #include "FairGenericStack.h" -#include "FairLogger.h" // for FairLogger -#include -#include -#include +#include "FairLogger.h" // for FairLogger + #include +#include #include +#include #include - -#include // strcmp +#include +#include // strcmp FairGenericStack::FairGenericStack() - : TVirtualMCStack(), - fLogger(FairLogger::GetLogger()), - fDetList(0), - fDetIter(0), - fVerbose(1), - fFSTrackMap(), - fFSTrackIter(), - fFSMovedIndex(-2), - fFSFirstSecondary(-2), - fFSNofSecondaries(0) -{ -} + : TVirtualMCStack() + , fLogger(FairLogger::GetLogger()) + , fDetList(0) + , fDetIter(0) + , fVerbose(1) + , fFSTrackMap() + , fFSTrackIter() + , fFSMovedIndex(-2) + , fFSFirstSecondary(-2) + , fFSNofSecondaries(0) +{} // ----- Constructor with estimated array dimension -------------------- FairGenericStack::FairGenericStack(Int_t) - : TVirtualMCStack(), - fLogger(FairLogger::GetLogger()), - fDetList(0), - fDetIter(0), - fVerbose(1), - fFSTrackMap(), - fFSTrackIter(), - fFSMovedIndex(-2), - fFSFirstSecondary(-2), - fFSNofSecondaries(0) -{ -} - -FairGenericStack::~FairGenericStack() -{ - delete fDetIter; -} + : TVirtualMCStack() + , fLogger(FairLogger::GetLogger()) + , fDetList(0) + , fDetIter(0) + , fVerbose(1) + , fFSTrackMap() + , fFSTrackIter() + , fFSMovedIndex(-2) + , fFSFirstSecondary(-2) + , fFSNofSecondaries(0) +{} + +FairGenericStack::~FairGenericStack() { delete fDetIter; } FairGenericStack::FairGenericStack(const FairGenericStack& rhs) - : TVirtualMCStack(rhs), - fLogger(FairLogger::GetLogger()), - fDetList(rhs.fDetList), - fDetIter(0), - fVerbose(rhs.fVerbose) -{ -} + : TVirtualMCStack(rhs) + , fLogger(FairLogger::GetLogger()) + , fDetList(rhs.fDetList) + , fDetIter(0) + , fVerbose(rhs.fVerbose) +{} FairGenericStack& FairGenericStack::operator=(const FairGenericStack& rhs) { - // check assignment to self - if (this == &rhs) return *this; + // check assignment to self + if (this == &rhs) + return *this; - // base class assignment - TVirtualMCStack::operator=(rhs); + // base class assignment + TVirtualMCStack::operator=(rhs); - // assignment oiperator - fLogger = 0; - fDetList = 0; - fDetIter = 0; - fVerbose = rhs.fVerbose; + // assignment oiperator + fLogger = 0; + fDetList = 0; + fDetIter = 0; + fVerbose = rhs.fVerbose; - return *this; + return *this; } void FairGenericStack::SetDetArrayList(TRefArray* detArray) { - fDetList=detArray; - if(fDetList!=0) { fDetIter=fDetList->MakeIterator(); } + fDetList = detArray; + if (fDetList != 0) { + fDetIter = fDetList->MakeIterator(); + } } FairGenericStack* FairGenericStack::CloneStack() const { - Fatal("CloneStack","Has to be overriden in multi-threading applications."); - return 0; + Fatal("CloneStack", "Has to be overriden in multi-threading applications."); + return 0; } -void FairGenericStack::FastSimMoveParticleTo(Double_t xx, Double_t yy, Double_t zz, Double_t tt, - Double_t px, Double_t py, Double_t pz, Double_t en) +void FairGenericStack::FastSimMoveParticleTo(Double_t xx, + Double_t yy, + Double_t zz, + Double_t tt, + Double_t px, + Double_t py, + Double_t pz, + Double_t en) { TLorentzVector curPos; TVirtualMC::GetMC()->TrackPosition(curPos); - LOG(debug) << "track is in " << curPos.X() << "," << curPos.Y() << "," << curPos.Z() << ", moving to " << xx << "," << yy << "," << zz; + LOG(debug) << "track is in " << curPos.X() << "," << curPos.Y() << "," << curPos.Z() << ", moving to " << xx << "," + << yy << "," << zz; TString curVolName(TVirtualMC::GetMC()->CurrentVolName()); - TString targetVolName(gGeoManager->FindNode(xx,yy,zz)->GetVolume()->GetName()); - if ( curVolName.EqualTo(targetVolName) ) { - LOG(fatal) << "FairStack::FastSimMoveParticleTo(" << xx << "," << yy << "," << zz << ": " - << curVolName << " = " << targetVolName << ") crashes the simulation."; - } - else { + TString targetVolName(gGeoManager->FindNode(xx, yy, zz)->GetVolume()->GetName()); + if (curVolName.EqualTo(targetVolName)) { + LOG(fatal) << "FairStack::FastSimMoveParticleTo(" << xx << "," << yy << "," << zz << ": " << curVolName << " = " + << targetVolName << ") crashes the simulation."; + } else { LOG(debug) << "gMC says track is in \"" << curVolName << "\" moving particle to \"" << targetVolName << "\"."; } - Int_t tobedone = 1; - Int_t parent = 0; // do not store it as mother - Int_t pdg = TVirtualMC::GetMC()->TrackPid(); - Double_t polx = 0.; - Double_t poly = 0.; - Double_t polz = 0.; - TMCProcess proc = kPPrimary;// not important, the track will not be saved - Int_t ntr = 0; // Track number; to be filled by the stack - Int_t status = 0; // not important, the track will not be saved + Int_t tobedone = 1; + Int_t parent = 0; // do not store it as mother + Int_t pdg = TVirtualMC::GetMC()->TrackPid(); + Double_t polx = 0.; + Double_t poly = 0.; + Double_t polz = 0.; + TMCProcess proc = kPPrimary; // not important, the track will not be saved + Int_t ntr = 0; // Track number; to be filled by the stack + Int_t status = 0; // not important, the track will not be saved Double_t weight = 0.; - PushTrack(tobedone, parent, pdg, - px, py, pz, en, - xx, yy, zz, tt, - polx, poly, polz, - proc, ntr, weight, status, -1); - fFSMovedIndex = GetListOfParticles()->GetEntries()-1; + PushTrack(tobedone, parent, pdg, px, py, pz, en, xx, yy, zz, tt, polx, poly, polz, proc, ntr, weight, status, -1); + fFSMovedIndex = GetListOfParticles()->GetEntries() - 1; Int_t trackID = TVirtualMC::GetMC()->GetStack()->GetCurrentTrackNumber(); - fFSTrackIter = fFSTrackMap.find(trackID); // check if this track is not already created by FastSimulation - if ( fFSTrackIter != fFSTrackMap.end() ) // indeed the track has been created by the FastSimulation mechanism - trackID = fFSTrackIter->second; // use the ID of the original track + fFSTrackIter = fFSTrackMap.find(trackID); // check if this track is not already created by FastSimulation + if (fFSTrackIter != fFSTrackMap.end()) // indeed the track has been created by the FastSimulation mechanism + trackID = fFSTrackIter->second; // use the ID of the original track fFSTrackMap[ntr] = trackID; - LOG(debug) << "FairStack::FastSimMoveParticleTo() created track number " << ntr << " to replace track number " << trackID; + LOG(debug) << "FairStack::FastSimMoveParticleTo() created track number " << ntr << " to replace track number " + << trackID; - if ( strcmp(TVirtualMC::GetMC()->GetName(),"TGeant3TGeo") == 0 ) { + if (strcmp(TVirtualMC::GetMC()->GetName(), "TGeant3TGeo") == 0) { TVirtualMC::GetMC()->StopTrack(); } } void FairGenericStack::FastSimStopParticle() { - if ( TVirtualMC::GetMC()->IsTrackStop() ) + if (TVirtualMC::GetMC()->IsTrackStop()) LOG(fatal) << "FairStack::FastSimStopParticle() tries to stop particle that was probably moved!"; fFSMovedIndex = -1; TVirtualMC::GetMC()->StopTrack(); } -void FairGenericStack::FastSimPushSecondary(Int_t parentID, Int_t pdgCode, - Double_t xx, Double_t yy, Double_t zz, Double_t tt, - Double_t px, Double_t py, Double_t pz, Double_t en, - Double_t polx, Double_t poly, Double_t polz, TMCProcess proc, - Double_t weight, Int_t is) +void FairGenericStack::FastSimPushSecondary(Int_t parentID, + Int_t pdgCode, + Double_t xx, + Double_t yy, + Double_t zz, + Double_t tt, + Double_t px, + Double_t py, + Double_t pz, + Double_t en, + Double_t polx, + Double_t poly, + Double_t polz, + TMCProcess proc, + Double_t weight, + Int_t is) { - Int_t tobedone = 1; - - Int_t ntr = 0; // Track number; to be filled by the stack - PushTrack(tobedone, parentID, pdgCode, - px, py, pz, en, - xx, yy, zz, tt, - polx, poly, polz, - proc, ntr, weight, is, -1); - if ( fFSNofSecondaries == 0 ) - fFSFirstSecondary = GetListOfParticles()->GetEntries()-1; + Int_t tobedone = 1; + + Int_t ntr = 0; // Track number; to be filled by the stack + PushTrack(tobedone, parentID, pdgCode, px, py, pz, en, xx, yy, zz, tt, polx, poly, polz, proc, ntr, weight, is, -1); + if (fFSNofSecondaries == 0) + fFSFirstSecondary = GetListOfParticles()->GetEntries() - 1; fFSNofSecondaries++; } -ClassImp(FairGenericStack) +ClassImp(FairGenericStack); diff --git a/base/sim/FairGenericStack.h b/base/sim/FairGenericStack.h index c6b564751c..9f8a29123c 100644 --- a/base/sim/FairGenericStack.h +++ b/base/sim/FairGenericStack.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -10,22 +10,18 @@ // ----- Created 10/08/04 by D. Bertini ----- // ------------------------------------------------------------------------- - /** FairGenericStack.h *@author D.Bertini * Generic MC stack class **/ - #ifndef FAIRGENERICSTACK_H #define FAIRGENERICSTACK_H +#include // for Double_t, Int_t, etc #include -#include // for TVirtualMCStack - -#include // for Double_t, Int_t, etc -#include // for TMCProcess - +#include // for TMCProcess +#include // for TVirtualMCStack #include #include @@ -63,12 +59,25 @@ class FairGenericStack : public TVirtualMCStack *@param is Generation status code (whatever that means) *@param secondparentID used fot the index of mother of primery in the list **/ - virtual void PushTrack(Int_t toBeDone, Int_t parentID, Int_t pdgCode, - Double_t px, Double_t py, Double_t pz, - Double_t e, Double_t vx, Double_t vy, - Double_t vz, Double_t time, Double_t polx, - Double_t poly, Double_t polz, TMCProcess proc, - Int_t& ntr, Double_t weight, Int_t is, Int_t secondparentID) = 0; + virtual void PushTrack(Int_t toBeDone, + Int_t parentID, + Int_t pdgCode, + Double_t px, + Double_t py, + Double_t pz, + Double_t e, + Double_t vx, + Double_t vy, + Double_t vz, + Double_t time, + Double_t polx, + Double_t poly, + Double_t polz, + TMCProcess proc, + Int_t& ntr, + Double_t weight, + Int_t is, + Int_t secondparentID) = 0; /** Fill the MCTrack output array, applying filter criteria **/ virtual void FillTrackArray() {} @@ -104,26 +113,52 @@ class FairGenericStack : public TVirtualMCStack *@param px,py,pz new momentum of the particle *@param en new energy of the particle **/ - virtual void FastSimMoveParticleTo(Double_t xx, Double_t yy, Double_t zz, Double_t tt, - Double_t px, Double_t py, Double_t pz, Double_t en); + virtual void FastSimMoveParticleTo(Double_t xx, + Double_t yy, + Double_t zz, + Double_t tt, + Double_t px, + Double_t py, + Double_t pz, + Double_t en); /** Fast simulation function to stop original particle. **/ - virtual void FastSimStopParticle (); + virtual void FastSimStopParticle(); /** Fast simulation function to generate secondaries. *@param xx,yy,zz position of the particle *@param tt proper time of the particle *@param px,py,pz momentum of the particle *@param en energy of the particle **/ - virtual void FastSimPushSecondary(Int_t parentID, Int_t pdgCode, - Double_t xx, Double_t yy, Double_t zz, Double_t tt, - Double_t px, Double_t py, Double_t pz, Double_t en, - Double_t polx, Double_t poly, Double_t polz, TMCProcess proc, - Double_t weight, Int_t is); + virtual void FastSimPushSecondary(Int_t parentID, + Int_t pdgCode, + Double_t xx, + Double_t yy, + Double_t zz, + Double_t tt, + Double_t px, + Double_t py, + Double_t pz, + Double_t en, + Double_t polx, + Double_t poly, + Double_t polz, + TMCProcess proc, + Double_t weight, + Int_t is); /** Allow FairFastSim the retrieval of moved particle position, p1 and p2 to get secondaries **/ - virtual std::tuple FastSimGetMovedIndex() { return std::make_tuple(fFSMovedIndex, fFSFirstSecondary, fFSNofSecondaries); } - virtual void FastSimClearMovedIndex () { fFSMovedIndex = -2; fFSFirstSecondary = -2; fFSNofSecondaries = 0; } + virtual std::tuple FastSimGetMovedIndex() + { + return std::make_tuple(fFSMovedIndex, fFSFirstSecondary, fFSNofSecondaries); + } + virtual void FastSimClearMovedIndex() + { + fFSMovedIndex = -2; + fFSFirstSecondary = -2; + fFSNofSecondaries = 0; + } - template void FastSimUpdateTrackIndex(T* point, Int_t& iTrack); + template + void FastSimUpdateTrackIndex(T* point, Int_t& iTrack); protected: /** Copy constructor */ @@ -132,10 +167,10 @@ class FairGenericStack : public TVirtualMCStack FairGenericStack& operator=(const FairGenericStack&); /** Fair Logger */ - FairLogger* fLogger;//! + FairLogger* fLogger; //! /** List of detectors registering hits in the simulation */ - TRefArray* fDetList; //! + TRefArray* fDetList; //! /** Iterator for the detector list*/ TIterator* fDetIter; @@ -144,22 +179,22 @@ class FairGenericStack : public TVirtualMCStack Int_t fVerbose; /** FastSimulation: STL map from new track index to original track index **/ - std::map fFSTrackMap; //! - std::map::iterator fFSTrackIter; //! - Int_t fFSMovedIndex; //! - Int_t fFSFirstSecondary; //! - Int_t fFSNofSecondaries; //! + std::map fFSTrackMap; //! + std::map::iterator fFSTrackIter; //! + Int_t fFSMovedIndex; //! + Int_t fFSFirstSecondary; //! + Int_t fFSNofSecondaries; //! - ClassDef(FairGenericStack,1) + ClassDef(FairGenericStack, 1) }; template void FairGenericStack::FastSimUpdateTrackIndex(T* point, Int_t& iTrack) { - fFSTrackIter = fFSTrackMap.find(iTrack); // check if point created by FastSimulation - if ( fFSTrackIter != fFSTrackMap.end() ) { // indeed the point has been created by the FastSimulation mechanism + fFSTrackIter = fFSTrackMap.find(iTrack); // check if point created by FastSimulation + if (fFSTrackIter != fFSTrackMap.end()) { // indeed the point has been created by the FastSimulation mechanism iTrack = fFSTrackIter->second; - point->SetTrackID(iTrack); // set proper TrackID + point->SetTrackID(iTrack); // set proper TrackID } } diff --git a/base/sim/FairGenericVMCConfig.cxx b/base/sim/FairGenericVMCConfig.cxx index 0701591446..335ab45412 100644 --- a/base/sim/FairGenericVMCConfig.cxx +++ b/base/sim/FairGenericVMCConfig.cxx @@ -16,32 +16,30 @@ #include -FairGenericVMCConfig::FairGenericVMCConfig() -{ -} +FairGenericVMCConfig::FairGenericVMCConfig() {} -FairGenericVMCConfig::~FairGenericVMCConfig() -{ -} +FairGenericVMCConfig::~FairGenericVMCConfig() {} void FairGenericVMCConfig::Setup(const char* mcEngine) { LOG(warning) << "FairGenericVMCConfig::Setup() Using gConfig.C macro DEPRACATED."; LOG(warning) << "Check FairRoot/examples/common/gconfig/ for current YAML implementation."; - TString lUserCuts = FairRunSim::Instance()->GetUserCuts(); + TString lUserCuts = FairRunSim::Instance()->GetUserCuts(); TString lUserConfig = FairRunSim::Instance()->GetUserConfig(); TString work = getenv("VMCWORKDIR"); - TString work_config = work+"/gconfig/"; + TString work_config = work + "/gconfig/"; work_config.ReplaceAll("//", "/"); TString Lib_config = getenv("GEANT4VMC_MACRO_DIR"); Lib_config.ReplaceAll("//", "/"); - if (!Lib_config.EndsWith("/") && !Lib_config.IsNull()) { Lib_config+="/"; } + if (!Lib_config.EndsWith("/") && !Lib_config.IsNull()) { + Lib_config += "/"; + } - TString config_dir= getenv("CONFIG_DIR"); - config_dir.ReplaceAll("//","/"); + TString config_dir = getenv("CONFIG_DIR"); + config_dir.ReplaceAll("//", "/"); Bool_t AbsPath = kFALSE; @@ -50,18 +48,21 @@ void FairGenericVMCConfig::Setup(const char* mcEngine) TString ConfigMacro; TString cuts = lUserCuts; //----------------------------------------------Geant4 Config----------------------------------------- - if (strcmp(mcEngine,"TGeant4") == 0) { + if (strcmp(mcEngine, "TGeant4") == 0) { TString g4LibMacro = "g4libs.C"; TString g4Macro; if (lUserConfig.IsNull()) { g4Macro = "g4Config.C"; lUserConfig = g4Macro; } else { - if (lUserConfig.Contains("/")) { AbsPath = kTRUE; } + if (lUserConfig.Contains("/")) { + AbsPath = kTRUE; + } g4Macro = lUserConfig; LOG(info) << "---------------User config is used: " << g4Macro.Data(); } - if (TString(gSystem->FindFile(config_dir.Data(), g4LibMacro)) != TString("")) { //be carfull after this call the string g4LibMacro is empty if not found!!!! + if (TString(gSystem->FindFile(config_dir.Data(), g4LibMacro)) + != TString("")) { // be carfull after this call the string g4LibMacro is empty if not found!!!! LOG(info) << "---User path for Configuration (g4libs.C) is used: " << config_dir.Data(); LibMacro = g4LibMacro; } else if (gSystem->AccessPathName((Lib_config + "g4libs.C").Data()) == false) { @@ -74,11 +75,14 @@ void FairGenericVMCConfig::Setup(const char* mcEngine) LOG(info) << "---User path for Configuration (g4Config.C) is used: " << config_dir.Data(); ConfigMacro = g4Macro; } else { - if (AbsPath) { ConfigMacro = lUserConfig; } - else { ConfigMacro = work_config + lUserConfig; } + if (AbsPath) { + ConfigMacro = lUserConfig; + } else { + ConfigMacro = work_config + lUserConfig; + } } //----------------------------------------------Geant3 Config----------------------------------------- - } else if (strcmp(mcEngine,"TGeant3") == 0) { + } else if (strcmp(mcEngine, "TGeant3") == 0) { TString g3LibMacro = "g3libs.C"; TString g3Macro = "g3Config.C"; if (lUserConfig.IsNull()) { @@ -86,35 +90,42 @@ void FairGenericVMCConfig::Setup(const char* mcEngine) lUserConfig = g3Macro; LOG(info) << "-------------- Standard Config is called ------------------------------------"; } else { - if (lUserConfig.Contains("/")) { AbsPath = kTRUE; } + if (lUserConfig.Contains("/")) { + AbsPath = kTRUE; + } g3Macro = lUserConfig; LOG(info) << "---------------User config is used: " << g3Macro.Data(); } - if (TString(gSystem->FindFile(config_dir.Data(),g3LibMacro)) != TString("")) { + if (TString(gSystem->FindFile(config_dir.Data(), g3LibMacro)) != TString("")) { LOG(info) << "---User path for Configuration (g3libs.C) is used: " << config_dir.Data(); LibMacro = g3LibMacro; - } else if (gSystem->AccessPathName((work_config+"g3libs.C").Data()) == false) { + } else if (gSystem->AccessPathName((work_config + "g3libs.C").Data()) == false) { // Note: file is existing if AccessPathName return false LOG(info) << "---VMCWORKDIR path for Configuration (g3libs.C) is used: " << work_config.Data(); LibMacro = work_config + "g3libs.C"; } LibFunction = "g3libs()"; - if (!AbsPath && TString(gSystem->FindFile(config_dir.Data(),g3Macro)) != TString("")) { + if (!AbsPath && TString(gSystem->FindFile(config_dir.Data(), g3Macro)) != TString("")) { LOG(info) << "---User path for Configuration (g3Config.C) is used: " << config_dir.Data(); ConfigMacro = g3Macro; } else { - if (AbsPath) { ConfigMacro = lUserConfig; } - else { ConfigMacro = work_config + lUserConfig; } + if (AbsPath) { + ConfigMacro = lUserConfig; + } else { + ConfigMacro = work_config + lUserConfig; + } } //----------------------------------------------Fluka Config----------------------------------------- - } else if (strcmp(mcEngine,"TFluka") == 0) { + } else if (strcmp(mcEngine, "TFluka") == 0) { TString flLibMacro = "fllibs.C"; TString flMacro = "flConfig.C"; if (lUserConfig.IsNull()) { flMacro = "flConfig.C"; lUserConfig = flMacro; } else { - if (lUserConfig.Contains("/")) { AbsPath = kTRUE; } + if (lUserConfig.Contains("/")) { + AbsPath = kTRUE; + } flMacro = lUserConfig; LOG(info) << "---------------User config is used: " << flMacro.Data(); } @@ -125,16 +136,19 @@ void FairGenericVMCConfig::Setup(const char* mcEngine) } LibMacro = flLibMacro; LibFunction = "fllibs()"; - if (!AbsPath && TString(gSystem->FindFile(config_dir.Data(),flMacro)) != TString("")) { + if (!AbsPath && TString(gSystem->FindFile(config_dir.Data(), flMacro)) != TString("")) { LOG(info) << "---User path for Configuration (flConfig.C) is used: " << config_dir.Data(); ConfigMacro = flMacro; } else { - if (AbsPath) { ConfigMacro = lUserConfig; } - else { ConfigMacro = work_config + lUserConfig; } + if (AbsPath) { + ConfigMacro = lUserConfig; + } else { + ConfigMacro = work_config + lUserConfig; + } } } //----------------------------------------------SetCuts------------------------------------------------ - if (TString(gSystem->FindFile(config_dir.Data(),cuts)) != TString("")) { + if (TString(gSystem->FindFile(config_dir.Data(), cuts)) != TString("")) { LOG(info) << "---User path for Cuts and Processes (SetCuts.C) is used: " << config_dir.Data(); } else { cuts = work_config + lUserCuts; @@ -152,4 +166,4 @@ void FairGenericVMCConfig::Setup(const char* mcEngine) gROOT->ProcessLine("SetCuts()"); } -ClassImp(FairGenericVMCConfig) +ClassImp(FairGenericVMCConfig); diff --git a/base/sim/FairGenericVMCConfig.h b/base/sim/FairGenericVMCConfig.h index 602eebddb4..861c90dc68 100644 --- a/base/sim/FairGenericVMCConfig.h +++ b/base/sim/FairGenericVMCConfig.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- diff --git a/base/sim/FairGeoParSet.cxx b/base/sim/FairGeoParSet.cxx index b27af6e0be..1f953c73bd 100644 --- a/base/sim/FairGeoParSet.cxx +++ b/base/sim/FairGeoParSet.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -11,39 +11,46 @@ // ------------------------------------------------------------------------- #include "FairGeoParSet.h" -#include // for TObjArray -#include "FairParamList.h" // for FairParamList -ClassImp(FairGeoParSet) +#include "FairParamList.h" // for FairParamList -FairGeoParSet::FairGeoParSet(const char* name,const char* title,const char* context) - : FairParGenericSet(name,title,context), - fGeoNodes(new TObjArray()), - fGeom(0) -{ -} +#include // for TObjArray -FairGeoParSet::~FairGeoParSet(void) -{ -} +ClassImp(FairGeoParSet); + +FairGeoParSet::FairGeoParSet(const char* name, const char* title, const char* context) + : FairParGenericSet(name, title, context) + , fGeoNodes(new TObjArray()) + , fGeom(0) +{} + +FairGeoParSet::~FairGeoParSet(void) {} void FairGeoParSet::clear(void) { - //delete fGeoNodes; -// delete fGeom; + // delete fGeoNodes; + // delete fGeom; } void FairGeoParSet::putParams(FairParamList* l) { - if (!l) { return; } - l->addObject("FairGeoNodes List", fGeoNodes); - l->addObject("Detector Geometry", fGeom); + if (!l) { + return; + } + l->addObject("FairGeoNodes List", fGeoNodes); + l->addObject("Detector Geometry", fGeom); } Bool_t FairGeoParSet::getParams(FairParamList* l) { - if (!l) { return kFALSE; } - if (!l->fillObject("FairGeoNodes List", fGeoNodes)) { return kFALSE; } - if (!l->fillObject("Detector Geometry", fGeom)) { return kFALSE; } - return kTRUE; + if (!l) { + return kFALSE; + } + if (!l->fillObject("FairGeoNodes List", fGeoNodes)) { + return kFALSE; + } + if (!l->fillObject("Detector Geometry", fGeom)) { + return kFALSE; + } + return kTRUE; } diff --git a/base/sim/FairGeoParSet.h b/base/sim/FairGeoParSet.h index fe869bafd2..f68c7204d2 100644 --- a/base/sim/FairGeoParSet.h +++ b/base/sim/FairGeoParSet.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FairGeoParSet_H @@ -14,9 +14,10 @@ * @version 1 * @since 12.10.04 */ -#include "FairParGenericSet.h" // for FairParGenericSet -#include // for Double_t, etc -#include // IWYU pragma: keep needed by cint +#include "FairParGenericSet.h" // for FairParGenericSet + +#include // for Double_t, etc +#include // IWYU pragma: keep needed by cint class FairParamList; class TObjArray; @@ -27,13 +28,13 @@ class FairGeoParSet : public FairParGenericSet /** * constructor * @param name : Parameter set name - * @param title: Parameter set title - * @param context: Parameter set context - */ + * @param title: Parameter set title + * @param context: Parameter set context + */ - FairGeoParSet(const char* name="FairGeoParSet", - const char* title="Class for base parameter io", - const char* context="BaseDefaultContext"); + FairGeoParSet(const char* name = "FairGeoParSet", + const char* title = "Class for base parameter io", + const char* context = "BaseDefaultContext"); /** dtor*/ ~FairGeoParSet(void); /** clear*/ @@ -41,7 +42,7 @@ class FairGeoParSet : public FairParGenericSet /** * Fills all persistent data members into the list for write. * @param FairParamList : Parameter list to be filled - */ + */ void putParams(FairParamList*); /** * Fills all persistent data members from the list after reading. The function @@ -54,31 +55,30 @@ class FairGeoParSet : public FairParGenericSet * Set the Geometry node list used in the simulation * @param array: TObjArray of Geometry nodes */ - void SetGeoNodes(TObjArray* array) {fGeoNodes=array;} + void SetGeoNodes(TObjArray* array) { fGeoNodes = array; } /** * Set the Geometry (TGeoManager) used in the simulation * @param Geom: TGeoManager of the full geometry */ - void SetGeometry(TGeoManager* Geom) {fGeom=Geom;} + void SetGeometry(TGeoManager* Geom) { fGeom = Geom; } /** - * Get the Geometry Nodes list used in the simulation - */ - TObjArray* GetGeoNodes() {return fGeoNodes;} + * Get the Geometry Nodes list used in the simulation + */ + TObjArray* GetGeoNodes() { return fGeoNodes; } /** * Get the geometry (TGeoManager) used in the simulation */ - TGeoManager* GetGeometry() {return fGeom;} + TGeoManager* GetGeometry() { return fGeom; } protected: /// List of FairGeoNodes for sensitive volumes - TObjArray* fGeoNodes; //! + TObjArray* fGeoNodes; //! /// Full Geometry - TGeoManager* fGeom; - ClassDef(FairGeoParSet,1) + TGeoManager* fGeom; + ClassDef(FairGeoParSet, 1) - private: - FairGeoParSet(const FairGeoParSet& L); - FairGeoParSet& operator= (const FairGeoParSet&) {return *this;} + private : FairGeoParSet(const FairGeoParSet& L); + FairGeoParSet& operator=(const FairGeoParSet&) { return *this; } }; #endif /* !FairGeoParSet_H */ diff --git a/base/sim/FairIon.cxx b/base/sim/FairIon.cxx index 30fcece196..8b815d0070 100644 --- a/base/sim/FairIon.cxx +++ b/base/sim/FairIon.cxx @@ -1,53 +1,53 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- // ----- FairIon source file ----- // ------------------------------------------------------------------------- #include "FairIon.h" + #include "FairLogger.h" #include #include -const Double_t FairIon::amu=0.931494028 ; // Gev/c**2 +const Double_t FairIon::amu = 0.931494028; // Gev/c**2 FairIon::FairIon() - :TNamed(), - fZ(0), - fA(0), - fQ(0), - fExcEnergy(0), - fMass(0), - fLogger(FairLogger::GetLogger()) -{ -} + : TNamed() + , fZ(0) + , fA(0) + , fQ(0) + , fExcEnergy(0) + , fMass(0) + , fLogger(FairLogger::GetLogger()) +{} -FairIon::FairIon(const char* name, Int_t z, Int_t a, Int_t q, Double_t e, - Double_t mass) - : TNamed(name, "User defined ion"), - fZ(z), - fA(a), - fQ(q), - fExcEnergy(e), - fMass(0), - fLogger(FairLogger::GetLogger()) +FairIon::FairIon(const char* name, Int_t z, Int_t a, Int_t q, Double_t e, Double_t mass) + : TNamed(name, "User defined ion") + , fZ(z) + , fA(a) + , fQ(q) + , fExcEnergy(e) + , fMass(0) + , fLogger(FairLogger::GetLogger()) { - TDatabasePDG* pdgDB = TDatabasePDG::Instance(); - TParticlePDG* kProton = pdgDB->GetParticle(2212); - Double_t kProtonMass=kProton->Mass(); + TDatabasePDG* pdgDB = TDatabasePDG::Instance(); + TParticlePDG* kProton = pdgDB->GetParticle(2212); + Double_t kProtonMass = kProton->Mass(); - if (mass == 0.) { fMass = kProtonMass * Double_t(a); } - else { fMass = mass; } - LOG(info) << "New Ion " << name << " Z=" << z << " A=" << a << " Charge=" << q << " Mass=" << fMass << " GeV "; + if (mass == 0.) { + fMass = kProtonMass * Double_t(a); + } else { + fMass = mass; + } + LOG(info) << "New Ion " << name << " Z=" << z << " A=" << a << " Charge=" << q << " Mass=" << fMass << " GeV "; } -FairIon::~FairIon() -{ -}; +FairIon::~FairIon(){}; -ClassImp(FairIon) +ClassImp(FairIon); diff --git a/base/sim/FairIon.h b/base/sim/FairIon.h index 60ed1f4bf9..08b0e9d1df 100644 --- a/base/sim/FairIon.h +++ b/base/sim/FairIon.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -18,16 +18,15 @@ ** from the constructor of the FairIonGenerator. **/ - #ifndef FAIRION_H #define FAIRION_H -#include // for TNamed -#include // for Int_t, Double_t, etc +#include // for Int_t, Double_t, etc +#include // for TNamed class FairLogger; -class FairIon: public TNamed +class FairIon : public TNamed { public: /** Default constructor **/ @@ -43,64 +42,65 @@ class FairIon: public TNamed ** If mass is not given, it will be set to a times the proton mass. **/ - FairIon(const char* name, Int_t z, Int_t a, Int_t q, Double_t e=0., Double_t m=0.); - void SetParams(const char* name, Int_t z, Int_t a, Int_t q, Double_t e=0., Double_t m=0.) { - SetName(name); - fZ=z; - fA=a; - fQ=q; - fExcEnergy=e; - fMass=m; + FairIon(const char* name, Int_t z, Int_t a, Int_t q, Double_t e = 0., Double_t m = 0.); + void SetParams(const char* name, Int_t z, Int_t a, Int_t q, Double_t e = 0., Double_t m = 0.) + { + SetName(name); + fZ = z; + fA = a; + fQ = q; + fExcEnergy = e; + fMass = m; } /** Destructor **/ virtual ~FairIon(); /** Accessors **/ /** - * Return the atomic number - */ - Int_t GetZ() const { return fZ; } + * Return the atomic number + */ + Int_t GetZ() const { return fZ; } /** * Return the atomic mass - */ - Int_t GetA() const { return fA; } + */ + Int_t GetA() const { return fA; } /** * Return the charge - */ - Int_t GetQ() const { return fQ; } + */ + Int_t GetQ() const { return fQ; } /** - * Return the excitation energy - */ + * Return the excitation energy + */ Double_t GetExcEnergy() const { return fExcEnergy; } /** - * Return the mass in GeV - */ - Double_t GetMass() const { return fMass; } + * Return the mass in GeV + */ + Double_t GetMass() const { return fMass; } /** Modifiers **/ /** - * Set the excitation energy - */ + * Set the excitation energy + */ void SetExcEnergy(Double_t eExc) { fExcEnergy = eExc; } /** - * Set the mass in GeV - */ - void SetMass(Double_t mass) { fMass = mass*amu; } + * Set the mass in GeV + */ + void SetMass(Double_t mass) { fMass = mass * amu; } private: - static Int_t fgNIon; //! /// Number of ions instantiated. One per generator. - Int_t fZ; /// Atomic number - Int_t fA; /// Atomic mass - Int_t fQ; /// Electric charge - Double_t fExcEnergy; /// Excitation energy [GeV] - Double_t fMass; /// Mass [GeV] - FairLogger* fLogger; //! /// FairLogger - static const Double_t amu; /// .931494028 Gev/c**2 + static Int_t fgNIon; //! /// Number of ions instantiated. One per generator. + Int_t fZ; /// Atomic number + Int_t fA; /// Atomic mass + Int_t fQ; /// Electric charge + Double_t fExcEnergy; /// Excitation energy [GeV] + Double_t fMass; /// Mass [GeV] + FairLogger* fLogger; //! /// FairLogger + static const Double_t amu; /// .931494028 Gev/c**2 FairIon(const FairIon&); FairIon& operator=(const FairIon&); - ClassDef(FairIon,2); + ClassDef(FairIon, 2); }; #endif diff --git a/base/sim/FairMCApplication.cxx b/base/sim/FairMCApplication.cxx index 9e654d3ca5..8a0e9e166e 100644 --- a/base/sim/FairMCApplication.cxx +++ b/base/sim/FairMCApplication.cxx @@ -11,387 +11,237 @@ // ------------------------------------------------------------------------- #include "FairMCApplication.h" -#include "FairDetector.h" // for FairDetector -#include "FairField.h" // for FairField -#include "FairGenericStack.h" // for FairGenericStack -#include "FairGeoInterface.h" // for FairGeoInterface -#include "FairGeoLoader.h" // for FairGeoLoader -#include "FairGeoMedia.h" // for FairGeoMedia -#include "FairGeoMedium.h" // for FairGeoMedium -#include "FairIon.h" // for FairIon -#include "FairLogger.h" // for FairLogger, MESSAGE_ORIGIN -#include "FairMCEventHeader.h" // for FairMCEventHeader -#include "FairMesh.h" // for FairMesh -#include "FairModule.h" // for FairModule, etc -#include "FairParticle.h" // for FairParticle -#include "FairPrimaryGenerator.h" // for FairPrimaryGenerator -#include "FairRadGridManager.h" // for FairRadGridManager -#include "FairRadLenManager.h" // for FairRadLenManager -#include "FairRadMapManager.h" // for FairRadMapManager -#include "FairRootManager.h" // for FairRootManager -#include "FairRun.h" // for FairRun -#include "FairRunInfo.h" // for FairRunInfo -#include "FairRunSim.h" // for FairRunSim -#include "FairRuntimeDb.h" // for FairRuntimeDb -#include "FairTask.h" // for FairTask -#include "FairTrajFilter.h" // for FairTrajFilter -#include "FairVolume.h" // for FairVolume -#include "FairRootFileSink.h" // for CloneForWorker (in MT mode only) - -#include // for TDatabasePDG -#include // for gGeoManager, TGeoManager -#include // for TGeoMedium -#include // for TGeoNode -#include // for TGeoPhysicalNode -#include // for TGeoTrack -#include // for TGeoVolume -#include // for TH2D -#include // for TInterpreter, gInterpreter -#include // for TIterator -#include // for TList, TListIter -#include // for TObjArray -#include // for TObject -#include // for TParticlePDG -#include // for TROOT, gROOT -#include // for TRefArray -#include // for TSystem, gSystem -#include // for TVirtualMC -#include // for TVirtualMCStack -#include // for THashList -#include // for TFile +#include "FairDetector.h" // for FairDetector +#include "FairField.h" // for FairField +#include "FairGenericStack.h" // for FairGenericStack +#include "FairGeoInterface.h" // for FairGeoInterface +#include "FairGeoLoader.h" // for FairGeoLoader +#include "FairGeoMedia.h" // for FairGeoMedia +#include "FairGeoMedium.h" // for FairGeoMedium +#include "FairIon.h" // for FairIon +#include "FairLogger.h" // for FairLogger, MESSAGE_ORIGIN +#include "FairMCEventHeader.h" // for FairMCEventHeader +#include "FairMesh.h" // for FairMesh +#include "FairModule.h" // for FairModule, etc +#include "FairParticle.h" // for FairParticle +#include "FairPrimaryGenerator.h" // for FairPrimaryGenerator +#include "FairRadGridManager.h" // for FairRadGridManager +#include "FairRadLenManager.h" // for FairRadLenManager +#include "FairRadMapManager.h" // for FairRadMapManager +#include "FairRootFileSink.h" // for CloneForWorker (in MT mode only) +#include "FairRootManager.h" // for FairRootManager +#include "FairRun.h" // for FairRun +#include "FairRunInfo.h" // for FairRunInfo +#include "FairRunSim.h" // for FairRunSim +#include "FairRuntimeDb.h" // for FairRuntimeDb +#include "FairTask.h" // for FairTask +#include "FairTrajFilter.h" // for FairTrajFilter +#include "FairVolume.h" // for FairVolume + +#include // for TDatabasePDG +#include // for TFile +#include // for gGeoManager, TGeoManager +#include // for TGeoMedium +#include // for TGeoNode +#include // for TGeoPhysicalNode +#include // for TGeoTrack +#include // for TGeoVolume +#include // for TH2D +#include // for THashList +#include // for TInterpreter, gInterpreter +#include // for TIterator +#include // for TList, TListIter +#include // for TObjArray +#include // for TObject +#include // for TParticlePDG +#include // for TROOT, gROOT +#include // for TRefArray +#include // for TSystem, gSystem +#include // for TVirtualMC +#include // for TVirtualMCStack class TParticle; -#include // for DBL_MAX -#include // for getenv, exit -#include // for pair - -#include // std::mutex -std::mutex mtx; // mutex for critical section +#include // for DBL_MAX +#include // std::mutex +#include // for getenv, exit +#include // for pair +std::mutex mtx; // mutex for critical section using std::pair; FairMCApplication* FairMCApplication::fgMasterInstance = 0; //_____________________________________________________________________________ -FairMCApplication::FairMCApplication(const char* name, const char* title, - TObjArray* ModList, const char*) - :TVirtualMCApplication(name,title), - fActiveDetectors(nullptr), - fFairTaskList(nullptr), - fDetectors(nullptr), - fDetMap(nullptr), - fModIter(nullptr), - fModules(nullptr), - fNoSenVolumes(0), - fPythiaDecayer(kFALSE), - fPythiaDecayerConfig(""), - fStack(nullptr), - fRootManager(nullptr), - fSenVolumes(nullptr), - fxField(nullptr), - fEvGen(nullptr), - fMcVersion(-1), - fTrajFilter(nullptr), - fTrajAccepted(kFALSE), - fUserDecay(kFALSE), - fUserDecayConfig(""), - fDebug(kFALSE), - fDisVol(nullptr), - fDisDet(nullptr), - fVolMap(), - fVolIter(), - fModVolMap(), - fModVolIter(), - fTrkPos(TLorentzVector(0,0,0,0)), - fRadLength(kFALSE), - fRadLenMan(nullptr), - fRadMap(kFALSE), - fRadMapMan(nullptr), - fRadGridMan(nullptr), - fEventHeader(nullptr), - fMCEventHeader(nullptr), - listActiveDetectors(), - listDetectors(), - fMC(nullptr), - fRun(nullptr), - fSaveCurrentEvent(kTRUE), - fState(FairMCApplicationState::kUnknownState), - fRunInfo(), - fGeometryIsInitialized(kFALSE) +FairMCApplication::FairMCApplication(const char* name, const char* title, TObjArray* ModList, const char*) + : TVirtualMCApplication(name, title) + , fActiveDetectors(nullptr) + , fFairTaskList(nullptr) + , fDetectors(nullptr) + , fDetMap(nullptr) + , fModIter(nullptr) + , fModules(nullptr) + , fNoSenVolumes(0) + , fPythiaDecayer(kFALSE) + , fPythiaDecayerConfig("") + , fStack(nullptr) + , fRootManager(nullptr) + , fSenVolumes(nullptr) + , fxField(nullptr) + , fEvGen(nullptr) + , fMcVersion(-1) + , fTrajFilter(nullptr) + , fTrajAccepted(kFALSE) + , fUserDecay(kFALSE) + , fUserDecayConfig("") + , fDebug(kFALSE) + , fDisVol(nullptr) + , fDisDet(nullptr) + , fVolMap() + , fVolIter() + , fModVolMap() + , fModVolIter() + , fTrkPos(TLorentzVector(0, 0, 0, 0)) + , fRadLength(kFALSE) + , fRadLenMan(nullptr) + , fRadMap(kFALSE) + , fRadMapMan(nullptr) + , fRadGridMan(nullptr) + , fEventHeader(nullptr) + , fMCEventHeader(nullptr) + , listActiveDetectors() + , listDetectors() + , fMC(nullptr) + , fRun(nullptr) + , fSaveCurrentEvent(kTRUE) + , fState(FairMCApplicationState::kUnknownState) + , fRunInfo() + , fGeometryIsInitialized(kFALSE) { -// Standard Simulation constructor - -// Create an ObjArray of Modules and its iterator - - LOG(debug) << "FairMCApplication-ctor " << this; - - fRun=FairRunSim::Instance(); - fModules=ModList; - fModIter = fModules->MakeIterator(); -// Create and fill a list of active detectors - fDetectors=new TRefArray; - fActiveDetectors=new TRefArray(); - fModIter->Reset(); - FairDetector* detector; - TObject* obj; - - while((obj=fModIter->Next())) { - detector=dynamic_cast(obj); - if (detector) { - fDetectors->Add(detector); - listDetectors.push_back(detector); - if (detector->IsActive()) { - fActiveDetectors->Add(detector); - listActiveDetectors.push_back(detector); - } - } - else if (!dynamic_cast(obj)) { - LOG(error) << "Dynamic cast fails. Object neither FairDetector nor FairModule in module list"; - } - } - -// Create a Task list - fFairTaskList= new FairTask("Task List", 1); - gROOT->GetListOfBrowsables()->Add(fFairTaskList); - fMcVersion=-1; - // Initialise fTrajFilter pointer - fTrajFilter = nullptr; - fDetMap=new TRefArray(1000); - fDisVol=0; - fDisDet=0; - -// This ctor is used to construct the application on master - fgMasterInstance = this; -} + // Standard Simulation constructor -//_____________________________________________________________________________ -FairMCApplication::FairMCApplication(const FairMCApplication& rhs) - :TVirtualMCApplication(rhs.GetName(),rhs.GetTitle()), - fActiveDetectors(nullptr), - fFairTaskList(nullptr), - fDetectors(nullptr), - fDetMap(nullptr), - fModIter(nullptr), - fModules(nullptr), - fNoSenVolumes(0), - fPythiaDecayer(kFALSE), - fPythiaDecayerConfig(rhs.fPythiaDecayerConfig), - fStack(nullptr), - fRootManager(nullptr), - fSenVolumes(nullptr), - fxField(rhs.fxField), - fEvGen(nullptr), - fMcVersion(rhs.fMcVersion), - fTrajFilter(nullptr), - fTrajAccepted(kFALSE), - fUserDecay(kFALSE), - fUserDecayConfig(rhs.fUserDecayConfig), - fDebug(rhs.fDebug), - fDisVol(nullptr), - fDisDet(nullptr), - fVolMap(), - fVolIter(), - fModVolMap(), - fModVolIter(), - fTrkPos(rhs.fTrkPos), - fRadLength(kFALSE), - fRadLenMan(nullptr), - fRadMap(kFALSE), - fRadMapMan(nullptr), - fRadGridMan(nullptr), - fEventHeader(nullptr), - fMCEventHeader(nullptr), - listActiveDetectors(), - listDetectors(), - fMC(nullptr), - fRun(nullptr), - fSaveCurrentEvent(kTRUE), - fState(FairMCApplicationState::kUnknownState), - fRunInfo(), - fGeometryIsInitialized(kFALSE) -{ -// Copy constructor -// Do not create Root manager - - LOG(debug) << "FairMCApplication-copy-ctor " << this; - -// Create an ObjArray of Modules and its iterator - fModules=new TObjArray(); - fModIter = fModules->MakeIterator(); - // Clone modules - TObject* obj; - rhs.fModIter->Reset(); - while((obj=rhs.fModIter->Next())) { - LOG(debug) << "cloning " << (static_cast(obj))->GetName(); - fModules->Add(static_cast(obj)->CloneModule()); - } - -// Create and fill a list of active detectors - fDetectors=new TRefArray; - fActiveDetectors=new TRefArray(); - fModIter->Reset(); - FairDetector* detector; - while((obj=fModIter->Next())) { - if (obj->InheritsFrom("FairDetector")) { - detector=dynamic_cast(obj); - if (detector) { - fDetectors->Add(detector); - listDetectors.push_back(detector); - if (detector->IsActive()) { - fActiveDetectors->Add(detector); - listActiveDetectors.push_back(detector); + // Create an ObjArray of Modules and its iterator + + LOG(debug) << "FairMCApplication-ctor " << this; + + fRun = FairRunSim::Instance(); + fModules = ModList; + fModIter = fModules->MakeIterator(); + // Create and fill a list of active detectors + fDetectors = new TRefArray; + fActiveDetectors = new TRefArray(); + fModIter->Reset(); + FairDetector* detector; + TObject* obj; + + while ((obj = fModIter->Next())) { + detector = dynamic_cast(obj); + if (detector) { + fDetectors->Add(detector); + listDetectors.push_back(detector); + if (detector->IsActive()) { + fActiveDetectors->Add(detector); + listActiveDetectors.push_back(detector); + } + } else if (!dynamic_cast(obj)) { + LOG(error) << "Dynamic cast fails. Object neither FairDetector nor FairModule in module list"; } - } else { - LOG(error) << "Dynamic cast fails."; - } } - } - // Clone stack - fStack = rhs.fStack->CloneStack(); - -// Create a Task list - // Let's try without it - //fFairTaskList= new FairTask("Task List", 1); - //gROOT->GetListOfBrowsables()->Add(fFairTaskList); + // Create a Task list + fFairTaskList = new FairTask("Task List", 1); + gROOT->GetListOfBrowsables()->Add(fFairTaskList); + fMcVersion = -1; + // Initialise fTrajFilter pointer + fTrajFilter = nullptr; + fDetMap = new TRefArray(1000); + fDisVol = 0; + fDisDet = 0; - fDetMap=new TRefArray(1000); -} -//_____________________________________________________________________________ -FairMCApplication::FairMCApplication() - :TVirtualMCApplication(), - fActiveDetectors(0), - fFairTaskList(0), - fDetectors(0), - fDetMap(0), - fModIter(0), - fModules(0), - fNoSenVolumes(0), - fPythiaDecayer(kFALSE), - fPythiaDecayerConfig(""), - fStack(0), - fRootManager(0), - fSenVolumes(0), - fxField(0), - fEvGen(0), - fMcVersion(-1), - fTrajFilter(nullptr), - fTrajAccepted(kFALSE), - fUserDecay(kFALSE), - fUserDecayConfig(""), - fDebug(kFALSE), - fDisVol(0), - fDisDet(0), - fVolMap(), - fVolIter(), - fModVolMap(), - fModVolIter(), - fTrkPos(TLorentzVector(0,0,0,0)), - fRadLength(kFALSE), - fRadLenMan(nullptr), - fRadMap(kFALSE), - fRadMapMan(nullptr), - fRadGridMan(nullptr), - fEventHeader(nullptr), - fMCEventHeader(nullptr), - listActiveDetectors(), - listDetectors(), - fMC(nullptr), - fRun(nullptr), - fSaveCurrentEvent(kTRUE), - fState(FairMCApplicationState::kUnknownState), - fRunInfo(), - fGeometryIsInitialized(kFALSE) -{ -// Default constructor -} -//_____________________________________________________________________________ -FairMCApplication::~FairMCApplication() -{ -// Destructor -// LOG(debug3) << "Enter Destructor of FairMCApplication"; - delete fStack; - delete fActiveDetectors; // don't do fActiveDetectors->Delete() here - // the modules are already deleted in FairRunSim - delete fDetectors; - delete fModIter; - // LOG(debug3) << "Leave Destructor of FairMCApplication"; - delete fMC; + // This ctor is used to construct the application on master + fgMasterInstance = this; } //_____________________________________________________________________________ -FairMCApplication& FairMCApplication::operator=(const FairMCApplication& rhs) +FairMCApplication::FairMCApplication(const FairMCApplication& rhs) + : TVirtualMCApplication(rhs.GetName(), rhs.GetTitle()) + , fActiveDetectors(nullptr) + , fFairTaskList(nullptr) + , fDetectors(nullptr) + , fDetMap(nullptr) + , fModIter(nullptr) + , fModules(nullptr) + , fNoSenVolumes(0) + , fPythiaDecayer(kFALSE) + , fPythiaDecayerConfig(rhs.fPythiaDecayerConfig) + , fStack(nullptr) + , fRootManager(nullptr) + , fSenVolumes(nullptr) + , fxField(rhs.fxField) + , fEvGen(nullptr) + , fMcVersion(rhs.fMcVersion) + , fTrajFilter(nullptr) + , fTrajAccepted(kFALSE) + , fUserDecay(kFALSE) + , fUserDecayConfig(rhs.fUserDecayConfig) + , fDebug(rhs.fDebug) + , fDisVol(nullptr) + , fDisDet(nullptr) + , fVolMap() + , fVolIter() + , fModVolMap() + , fModVolIter() + , fTrkPos(rhs.fTrkPos) + , fRadLength(kFALSE) + , fRadLenMan(nullptr) + , fRadMap(kFALSE) + , fRadMapMan(nullptr) + , fRadGridMan(nullptr) + , fEventHeader(nullptr) + , fMCEventHeader(nullptr) + , listActiveDetectors() + , listDetectors() + , fMC(nullptr) + , fRun(nullptr) + , fSaveCurrentEvent(kTRUE) + , fState(FairMCApplicationState::kUnknownState) + , fRunInfo() + , fGeometryIsInitialized(kFALSE) { -// Assignment operator - - // check assignment to self - if (this != &rhs) { - - // base class assignment - TVirtualMCApplication::operator=(rhs); - - fActiveDetectors = nullptr; - fFairTaskList = nullptr; - fDetectors = nullptr; - fDetMap = nullptr; - fModIter = nullptr; - fModules = nullptr; - fNoSenVolumes = 0; - fPythiaDecayer = kFALSE; - fPythiaDecayerConfig = rhs.fPythiaDecayerConfig; - fStack = nullptr; - fRootManager = nullptr; - fSenVolumes = nullptr; - fxField = rhs.fxField; - fEvGen = nullptr; - fMcVersion = rhs.fMcVersion; - fTrajFilter = nullptr; - fTrajAccepted = kFALSE; - fUserDecay = kFALSE; - fUserDecayConfig = rhs.fUserDecayConfig; - fDebug = rhs.fDebug; - fDisVol = nullptr; - fDisDet = nullptr; - fTrkPos = rhs.fTrkPos; - fRadLength = kFALSE; - fRadLenMan = nullptr; - fRadMap = kFALSE; - fRadMapMan = nullptr; - fRadGridMan = nullptr; - fEventHeader = nullptr; - fMCEventHeader = nullptr; - fGeometryIsInitialized = kFALSE; - + // Copy constructor // Do not create Root manager + LOG(debug) << "FairMCApplication-copy-ctor " << this; + // Create an ObjArray of Modules and its iterator - fModules=new TObjArray(); + fModules = new TObjArray(); fModIter = fModules->MakeIterator(); // Clone modules TObject* obj; - while((obj=rhs.fModIter->Next())) { - fModules->Add(static_cast(obj)->CloneModule()); + rhs.fModIter->Reset(); + while ((obj = rhs.fModIter->Next())) { + LOG(debug) << "cloning " << (static_cast(obj))->GetName(); + fModules->Add(static_cast(obj)->CloneModule()); } // Create and fill a list of active detectors - fDetectors=new TRefArray; - fActiveDetectors=new TRefArray(); + fDetectors = new TRefArray; + fActiveDetectors = new TRefArray(); fModIter->Reset(); FairDetector* detector; - while((obj=fModIter->Next())) { - if (obj->InheritsFrom("FairDetector")) { - detector=dynamic_cast(obj); - if (detector) { - fDetectors->Add(detector); - listDetectors.push_back(detector); - if (detector->IsActive()) { - fActiveDetectors->Add(detector); - listActiveDetectors.push_back(detector); - } - } else { - LOG(error) << "Dynamic cast fails."; + while ((obj = fModIter->Next())) { + if (obj->InheritsFrom("FairDetector")) { + detector = dynamic_cast(obj); + if (detector) { + fDetectors->Add(detector); + listDetectors.push_back(detector); + if (detector->IsActive()) { + fActiveDetectors->Add(detector); + listActiveDetectors.push_back(detector); + } + } else { + LOG(error) << "Dynamic cast fails."; + } } - } } // Clone stack @@ -399,1112 +249,1235 @@ FairMCApplication& FairMCApplication::operator=(const FairMCApplication& rhs) // Create a Task list // Let's try without it - //fFairTaskList= new FairTask("Task List", 1); - //gROOT->GetListOfBrowsables()->Add(fFairTaskList); + // fFairTaskList= new FairTask("Task List", 1); + // gROOT->GetListOfBrowsables()->Add(fFairTaskList); + + fDetMap = new TRefArray(1000); +} +//_____________________________________________________________________________ +FairMCApplication::FairMCApplication() + : TVirtualMCApplication() + , fActiveDetectors(0) + , fFairTaskList(0) + , fDetectors(0) + , fDetMap(0) + , fModIter(0) + , fModules(0) + , fNoSenVolumes(0) + , fPythiaDecayer(kFALSE) + , fPythiaDecayerConfig("") + , fStack(0) + , fRootManager(0) + , fSenVolumes(0) + , fxField(0) + , fEvGen(0) + , fMcVersion(-1) + , fTrajFilter(nullptr) + , fTrajAccepted(kFALSE) + , fUserDecay(kFALSE) + , fUserDecayConfig("") + , fDebug(kFALSE) + , fDisVol(0) + , fDisDet(0) + , fVolMap() + , fVolIter() + , fModVolMap() + , fModVolIter() + , fTrkPos(TLorentzVector(0, 0, 0, 0)) + , fRadLength(kFALSE) + , fRadLenMan(nullptr) + , fRadMap(kFALSE) + , fRadMapMan(nullptr) + , fRadGridMan(nullptr) + , fEventHeader(nullptr) + , fMCEventHeader(nullptr) + , listActiveDetectors() + , listDetectors() + , fMC(nullptr) + , fRun(nullptr) + , fSaveCurrentEvent(kTRUE) + , fState(FairMCApplicationState::kUnknownState) + , fRunInfo() + , fGeometryIsInitialized(kFALSE) +{ + // Default constructor +} +//_____________________________________________________________________________ +FairMCApplication::~FairMCApplication() +{ + // Destructor + // LOG(debug3) << "Enter Destructor of FairMCApplication"; + delete fStack; + delete fActiveDetectors; // don't do fActiveDetectors->Delete() here + // the modules are already deleted in FairRunSim + delete fDetectors; + delete fModIter; + // LOG(debug3) << "Leave Destructor of FairMCApplication"; + delete fMC; +} + +//_____________________________________________________________________________ +FairMCApplication& FairMCApplication::operator=(const FairMCApplication& rhs) +{ + // Assignment operator + + // check assignment to self + if (this != &rhs) { + + // base class assignment + TVirtualMCApplication::operator=(rhs); + + fActiveDetectors = nullptr; + fFairTaskList = nullptr; + fDetectors = nullptr; + fDetMap = nullptr; + fModIter = nullptr; + fModules = nullptr; + fNoSenVolumes = 0; + fPythiaDecayer = kFALSE; + fPythiaDecayerConfig = rhs.fPythiaDecayerConfig; + fStack = nullptr; + fRootManager = nullptr; + fSenVolumes = nullptr; + fxField = rhs.fxField; + fEvGen = nullptr; + fMcVersion = rhs.fMcVersion; + fTrajFilter = nullptr; + fTrajAccepted = kFALSE; + fUserDecay = kFALSE; + fUserDecayConfig = rhs.fUserDecayConfig; + fDebug = rhs.fDebug; + fDisVol = nullptr; + fDisDet = nullptr; + fTrkPos = rhs.fTrkPos; + fRadLength = kFALSE; + fRadLenMan = nullptr; + fRadMap = kFALSE; + fRadMapMan = nullptr; + fRadGridMan = nullptr; + fEventHeader = nullptr; + fMCEventHeader = nullptr; + fGeometryIsInitialized = kFALSE; + + // Do not create Root manager + + // Create an ObjArray of Modules and its iterator + fModules = new TObjArray(); + fModIter = fModules->MakeIterator(); + // Clone modules + TObject* obj; + while ((obj = rhs.fModIter->Next())) { + fModules->Add(static_cast(obj)->CloneModule()); + } - fDetMap=new TRefArray(1000); + // Create and fill a list of active detectors + fDetectors = new TRefArray; + fActiveDetectors = new TRefArray(); + fModIter->Reset(); + FairDetector* detector; + while ((obj = fModIter->Next())) { + if (obj->InheritsFrom("FairDetector")) { + detector = dynamic_cast(obj); + if (detector) { + fDetectors->Add(detector); + listDetectors.push_back(detector); + if (detector->IsActive()) { + fActiveDetectors->Add(detector); + listActiveDetectors.push_back(detector); + } + } else { + LOG(error) << "Dynamic cast fails."; + } + } + } + + // Clone stack + fStack = rhs.fStack->CloneStack(); - fState = rhs.fState; - } + // Create a Task list + // Let's try without it + // fFairTaskList= new FairTask("Task List", 1); + // gROOT->GetListOfBrowsables()->Add(fFairTaskList); - return *this; + fDetMap = new TRefArray(1000); + + fState = rhs.fState; + } + return *this; } //_____________________________________________________________________________ void FairMCApplication::InitMC(const char*, const char*) { -// Initialize MC. -// --- -// This methode is called from FairRunSim::SetMCConfig which excucute first the gconfig -// macro that creates the MC instance (G3 or G4) - - fMC=TVirtualMC::GetMC(); - - if (fMC==0) { - LOG(fatal)<< "No MC engine defined"; - } - - fStack = dynamic_cast(fMC->GetStack()) ; - if (fStack==nullptr) { - LOG(fatal) << "No Stack defined."; - } - fMC->SetMagField(fxField); - - fRootManager = FairRootManager::Instance(); - //fRootManager->SetDebug(true); - - fMC->Init(); - fMC->BuildPhysics(); - TString MCName=fMC->GetName(); - if (MCName == "TGeant3" || MCName == "TGeant3TGeo") { - fMcVersion = 0 ; - } else if (MCName == "TGeant4") { - fMcVersion = 1; - } else if (MCName == "TFluka") { - fMcVersion = 2; - } else { - fMcVersion = 3; //Geane - } - fTrajFilter = FairTrajFilter::Instance(); - - LOG(info) << "Monte Carlo Engine Initialisation with: " << MCName.Data(); + // Initialize MC. + // --- + // This methode is called from FairRunSim::SetMCConfig which excucute first the gconfig + // macro that creates the MC instance (G3 or G4) + + fMC = TVirtualMC::GetMC(); + + if (fMC == 0) { + LOG(fatal) << "No MC engine defined"; + } + + fStack = dynamic_cast(fMC->GetStack()); + if (fStack == nullptr) { + LOG(fatal) << "No Stack defined."; + } + fMC->SetMagField(fxField); + + fRootManager = FairRootManager::Instance(); + // fRootManager->SetDebug(true); + + fMC->Init(); + fMC->BuildPhysics(); + TString MCName = fMC->GetName(); + if (MCName == "TGeant3" || MCName == "TGeant3TGeo") { + fMcVersion = 0; + } else if (MCName == "TGeant4") { + fMcVersion = 1; + } else if (MCName == "TFluka") { + fMcVersion = 2; + } else { + fMcVersion = 3; // Geane + } + fTrajFilter = FairTrajFilter::Instance(); + + LOG(info) << "Monte Carlo Engine Initialisation with: " << MCName.Data(); } //_____________________________________________________________________________ void FairMCApplication::RunMC(Int_t nofEvents) { - // Reset the time for FairRunInfo. Otherwise the time of the - // first event will include the time needed for initilization. - fRunInfo.Reset(); + // Reset the time for FairRunInfo. Otherwise the time of the + // first event will include the time needed for initilization. + fRunInfo.Reset(); - /** Set the list of active detectors to the stack*/ - fStack->SetDetArrayList(fActiveDetectors); + /** Set the list of active detectors to the stack*/ + fStack->SetDetArrayList(fActiveDetectors); - // MC run. - fMC->ProcessRun(nofEvents); - // finish run - FinishRun(); + // MC run. + fMC->ProcessRun(nofEvents); + // finish run + FinishRun(); } //____________________________________________________________________________ void FairMCApplication::FinishRun() { -// Finish MC run. -// --- - - LOG(debug) << "FairMCMCApplication::FinishRun() start"; - - for (auto detectorPtr : listActiveDetectors) - { - detectorPtr->FinishRun(); - } - - - // TO DO: clone this in MT mode ? - if (fFairTaskList) { - fFairTaskList->FinishTask(); - } - //fRootManager->Fill(); - - FairPrimaryGenerator* gen = FairRunSim::Instance()->GetPrimaryGenerator(); - //FairMCEventHeader* header = gen->GetEvent(); - Int_t nprimary = gen->GetTotPrimary(); - TObjArray* meshlist = nullptr; - - // Only in sequential mode - if (fRadGridMan) { - - meshlist = fRadGridMan->GetMeshList(); - - TH2D* tid = nullptr; - TH2D* flu = nullptr; - TH2D* seu = nullptr; - - LOG(info) << "======================================================="; - LOG(info) << " Dosimetry histos saving in \"" << fRadGridMan->GetOutputFileName() << "\""; - LOG(info) << "======================================================="; - - TFile* radGridFile = TFile::Open(fRadGridMan->GetOutputFileName(),"recreate"); - radGridFile->mkdir("Dosimetry"); - radGridFile->cd("Dosimetry"); - - for(Int_t i=0; iGetEntriesFast(); i++) { - FairMesh* aMesh = dynamic_cast(meshlist->At(i)); - if (aMesh) { - aMesh->Scale(1./nprimary); - tid = aMesh->GetMeshTid(); - flu = aMesh->GetMeshFlu(); - seu = aMesh->GetMeshSEU(); - tid->Write(); - flu->Write(); - seu->Write(); - } - } - radGridFile->Write(); - radGridFile->Close(); - delete radGridFile; - } - - // Save histograms with memory and runtime information in the output file - if (FairRunSim::Instance()->IsRunInfoGenerated()) { - fRunInfo.WriteInfo(); - } - - if (!fRadGridMan && fRootManager) { - fRootManager->Write(); - fRootManager->CloseSink(); - } - - if (! fMC->IsMT()) { - UndoGeometryModifications(); - } - - LOG(debug) << "Done FairMCMCApplication::FinishRun()"; + // Finish MC run. + // --- + + LOG(debug) << "FairMCMCApplication::FinishRun() start"; + + for (auto detectorPtr : listActiveDetectors) { + detectorPtr->FinishRun(); + } + + // TO DO: clone this in MT mode ? + if (fFairTaskList) { + fFairTaskList->FinishTask(); + } + // fRootManager->Fill(); + + FairPrimaryGenerator* gen = FairRunSim::Instance()->GetPrimaryGenerator(); + // FairMCEventHeader* header = gen->GetEvent(); + Int_t nprimary = gen->GetTotPrimary(); + TObjArray* meshlist = nullptr; + + // Only in sequential mode + if (fRadGridMan) { + + meshlist = fRadGridMan->GetMeshList(); + + TH2D* tid = nullptr; + TH2D* flu = nullptr; + TH2D* seu = nullptr; + + LOG(info) << "======================================================="; + LOG(info) << " Dosimetry histos saving in \"" << fRadGridMan->GetOutputFileName() << "\""; + LOG(info) << "======================================================="; + + TFile* radGridFile = TFile::Open(fRadGridMan->GetOutputFileName(), "recreate"); + radGridFile->mkdir("Dosimetry"); + radGridFile->cd("Dosimetry"); + + for (Int_t i = 0; i < meshlist->GetEntriesFast(); i++) { + FairMesh* aMesh = dynamic_cast(meshlist->At(i)); + if (aMesh) { + aMesh->Scale(1. / nprimary); + tid = aMesh->GetMeshTid(); + flu = aMesh->GetMeshFlu(); + seu = aMesh->GetMeshSEU(); + tid->Write(); + flu->Write(); + seu->Write(); + } + } + radGridFile->Write(); + radGridFile->Close(); + delete radGridFile; + } + + // Save histograms with memory and runtime information in the output file + if (FairRunSim::Instance()->IsRunInfoGenerated()) { + fRunInfo.WriteInfo(); + } + + if (!fRadGridMan && fRootManager) { + fRootManager->Write(); + fRootManager->CloseSink(); + } + + if (!fMC->IsMT()) { + UndoGeometryModifications(); + } + + LOG(debug) << "Done FairMCMCApplication::FinishRun()"; } //_____________________________________________________________________________ void FairMCApplication::BeginEvent() { -// User actions at beginning of event -// --- + // User actions at beginning of event + // --- - for (auto detectorPtr : listActiveDetectors) - { - detectorPtr->BeginEvent(); + for (auto detectorPtr : listActiveDetectors) { + detectorPtr->BeginEvent(); } } //_____________________________________________________________________________ void FairMCApplication::BeginPrimary() { -// User actions at beginning of a primary track -// --- - for (auto detectorPtr : listActiveDetectors) - { - detectorPtr->BeginPrimary(); + // User actions at beginning of a primary track + // --- + for (auto detectorPtr : listActiveDetectors) { + detectorPtr->BeginPrimary(); } } //_____________________________________________________________________________ void FairMCApplication::PreTrack() { -// User actions at beginning of each track -// --- - - for (auto detectorPtr : listActiveDetectors) - { - detectorPtr->PreTrack(); - } - - - fTrajAccepted=kFALSE; - if (nullptr != fTrajFilter) { - // Get the pointer to current track - TParticle* particle = fStack->GetCurrentTrack(); -// LOG(debug) << " FairMCApplication::PreTrack(): " << particle; - // Apply cuts - fTrajAccepted = fTrajFilter->IsAccepted(particle); - if (fTrajAccepted) { - // Add trajectory to geo manager - // Int_t trackId = fStack->GetCurrentTrackNumber(); - TGeoTrack* fTrack=fTrajFilter->CheckAddTrack(fMC->GetStack()->GetCurrentTrackNumber(),particle); - // TLorentzVector pos; - fMC->TrackPosition(fTrkPos); - fTrack->AddPoint(fTrkPos.X(), fTrkPos.Y(), fTrkPos.Z(), fTrkPos.T()); - } - } + // User actions at beginning of each track + // --- + + for (auto detectorPtr : listActiveDetectors) { + detectorPtr->PreTrack(); + } + + fTrajAccepted = kFALSE; + if (nullptr != fTrajFilter) { + // Get the pointer to current track + TParticle* particle = fStack->GetCurrentTrack(); + // LOG(debug) << " FairMCApplication::PreTrack(): " << particle; + // Apply cuts + fTrajAccepted = fTrajFilter->IsAccepted(particle); + if (fTrajAccepted) { + // Add trajectory to geo manager + // Int_t trackId = fStack->GetCurrentTrackNumber(); + TGeoTrack* fTrack = fTrajFilter->CheckAddTrack(fMC->GetStack()->GetCurrentTrackNumber(), particle); + // TLorentzVector pos; + fMC->TrackPosition(fTrkPos); + fTrack->AddPoint(fTrkPos.X(), fTrkPos.Y(), fTrkPos.Z(), fTrkPos.T()); + } + } } //_____________________________________________________________________________ TVirtualMCApplication* FairMCApplication::CloneForWorker() const { - mtx.lock(); - LOG(info) << "FairMCApplication::CloneForWorker "; - - // Create new FairRunSim object on worker - // and pass some data from master FairRunSim object - FairRunSim* workerRun = new FairRunSim(kFALSE); - workerRun->SetName(fRun->GetName()); // Transport engine - workerRun->SetSink(fRun->GetSink()->CloneSink()); - - // Trajectories filter is created explicitly as we do not call - // FairRunSim::Init on workers - if (fRun->GetStoreTraj()) { - new FairTrajFilter(); - } + mtx.lock(); + LOG(info) << "FairMCApplication::CloneForWorker "; + + // Create new FairRunSim object on worker + // and pass some data from master FairRunSim object + FairRunSim* workerRun = new FairRunSim(kFALSE); + workerRun->SetName(fRun->GetName()); // Transport engine + workerRun->SetSink(fRun->GetSink()->CloneSink()); + + // Trajectories filter is created explicitly as we do not call + // FairRunSim::Init on workers + if (fRun->GetStoreTraj()) { + new FairTrajFilter(); + } - // Create new FairMCApplication object on worker - FairMCApplication* workerApplication = new FairMCApplication(*this); - workerApplication->SetGenerator(fEvGen->ClonePrimaryGenerator()); + // Create new FairMCApplication object on worker + FairMCApplication* workerApplication = new FairMCApplication(*this); + workerApplication->SetGenerator(fEvGen->ClonePrimaryGenerator()); - mtx.unlock(); + mtx.unlock(); - return workerApplication; + return workerApplication; } //_____________________________________________________________________________ void FairMCApplication::InitOnWorker() { - // Create Root manager - fRootManager = FairRootManager::Instance(); + // Create Root manager + fRootManager = FairRootManager::Instance(); - LOG(info) << "FairMCApplication::InitForWorker " - << fRootManager->GetInstanceId() << " " << this; + LOG(info) << "FairMCApplication::InitForWorker " << fRootManager->GetInstanceId() << " " << this; - // Set FairRunSim worker(just for consistency, not needed on worker) - fRun = FairRunSim::Instance(); + // Set FairRunSim worker(just for consistency, not needed on worker) + fRun = FairRunSim::Instance(); - // Generate per-thread file name - // and create a new sink on worker - // moved to CloneForWorker and specific sink->CloneSink(); + // Generate per-thread file name + // and create a new sink on worker + // moved to CloneForWorker and specific sink->CloneSink(); - fRootManager->InitSink(); + fRootManager->InitSink(); - // Cache thread-local gMC - fMC = gMC; + // Cache thread-local gMC + fMC = gMC; - // Set data to MC - fMC->SetStack(fStack); - fMC->SetMagField(fxField); + // Set data to MC + fMC->SetStack(fStack); + fMC->SetMagField(fxField); - LOG(info) << "Monte Carlo Engine Worker Initialisation with: " << fMC->GetName(); + LOG(info) << "Monte Carlo Engine Worker Initialisation with: " << fMC->GetName(); } //_____________________________________________________________________________ void FairMCApplication::FinishRunOnWorker() { - LOG(debug) << "FairMCApplication::FinishRunOnWorker: "; + LOG(debug) << "FairMCApplication::FinishRunOnWorker: "; - FinishRun(); + FinishRun(); } //_____________________________________________________________________________ void FairMCApplication::Stepping() { -// User actions at each step -// --- - - // Work around for Fluka VMC, which does not call - // MCApplication::PreTrack() - static Int_t TrackId = 0; - if (fMcVersion ==2 || fMC->GetStack()->GetCurrentTrackNumber() != TrackId) { - PreTrack(); - TrackId = fMC->GetStack()->GetCurrentTrackNumber(); - } - - // Check if the volume with id is in the volume multimap. - // If it is not in the map the volume is not a sensitive volume - // and we do not call nay of our ProcessHits functions. - - // If the volume is in the multimap, check in second step if the current - // copy is alredy inside the multimap. - // If the volume is not in the multimap add the copy of the volume to the - // multimap. - // In any case call the ProcessHits function for this specific detector. - Int_t copyNo; - Int_t id = fMC->CurrentVolID(copyNo); - Bool_t InMap =kFALSE; - fDisVol=0; - fDisDet=0; - Int_t fCopyNo=0; - fVolIter =fVolMap.find(id); - - if (fVolIter!=fVolMap.end()) { - - // Call Process hits for FairVolume with this id, copyNo - do { - fDisVol=fVolIter->second; - fCopyNo=fDisVol->getCopyNo(); - if (copyNo==fCopyNo) { - fDisDet=fDisVol->GetDetector(); - if (fDisDet) { - fDisDet->ProcessHits(fDisVol); + // User actions at each step + // --- + + // Work around for Fluka VMC, which does not call + // MCApplication::PreTrack() + static Int_t TrackId = 0; + if (fMcVersion == 2 || fMC->GetStack()->GetCurrentTrackNumber() != TrackId) { + PreTrack(); + TrackId = fMC->GetStack()->GetCurrentTrackNumber(); + } + + // Check if the volume with id is in the volume multimap. + // If it is not in the map the volume is not a sensitive volume + // and we do not call nay of our ProcessHits functions. + + // If the volume is in the multimap, check in second step if the current + // copy is alredy inside the multimap. + // If the volume is not in the multimap add the copy of the volume to the + // multimap. + // In any case call the ProcessHits function for this specific detector. + Int_t copyNo; + Int_t id = fMC->CurrentVolID(copyNo); + Bool_t InMap = kFALSE; + fDisVol = 0; + fDisDet = 0; + Int_t fCopyNo = 0; + fVolIter = fVolMap.find(id); + + if (fVolIter != fVolMap.end()) { + + // Call Process hits for FairVolume with this id, copyNo + do { + fDisVol = fVolIter->second; + fCopyNo = fDisVol->getCopyNo(); + if (copyNo == fCopyNo) { + fDisDet = fDisVol->GetDetector(); + if (fDisDet) { + fDisDet->ProcessHits(fDisVol); + } + InMap = kTRUE; + break; + } + fVolIter++; + } while (fVolIter != fVolMap.upper_bound(id)); + + // if (fDisVol && !InMap) { // fDisVolume is set previously, no check needed + + // Create new FairVolume with this id, copyNo. + // Use the FairVolume with the same id found in the map to get + // the link to the detector. + // Seems that this never happens (?) + if (!InMap) { + // cout << "Volume not in map; fDisVol ? " << fDisVol << endl + FairVolume* fNewV = new FairVolume(fMC->CurrentVolName(), id); + fNewV->setMCid(id); + fNewV->setModId(fDisVol->getModId()); + fNewV->SetModule(fDisVol->GetModule()); + fNewV->setCopyNo(copyNo); + fVolMap.insert(pair(id, fNewV)); + fDisDet = fDisVol->GetDetector(); + + // LOG(info) << "FairMCApplication::Stepping: new fair volume" + // << id << " " << copyNo << " " << fDisDet; + if (fDisDet) { + fDisDet->ProcessHits(fNewV); + } } - InMap=kTRUE; - break; - } - fVolIter++; - } while (fVolIter != fVolMap.upper_bound(id)); - - // if (fDisVol && !InMap) { // fDisVolume is set previously, no check needed - - // Create new FairVolume with this id, copyNo. - // Use the FairVolume with the same id found in the map to get - // the link to the detector. - // Seems that this never happens (?) - if (!InMap) { - // cout << "Volume not in map; fDisVol ? " << fDisVol << endl - FairVolume* fNewV=new FairVolume(fMC->CurrentVolName(), id); - fNewV->setMCid(id); - fNewV->setModId(fDisVol->getModId()); - fNewV->SetModule(fDisVol->GetModule()); - fNewV->setCopyNo(copyNo); - fVolMap.insert(pair(id, fNewV)); - fDisDet=fDisVol->GetDetector(); - - // LOG(info) << "FairMCApplication::Stepping: new fair volume" - // << id << " " << copyNo << " " << fDisDet; - if (fDisDet) { - fDisDet->ProcessHits(fNewV); - } - } - } - - // If information about the tracks should be stored the information as to be - // stored for any step. - // Information about each single step has also to be stored for the other - // special run modes of the simulation which are used to store information - // about - // 1.) Radiation length in each volume - // 2.) Energy deposition in each volume - // 3.) Fluence of particles through a defined plane which can be anywhere - // in the geometry. This plane has not to be correlated with any real - // volume - if (fTrajAccepted) { - if (fMC->TrackStep() > fTrajFilter->GetStepSizeCut()) { - fMC->TrackPosition(fTrkPos); - fTrajFilter->GetCurrentTrk()->AddPoint(fTrkPos.X(), fTrkPos.Y(), fTrkPos.Z(), fTrkPos.T()); - } - } - if (fRadLenMan) { - id = fMC->CurrentVolID(copyNo); - fModVolIter = fgMasterInstance->fModVolMap.find(id); - fRadLenMan->AddPoint(fModVolIter->second); - } - if (fRadMapMan) { - id = fMC->CurrentVolID(copyNo); - fModVolIter = fgMasterInstance->fModVolMap.find(id); - fRadMapMan->AddPoint(fModVolIter->second); - } - if (fRadGridMan) { - fRadGridMan->FillMeshList(); - } + } + // If information about the tracks should be stored the information as to be + // stored for any step. + // Information about each single step has also to be stored for the other + // special run modes of the simulation which are used to store information + // about + // 1.) Radiation length in each volume + // 2.) Energy deposition in each volume + // 3.) Fluence of particles through a defined plane which can be anywhere + // in the geometry. This plane has not to be correlated with any real + // volume + if (fTrajAccepted) { + if (fMC->TrackStep() > fTrajFilter->GetStepSizeCut()) { + fMC->TrackPosition(fTrkPos); + fTrajFilter->GetCurrentTrk()->AddPoint(fTrkPos.X(), fTrkPos.Y(), fTrkPos.Z(), fTrkPos.T()); + } + } + if (fRadLenMan) { + id = fMC->CurrentVolID(copyNo); + fModVolIter = fgMasterInstance->fModVolMap.find(id); + fRadLenMan->AddPoint(fModVolIter->second); + } + if (fRadMapMan) { + id = fMC->CurrentVolID(copyNo); + fModVolIter = fgMasterInstance->fModVolMap.find(id); + fRadMapMan->AddPoint(fModVolIter->second); + } + if (fRadGridMan) { + fRadGridMan->FillMeshList(); + } } //_____________________________________________________________________________ void FairMCApplication::PostTrack() { -// User actions after finishing of each track -// --- - for (auto detectorPtr : listActiveDetectors) - { - detectorPtr->PostTrack(); - } - + // User actions after finishing of each track + // --- + for (auto detectorPtr : listActiveDetectors) { + detectorPtr->PostTrack(); + } } //_____________________________________________________________________________ void FairMCApplication::FinishPrimary() { -// User actions after finishing of a primary track -// --- - for (auto detectorPtr : listActiveDetectors) - { - detectorPtr->FinishPrimary(); - } - - fStack->FinishPrimary(); + // User actions after finishing of a primary track + // --- + for (auto detectorPtr : listActiveDetectors) { + detectorPtr->FinishPrimary(); + } + + fStack->FinishPrimary(); } //_____________________________________________________________________________ void FairMCApplication::StopRun() { - FinishEvent(); - FinishRun(); - if (fRootManager) { - fRootManager->Write(); - fRootManager->CloseSink(); - } - LOG(warn) << "StopRun() exiting not safetly oopps !!!@@@!!!"; - exit(0) ; + FinishEvent(); + FinishRun(); + if (fRootManager) { + fRootManager->Write(); + fRootManager->CloseSink(); + } + LOG(warn) << "StopRun() exiting not safetly oopps !!!@@@!!!"; + exit(0); } //_____________________________________________________________________________ void FairMCApplication::StopMCRun() { - if (fMC) fMC->StopRun(); + if (fMC) + fMC->StopRun(); } //_____________________________________________________________________________ void FairMCApplication::FinishEvent() { -// User actions after finishing of an event -// --- - LOG(debug) << "[" << fRootManager->GetInstanceId() << " FairMCMCApplication::FinishEvent: " << fMCEventHeader->GetEventID() << " (MC " << gMC->CurrentEvent() << ")"; - if ( gMC->IsMT() && fRun->GetSink()->GetSinkType() == kONLINESINK ) { // fix the rare case when running G4 multithreaded on MQ - fMCEventHeader->SetEventID(gMC->CurrentEvent()+1); - } - - // --> Fill the stack output array - fStack->FillTrackArray(); - // --> Update track indizes in MCTracks and MCPoints - fStack->UpdateTrackIndex(fActiveDetectors); - // --> Screen output of stack - // fStack->Print(); - - if (fFairTaskList) { - fFairTaskList->ExecuteTask(""); - fFairTaskList->FinishEvent(); - } - - for (auto detectorPtr : listActiveDetectors) - { - detectorPtr->FinishEvent(); - } - - if (fRootManager && fSaveCurrentEvent) { - fRootManager->Fill(); - } else { - fSaveCurrentEvent = kTRUE; - } - - for (auto detectorPtr : listActiveDetectors) - { - detectorPtr->EndOfEvent(); - } - - fStack->Reset(); - if (nullptr != fTrajFilter) { - fTrajFilter->Reset(); -// TObjArray* fListOfTracks=gGeoManager->GetListOfTracks(); -// fListOfTracks->Delete(); - gGeoManager->GetListOfTracks()->Delete(); - } - if (nullptr !=fRadLenMan) { - fRadLenMan->Reset(); - } - if (nullptr !=fRadMapMan) { - fRadMapMan->Reset(); - } - - // Store information about runtime for one event and memory consuption - // for later usage. - if ((FairRunSim::Instance()->IsRunInfoGenerated()) && ! gMC->IsMT()) { - fRunInfo.StoreInfo(); - } + // User actions after finishing of an event + // --- + LOG(debug) << "[" << fRootManager->GetInstanceId() + << " FairMCMCApplication::FinishEvent: " << fMCEventHeader->GetEventID() << " (MC " + << gMC->CurrentEvent() << ")"; + if (gMC->IsMT() + && fRun->GetSink()->GetSinkType() == kONLINESINK) { // fix the rare case when running G4 multithreaded on MQ + fMCEventHeader->SetEventID(gMC->CurrentEvent() + 1); + } + + // --> Fill the stack output array + fStack->FillTrackArray(); + // --> Update track indizes in MCTracks and MCPoints + fStack->UpdateTrackIndex(fActiveDetectors); + // --> Screen output of stack + // fStack->Print(); + + if (fFairTaskList) { + fFairTaskList->ExecuteTask(""); + fFairTaskList->FinishEvent(); + } + + for (auto detectorPtr : listActiveDetectors) { + detectorPtr->FinishEvent(); + } + + if (fRootManager && fSaveCurrentEvent) { + fRootManager->Fill(); + } else { + fSaveCurrentEvent = kTRUE; + } + + for (auto detectorPtr : listActiveDetectors) { + detectorPtr->EndOfEvent(); + } + + fStack->Reset(); + if (nullptr != fTrajFilter) { + fTrajFilter->Reset(); + // TObjArray* fListOfTracks=gGeoManager->GetListOfTracks(); + // fListOfTracks->Delete(); + gGeoManager->GetListOfTracks()->Delete(); + } + if (nullptr != fRadLenMan) { + fRadLenMan->Reset(); + } + if (nullptr != fRadMapMan) { + fRadMapMan->Reset(); + } + + // Store information about runtime for one event and memory consuption + // for later usage. + if ((FairRunSim::Instance()->IsRunInfoGenerated()) && !gMC->IsMT()) { + fRunInfo.StoreInfo(); + } } //_____________________________________________________________________________ Double_t FairMCApplication::TrackingRmax() const { -// No limit -// --- - return DBL_MAX; + // No limit + // --- + return DBL_MAX; } //_____________________________________________________________________________ Double_t FairMCApplication::TrackingZmax() const { -// No limit -// --- - return DBL_MAX; + // No limit + // --- + return DBL_MAX; } //_____________________________________________________________________________ -void FairMCApplication::SetField(FairField* field) -{ - fxField=field; -} +void FairMCApplication::SetField(FairField* field) { fxField = field; } //_____________________________________________________________________________ void FairMCApplication::ConstructOpGeometry() { - FairGeoLoader* loader=FairGeoLoader::Instance(); - FairGeoInterface* GeoInterface =loader->getGeoInterface(); - FairGeoMedia* media= GeoInterface->getMedia(); - TList* MediaList= media->getListOfMedia(); - TListIter iter(MediaList); - FairGeoMedium* medium; - Int_t NK=0; - Double_t p[4]; - while((medium=dynamic_cast(iter.Next()))) { - NK=medium->getNpckov(); - if (NK>0) { - Int_t Mid=0; - TGeoMedium* Med = 0; - if (gGeoManager && (Med = gGeoManager->GetMedium(medium->GetName()))) { - Mid=Med->GetId(); - } else { - Mid=medium->getMediumIndex(); - if (Mid<=0) { - continue; + FairGeoLoader* loader = FairGeoLoader::Instance(); + FairGeoInterface* GeoInterface = loader->getGeoInterface(); + FairGeoMedia* media = GeoInterface->getMedia(); + TList* MediaList = media->getListOfMedia(); + TListIter iter(MediaList); + FairGeoMedium* medium; + Int_t NK = 0; + Double_t p[4]; + while ((medium = dynamic_cast(iter.Next()))) { + NK = medium->getNpckov(); + if (NK > 0) { + Int_t Mid = 0; + TGeoMedium* Med = 0; + if (gGeoManager && (Med = gGeoManager->GetMedium(medium->GetName()))) { + Mid = Med->GetId(); + } else { + Mid = medium->getMediumIndex(); + if (Mid <= 0) { + continue; + } + } + Double_t ppckov[NK], absco[NK], effic[NK], rindex[NK]; + for (Int_t i = 0; i < NK; i++) { + medium->getCerenkovPar(i, p); + ppckov[i] = p[0] * 1E-9; + absco[i] = p[1]; + effic[i] = p[2]; + rindex[i] = p[3]; + } + TVirtualMC::GetMC()->SetCerenkov(Mid, NK, ppckov, absco, effic, rindex); } - } - Double_t ppckov[NK], absco[NK], effic[NK],rindex[NK]; - for (Int_t i=0; igetCerenkovPar(i, p); - ppckov[i]=p[0]*1E-9; - absco[i]=p[1]; - effic[i]=p[2]; - rindex[i]=p[3]; - } - TVirtualMC::GetMC()->SetCerenkov(Mid, NK, ppckov,absco, effic, rindex); - } - } - fModIter->Reset(); - FairModule* Mod=nullptr; - while((Mod = dynamic_cast(fModIter->Next()))) { - Mod->ConstructOpGeometry(); - } + } + fModIter->Reset(); + FairModule* Mod = nullptr; + while ((Mod = dynamic_cast(fModIter->Next()))) { + Mod->ConstructOpGeometry(); + } } //_____________________________________________________________________________ void FairMCApplication::ConstructGeometry() { -// Construct geometry and also fill following member data: -// - fModVolMap: (volId,moduleId) -// - fSenVolumes: list of sensitive volumes - if (!gGeoManager) { - LOG(fatal) << "gGeoManager not initialized at FairMCApplication::ConstructGeometry\n"; - } - - fState = FairMCApplicationState::kConstructGeometry; - - fModIter->Reset(); - FairModule* Mod=nullptr; - Int_t NoOfVolumes=0; - Int_t NoOfVolumesBefore=0; - Int_t ModId=0; - - TObjArray* tgeovolumelist = gGeoManager->GetListOfVolumes(); - - while((Mod = dynamic_cast(fModIter->Next()))) { - NoOfVolumesBefore=tgeovolumelist->GetEntriesFast(); - Mod->InitParContainers(); - Mod->ConstructGeometry(); - ModId=Mod->GetModId(); - NoOfVolumes=tgeovolumelist->GetEntriesFast(); - for (Int_t n=NoOfVolumesBefore; n < NoOfVolumes; n++) { - TGeoVolume* v = (TGeoVolume*) tgeovolumelist->At(n); - fModVolMap.insert(pair(v->GetNumber(),ModId)); - } - } - - // LOG(debug) << "FairMCApplication::ConstructGeometry() : Now closing the geometry"; - int NoOfVolumesBeforeClose = tgeovolumelist->GetEntries(); - gGeoManager->CloseGeometry(); // close geometry - int NoOfVolumesAfterClose = tgeovolumelist->GetEntries(); - - // Check if CloseGeometry has modified the volume list which might happen for - // runtime shapes (parametrizations,etc). If this is the case, our lookup structures - // built above are likely out of date. Issue at least a warning here. - if (NoOfVolumesBeforeClose != NoOfVolumesAfterClose) { - LOG(error) << "TGeoManager::CloseGeometry() modified the volume list from " << NoOfVolumesBeforeClose - << " to " << NoOfVolumesAfterClose << "\n" - << "This almost certainly means inconsistent lookup structures used in simulation/stepping.\n"; - } - - if (fRun->IsImportTGeoToVMC()) { - TVirtualMC::GetMC()->SetRootGeometry(); // notify VMC about Root geometry - LOG(info) << "TGeometry will be imported to VMC" << "\n"; - } - else { - LOG(info) << "TGeometry will not be imported to VMC" << "\n"; - } - Int_t Counter=0; - TDatabasePDG* pdgDatabase = TDatabasePDG::Instance(); - const THashList *list=pdgDatabase->ParticleList(); - if (list==0)pdgDatabase->ReadPDGTable(); - list =pdgDatabase->ParticleList(); - if (list!=0){ - TIterator *particleIter = list->MakeIterator(); - TParticlePDG *Particle=0; - while((Particle=dynamic_cast (particleIter->Next())) && (Counter <= 256)) { - TString Name= gGeoManager->GetPdgName(Particle->PdgCode()); - // LOG(info) << Counter <<" : Particle name: "<< Name.Data() << " PDG " << Particle->PdgCode(); - if (Name=="XXX") gGeoManager->SetPdgName(Particle->PdgCode(), Particle->GetName()); - Counter++; - } - delete particleIter; - } - fModIter->Reset(); - while((Mod = dynamic_cast(fModIter->Next()))) { - Mod->RegisterAlignmentMatrices(); - } - - // dont use this here anymore, use FairMCApplication::MisalignGeometry - // fRun->AlignGeometry() - - gGeoManager->RefreshPhysicalNodes(kFALSE); - - fState = FairMCApplicationState::kUnknownState; + // Construct geometry and also fill following member data: + // - fModVolMap: (volId,moduleId) + // - fSenVolumes: list of sensitive volumes + if (!gGeoManager) { + LOG(fatal) << "gGeoManager not initialized at FairMCApplication::ConstructGeometry\n"; + } + + fState = FairMCApplicationState::kConstructGeometry; + + fModIter->Reset(); + FairModule* Mod = nullptr; + Int_t NoOfVolumes = 0; + Int_t NoOfVolumesBefore = 0; + Int_t ModId = 0; + + TObjArray* tgeovolumelist = gGeoManager->GetListOfVolumes(); + + while ((Mod = dynamic_cast(fModIter->Next()))) { + NoOfVolumesBefore = tgeovolumelist->GetEntriesFast(); + Mod->InitParContainers(); + Mod->ConstructGeometry(); + ModId = Mod->GetModId(); + NoOfVolumes = tgeovolumelist->GetEntriesFast(); + for (Int_t n = NoOfVolumesBefore; n < NoOfVolumes; n++) { + TGeoVolume* v = (TGeoVolume*)tgeovolumelist->At(n); + fModVolMap.insert(pair(v->GetNumber(), ModId)); + } + } + + // LOG(debug) << "FairMCApplication::ConstructGeometry() : Now closing the geometry"; + int NoOfVolumesBeforeClose = tgeovolumelist->GetEntries(); + gGeoManager->CloseGeometry(); // close geometry + int NoOfVolumesAfterClose = tgeovolumelist->GetEntries(); + + // Check if CloseGeometry has modified the volume list which might happen for + // runtime shapes (parametrizations,etc). If this is the case, our lookup structures + // built above are likely out of date. Issue at least a warning here. + if (NoOfVolumesBeforeClose != NoOfVolumesAfterClose) { + LOG(error) << "TGeoManager::CloseGeometry() modified the volume list from " << NoOfVolumesBeforeClose << " to " + << NoOfVolumesAfterClose << "\n" + << "This almost certainly means inconsistent lookup structures used in simulation/stepping.\n"; + } + + if (fRun->IsImportTGeoToVMC()) { + TVirtualMC::GetMC()->SetRootGeometry(); // notify VMC about Root geometry + LOG(info) << "TGeometry will be imported to VMC" + << "\n"; + } else { + LOG(info) << "TGeometry will not be imported to VMC" + << "\n"; + } + Int_t Counter = 0; + TDatabasePDG* pdgDatabase = TDatabasePDG::Instance(); + const THashList* list = pdgDatabase->ParticleList(); + if (list == 0) + pdgDatabase->ReadPDGTable(); + list = pdgDatabase->ParticleList(); + if (list != 0) { + TIterator* particleIter = list->MakeIterator(); + TParticlePDG* Particle = 0; + while ((Particle = dynamic_cast(particleIter->Next())) && (Counter <= 256)) { + TString Name = gGeoManager->GetPdgName(Particle->PdgCode()); + // LOG(info) << Counter <<" : Particle name: "<< Name.Data() << " PDG " << Particle->PdgCode(); + if (Name == "XXX") + gGeoManager->SetPdgName(Particle->PdgCode(), Particle->GetName()); + Counter++; + } + delete particleIter; + } + fModIter->Reset(); + while ((Mod = dynamic_cast(fModIter->Next()))) { + Mod->RegisterAlignmentMatrices(); + } + + // dont use this here anymore, use FairMCApplication::MisalignGeometry + // fRun->AlignGeometry() + + gGeoManager->RefreshPhysicalNodes(kFALSE); + + fState = FairMCApplicationState::kUnknownState; } // ____________________________________________________________________________ Bool_t FairMCApplication::MisalignGeometry() { - // call this only here - fRun->AlignGeometry(); - return true; + // call this only here + fRun->AlignGeometry(); + return true; } //_____________________________________________________________________________ void FairMCApplication::InitGeometry() { - fState = FairMCApplicationState::kInitGeometry; - - LOG(info) << "FairMCApplication::InitGeometry: " - << fRootManager->GetInstanceId(); - - //ToBeDone - // Recently the InitGeometry is called twice from the G4VMC, This is a work around tell the problem get fixed in G4VMC - if (fGeometryIsInitialized) return; - - /// Initialize geometry - - /** Register stack and detector collections*/ - FairVolume* fv=0; - Int_t id=0; - fModIter->Reset(); - - // Register stack - if (fEvGen && fStack && fRootManager) { - fStack->Register(); - } else { - LOG(warn) << "Stack is not registered "; - } - - /** SetSpecialPhysicsCuts for FairDetector objects and all passive modules inheriting from FairModule */ - // initialize and register FairDetector objects in addition - // Note: listActiveDetectors or fActiveDetectors not used to include passive modules in the same loop. - FairModule* module; - FairDetector* detector; - TObject* obj; - fModIter->Reset(); - while((obj=fModIter->Next())) { - detector=dynamic_cast(obj); - module=dynamic_cast(obj); - if (module) { - module->SetSpecialPhysicsCuts(); - } - if (detector) { - // check whether detector is active - if (detector->IsActive()) { - detector->Initialize(); - detector->Register(); - } - } - } - fModIter->Reset(); - - /**Tasks has to be initialized here, they have access to the detector branches and still can create objects in the tree*/ - /// There is always a Main Task ! - /// so .. always a InitTasks() is called - if (fFairTaskList) { - InitTasks(); - } - - // store the EventHeader Info - // Get and register EventHeader - UInt_t runId = FairRunSim::Instance()->GetRunId(); - - LOG(info) << "Simulation RunID: " << runId; - - // Get and register the MCEventHeader - fMCEventHeader = FairRunSim::Instance()->GetMCEventHeader(); - fMCEventHeader->SetRunID(runId); - if (fRootManager) { - fMCEventHeader->Register(); - } - - if (fEvGen) { - fEvGen->SetEvent(fMCEventHeader); - } - fTrajFilter = FairTrajFilter::Instance(); - if (nullptr != fTrajFilter) { - fTrajFilter->Init(); - } - if (nullptr !=fRadLenMan) { - fRadLenMan->Init(); - } - if (nullptr !=fRadMapMan) { - fRadMapMan->Init(); - } - if (nullptr !=fRadGridMan) { - fRadGridMan->Init(); - } - - /// save Geo Params in Output file - if (fRootManager) { - fRootManager->WriteFolder(); - } - - // Get static thread local svList - fSenVolumes=FairModule::svList; - if (fSenVolumes) { - fNoSenVolumes=fSenVolumes->GetEntries(); - } - - // Fill sensitive volumes in fVolMap - for (Int_t i = 0 ; i < fNoSenVolumes ; i++) { - - fv= dynamic_cast(fSenVolumes->At(i)); - if (!fv) { - LOG(error) << "No FairVolume in fSenVolumes at position " << i; - continue; - } - id=fv->getMCid(); - if (fv->getGeoNode()==0) { - TGeoNode* fN=0; - TGeoVolume* v=gGeoManager->GetVolume(fv->GetName()); - TObjArray* fNs=0; - if (v) { - fNs=v->GetNodes(); - } - if (fNs) { - for(Int_t k=0; kGetEntriesFast(); k++) { - fN=dynamic_cast(fNs->At(k)); - if (!fN) { - LOG(error) << "No TGeoNode in fNs at position " << k; - continue; - } - FairVolume* fNewV=new FairVolume(fv->GetName(), id); - fNewV->setModId(fv->getModId()); - fNewV->SetModule(fv->GetModule()); - fNewV->setCopyNo(fN->GetNumber()); - fNewV->setMCid(id); - fVolMap.insert(pair(id, fNewV)); - } - } - else { - FairVolume* fNewV=new FairVolume(fv->GetName(), id); - fNewV->setModId(fv->getModId()); - fNewV->SetModule(fv->GetModule()); - fNewV->setCopyNo(1); - fNewV->setMCid(id); - fVolMap.insert(pair(id, fNewV)); - } + fState = FairMCApplicationState::kInitGeometry; + + LOG(info) << "FairMCApplication::InitGeometry: " << fRootManager->GetInstanceId(); + + // ToBeDone + // Recently the InitGeometry is called twice from the G4VMC, This is a work around tell the problem get fixed in + // G4VMC + if (fGeometryIsInitialized) + return; + + /// Initialize geometry + + /** Register stack and detector collections*/ + FairVolume* fv = 0; + Int_t id = 0; + fModIter->Reset(); + + // Register stack + if (fEvGen && fStack && fRootManager) { + fStack->Register(); } else { - fVolMap.insert(pair(id, fv)); + LOG(warn) << "Stack is not registered "; + } + + /** SetSpecialPhysicsCuts for FairDetector objects and all passive modules inheriting from FairModule */ + // initialize and register FairDetector objects in addition + // Note: listActiveDetectors or fActiveDetectors not used to include passive modules in the same loop. + FairModule* module; + FairDetector* detector; + TObject* obj; + fModIter->Reset(); + while ((obj = fModIter->Next())) { + detector = dynamic_cast(obj); + module = dynamic_cast(obj); + if (module) { + module->SetSpecialPhysicsCuts(); + } + if (detector) { + // check whether detector is active + if (detector->IsActive()) { + detector->Initialize(); + detector->Register(); + } + } + } + fModIter->Reset(); + + /**Tasks has to be initialized here, they have access to the detector branches and still can create objects in the + * tree*/ + /// There is always a Main Task ! + /// so .. always a InitTasks() is called + if (fFairTaskList) { + InitTasks(); + } + + // store the EventHeader Info + // Get and register EventHeader + UInt_t runId = FairRunSim::Instance()->GetRunId(); + + LOG(info) << "Simulation RunID: " << runId; + + // Get and register the MCEventHeader + fMCEventHeader = FairRunSim::Instance()->GetMCEventHeader(); + fMCEventHeader->SetRunID(runId); + if (fRootManager) { + fMCEventHeader->Register(); } - } // end off loop Fill sensitive volumes - fGeometryIsInitialized=kTRUE; + if (fEvGen) { + fEvGen->SetEvent(fMCEventHeader); + } + fTrajFilter = FairTrajFilter::Instance(); + if (nullptr != fTrajFilter) { + fTrajFilter->Init(); + } + if (nullptr != fRadLenMan) { + fRadLenMan->Init(); + } + if (nullptr != fRadMapMan) { + fRadMapMan->Init(); + } + if (nullptr != fRadGridMan) { + fRadGridMan->Init(); + } + + /// save Geo Params in Output file + if (fRootManager) { + fRootManager->WriteFolder(); + } - fState = FairMCApplicationState::kUnknownState; + // Get static thread local svList + fSenVolumes = FairModule::svList; + if (fSenVolumes) { + fNoSenVolumes = fSenVolumes->GetEntries(); + } + + // Fill sensitive volumes in fVolMap + for (Int_t i = 0; i < fNoSenVolumes; i++) { + + fv = dynamic_cast(fSenVolumes->At(i)); + if (!fv) { + LOG(error) << "No FairVolume in fSenVolumes at position " << i; + continue; + } + id = fv->getMCid(); + if (fv->getGeoNode() == 0) { + TGeoNode* fN = 0; + TGeoVolume* v = gGeoManager->GetVolume(fv->GetName()); + TObjArray* fNs = 0; + if (v) { + fNs = v->GetNodes(); + } + if (fNs) { + for (Int_t k = 0; k < fNs->GetEntriesFast(); k++) { + fN = dynamic_cast(fNs->At(k)); + if (!fN) { + LOG(error) << "No TGeoNode in fNs at position " << k; + continue; + } + FairVolume* fNewV = new FairVolume(fv->GetName(), id); + fNewV->setModId(fv->getModId()); + fNewV->SetModule(fv->GetModule()); + fNewV->setCopyNo(fN->GetNumber()); + fNewV->setMCid(id); + fVolMap.insert(pair(id, fNewV)); + } + } else { + FairVolume* fNewV = new FairVolume(fv->GetName(), id); + fNewV->setModId(fv->getModId()); + fNewV->SetModule(fv->GetModule()); + fNewV->setCopyNo(1); + fNewV->setMCid(id); + fVolMap.insert(pair(id, fNewV)); + } + } else { + fVolMap.insert(pair(id, fv)); + } + } // end off loop Fill sensitive volumes + + fGeometryIsInitialized = kTRUE; + + fState = FairMCApplicationState::kUnknownState; } //_____________________________________________________________________________ void FairMCApplication::GeneratePrimaries() { -// Fill the user stack (derived from TVirtualMCStack) with primary particles. -// --- - LOG(debug) << "FairMCApplication::GeneratePrimaries: " << fEvGen; - - if (fEvGen) { -// LOG(debug) << "FairMCApplication::GeneratePrimaries()"; - if (!fEvGen->GenerateEvent(fStack)) { - StopRun(); + // Fill the user stack (derived from TVirtualMCStack) with primary particles. + // --- + LOG(debug) << "FairMCApplication::GeneratePrimaries: " << fEvGen; + + if (fEvGen) { + // LOG(debug) << "FairMCApplication::GeneratePrimaries()"; + if (!fEvGen->GenerateEvent(fStack)) { + StopRun(); + } } - } } //_____________________________________________________________________________ FairDetector* FairMCApplication::GetDetector(const char* DetName) { - return dynamic_cast(fModules->FindObject(DetName)); + return dynamic_cast(fModules->FindObject(DetName)); } //_____________________________________________________________________________ -void FairMCApplication::AddIons() +void FairMCApplication::AddIons() { - TDatabasePDG* pdgDatabase = TDatabasePDG::Instance(); - TObjArray* NewIons=fRun->GetUserDefIons(); - TIterator* Iter=NewIons->MakeIterator(); - Iter->Reset(); - TObject* obj=0; - FairIon* ion=0; - while((obj=Iter->Next())) { - ion=dynamic_cast (obj); - if (ion) { - // Check if an ion with the calculated pdg code already exists in the - // TDatabasePDG. - // If the ion already exist don't create a new one because this fails for - // Geant4. Instead modify the FairIon to use the already existing ion - // from the TDatabasePDG. - // The problem occured for example for Alphas which exist already. - Int_t ionPdg = GetIonPdg(ion->GetZ(), ion->GetA()); - if (!pdgDatabase->GetParticle(ionPdg)) { - fMC->DefineIon(ion->GetName(), ion->GetZ(), ion->GetA(), ion->GetQ(), - ion->GetExcEnergy(),ion->GetMass()); - - } else { - ion->SetName(pdgDatabase->GetParticle(ionPdg)->GetName()); - } - //Add Ion to gGeoManager visualization - if (gGeoManager) { - gGeoManager->SetPdgName(pdgDatabase->GetParticle(ion->GetName())->PdgCode(),ion->GetName()); - } - LOG(info) << "Add Ion: " << ion->GetName() << " with PDG " << pdgDatabase->GetParticle(ion->GetName())->PdgCode(); - } - } - delete Iter; - /** Initialize the event generator */ - if (fEvGen) { - fEvGen->Init(); - } + TDatabasePDG* pdgDatabase = TDatabasePDG::Instance(); + TObjArray* NewIons = fRun->GetUserDefIons(); + TIterator* Iter = NewIons->MakeIterator(); + Iter->Reset(); + TObject* obj = 0; + FairIon* ion = 0; + while ((obj = Iter->Next())) { + ion = dynamic_cast(obj); + if (ion) { + // Check if an ion with the calculated pdg code already exists in the + // TDatabasePDG. + // If the ion already exist don't create a new one because this fails for + // Geant4. Instead modify the FairIon to use the already existing ion + // from the TDatabasePDG. + // The problem occured for example for Alphas which exist already. + Int_t ionPdg = GetIonPdg(ion->GetZ(), ion->GetA()); + if (!pdgDatabase->GetParticle(ionPdg)) { + fMC->DefineIon( + ion->GetName(), ion->GetZ(), ion->GetA(), ion->GetQ(), ion->GetExcEnergy(), ion->GetMass()); + + } else { + ion->SetName(pdgDatabase->GetParticle(ionPdg)->GetName()); + } + // Add Ion to gGeoManager visualization + if (gGeoManager) { + gGeoManager->SetPdgName(pdgDatabase->GetParticle(ion->GetName())->PdgCode(), ion->GetName()); + } + LOG(info) << "Add Ion: " << ion->GetName() << " with PDG " + << pdgDatabase->GetParticle(ion->GetName())->PdgCode(); + } + } + delete Iter; + /** Initialize the event generator */ + if (fEvGen) { + fEvGen->Init(); + } } //_____________________________________________________________________________ -void FairMCApplication::AddParticles() +void FairMCApplication::AddParticles() { - TObjArray* NewPart = fRun->GetUserDefParticles(); - TIterator* parIter = NewPart->MakeIterator(); - parIter->Reset(); - - // check MC engine is not null (fMC is 0x00 at this line in case of Geant4) - TVirtualMC* curMC = TVirtualMC::GetMC(); - if (!curMC) LOG(fatal)<<"No MC engine was defined before AddParticles()"; - - TObject* obj=0; - FairParticle* particle=0; - while ((obj = parIter->Next())) { - particle = dynamic_cast (obj); - if (particle) { // (Int_t pdg, const char* name, TMCParticleType type, Double_t mass, Double_t charge, Double_t lifetime); - LOG(info) << "Add Particle: " << particle->GetName() << " with PDG " << particle->GetPDG() << "\n"<< - particle->GetName() << " // const TString& name \n" << - particle->GetMCType()<<" // TMCParticleType mcType \n" << - particle->GetMass()<<" // Double_t mass \n" << - particle->GetCharge()<<" // Double_t charge \n" << - particle->GetDecayTime()<<" // Double_t lifetime \n" << - particle->GetPType()<< " // const TString& pType, \n" << - particle->GetWidth()<< " // Double_t width \n" << - particle->GetSpin()<< " // Int_t iSpin \n" << - particle->GetiParity()<< " // Int_t iParity \n" << - particle->GetConjugation()<<" // Int_t iConjugation \n" << - particle->GetIsospin()<< " // Int_t iIsospin \n" << - particle->GetIsospinZ()<< " // Int_t iIsospinZ \n" << - particle->GetgParity()<< " // Int_t gParity \n" << - particle->GetLepton()<< " // Int_t lepton \n" << - particle->GetBaryon()<< " // Int_t baryon \n" << - particle->IsStable() << " // Bool_t stable \n"; - - curMC->DefineParticle(particle->GetPDG(), // Int_t pdg - particle->GetName(), // const TString& name - particle->GetMCType(), // TMCParticleType mcType - particle->GetMass(), // Double_t mass - particle->GetCharge(), // Double_t charge - particle->GetDecayTime(), // Double_t lifetime - particle->GetPType(), // const TString& pType, - particle->GetWidth(), // Double_t width - particle->GetSpin(), // Int_t iSpin - particle->GetiParity(), // Int_t iParity - particle->GetConjugation(), // Int_t iConjugation - particle->GetIsospin(), // Int_t iIsospin - particle->GetIsospinZ(), // Int_t iIsospinZ - particle->GetgParity(), // Int_t gParity - particle->GetLepton(), // Int_t lepton - particle->GetBaryon(), // Int_t baryon - particle->IsStable() // Bool_t stable - ); - - //Add Particle to gGeoManager visualization - if (gGeoManager) - gGeoManager->SetPdgName(particle->GetPDG(), particle->GetName()); - } - } - - delete parIter; - AddDecayModes(); + TObjArray* NewPart = fRun->GetUserDefParticles(); + TIterator* parIter = NewPart->MakeIterator(); + parIter->Reset(); + + // check MC engine is not null (fMC is 0x00 at this line in case of Geant4) + TVirtualMC* curMC = TVirtualMC::GetMC(); + if (!curMC) + LOG(fatal) << "No MC engine was defined before AddParticles()"; + + TObject* obj = 0; + FairParticle* particle = 0; + while ((obj = parIter->Next())) { + particle = dynamic_cast(obj); + if (particle) { // (Int_t pdg, const char* name, TMCParticleType type, Double_t mass, Double_t charge, + // Double_t lifetime); + LOG(info) << "Add Particle: " << particle->GetName() << " with PDG " << particle->GetPDG() << "\n" + << particle->GetName() << " // const TString& name \n" + << particle->GetMCType() << " // TMCParticleType mcType \n" + << particle->GetMass() << " // Double_t mass \n" + << particle->GetCharge() << " // Double_t charge \n" + << particle->GetDecayTime() << " // Double_t lifetime \n" + << particle->GetPType() << " // const TString& pType, \n" + << particle->GetWidth() << " // Double_t width \n" + << particle->GetSpin() << " // Int_t iSpin \n" + << particle->GetiParity() << " // Int_t iParity \n" + << particle->GetConjugation() << " // Int_t iConjugation \n" + << particle->GetIsospin() << " // Int_t iIsospin \n" + << particle->GetIsospinZ() << " // Int_t iIsospinZ \n" + << particle->GetgParity() << " // Int_t gParity \n" + << particle->GetLepton() << " // Int_t lepton \n" + << particle->GetBaryon() << " // Int_t baryon \n" + << particle->IsStable() << " // Bool_t stable \n"; + + curMC->DefineParticle(particle->GetPDG(), // Int_t pdg + particle->GetName(), // const TString& name + particle->GetMCType(), // TMCParticleType mcType + particle->GetMass(), // Double_t mass + particle->GetCharge(), // Double_t charge + particle->GetDecayTime(), // Double_t lifetime + particle->GetPType(), // const TString& pType, + particle->GetWidth(), // Double_t width + particle->GetSpin(), // Int_t iSpin + particle->GetiParity(), // Int_t iParity + particle->GetConjugation(), // Int_t iConjugation + particle->GetIsospin(), // Int_t iIsospin + particle->GetIsospinZ(), // Int_t iIsospinZ + particle->GetgParity(), // Int_t gParity + particle->GetLepton(), // Int_t lepton + particle->GetBaryon(), // Int_t baryon + particle->IsStable() // Bool_t stable + ); + + // Add Particle to gGeoManager visualization + if (gGeoManager) + gGeoManager->SetPdgName(particle->GetPDG(), particle->GetName()); + } + } + + delete parIter; + AddDecayModes(); } //_____________________________________________________________________________ void FairMCApplication::AddDecayModes() { - TString work = getenv("VMCWORKDIR"); - TString work_config=work+"/gconfig/"; - work_config.ReplaceAll("//","/"); - - TString config_dir= getenv("CONFIG_DIR"); - config_dir.ReplaceAll("//","/"); + TString work = getenv("VMCWORKDIR"); + TString work_config = work + "/gconfig/"; + work_config.ReplaceAll("//", "/"); - Bool_t AbsPath=kFALSE; + TString config_dir = getenv("CONFIG_DIR"); + config_dir.ReplaceAll("//", "/"); - if (!config_dir.EndsWith("/")) { - config_dir+="/"; - } - // set Pythia as external decayer + Bool_t AbsPath = kFALSE; - if (fPythiaDecayer) { - TString decayConfig; - if (fPythiaDecayerConfig.IsNull()) { - decayConfig="DecayConfig.C"; - fPythiaDecayerConfig= decayConfig; - } else { - if (fPythiaDecayerConfig.Contains("/")) { - AbsPath=kTRUE; - } - decayConfig=fPythiaDecayerConfig; + if (!config_dir.EndsWith("/")) { + config_dir += "/"; } + // set Pythia as external decayer - if (!AbsPath && TString(gSystem->FindFile(config_dir.Data(), decayConfig)) != TString("")) { - LOG(info) << "---User path for Configuration (DecayConfig.C) is used : " - << config_dir.Data(); - } else { - if (AbsPath) { - decayConfig= fPythiaDecayerConfig; - } else { - decayConfig=work_config+ fPythiaDecayerConfig ; - } - } - // Add decay modes using an external configuration script - LOG(info) << "External Decay Modes with script \n " - << decayConfig.Data(); - // Load configuration script and execute it - Int_t pyt= gROOT->LoadMacro(decayConfig.Data()); - if (pyt==0) { - gInterpreter->ProcessLine("DecayConfig()"); - } - } - // set user defined phase space decay for particles (ions) - AbsPath=kFALSE; - if (fUserDecay) { - TString Userdecay; - if (fUserDecayConfig.IsNull()) { - Userdecay="UserDecay.C"; - fUserDecayConfig =Userdecay; - } else { - if (fUserDecayConfig.Contains("/")) { - AbsPath=kTRUE; - } - Userdecay= fUserDecayConfig; + if (fPythiaDecayer) { + TString decayConfig; + if (fPythiaDecayerConfig.IsNull()) { + decayConfig = "DecayConfig.C"; + fPythiaDecayerConfig = decayConfig; + } else { + if (fPythiaDecayerConfig.Contains("/")) { + AbsPath = kTRUE; + } + decayConfig = fPythiaDecayerConfig; + } + + if (!AbsPath && TString(gSystem->FindFile(config_dir.Data(), decayConfig)) != TString("")) { + LOG(info) << "---User path for Configuration (DecayConfig.C) is used : " << config_dir.Data(); + } else { + if (AbsPath) { + decayConfig = fPythiaDecayerConfig; + } else { + decayConfig = work_config + fPythiaDecayerConfig; + } + } + // Add decay modes using an external configuration script + LOG(info) << "External Decay Modes with script \n " << decayConfig.Data(); + // Load configuration script and execute it + Int_t pyt = gROOT->LoadMacro(decayConfig.Data()); + if (pyt == 0) { + gInterpreter->ProcessLine("DecayConfig()"); + } } + // set user defined phase space decay for particles (ions) + AbsPath = kFALSE; + if (fUserDecay) { + TString Userdecay; + if (fUserDecayConfig.IsNull()) { + Userdecay = "UserDecay.C"; + fUserDecayConfig = Userdecay; + } else { + if (fUserDecayConfig.Contains("/")) { + AbsPath = kTRUE; + } + Userdecay = fUserDecayConfig; + } - if (!AbsPath && TString(gSystem->FindFile(config_dir.Data(), Userdecay)) != TString("")) { - LOG(info) << "---User path for Configuration (UserDecay.C) is used : " - << config_dir.Data(); - } else { - if (AbsPath) { - Userdecay=fUserDecayConfig; - } else { - Userdecay=work_config+fUserDecayConfig; - } - } - LOG(info) << "User Decay Modes with script \n " - << Userdecay.Data(); - Int_t dec= gROOT->LoadMacro(Userdecay.Data()); - if (dec==0) { - gInterpreter->ProcessLine("UserDecayConfig()"); - } - } + if (!AbsPath && TString(gSystem->FindFile(config_dir.Data(), Userdecay)) != TString("")) { + LOG(info) << "---User path for Configuration (UserDecay.C) is used : " << config_dir.Data(); + } else { + if (AbsPath) { + Userdecay = fUserDecayConfig; + } else { + Userdecay = work_config + fUserDecayConfig; + } + } + LOG(info) << "User Decay Modes with script \n " << Userdecay.Data(); + Int_t dec = gROOT->LoadMacro(Userdecay.Data()); + if (dec == 0) { + gInterpreter->ProcessLine("UserDecayConfig()"); + } + } } //_____________________________________________________________________________ -FairPrimaryGenerator* FairMCApplication::GetGenerator() -{ - return fEvGen; -} +FairPrimaryGenerator* FairMCApplication::GetGenerator() { return fEvGen; } //_____________________________________________________________________________ -void FairMCApplication::SetGenerator(FairPrimaryGenerator* pGen) -{ - fEvGen=pGen; -} +void FairMCApplication::SetGenerator(FairPrimaryGenerator* pGen) { fEvGen = pGen; } //_____________________________________________________________________________ void FairMCApplication::AddTask(TTask* fTask) { - if (! fFairTaskList) { - fFairTaskList= new FairTask("Task List", 1); - gROOT->GetListOfBrowsables()->Add(fFairTaskList); - } - fFairTaskList->Add(fTask); - SetParTask(); + if (!fFairTaskList) { + fFairTaskList = new FairTask("Task List", 1); + gROOT->GetListOfBrowsables()->Add(fFairTaskList); + } + fFairTaskList->Add(fTask); + SetParTask(); } //_____________________________________________________________________________ -FairGenericStack* FairMCApplication::GetStack() -{ - return fStack; -} +FairGenericStack* FairMCApplication::GetStack() { return fStack; } //_____________________________________________________________________________ -TTask* FairMCApplication::GetListOfTasks() -{ - return fFairTaskList; -} +TTask* FairMCApplication::GetListOfTasks() { return fFairTaskList; } //_____________________________________________________________________________ void FairMCApplication::SetParTask() { - // Only RTDB init when more than Main Task list - if (FairRun::Instance()->GetNTasks() >= 1) { - fFairTaskList->SetParTask(); - } - fModIter->Reset(); - FairModule* Mod=nullptr; - while((Mod = dynamic_cast(fModIter->Next()))) { - Mod->SetParContainers(); - } - FairRuntimeDb* fRTdb= FairRun::Instance()->GetRuntimeDb(); - fRTdb->initContainers(FairRunSim::Instance()->GetRunId()); - + // Only RTDB init when more than Main Task list + if (FairRun::Instance()->GetNTasks() >= 1) { + fFairTaskList->SetParTask(); + } + fModIter->Reset(); + FairModule* Mod = nullptr; + while ((Mod = dynamic_cast(fModIter->Next()))) { + Mod->SetParContainers(); + } + FairRuntimeDb* fRTdb = FairRun::Instance()->GetRuntimeDb(); + fRTdb->initContainers(FairRunSim::Instance()->GetRunId()); } //_____________________________________________________________________________ void FairMCApplication::InitTasks() { - // Only RTDB init when more than Main Task list - if (FairRun::Instance()->GetNTasks() >= 1) { - LOG(info) << "Initialize Tasks--------------------------"; - fFairTaskList->InitTask(); - - } + // Only RTDB init when more than Main Task list + if (FairRun::Instance()->GetNTasks() >= 1) { + LOG(info) << "Initialize Tasks--------------------------"; + fFairTaskList->InitTask(); + } } //_____________________________________________________________________________ TChain* FairMCApplication::GetChain() { - if (fRootManager) { - return fRootManager->GetInChain(); - } else { - LOG(warn) << "The function is not available in MT mode"; - return 0; - } + if (fRootManager) { + return fRootManager->GetInChain(); + } else { + LOG(warn) << "The function is not available in MT mode"; + return 0; + } } //_____________________________________________________________________________ -void FairMCApplication::SetRadiationLengthReg(Bool_t RadLen) +void FairMCApplication::SetRadiationLengthReg(Bool_t RadLen) { - fRadLength=RadLen; - if (fRadLength) { - fRadLenMan= new FairRadLenManager(); - } + fRadLength = RadLen; + if (fRadLength) { + fRadLenMan = new FairRadLenManager(); + } } //_____________________________________________________________________________ -void FairMCApplication::SetRadiationMapReg(Bool_t RadMap) +void FairMCApplication::SetRadiationMapReg(Bool_t RadMap) { - fRadMap=RadMap; - if (fRadMap) { - fRadMapMan= new FairRadMapManager(); - } + fRadMap = RadMap; + if (fRadMap) { + fRadMapMan = new FairRadMapManager(); + } } //_____________________________________________________________________________ -void FairMCApplication::AddMeshList(TObjArray* meshList) +void FairMCApplication::AddMeshList(TObjArray* meshList) { - if (!fRadGridMan) { - fRadGridMan = new FairRadGridManager(); - } - fRadGridMan->AddMeshList (meshList); + if (!fRadGridMan) { + fRadGridMan = new FairRadGridManager(); + } + fRadGridMan->AddMeshList(meshList); } //_____________________________________________________________________________ Int_t FairMCApplication::GetIonPdg(Int_t z, Int_t a) const { - // Acording to - // http://pdg.lbl.gov/2012/reviews/rpp2012-rev-monte-carlo-numbering.pdf + // Acording to + // http://pdg.lbl.gov/2012/reviews/rpp2012-rev-monte-carlo-numbering.pdf - return 1000000000 + 10*1000*z + 10*a; + return 1000000000 + 10 * 1000 * z + 10 * a; } //_____________________________________________________________________________ -void FairMCApplication::UndoGeometryModifications() +void FairMCApplication::UndoGeometryModifications() { - // Undo all misalignment done in the MisalignGeometry methods of the - // several FairModuls. - // In the output (parameter container and separate geometry file) - // only the ideal geometry is stored. - // I don't know any better way than to loop over all physical nodes - // and to set the matrix back to the original one. - // TODO: Check if it is more easy to write the ideal geometry before - // the geometry is misaligned. In this case one does not have - // to revert the misalignment. - - TObjArray* physNodes = gGeoManager->GetListOfPhysicalNodes(); - Int_t numPhysNodes=physNodes->GetEntriesFast(); - - if (0 == numPhysNodes) return; - - //fRootManager->CreateGeometryFile("misaligned_geometry.root"); - LOG(info)<<"Undo all misalignment"; - - TGeoPhysicalNode* node = nullptr; - TGeoHMatrix* ng3 = nullptr; - for(Int_t k=0; k(physNodes->At(k)); - ng3 = node->GetOriginalMatrix(); //"real" global matrix, what survey sees - node->Align(ng3); - } - - gGeoManager->ClearPhysicalNodes(kFALSE); + // Undo all misalignment done in the MisalignGeometry methods of the + // several FairModuls. + // In the output (parameter container and separate geometry file) + // only the ideal geometry is stored. + // I don't know any better way than to loop over all physical nodes + // and to set the matrix back to the original one. + // TODO: Check if it is more easy to write the ideal geometry before + // the geometry is misaligned. In this case one does not have + // to revert the misalignment. + + TObjArray* physNodes = gGeoManager->GetListOfPhysicalNodes(); + Int_t numPhysNodes = physNodes->GetEntriesFast(); + + if (0 == numPhysNodes) + return; + + // fRootManager->CreateGeometryFile("misaligned_geometry.root"); + LOG(info) << "Undo all misalignment"; + + TGeoPhysicalNode* node = nullptr; + TGeoHMatrix* ng3 = nullptr; + for (Int_t k = 0; k < numPhysNodes; k++) { + node = static_cast(physNodes->At(k)); + ng3 = node->GetOriginalMatrix(); //"real" global matrix, what survey sees + node->Align(ng3); + } + gGeoManager->ClearPhysicalNodes(kFALSE); } -ClassImp(FairMCApplication) +ClassImp(FairMCApplication); diff --git a/base/sim/FairMCApplication.h b/base/sim/FairMCApplication.h index a4d4887734..739fc4fd9d 100644 --- a/base/sim/FairMCApplication.h +++ b/base/sim/FairMCApplication.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -13,16 +13,14 @@ #ifndef FAIR_MC_APPLICATION_H #define FAIR_MC_APPLICATION_H +#include "FairRunInfo.h" // for FairRunInfo -#include "FairRunInfo.h" // for FairRunInfo - -#include // for TVirtualMCApplication -#include // for Int_t, Bool_t, Double_t, etc -#include // for TLorentzVector -#include // for TString - -#include // for map, multimap, etc -#include // for list +#include // for Int_t, Bool_t, Double_t, etc +#include // for TLorentzVector +#include // for TString +#include // for TVirtualMCApplication +#include // for list +#include // for map, multimap, etc class FairDetector; class FairEventHeader; @@ -45,7 +43,12 @@ class TRefArray; class TTask; class TVirtualMC; -enum class FairMCApplicationState {kUnknownState, kConstructGeometry, kInitGeometry}; +enum class FairMCApplicationState +{ + kUnknownState, + kConstructGeometry, + kInitGeometry +}; /** * The Main Application ( Interface to MonteCarlo application ) @@ -58,69 +61,69 @@ class FairMCApplication : public TVirtualMCApplication { public: /** Standard constructor - *@param name name - *@param title title - *@param ModList a TObjArray containing all detectors and modules used in this simulation - *@param MatName material file name - */ - FairMCApplication(const char* name, const char* title, TObjArray* ModList, const char* MatName); + *@param name name + *@param title title + *@param ModList a TObjArray containing all detectors and modules used in this simulation + *@param MatName material file name + */ + FairMCApplication(const char* name, const char* title, TObjArray* ModList, const char* MatName); /** default constructor - */ + */ FairMCApplication(); /** default destructor - */ + */ virtual ~FairMCApplication(); /** Singelton instance - */ + */ static FairMCApplication* Instance(); - virtual void AddDecayModes(); + virtual void AddDecayModes(); /** Add user defined particles (optional) */ - virtual void AddParticles(); // MC Application + virtual void AddParticles(); // MC Application /** Add user defined ions (optional) */ - virtual void AddIons(); // MC Application + virtual void AddIons(); // MC Application /** - *Add user defined Tasks to be executed after each event (optional) - * @param fTask: Task that has to be excuted during simulation - */ - void AddTask(TTask* fTask); + *Add user defined Tasks to be executed after each event (optional) + * @param fTask: Task that has to be excuted during simulation + */ + void AddTask(TTask* fTask); /** Define actions at the beginning of the event */ - virtual void BeginEvent(); // MC Application + virtual void BeginEvent(); // MC Application /** Define actions at the beginning of primary track */ - virtual void BeginPrimary(); // MC Application + virtual void BeginPrimary(); // MC Application /** Construct user geometry */ - virtual void ConstructGeometry(); // MC Application + virtual void ConstructGeometry(); // MC Application /** Align or misalign geometry before actual run */ - virtual Bool_t MisalignGeometry(); + virtual Bool_t MisalignGeometry(); /** Define parameters for optical processes (optional) */ - virtual void ConstructOpGeometry(); // MC Application + virtual void ConstructOpGeometry(); // MC Application /** Define actions at the end of event */ - virtual void FinishEvent(); // MC Application + virtual void FinishEvent(); // MC Application /** Define actions at the end of primary track */ - virtual void FinishPrimary(); // MC Application + virtual void FinishPrimary(); // MC Application /** Define actions at the end of run */ - void FinishRun(); + void FinishRun(); /** Generate primary particles */ - virtual void GeneratePrimaries(); // MC Application + virtual void GeneratePrimaries(); // MC Application /** Return detector by name */ - FairDetector* GetDetector(const char* DetName); + FairDetector* GetDetector(const char* DetName); /** Return Field used in simulation*/ - FairField* GetField() {return fxField;} + FairField* GetField() { return fxField; } /**Return primary generator*/ - FairPrimaryGenerator* GetGenerator(); + FairPrimaryGenerator* GetGenerator(); /**Return list of tasks*/ - TTask* GetListOfTasks(); - FairGenericStack* GetStack(); - TChain* GetChain(); + TTask* GetListOfTasks(); + FairGenericStack* GetStack(); + TChain* GetChain(); /** Initialize geometry */ - virtual void InitGeometry(); // MC Application + virtual void InitGeometry(); // MC Application /** Initialize MC engine */ - void InitMC(const char* setup, const char* cuts); + void InitMC(const char* setup, const char* cuts); /** Initialize Tasks if any*/ - void InitTasks(); + void InitTasks(); /**Define actions at the end of each track */ - virtual void PostTrack(); // MC Application + virtual void PostTrack(); // MC Application /** Define actions at the beginning of each track*/ - virtual void PreTrack(); // MC Application + virtual void PreTrack(); // MC Application /** Clone for worker (used in MT mode only) */ virtual TVirtualMCApplication* CloneForWorker() const; @@ -134,70 +137,72 @@ class FairMCApplication : public TVirtualMCApplication /** Run the MC engine * @param nofEvents : number of events to simulate */ - void RunMC(Int_t nofEvents); + void RunMC(Int_t nofEvents); /** - * Set the magnetic field for simulation - * @param field: magnetic field - */ - void SetField(FairField* field); + * Set the magnetic field for simulation + * @param field: magnetic field + */ + void SetField(FairField* field); /** * Set the event generator for simulation * @param fxGenerator: Event generator(s) */ - void SetGenerator(FairPrimaryGenerator* fxGenerator); + void SetGenerator(FairPrimaryGenerator* fxGenerator); /** * Set the parameter containers needed by Tasks(if any) */ - void SetParTask(); + void SetParTask(); /** * Switch for using Pythia as external decayer - * @param decayer: if TRUE pythia will decay particles specifid in the Decay Config macro (see SetPythiaDecayerConfig) + * @param decayer: if TRUE pythia will decay particles specifid in the Decay Config macro (see + * SetPythiaDecayerConfig) */ - void SetPythiaDecayer(Bool_t decayer) {fPythiaDecayer=decayer;} + void SetPythiaDecayer(Bool_t decayer) { fPythiaDecayer = decayer; } /** - * set the decay configuration macro to be used by Pythia - */ - void SetPythiaDecayerConfig(const TString decayerConf) {fPythiaDecayerConfig=decayerConf;} + * set the decay configuration macro to be used by Pythia + */ + void SetPythiaDecayerConfig(const TString decayerConf) { fPythiaDecayerConfig = decayerConf; } /** - * Switch for using the radiation length manager - */ - void SetRadiationLengthReg(Bool_t RadLen); + * Switch for using the radiation length manager + */ + void SetRadiationLengthReg(Bool_t RadLen); /** - * Switch for using the radiation map manager - */ - void SetRadiationMapReg(Bool_t RadMap); + * Switch for using the radiation map manager + */ + void SetRadiationMapReg(Bool_t RadMap); /** - * Switch for debuging the tracking - */ - void SetTrackingDebugMode( Bool_t set ) {fDebug = set;} + * Switch for debuging the tracking + */ + void SetTrackingDebugMode(Bool_t set) { fDebug = set; } /** - * Switch for using 2 or 3 body phase-space decay - * @param decay: if TRUE 2/3 body phase space decay will be used for particle specified in the User Decay Config macro (see SetUserDecayConfig) - */ - void SetUserDecay(Bool_t decay) {fUserDecay= decay;} + * Switch for using 2 or 3 body phase-space decay + * @param decay: if TRUE 2/3 body phase space decay will be used for particle specified in the User Decay Config + * macro (see SetUserDecayConfig) + */ + void SetUserDecay(Bool_t decay) { fUserDecay = decay; } /** - * set the decay configuration macro to be used by user decay - */ - void SetUserDecayConfig(const TString decayerConf) {fUserDecayConfig= decayerConf;} + * set the decay configuration macro to be used by user decay + */ + void SetUserDecayConfig(const TString decayerConf) { fUserDecayConfig = decayerConf; } /** Define action at each step, dispatch the action to the corresponding detectors */ - virtual void Stepping(); // MC Application + virtual void Stepping(); // MC Application /** Stop the run*/ - virtual void StopRun(); + virtual void StopRun(); /** Stop the run*/ - virtual void StopMCRun(); + virtual void StopMCRun(); /**Define maximum radius for tracking (optional) */ - virtual Double_t TrackingRmax() const; // MC Application + virtual Double_t TrackingRmax() const; // MC Application /** Define maximum z for tracking (optional) */ - virtual Double_t TrackingZmax() const; // MC Application + virtual Double_t TrackingZmax() const; // MC Application - void AddMeshList ( TObjArray* meshList ); + void AddMeshList(TObjArray* meshList); /** - * Set if the current event should be written to the output file. - * The default value which is set back after each event is to store - * the event. - */ - void SetSaveCurrentEvent(Bool_t set) {fSaveCurrentEvent=set;} + * Set if the current event should be written to the output file. + * The default value which is set back after each event is to store + * the event. + */ + void SetSaveCurrentEvent(Bool_t set) { fSaveCurrentEvent = set; } /** * Get the current application state. @@ -213,100 +218,101 @@ class FairMCApplication : public TVirtualMCApplication protected: // data members /**List of active detector */ - TRefArray* fActiveDetectors; + TRefArray* fActiveDetectors; /**List of FairTask*/ - FairTask* fFairTaskList;//! + FairTask* fFairTaskList; //! /**detector list (Passive and Active)*/ - TRefArray* fDetectors; + TRefArray* fDetectors; /**Map used for dispatcher*/ - TRefArray* fDetMap; + TRefArray* fDetMap; /**Iterator for Module list*/ - TIterator* fModIter; //! + TIterator* fModIter; //! /**Module list in simulation*/ - TObjArray* fModules; + TObjArray* fModules; /**Number of sensetive volumes in simulation session*/ - Int_t fNoSenVolumes; //! + Int_t fNoSenVolumes; //! /**flag for using Pythia as external decayer */ - Bool_t fPythiaDecayer; + Bool_t fPythiaDecayer; /** Pythia decay config macro*/ - TString fPythiaDecayerConfig; //! + TString fPythiaDecayerConfig; //! /** Simulation Stack */ - FairGenericStack* fStack; //! + FairGenericStack* fStack; //! /**Pointer to thr I/O Manager */ - FairRootManager* fRootManager; //! + FairRootManager* fRootManager; //! /**List of sensetive volumes in all detectors*/ - TRefArray* fSenVolumes; //! + TRefArray* fSenVolumes; //! /**Magnetic Field Pointer*/ - FairField* fxField; // + FairField* fxField; // /**Primary generator*/ - FairPrimaryGenerator* fEvGen; // + FairPrimaryGenerator* fEvGen; // /**MC Engine 1= Geant3, 2 = Geant4*/ - Int_t fMcVersion; // mc Version + Int_t fMcVersion; // mc Version /** Track visualization manager */ - FairTrajFilter* fTrajFilter; //! + FairTrajFilter* fTrajFilter; //! /**Flag for accepted tracks for visualization*/ - Bool_t fTrajAccepted; //! + Bool_t fTrajAccepted; //! /**Flag for using user decay*/ - Bool_t fUserDecay; + Bool_t fUserDecay; /**User decay config macro*/ - TString fUserDecayConfig; //! + TString fUserDecayConfig; //! /** Debug flag*/ - Bool_t fDebug;//! + Bool_t fDebug; //! /**dispatcher internal use */ - FairVolume* fDisVol; + FairVolume* fDisVol; /**dispatcher internal use */ - FairDetector* fDisDet; + FairDetector* fDisDet; /**dispatcher internal use */ - std::multimap fVolMap;//! + std::multimap fVolMap; //! /**dispatcher internal use */ - std::multimap ::iterator fVolIter; //! + std::multimap::iterator fVolIter; //! /** Track position*/ /**dispatcher internal use RadLeng*/ - std::map fModVolMap;//! + std::map fModVolMap; //! /**dispatcher internal use RadLen*/ - std::map ::iterator fModVolIter; //! - TLorentzVector fTrkPos; //! + std::map::iterator fModVolIter; //! + TLorentzVector fTrkPos; //! /** Flag for Radiation length register mode */ - Bool_t fRadLength; //! + Bool_t fRadLength; //! /**Radiation length Manager*/ - FairRadLenManager* fRadLenMan; //! + FairRadLenManager* fRadLenMan; //! /** Flag for Radiation map register mode */ - Bool_t fRadMap; //! + Bool_t fRadMap; //! /**Radiation Map Manager*/ - FairRadMapManager* fRadMapMan; //! + FairRadMapManager* fRadMapMan; //! /**Radiation map Grid Manager*/ - FairRadGridManager* fRadGridMan; //! + FairRadGridManager* fRadGridMan; //! - FairEventHeader* fEventHeader; //! + FairEventHeader* fEventHeader; //! - FairMCEventHeader* fMCEventHeader; //! + FairMCEventHeader* fMCEventHeader; //! /** list of senstive detectors used in the simuation session*/ - std::list listActiveDetectors; //! + std::list listActiveDetectors; //! /** list of all detectors used in the simuation session*/ - std::list listDetectors; //! + std::list listDetectors; //! /** Pointer to the current MC engine //! */ - TVirtualMC* fMC; + TVirtualMC* fMC; /** Pointer to FairRunSim //! */ - FairRunSim* fRun; + FairRunSim* fRun; /** Flag if the current event should be saved */ Bool_t fSaveCurrentEvent; /** Current state */ - FairMCApplicationState fState; //! + FairMCApplicationState fState; //! - ClassDef(FairMCApplication,4) //Interface to MonteCarlo application + ClassDef(FairMCApplication, 4) // Interface to MonteCarlo application - private: - /** Protected copy constructor */ - FairMCApplication(const FairMCApplication&); + private + : + /** Protected copy constructor */ + FairMCApplication(const FairMCApplication&); /** Protected assignment operator */ FairMCApplication& operator=(const FairMCApplication&); - FairRunInfo fRunInfo;//! - Bool_t fGeometryIsInitialized; + FairRunInfo fRunInfo; //! + Bool_t fGeometryIsInitialized; static FairMCApplication* fgMasterInstance; }; @@ -314,6 +320,8 @@ class FairMCApplication : public TVirtualMCApplication // inline functions inline FairMCApplication* FairMCApplication::Instance() -{ return static_cast(TVirtualMCApplication::Instance());} +{ + return static_cast(TVirtualMCApplication::Instance()); +} #endif diff --git a/base/sim/FairModule.cxx b/base/sim/FairModule.cxx index 573e71756b..dbc7b70c10 100644 --- a/base/sim/FairModule.cxx +++ b/base/sim/FairModule.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -12,445 +12,451 @@ /* Generated by Together */ #include "FairModule.h" -#include "FairGeoParSet.h" // for FairBaseParSet -#include "FairGeoBuilder.h" // for FairGeoBuilder -#include "FairGeoInterface.h" // for FairGeoInterface -#include "FairGeoLoader.h" // for FairGeoLoader -#include "FairGeoMedia.h" // for FairGeoMedia -#include "FairGeoNode.h" // for FairGeoNode -#include "FairRun.h" // for FairRun -#include "FairRuntimeDb.h" // for FairRuntimeDb -#include "FairVolume.h" // for FairVolume -#include "FairVolumeList.h" // for FairVolumeList +#include "FairGeoBuilder.h" // for FairGeoBuilder +#include "FairGeoInterface.h" // for FairGeoInterface +#include "FairGeoLoader.h" // for FairGeoLoader +#include "FairGeoMedia.h" // for FairGeoMedia +#include "FairGeoNode.h" // for FairGeoNode +#include "FairGeoParSet.h" // for FairBaseParSet #include "FairMCApplication.h" - -#include // for TBuffer, operator<<, etc -#include // for TIter -#include // for TFile -#include // for TGeoManager, gGeoManager -#include // for TGeoMedium -#include // for TGeoMaterial -#include // for TGeoMatrix, TGeoHMatrix -#include // for TGeoNode -#include // for TGeoVolume -#include // for TGeoVoxelFinder -#include // for TKey -#include // for TList, TListIter -#include // for TObjArray -#include // for TObject -#include // for TRefArray -#include // for TSystem, gSystem +#include "FairRun.h" // for FairRun +#include "FairRuntimeDb.h" // for FairRuntimeDb +#include "FairVolume.h" // for FairVolume +#include "FairVolumeList.h" // for FairVolumeList + +#include // for TBuffer, operator<<, etc +#include // for TIter +#include // for TFile +#include // for TGeoManager, gGeoManager +#include // for TGeoMaterial +#include // for TGeoMatrix, TGeoHMatrix +#include // for TGeoMedium +#include // for TGeoNode +#include // for TGeoVolume +#include // for TGeoVoxelFinder +#include // for TKey +#include // for TList, TListIter +#include // for TObjArray +#include // for TObject +#include // for TRefArray +#include // for TSystem, gSystem #include #ifdef ROOT_HAS_GDML #include #endif -#include // for getenv -#include // for strcmp, strlen #include +#include // for getenv +#include // for strcmp, strlen class FairGeoMedium; -thread_local TArrayI* FairModule::volNumber=0; -thread_local Int_t FairModule::fNbOfVolumes=0; -thread_local FairVolumeList* FairModule::vList=0; -thread_local TRefArray* FairModule::svList=0; +thread_local TArrayI* FairModule::volNumber = 0; +thread_local Int_t FairModule::fNbOfVolumes = 0; +thread_local FairVolumeList* FairModule::vList = 0; +thread_local TRefArray* FairModule::svList = 0; void FairModule::ConstructGeometry() { - LOG(warn)<<"The method ConstructGeometry has to be implemented in the detector class which inherits from FairModule"; + LOG(warn) + << "The method ConstructGeometry has to be implemented in the detector class which inherits from FairModule"; } void FairModule::ConstructOpGeometry() { - LOG(debug2)<<"The method ConstructOpGeometry has to be implemented in the detector class which inherits from FairModule"; -} - -FairModule::~FairModule() -{ - + LOG(debug2) + << "The method ConstructOpGeometry has to be implemented in the detector class which inherits from FairModule"; } -FairModule::FairModule(const char* Name, const char* title ,Bool_t Active) - :TNamed(Name, title), - fMotherVolumeName(""), - fgeoVer("Not defined"), - fgeoName("Not defined"), - fModId(-1), - fActive(Active), - fNbOfSensitiveVol(0), - fVerboseLevel(0), - flGeoPar(0), - fGeoSaved(kFALSE), - fMC(0) +FairModule::~FairModule() {} + +FairModule::FairModule(const char* Name, const char* title, Bool_t Active) + : TNamed(Name, title) + , fMotherVolumeName("") + , fgeoVer("Not defined") + , fgeoName("Not defined") + , fModId(-1) + , fActive(Active) + , fNbOfSensitiveVol(0) + , fVerboseLevel(0) + , flGeoPar(0) + , fGeoSaved(kFALSE) + , fMC(0) { - if(!svList) { svList=new TRefArray(); } - if(!vList) { vList=new FairVolumeList(); } - + if (!svList) { + svList = new TRefArray(); + } + if (!vList) { + vList = new FairVolumeList(); + } } FairModule::FairModule(const FairModule& rhs) - :TNamed(rhs), - fMotherVolumeName(rhs.fMotherVolumeName), - fgeoVer(rhs.fgeoVer), - fgeoName(rhs.fgeoName), - fModId(rhs.fModId), - fActive(rhs.fActive), - fNbOfSensitiveVol(rhs.fNbOfSensitiveVol), - fVerboseLevel(rhs.fVerboseLevel), - flGeoPar(0), - fGeoSaved(rhs.fGeoSaved), - fMC(0) + : TNamed(rhs) + , fMotherVolumeName(rhs.fMotherVolumeName) + , fgeoVer(rhs.fgeoVer) + , fgeoName(rhs.fgeoName) + , fModId(rhs.fModId) + , fActive(rhs.fActive) + , fNbOfSensitiveVol(rhs.fNbOfSensitiveVol) + , fVerboseLevel(rhs.fVerboseLevel) + , flGeoPar(0) + , fGeoSaved(rhs.fGeoSaved) + , fMC(0) { - if(!svList) { - svList=new TRefArray(); - for (Int_t i=0; i < rhs.svList->GetEntries(); i++) { - svList->Add(rhs.svList->At(i)); + if (!svList) { + svList = new TRefArray(); + for (Int_t i = 0; i < rhs.svList->GetEntries(); i++) { + svList->Add(rhs.svList->At(i)); + } } - } - if(!vList) { - vList=new FairVolumeList(); - for (Int_t i=0; i < rhs.vList->getEntries(); i++) { - vList->addVolume(rhs.vList->At(i)); + if (!vList) { + vList = new FairVolumeList(); + for (Int_t i = 0; i < rhs.vList->getEntries(); i++) { + vList->addVolume(rhs.vList->At(i)); + } } - } - - // Initialize cached pointer to MC (on worker) - fMC = TVirtualMC::GetMC(); - - // TO DO - add when we know what type is the elements of flGeoPar - //flGeoPar=new TObjArray(); - //TIter it = rhs.flGeoPar->MakeIterator(); - // Copy parameters - //TObject* obj; - //while((obj=it->Next())) { - // flGeoPar->Add(...); - //} + // Initialize cached pointer to MC (on worker) + fMC = TVirtualMC::GetMC(); + + // TO DO - add when we know what type is the elements of flGeoPar + // flGeoPar=new TObjArray(); + // TIter it = rhs.flGeoPar->MakeIterator(); + // Copy parameters + // TObject* obj; + // while((obj=it->Next())) { + // flGeoPar->Add(...); + //} } FairModule::FairModule() - : TNamed(), - fMotherVolumeName(""), - fgeoVer("Not defined"), - fgeoName("Not defined"), - fModId(-1), - fActive(kFALSE), - fNbOfSensitiveVol(0), - fVerboseLevel(0), - flGeoPar(0), - fGeoSaved(kFALSE) -{ -} - -FairModule& FairModule::operator= (const FairModule& rhs) + : TNamed() + , fMotherVolumeName("") + , fgeoVer("Not defined") + , fgeoName("Not defined") + , fModId(-1) + , fActive(kFALSE) + , fNbOfSensitiveVol(0) + , fVerboseLevel(0) + , flGeoPar(0) + , fGeoSaved(kFALSE) +{} + +FairModule& FairModule::operator=(const FairModule& rhs) { - // check assignment to self - if (this == &rhs) return *this; - - // base class assignment - TNamed::operator=(rhs); - - // assignment operator - fMotherVolumeName = rhs.fMotherVolumeName; - fgeoVer = rhs.fgeoVer; - fgeoName = rhs.fgeoName; - fModId = rhs.fModId; - fActive = rhs.fActive; - fNbOfSensitiveVol = rhs.fNbOfSensitiveVol; - fVerboseLevel = rhs.fVerboseLevel; - flGeoPar = 0; - fGeoSaved = rhs.fGeoSaved; - - // TO DO - add when we know what type is the elements of flGeoPar - //flGeoPar=new TObjArray(); - //TIter it = rhs.flGeoPar->MakeIterator(); - // copy parameters - //TObject* obj; - //while((obj=it->Next())) { - // flGeoPar->Add(...); - //} - - return *this; + // check assignment to self + if (this == &rhs) + return *this; + + // base class assignment + TNamed::operator=(rhs); + + // assignment operator + fMotherVolumeName = rhs.fMotherVolumeName; + fgeoVer = rhs.fgeoVer; + fgeoName = rhs.fgeoName; + fModId = rhs.fModId; + fActive = rhs.fActive; + fNbOfSensitiveVol = rhs.fNbOfSensitiveVol; + fVerboseLevel = rhs.fVerboseLevel; + flGeoPar = 0; + fGeoSaved = rhs.fGeoSaved; + + // TO DO - add when we know what type is the elements of flGeoPar + // flGeoPar=new TObjArray(); + // TIter it = rhs.flGeoPar->MakeIterator(); + // copy parameters + // TObject* obj; + // while((obj=it->Next())) { + // flGeoPar->Add(...); + //} + + return *this; } void FairModule::Streamer(TBuffer& b) { - TNamed::Streamer(b); - - - if (b.IsReading()) { - fgeoVer.Streamer(b); - fgeoName.Streamer(b); - b >> fActive; - b >> fModId; - } else { - fgeoVer.Streamer(b); - fgeoName.Streamer(b); - b << fActive; - b << fModId; - } + TNamed::Streamer(b); + if (b.IsReading()) { + fgeoVer.Streamer(b); + fgeoName.Streamer(b); + b >> fActive; + b >> fModId; + } else { + fgeoVer.Streamer(b); + fgeoName.Streamer(b); + b << fActive; + b << fModId; + } } void FairModule::SetGeometryFileName(TString fname, TString) { - // If absolute path is given as argument, try to find it there. - // If the file don't exist break. Don't look anywhere else. - if ( fname.BeginsWith("/") ) { - if ( gSystem->AccessPathName(fname.Data()) ) { - LOG(fatal) << fName << ": geometry file " << fname - << " not found in absolut path!"; - fgeoName = ""; - } // file not found - fgeoName = fname; - LOG(debug) << fName << ": using geometry file " - << fgeoName; - return; - } - - // If GEOMPATH is set, try to find the file there. - // If there is no such file go on to look in the default location. - TString userPath = getenv("GEOMPATH"); - userPath.ReplaceAll("//","/"); - if ( ! userPath.IsNull() ) { - if ( ! userPath.EndsWith("/") ) { - userPath += "/"; - } - fgeoName = userPath + fname; - if ( ! gSystem->AccessPathName(fgeoName.Data()) ) { - LOG(debug) << fName << ": using geometry file " << fgeoName; - return; - } - LOG(debug) << fName << ": geometry file " << fname - << " not found in GEOMPATH " - << userPath; - } - - // Look in the standard path - fgeoName = getenv("VMCWORKDIR"); - fgeoName += "/geometry/" + fname; - if ( ! gSystem->AccessPathName(fgeoName.Data()) ) { - LOG(debug) << fName << ": using geometry file " - << fgeoName; - return; - } + // If absolute path is given as argument, try to find it there. + // If the file don't exist break. Don't look anywhere else. + if (fname.BeginsWith("/")) { + if (gSystem->AccessPathName(fname.Data())) { + LOG(fatal) << fName << ": geometry file " << fname << " not found in absolut path!"; + fgeoName = ""; + } // file not found + fgeoName = fname; + LOG(debug) << fName << ": using geometry file " << fgeoName; + return; + } - // File not found - LOG(fatal) << fName << ": geometry file " << fname - << " not found in standard path "; - fgeoName = ""; - return; + // If GEOMPATH is set, try to find the file there. + // If there is no such file go on to look in the default location. + TString userPath = getenv("GEOMPATH"); + userPath.ReplaceAll("//", "/"); + if (!userPath.IsNull()) { + if (!userPath.EndsWith("/")) { + userPath += "/"; + } + fgeoName = userPath + fname; + if (!gSystem->AccessPathName(fgeoName.Data())) { + LOG(debug) << fName << ": using geometry file " << fgeoName; + return; + } + LOG(debug) << fName << ": geometry file " << fname << " not found in GEOMPATH " << userPath; + } + + // Look in the standard path + fgeoName = getenv("VMCWORKDIR"); + fgeoName += "/geometry/" + fname; + if (!gSystem->AccessPathName(fgeoName.Data())) { + LOG(debug) << fName << ": using geometry file " << fgeoName; + return; + } + // File not found + LOG(fatal) << fName << ": geometry file " << fname << " not found in standard path "; + fgeoName = ""; + return; } void FairModule::ProcessNodes(TList* aList) { - if(FairMCApplicationState::kConstructGeometry != FairMCApplication::Instance()->GetState()) - { - LOG(fatal) << "Detected call to FairModule::ProcessNodes() \ + if (FairMCApplicationState::kConstructGeometry != FairMCApplication::Instance()->GetState()) { + LOG(fatal) << "Detected call to FairModule::ProcessNodes() \ while not in FairMCApplication::ConstructGeometry()\n\ Call templated function FairModule::ConstructASCIIGeometry()\ from ConstructGeometry() of your detector class. Aborting..."; - } - - if(!svList) { svList=new TRefArray(); } - if(!vList) { vList=new FairVolumeList(); } - - TListIter iter(aList); - FairGeoNode* node = nullptr; - FairGeoNode* MotherNode = nullptr; - FairVolume* volume = nullptr; - FairRuntimeDb* rtdb = FairRun::Instance()->GetRuntimeDb(); - FairGeoParSet* par = static_cast(rtdb->getContainer("FairGeoParSet")); - TObjArray* fNodes = par->GetGeoNodes(); - while( (node = static_cast(iter.Next())) ) { - - node->calcLabTransform(); - MotherNode=node->getMotherNode(); - volume = new FairVolume( node->getTruncName(), fNbOfVolumes++); - volume->setRealName(node->GetName()); - vList->addVolume(volume); - volume->setGeoNode(node); - volume->setCopyNo( node->getCopyNo()); - - if(MotherNode!=0) { - volume->setMotherId(node->getMCid()); - volume->setMotherCopyNo(MotherNode->getCopyNo()); - } - FairGeoVolume* aVol=nullptr; - - if ( node->isSensitive() && fActive ) { - volume->setModId(fModId); - volume->SetModule(this); - svList->Add(volume); - aVol = dynamic_cast ( node ); - fNodes->AddLast( aVol ); - fNbOfSensitiveVol++; - } - } + } + + if (!svList) { + svList = new TRefArray(); + } + if (!vList) { + vList = new FairVolumeList(); + } + + TListIter iter(aList); + FairGeoNode* node = nullptr; + FairGeoNode* MotherNode = nullptr; + FairVolume* volume = nullptr; + FairRuntimeDb* rtdb = FairRun::Instance()->GetRuntimeDb(); + FairGeoParSet* par = static_cast(rtdb->getContainer("FairGeoParSet")); + TObjArray* fNodes = par->GetGeoNodes(); + while ((node = static_cast(iter.Next()))) { + + node->calcLabTransform(); + MotherNode = node->getMotherNode(); + volume = new FairVolume(node->getTruncName(), fNbOfVolumes++); + volume->setRealName(node->GetName()); + vList->addVolume(volume); + volume->setGeoNode(node); + volume->setCopyNo(node->getCopyNo()); + + if (MotherNode != 0) { + volume->setMotherId(node->getMCid()); + volume->setMotherCopyNo(MotherNode->getCopyNo()); + } + FairGeoVolume* aVol = nullptr; + + if (node->isSensitive() && fActive) { + volume->setModId(fModId); + volume->SetModule(this); + svList->Add(volume); + aVol = dynamic_cast(node); + fNodes->AddLast(aVol); + fNbOfSensitiveVol++; + } + } } -void FairModule::AddSensitiveVolume(TGeoVolume* v) +void FairModule::AddSensitiveVolume(TGeoVolume* v) { - LOG(debug2)<<"AddSensitiveVolume " << v->GetName(); - - // Only register volumes which are not already registered - // Otherwise the stepping will be slowed down - if( ! vList->findObject(v->GetName() ) ) { - FairVolume* volume = nullptr; - volume = new FairVolume(v->GetName(), fNbOfVolumes++); - vList->addVolume(volume); - volume->setModId(fModId); - volume->SetModule(this); - svList->Add(volume); - fNbOfSensitiveVol++; - } + LOG(debug2) << "AddSensitiveVolume " << v->GetName(); + + // Only register volumes which are not already registered + // Otherwise the stepping will be slowed down + if (!vList->findObject(v->GetName())) { + FairVolume* volume = nullptr; + volume = new FairVolume(v->GetName(), fNbOfVolumes++); + vList->addVolume(volume); + volume->setModId(fModId); + volume->SetModule(this); + svList->Add(volume); + fNbOfSensitiveVol++; + } } FairVolume* FairModule::getFairVolume(FairGeoNode* fN) { - FairVolume* fv; - FairVolume* fvol=0; - for(Int_t i=0; igetEntries(); i++) { - fv=vList->At(i); - if((fv->getGeoNode())==fN) { - fvol=fv; - return fvol; - break; - } - } - return fvol; + FairVolume* fv; + FairVolume* fvol = 0; + for (Int_t i = 0; i < vList->getEntries(); i++) { + fv = vList->At(i); + if ((fv->getGeoNode()) == fN) { + fvol = fv; + return fvol; + break; + } + } + return fvol; } void FairModule::ConstructRootGeometry(TGeoMatrix* shiftM) { - /** Construct the detector geometry from ROOT files, possible inputs are: - * 1. A TGeoVolume as a mother (master) volume containing the detector geometry - * 2. A TGeoManager with the detector geometry - * 3. A TGeoVolume as a mother or Master volume which is the output of the CAD2ROOT geometry, in this case - * the materials are not proprely defined and had to be reset - * In all cases we have to check that the material properties are the same or is the materials defined in - * the current simulation session - */ - TGeoManager* OldGeo=gGeoManager; - TGeoManager* NewGeo=0; - TGeoVolume* volume=0;; - TFile* f=TFile::Open(GetGeometryFileName().Data()); - TList* l= f->GetListOfKeys(); - TKey* key; - TIter next( l); - TGeoNode* n=0; - TGeoVolume* v1=0; - while ((key = static_cast(next()))) { - /**loop inside the delivered root file and try to fine a TGeoManager object - * the first TGeoManager found will be read - */ - if (strcmp(key->GetClassName(),"TGeoManager") != 0) { continue; } - gGeoManager=0; - NewGeo = static_cast(key->ReadObj()); - break; - } - if (NewGeo!=0) { - /** in case a TGeoManager was found get the top most volume and the node - */ - - NewGeo->cd(); - volume=static_cast(NewGeo->GetNode(0)->GetDaughter(0)->GetVolume()); - v1=volume->MakeCopyVolume(volume->GetShape()); - // n=NewGeo->GetTopNode(); - n=v1->GetNode(0); - // NewGeo=0; - // delete NewGeo; //move it to the end of the method - - } else { - /** The file does not contain any TGeoManager, so we assume to have a file with a TGeoVolume - * try to look for a TGeoVolume inside the file + /** Construct the detector geometry from ROOT files, possible inputs are: + * 1. A TGeoVolume as a mother (master) volume containing the detector geometry + * 2. A TGeoManager with the detector geometry + * 3. A TGeoVolume as a mother or Master volume which is the output of the CAD2ROOT geometry, in this case + * the materials are not proprely defined and had to be reset + * In all cases we have to check that the material properties are the same or is the materials defined in + * the current simulation session */ + TGeoManager* OldGeo = gGeoManager; + TGeoManager* NewGeo = 0; + TGeoVolume* volume = 0; + ; + TFile* f = TFile::Open(GetGeometryFileName().Data()); + TList* l = f->GetListOfKeys(); + TKey* key; + TIter next(l); + TGeoNode* n = 0; + TGeoVolume* v1 = 0; + while ((key = static_cast(next()))) { + /**loop inside the delivered root file and try to fine a TGeoManager object + * the first TGeoManager found will be read + */ + if (strcmp(key->GetClassName(), "TGeoManager") != 0) { + continue; + } + gGeoManager = 0; + NewGeo = static_cast(key->ReadObj()); + break; + } + if (NewGeo != 0) { + /** in case a TGeoManager was found get the top most volume and the node + */ + + NewGeo->cd(); + volume = static_cast(NewGeo->GetNode(0)->GetDaughter(0)->GetVolume()); + v1 = volume->MakeCopyVolume(volume->GetShape()); + // n=NewGeo->GetTopNode(); + n = v1->GetNode(0); + // NewGeo=0; + // delete NewGeo; //move it to the end of the method - key=static_cast(l->At(0)); //Get the first key in the list - volume=dynamic_cast (key->ReadObj()); - if(volume!=0) { n=volume->GetNode(0); } - if(n!=0) { v1=n->GetVolume(); } - } - - if(v1==0) { - LOG(fatal)<<"Could not find any geometry in file " << GetGeometryFileName().Data(); - } else { - gGeoManager=OldGeo; - gGeoManager->cd(); - // If AddToVolume is empty add the volume to the top volume Cave - // If it is defined check i´f the volume exists and if it exists add the volume from the root file - // to the already existing volume - TGeoVolume* Cave=nullptr; - if ( 0 == fMotherVolumeName.Length() ) { - Cave= gGeoManager->GetTopVolume(); } else { - Cave = gGeoManager->GetVolume(fMotherVolumeName); - } - if(Cave!=nullptr) { - /** Everything is OK, we have a TGeoVolume and now we add it to the simulation TGeoManager */ - gGeoManager->AddVolume(v1); - /** Force rebuilding of voxels */ - TGeoVoxelFinder* voxels = v1->GetVoxels(); - if (voxels) { voxels->SetNeedRebuild(); } - - // else { fLogger->Fatal(MESSAGE_ORIGIN, "\033[5m\033[31mFairModule::ConstructRootGeometry(): could not find voxels \033[0m"); } - - /**To avoid having different names of the default matrices - * because we could have get the volume from another - * TGeoManager, we reset the default matrix name - */ - TGeoMatrix* M = n->GetMatrix(); - - // very nasty! - TGeoHMatrix* M2 = new TGeoHMatrix(*M); - - // For debugging - //M2->Dump(); - //const Double_t* transl1 = M2->GetTranslation(); - //std::cout << transl1[0] << "\t" << transl1[1] << "\t" << transl1[2] << std::endl; - //if (shiftM) { - // shiftM->Dump(); - // const Double_t* transl2 = shiftM->GetTranslation(); - // std::cout << transl2[0] << "\t" << transl2[1] << "\t" << transl2[2] << std::endl; - //} - - if (shiftM) { - M2->Multiply(shiftM); // HACK! - } - - SetDefaultMatrixName(M2); - - //TODO - // I don't really understand this juggling with the matices, - // so, please, take care of how it works with my changes. - // Egor. - - /** Now we can remove the matrix so that the new geomanager will rebuild it properly*/ - gGeoManager->GetListOfMatrices()->Remove(M2); - TGeoHMatrix* global = gGeoManager->GetHMatrix(); - gGeoManager->GetListOfMatrices()->Remove(global); //Remove the Identity matrix - /** Now we can add the node to the existing cave */ - - Cave->AddNode(v1, 0, M2); - /** correction from O. Merle: in case of a TGeoVolume (v1) set the material properly */ - - AssignMediumAtImport(v1); - /** now go through the herachy and set the materials properly, this is important becase the CAD converter - * produce TGeoVolumes with materials that have only names and no properties - */ - ExpandNode(n); - delete NewGeo; - delete f; + /** The file does not contain any TGeoManager, so we assume to have a file with a TGeoVolume + * try to look for a TGeoVolume inside the file + */ + + key = static_cast(l->At(0)); // Get the first key in the list + volume = dynamic_cast(key->ReadObj()); + if (volume != 0) { + n = volume->GetNode(0); + } + if (n != 0) { + v1 = n->GetVolume(); + } + } + + if (v1 == 0) { + LOG(fatal) << "Could not find any geometry in file " << GetGeometryFileName().Data(); } else { - LOG(fatal)<<"Could not find the given mother volume "<< fMotherVolumeName.Data() << " where the geomanger should be added."; + gGeoManager = OldGeo; + gGeoManager->cd(); + // If AddToVolume is empty add the volume to the top volume Cave + // If it is defined check i´f the volume exists and if it exists add the volume from the root file + // to the already existing volume + TGeoVolume* Cave = nullptr; + if (0 == fMotherVolumeName.Length()) { + Cave = gGeoManager->GetTopVolume(); + } else { + Cave = gGeoManager->GetVolume(fMotherVolumeName); + } + if (Cave != nullptr) { + /** Everything is OK, we have a TGeoVolume and now we add it to the simulation TGeoManager */ + gGeoManager->AddVolume(v1); + /** Force rebuilding of voxels */ + TGeoVoxelFinder* voxels = v1->GetVoxels(); + if (voxels) { + voxels->SetNeedRebuild(); + } + + // else { fLogger->Fatal(MESSAGE_ORIGIN, "\033[5m\033[31mFairModule::ConstructRootGeometry(): could not find + // voxels \033[0m"); } + + /**To avoid having different names of the default matrices + * because we could have get the volume from another + * TGeoManager, we reset the default matrix name + */ + TGeoMatrix* M = n->GetMatrix(); + + // very nasty! + TGeoHMatrix* M2 = new TGeoHMatrix(*M); + + // For debugging + // M2->Dump(); + // const Double_t* transl1 = M2->GetTranslation(); + // std::cout << transl1[0] << "\t" << transl1[1] << "\t" << transl1[2] << std::endl; + // if (shiftM) { + // shiftM->Dump(); + // const Double_t* transl2 = shiftM->GetTranslation(); + // std::cout << transl2[0] << "\t" << transl2[1] << "\t" << transl2[2] << std::endl; + //} + + if (shiftM) { + M2->Multiply(shiftM); // HACK! + } + + SetDefaultMatrixName(M2); + + // TODO + // I don't really understand this juggling with the matices, + // so, please, take care of how it works with my changes. + // Egor. + + /** Now we can remove the matrix so that the new geomanager will rebuild it properly*/ + gGeoManager->GetListOfMatrices()->Remove(M2); + TGeoHMatrix* global = gGeoManager->GetHMatrix(); + gGeoManager->GetListOfMatrices()->Remove(global); // Remove the Identity matrix + /** Now we can add the node to the existing cave */ + + Cave->AddNode(v1, 0, M2); + /** correction from O. Merle: in case of a TGeoVolume (v1) set the material properly */ + + AssignMediumAtImport(v1); + /** now go through the herachy and set the materials properly, this is important becase the CAD converter + * produce TGeoVolumes with materials that have only names and no properties + */ + ExpandNode(n); + delete NewGeo; + delete f; + } else { + LOG(fatal) << "Could not find the given mother volume " << fMotherVolumeName.Data() + << " where the geomanger should be added."; + } } - } } #ifdef ROOT_HAS_GDML @@ -458,58 +464,54 @@ void FairModule::ConstructRootGeometry(TGeoMatrix* shiftM) void FairModule::ConstructGDMLGeometry(TGeoMatrix* posrot) { // Parse the GDML file - TFile *old = gFile; - TGDMLParse parser; - TGeoVolume* gdmlTop; - gdmlTop = parser.GDMLReadFile(GetGeometryFileName()); + TFile* old = gFile; + TGDMLParse parser; + TGeoVolume* gdmlTop; + gdmlTop = parser.GDMLReadFile(GetGeometryFileName()); // Change ID of media. TGDMLParse starts allways from 0. Need to shift. ReAssignMediaId(); // Add volume to the cave and go through it recursively - gGeoManager->GetTopVolume()->AddNode(gdmlTop,1,posrot); - ExpandNodeForGDML(gGeoManager->GetTopVolume()->GetNode(gGeoManager->GetTopVolume()->GetNdaughters()-1)); + gGeoManager->GetTopVolume()->AddNode(gdmlTop, 1, posrot); + ExpandNodeForGDML(gGeoManager->GetTopVolume()->GetNode(gGeoManager->GetTopVolume()->GetNdaughters() - 1)); gFile = old; } void FairModule::ExpandNodeForGDML(TGeoNode* curNode) { // Get pointer to volume and assign medium - TGeoVolume* curVol = curNode->GetVolume(); + TGeoVolume* curVol = curNode->GetVolume(); AssignMediumAtImport(curVol); // Check if the volume is sensitive - if ( (this->InheritsFrom("FairDetector")) && IsSensitive(curVol->GetName())) { - LOG(debug2)<<"Sensitive Volume "<< curVol->GetName(); + if ((this->InheritsFrom("FairDetector")) && IsSensitive(curVol->GetName())) { + LOG(debug2) << "Sensitive Volume " << curVol->GetName(); AddSensitiveVolume(curVol); } - //! Recursevly go down the tree of nodes - if (curVol->GetNdaughters() != 0) - { - TObjArray* NodeChildList = curVol->GetNodes(); - TGeoNode* curNodeChild; - for (Int_t j=0; jGetEntriesFast(); j++) - { - curNodeChild = static_cast(NodeChildList->At(j)); - ExpandNodeForGDML(curNodeChild); - } + //! Recursevly go down the tree of nodes + if (curVol->GetNdaughters() != 0) { + TObjArray* NodeChildList = curVol->GetNodes(); + TGeoNode* curNodeChild; + for (Int_t j = 0; j < NodeChildList->GetEntriesFast(); j++) { + curNodeChild = static_cast(NodeChildList->At(j)); + ExpandNodeForGDML(curNodeChild); } + } } #else void FairModule::ConstructGDMLGeometry(TGeoMatrix* posrot) { - LOG(error) << "Could not construct magnet geometry from gdml file."; - LOG(error) << "The used ROOT version does not support gdml."; - LOG(error) << "Please recompile ROOT with gdml support."; - LOG(fatal) << "Stop execution at this point."; + LOG(error) << "Could not construct magnet geometry from gdml file."; + LOG(error) << "The used ROOT version does not support gdml."; + LOG(error) << "Please recompile ROOT with gdml support."; + LOG(fatal) << "Stop execution at this point."; } -void FairModule::ExpandNodeForGDML(TGeoNode* curNode) -{ -} +void FairModule::ExpandNodeForGDML(TGeoNode* curNode) {} #endif @@ -521,11 +523,10 @@ void FairModule::ReAssignMediaId() TList* media = gGeoManager->GetListOfMedia(); // Loop over new media which are not in GeoBase and shift the ID TGeoMedium* med; -// TGeoMedium* med2; - for(Int_t i = geoBuilder->GetNMedia(); i < media->GetEntries(); i++) - { + // TGeoMedium* med2; + for (Int_t i = geoBuilder->GetNMedia(); i < media->GetEntries(); i++) { med = static_cast(media->At(i)); - med->SetId(i+1); + med->SetId(i + 1); } // Change GeoBase medium index geoBuilder->SetNMedia(media->GetEntries()); @@ -536,15 +537,11 @@ void FairModule::ReAssignMediaId() // map for existing materials std::map mapMatName; TGeoMaterial* mat; - while( (mat = static_cast(next1())) ) - { + while ((mat = static_cast(next1()))) { // If material exist - delete dublicated. If not - set the flag - if(mapMatName[mat->GetName()]) - { + if (mapMatName[mat->GetName()]) { materials->Remove(mat); - } - else - { + } else { mapMatName[mat->GetName()] = kTRUE; } } @@ -552,148 +549,170 @@ void FairModule::ReAssignMediaId() void FairModule::ConstructASCIIGeometry() { - LOG(warn)<<"The method ConstructASCIIGeometry has to be implemented in the detector class which inherits from FairModule"; + LOG(warn) << "The method ConstructASCIIGeometry has to be implemented in the detector class which inherits from " + "FairModule"; } Bool_t FairModule::CheckIfSensitive(std::string) { - LOG(warn)<<"The method CheckIfSensitive is deprecated. Use IsSensitive."; + LOG(warn) << "The method CheckIfSensitive is deprecated. Use IsSensitive."; return kFALSE; } //__________________________________________________________________________ Bool_t FairModule::IsSensitive(const std::string& name) { - LOG(warn)<<"Implement IsSensitive in the detector class which inherits from FairModule"; - LOG(warn)<<"For now calling the obsolete function CheckIfSensitive"; + LOG(warn) << "Implement IsSensitive in the detector class which inherits from FairModule"; + LOG(warn) << "For now calling the obsolete function CheckIfSensitive"; return CheckIfSensitive(name); } void FairModule::ExpandNode(TGeoNode* fN) { - //FairGeoLoader* geoLoad = FairGeoLoader::Instance(); - //FairGeoInterface* geoFace = geoLoad->getGeoInterface(); - //FairGeoMedia* Media = geoFace->getMedia(); - //FairGeoBuilder* geobuild=geoLoad->getGeoBuilder(); - TGeoMatrix* Matrix =fN->GetMatrix(); - if(gGeoManager->GetListOfMatrices()->FindObject(Matrix)) { gGeoManager->GetListOfMatrices()->Remove(Matrix); } - TGeoVolume* v1=fN->GetVolume(); - TObjArray* NodeList=v1->GetNodes(); - for (Int_t Nod=0; NodGetEntriesFast(); Nod++) { - TGeoNode* fNode =static_cast(NodeList->At(Nod)); - TGeoMatrix* M =fNode->GetMatrix(); - //M->SetDefaultName(); - SetDefaultMatrixName(M); - if(fNode->GetNdaughters()>0) { ExpandNode(fNode); } - TGeoVolume* v= fNode->GetVolume(); - AssignMediumAtImport(v); - if (!gGeoManager->FindVolumeFast(v->GetName())) { - LOG(debug2)<<"Register Volume " << v->GetName(); - v->RegisterYourself(); - } - if ( (this->InheritsFrom("FairDetector")) && IsSensitive(v->GetName())) { - LOG(debug2)<<"Sensitive Volume "<< v->GetName(); - AddSensitiveVolume(v); - } - v->GetShape()->AfterStreamer(); - } + // FairGeoLoader* geoLoad = FairGeoLoader::Instance(); + // FairGeoInterface* geoFace = geoLoad->getGeoInterface(); + // FairGeoMedia* Media = geoFace->getMedia(); + // FairGeoBuilder* geobuild=geoLoad->getGeoBuilder(); + TGeoMatrix* Matrix = fN->GetMatrix(); + if (gGeoManager->GetListOfMatrices()->FindObject(Matrix)) { + gGeoManager->GetListOfMatrices()->Remove(Matrix); + } + TGeoVolume* v1 = fN->GetVolume(); + TObjArray* NodeList = v1->GetNodes(); + for (Int_t Nod = 0; Nod < NodeList->GetEntriesFast(); Nod++) { + TGeoNode* fNode = static_cast(NodeList->At(Nod)); + TGeoMatrix* M = fNode->GetMatrix(); + // M->SetDefaultName(); + SetDefaultMatrixName(M); + if (fNode->GetNdaughters() > 0) { + ExpandNode(fNode); + } + TGeoVolume* v = fNode->GetVolume(); + AssignMediumAtImport(v); + if (!gGeoManager->FindVolumeFast(v->GetName())) { + LOG(debug2) << "Register Volume " << v->GetName(); + v->RegisterYourself(); + } + if ((this->InheritsFrom("FairDetector")) && IsSensitive(v->GetName())) { + LOG(debug2) << "Sensitive Volume " << v->GetName(); + AddSensitiveVolume(v); + } + v->GetShape()->AfterStreamer(); + } } void FairModule::SetDefaultMatrixName(TGeoMatrix* matrix) { - // Copied from root TGeoMatrix::SetDefaultName() and modified (memory leak) - // If no name was supplied in the ctor, the type of transformation is checked. - // A letter will be prepended to the name : - // t - translation - // r - rotation - // s - scale - // c - combi (translation + rotation) - // g - general (tr+rot+scale) - // The index of the transformation in gGeoManager list of transformations will - // be appended. - if (!gGeoManager) { return; } - if (strlen(matrix->GetName())) { return; } - char type = 'n'; - if (matrix->IsTranslation()) { type = 't'; } - if (matrix->IsRotation()) { type = 'r'; } - if (matrix->IsScale()) { type = 's'; } - if (matrix->IsCombi()) { type = 'c'; } - if (matrix->IsGeneral()) { type = 'g'; } - TObjArray* matrices = gGeoManager->GetListOfMatrices(); - Int_t index = 0; - if (matrices) { index =matrices->GetEntriesFast() - 1; } - matrix->SetName(Form("%c%i", type, index)); + // Copied from root TGeoMatrix::SetDefaultName() and modified (memory leak) + // If no name was supplied in the ctor, the type of transformation is checked. + // A letter will be prepended to the name : + // t - translation + // r - rotation + // s - scale + // c - combi (translation + rotation) + // g - general (tr+rot+scale) + // The index of the transformation in gGeoManager list of transformations will + // be appended. + if (!gGeoManager) { + return; + } + if (strlen(matrix->GetName())) { + return; + } + char type = 'n'; + if (matrix->IsTranslation()) { + type = 't'; + } + if (matrix->IsRotation()) { + type = 'r'; + } + if (matrix->IsScale()) { + type = 's'; + } + if (matrix->IsCombi()) { + type = 'c'; + } + if (matrix->IsGeneral()) { + type = 'g'; + } + TObjArray* matrices = gGeoManager->GetListOfMatrices(); + Int_t index = 0; + if (matrices) { + index = matrices->GetEntriesFast() - 1; + } + matrix->SetName(Form("%c%i", type, index)); } void FairModule::AssignMediumAtImport(TGeoVolume* v) { - /** - * Assign medium to the the volume v, this has to be done in all cases: - * case 1: For CAD converted volumes they have no mediums (only names) - * case 2: TGeoVolumes, we need to be sure that the material is defined in this session - */ - FairGeoMedia* Media = FairGeoLoader::Instance()->getGeoInterface()->getMedia(); - FairGeoBuilder* geobuild = FairGeoLoader::Instance()->getGeoBuilder(); - - TGeoMedium* med1=v->GetMedium(); - - - if(med1) { - // In newer ROOT version also a TGeoVolumeAssembly has a material and medium. - // This medium is called dummy and is automatically set when the geometry is constructed. - // Since this material and medium is neither in the TGeoManager (at this point) nor in our - // ASCII file we have to create it the same way it is done in TGeoVolume::CreateDummyMedium() - // In the end the new medium and material has to be added to the TGeomanager, because this is - // not done automatically when using the default constructor. For all other constructors the - // newly created medium or material is added to the TGeomanger. - // Create the medium and material only the first time. - TString medName = static_cast(med1->GetName()); - if ( medName.EqualTo("dummy") && nullptr == gGeoManager->GetMedium(medName) ) { - - TGeoMaterial *dummyMaterial = new TGeoMaterial(); - dummyMaterial->SetName("dummy"); - - TGeoMedium* dummyMedium = new TGeoMedium(); - dummyMedium->SetName("dummy"); - dummyMedium->SetMaterial(dummyMaterial); - - gGeoManager->GetListOfMedia()->Add(dummyMedium); - gGeoManager->AddMaterial(dummyMaterial); - } - - TGeoMaterial* mat1=v->GetMaterial(); - TGeoMaterial* newMat = gGeoManager->GetMaterial(mat1->GetName()); - if( newMat==0) { - /**The Material is not defined in the TGeoManager, we try to create one if we have enough information about it*/ - FairGeoMedium* FairMedium=Media->getMedium(mat1->GetName()); - if (!FairMedium) { - LOG(fatal)<<"Material "<< mat1->GetName() << "is not defined in ASCII file nor in Root file."; - // FairMedium=new FairGeoMedium(mat1->GetName()); - // Media->addMedium(FairMedium); - } else { - - Int_t nmed=geobuild->createMedium(FairMedium); - v->SetMedium(gGeoManager->GetMedium(nmed)); - gGeoManager->SetAllIndex(); - } + /** + * Assign medium to the the volume v, this has to be done in all cases: + * case 1: For CAD converted volumes they have no mediums (only names) + * case 2: TGeoVolumes, we need to be sure that the material is defined in this session + */ + FairGeoMedia* Media = FairGeoLoader::Instance()->getGeoInterface()->getMedia(); + FairGeoBuilder* geobuild = FairGeoLoader::Instance()->getGeoBuilder(); + + TGeoMedium* med1 = v->GetMedium(); + + if (med1) { + // In newer ROOT version also a TGeoVolumeAssembly has a material and medium. + // This medium is called dummy and is automatically set when the geometry is constructed. + // Since this material and medium is neither in the TGeoManager (at this point) nor in our + // ASCII file we have to create it the same way it is done in TGeoVolume::CreateDummyMedium() + // In the end the new medium and material has to be added to the TGeomanager, because this is + // not done automatically when using the default constructor. For all other constructors the + // newly created medium or material is added to the TGeomanger. + // Create the medium and material only the first time. + TString medName = static_cast(med1->GetName()); + if (medName.EqualTo("dummy") && nullptr == gGeoManager->GetMedium(medName)) { + + TGeoMaterial* dummyMaterial = new TGeoMaterial(); + dummyMaterial->SetName("dummy"); + + TGeoMedium* dummyMedium = new TGeoMedium(); + dummyMedium->SetName("dummy"); + dummyMedium->SetMaterial(dummyMaterial); + + gGeoManager->GetListOfMedia()->Add(dummyMedium); + gGeoManager->AddMaterial(dummyMaterial); + } + + TGeoMaterial* mat1 = v->GetMaterial(); + TGeoMaterial* newMat = gGeoManager->GetMaterial(mat1->GetName()); + if (newMat == 0) { + /**The Material is not defined in the TGeoManager, we try to create one if we have enough information about + * it*/ + FairGeoMedium* FairMedium = Media->getMedium(mat1->GetName()); + if (!FairMedium) { + LOG(fatal) << "Material " << mat1->GetName() << "is not defined in ASCII file nor in Root file."; + // FairMedium=new FairGeoMedium(mat1->GetName()); + // Media->addMedium(FairMedium); + } else { + + Int_t nmed = geobuild->createMedium(FairMedium); + v->SetMedium(gGeoManager->GetMedium(nmed)); + gGeoManager->SetAllIndex(); + } + } else { + /**Material is already available in the TGeoManager and we can set it */ + TGeoMedium* med2 = gGeoManager->GetMedium(mat1->GetName()); + v->SetMedium(med2); + } } else { - /**Material is already available in the TGeoManager and we can set it */ - TGeoMedium* med2= gGeoManager->GetMedium(mat1->GetName()); - v->SetMedium(med2); - } - } else { - if (strcmp(v->ClassName(),"TGeoVolumeAssembly") != 0) { - //[R.K.-3.3.08] // When there is NO material defined, set it to avoid conflicts in Geant - LOG(fatal)<<"The volume "<< v->GetName() << "has no medium information and not an Assembly so we have to quit"; + if (strcmp(v->ClassName(), "TGeoVolumeAssembly") != 0) { + //[R.K.-3.3.08] // When there is NO material defined, set it to avoid conflicts in Geant + LOG(fatal) << "The volume " << v->GetName() + << "has no medium information and not an Assembly so we have to quit"; + } } - } } FairModule* FairModule::CloneModule() const { - Fatal("CloneModule","Has to be overriden in multi-threading applications."); - return 0; + Fatal("CloneModule", "Has to be overriden in multi-threading applications."); + return 0; } -ClassImp(FairModule) +ClassImp(FairModule); diff --git a/base/sim/FairModule.h b/base/sim/FairModule.h index fd24b0f4a6..22647564cf 100644 --- a/base/sim/FairModule.h +++ b/base/sim/FairModule.h @@ -1,28 +1,27 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRMODULE_H #define FAIRMODULE_H -#include "FairGeoInterface.h" // for FairGeoInterface -#include "FairGeoLoader.h" // for FairGeoLoader -#include "FairGeoNode.h" // for FairGeoNode -#include "FairGeoVolume.h" // for FairGeoVolume +#include "FairGeoInterface.h" // for FairGeoInterface +#include "FairGeoLoader.h" // for FairGeoLoader +#include "FairGeoNode.h" // for FairGeoNode +#include "FairGeoVolume.h" // for FairGeoVolume #include "FairLogger.h" -#include "FairRun.h" // for FairRun -#include "FairRuntimeDb.h" // for FairRuntimeDb +#include "FairRun.h" // for FairRun +#include "FairRuntimeDb.h" // for FairRuntimeDb -#include // for TNamed -#include // for Bool_t, Int_t, etc -#include // for TList (ptr only), TListIter -#include // for TObjArray -#include // for TString, operator!= - -#include // for string +#include // for Bool_t, Int_t, etc +#include // for TList (ptr only), TListIter +#include // for TNamed +#include // for TObjArray +#include // for TString, operator!= +#include // for string class FairVolumeList; class FairVolume; @@ -44,101 +43,104 @@ class TVirtualMC; * Changelog: 29.02.2012 [O.Merle] Fixed missing material assignment for top volume. * ... and please - add some documentation to your code. */ -class FairModule: public TNamed +class FairModule : public TNamed { public: /**default ctor*/ FairModule(); /**Standard ctor*/ - FairModule(const char* Name, const char* title, Bool_t Active=kFALSE); + FairModule(const char* Name, const char* title, Bool_t Active = kFALSE); /**default dtor*/ - virtual ~FairModule(); + virtual ~FairModule(); /**Print method should be implemented in detector or module*/ - virtual void Print(Option_t*) const {;} + virtual void Print(Option_t*) const { ; } /**Set the geometry file name o be used*/ - virtual void SetGeometryFileName(TString fname, TString geoVer="0"); + virtual void SetGeometryFileName(TString fname, TString geoVer = "0"); /**Get the Geometry file name*/ - virtual TString GetGeometryFileName() {return fgeoName ;} + virtual TString GetGeometryFileName() { return fgeoName; } /**Get the geometry file version if used*/ - virtual TString GetGeometryFileVer() {return fgeoVer ;} + virtual TString GetGeometryFileVer() { return fgeoVer; } /**method called from the MC application to construct the geometry, has to be implimented by user*/ - virtual void ConstructGeometry(); + virtual void ConstructGeometry(); /**method called from the MC application to set optical geometry properties*/ - virtual void ConstructOpGeometry(); + virtual void ConstructOpGeometry(); /**construct geometry from root files (TGeo)*/ - virtual void ConstructRootGeometry(TGeoMatrix* shiftM=nullptr); + virtual void ConstructRootGeometry(TGeoMatrix* shiftM = nullptr); /**construct geometry from standard ASSCII files (Hades Format)*/ - virtual void ConstructASCIIGeometry(); + virtual void ConstructASCIIGeometry(); /** Modify the geometry for the simulation run using methods of the Root geometry package */ - virtual void ModifyGeometry() __attribute__((deprecated("Use FairAlignmentHandler instead, see Tutorial4 for examples"))) { - LOG(warn) << "This function is deprecated. Use FairAlignmentHandler instead, see Tutorial4 for examples."; + virtual void ModifyGeometry() + __attribute__((deprecated("Use FairAlignmentHandler instead, see Tutorial4 for examples"))) + { + LOG(warn) << "This function is deprecated. Use FairAlignmentHandler instead, see Tutorial4 for examples."; } - virtual void RegisterAlignmentMatrices() {;} + virtual void RegisterAlignmentMatrices() { ; } /**construct geometry from GDML files*/ - virtual void ConstructGDMLGeometry(TGeoMatrix*); - /** custom settings of processes and cuts for media to be forwarded to the + virtual void ConstructGDMLGeometry(TGeoMatrix*); + /** custom settings of processes and cuts for media to be forwarded to the ** detector simulation */ - virtual void SetSpecialPhysicsCuts() {;} + virtual void SetSpecialPhysicsCuts() { ; } /** Clone this object (used in MT mode only)*/ virtual FairModule* CloneModule() const; /** Init worker run (used in MT mode only) */ - virtual void BeginWorkerRun() const {;} + virtual void BeginWorkerRun() const { ; } /** Finish worker run (used in MT mode only) */ - virtual void FinishWorkerRun() const {;} + virtual void FinishWorkerRun() const { ; } /**template function to construct geometry. to be used in derived classes.*/ template - void ConstructASCIIGeometry(T* dataType1, TString containerName="", U* datatype2 = nullptr); + void ConstructASCIIGeometry(T* dataType1, TString containerName = "", U* datatype2 = nullptr); - /**Set the sensitivity flag for volumes, called from ConstructASCIIRootGeometry(), and has to be implimented for detectors - * which use ConstructASCIIRootGeometry() to build the geometry */ - virtual Bool_t IsSensitive(const std::string& name); + /**Set the sensitivity flag for volumes, called from ConstructASCIIRootGeometry(), and has to be implimented for + * detectors which use ConstructASCIIRootGeometry() to build the geometry */ + virtual Bool_t IsSensitive(const std::string& name); /**The function below is depracated, please change to the new method above */ - virtual Bool_t CheckIfSensitive(std::string name); + virtual Bool_t CheckIfSensitive(std::string name); /**called from ConstructRootGeometry()*/ - virtual void ExpandNode(TGeoNode* Node); + virtual void ExpandNode(TGeoNode* Node); /**called from ConstructGDMLGeometry()*/ - virtual void ExpandNodeForGDML(TGeoNode*); + virtual void ExpandNodeForGDML(TGeoNode*); /**return the MC id of a volume named vname*/ - virtual Int_t getVolId( const TString& ) const {return 0;} + virtual Int_t getVolId(const TString&) const { return 0; } /**return the detector/Module id (which was set in the sim macro for the detector)*/ - Int_t GetModId() {return fModId;} + Int_t GetModId() { return fModId; } /**Set the verbose level in this detector*/ - void SetVerboseLevel(Int_t level) {fVerboseLevel=level;} + void SetVerboseLevel(Int_t level) { fVerboseLevel = level; } /**return the detector status */ - Bool_t IsActive() {return fActive;} + Bool_t IsActive() { return fActive; } /**set the detector/module id*/ - void SetModId(Int_t id) {fModId=id;} + void SetModId(Int_t id) { fModId = id; } /** Set the name of the mother volume to which a new geometry is added. ** This function is needed for geometries which are defined as ROOT geometry manager. **/ - void SetMotherVolume(TString volName) {fMotherVolumeName=volName;} + void SetMotherVolume(TString volName) { fMotherVolumeName = volName; } /**called from ConstuctASCIIGeometry*/ - void ProcessNodes ( TList* aList ); + void ProcessNodes(TList* aList); /**Set the parameter containers*/ - virtual void SetParContainers() {;} + virtual void SetParContainers() { ; } /** Initialize everything which has to be done before the construction and modification ** of the geometry. Mostly this is needed to read data from the parameter containers.*/ - virtual void InitParContainers() {;} + virtual void InitParContainers() { ; } /**return the geo parameter of this detector/module*/ - TList* GetListOfGeoPar() { return flGeoPar;} + TList* GetListOfGeoPar() { return flGeoPar; } /**list of volumes in a simulation session*/ - static thread_local FairVolumeList* vList; //! + static thread_local FairVolumeList* vList; //! /**total number of volumes in a simulaion session*/ - static thread_local Int_t fNbOfVolumes; //! + static thread_local Int_t fNbOfVolumes; //! /**list of all sensitive volumes in a simulaion session*/ - static thread_local TRefArray* svList; //! + static thread_local TRefArray* svList; //! + + static thread_local TArrayI* volNumber; //! + TString fMotherVolumeName; //! + FairVolume* getFairVolume(FairGeoNode* fNode); + void AddSensitiveVolume(TGeoVolume* v); - static thread_local TArrayI* volNumber; //! - TString fMotherVolumeName; //! - FairVolume* getFairVolume(FairGeoNode* fNode); - void AddSensitiveVolume(TGeoVolume* v); private: /** Re-implimented from ROOT: TGeoMatrix::SetDefaultName() */ void SetDefaultMatrixName(TGeoMatrix* matrix); - void AssignMediumAtImport(TGeoVolume* v); // O.Merle, 29.02.2012 - see impl. + void AssignMediumAtImport(TGeoVolume* v); // O.Merle, 29.02.2012 - see impl. /**called from ConstructGDMLGeometry. Changes default ID created by TGDMLParse*/ void ReAssignMediaId(); @@ -147,65 +149,64 @@ class FairModule: public TNamed protected: FairModule(const FairModule&); FairModule& operator=(const FairModule&); - TString fgeoVer; - TString fgeoName; - Int_t fModId; - Bool_t fActive; - Int_t fNbOfSensitiveVol; //! - Int_t fVerboseLevel; - TList* flGeoPar; //! list of Detector Geometry parameters - Bool_t fGeoSaved; //! flag for initialisation - TVirtualMC* fMC; //! cahed pointer to MC (available only after initialization) - - ClassDef( FairModule,4) + TString fgeoVer; + TString fgeoName; + Int_t fModId; + Bool_t fActive; + Int_t fNbOfSensitiveVol; //! + Int_t fVerboseLevel; + TList* flGeoPar; //! list of Detector Geometry parameters + Bool_t fGeoSaved; //! flag for initialisation + TVirtualMC* fMC; //! cahed pointer to MC (available only after initialization) + + ClassDef(FairModule, 4) }; template void FairModule::ConstructASCIIGeometry(T* dataType1, TString containerName, U*) { - FairGeoLoader* loader=FairGeoLoader::Instance(); - FairGeoInterface* GeoInterface =loader->getGeoInterface(); - T* MGeo=new T(); - MGeo->print(); - MGeo->setGeomFile(GetGeometryFileName()); - GeoInterface->addGeoModule(MGeo); - Bool_t rc = GeoInterface->readSet(MGeo); - if ( rc ) { MGeo->create(loader->getGeoBuilder()); } - - TList* volList = MGeo->getListOfVolumes(); - // store geo parameter - FairRun* fRun = FairRun::Instance(); - FairRuntimeDb* rtdb= FairRun::Instance()->GetRuntimeDb(); - - dataType1 = MGeo; - - if ( "" != containerName) { - LOG(info) << "Add GeoNodes for "<< MGeo->getDescription() - << " to container " << containerName; - - // U par=(U)(rtdb->getContainer(containerName)); - U* par=static_cast(rtdb->getContainer(containerName)); - TObjArray* fSensNodes = par->GetGeoSensitiveNodes(); - TObjArray* fPassNodes = par->GetGeoPassiveNodes(); - - TListIter iter(volList); - FairGeoNode* node = nullptr; - FairGeoVolume* aVol=nullptr; - - while( (node = static_cast(iter.Next())) ) { - aVol = dynamic_cast ( node ); - if ( node->isSensitive() ) { - fSensNodes->AddLast( aVol ); - } else { - fPassNodes->AddLast( aVol ); - } + FairGeoLoader* loader = FairGeoLoader::Instance(); + FairGeoInterface* GeoInterface = loader->getGeoInterface(); + T* MGeo = new T(); + MGeo->print(); + MGeo->setGeomFile(GetGeometryFileName()); + GeoInterface->addGeoModule(MGeo); + Bool_t rc = GeoInterface->readSet(MGeo); + if (rc) { + MGeo->create(loader->getGeoBuilder()); } - ProcessNodes( volList ); - par->setChanged(); - par->setInputVersion(fRun->GetRunId(),1); - } + TList* volList = MGeo->getListOfVolumes(); + // store geo parameter + FairRun* fRun = FairRun::Instance(); + FairRuntimeDb* rtdb = FairRun::Instance()->GetRuntimeDb(); + + dataType1 = MGeo; + + if ("" != containerName) { + LOG(info) << "Add GeoNodes for " << MGeo->getDescription() << " to container " << containerName; + + // U par=(U)(rtdb->getContainer(containerName)); + U* par = static_cast(rtdb->getContainer(containerName)); + TObjArray* fSensNodes = par->GetGeoSensitiveNodes(); + TObjArray* fPassNodes = par->GetGeoPassiveNodes(); + + TListIter iter(volList); + FairGeoNode* node = nullptr; + FairGeoVolume* aVol = nullptr; + + while ((node = static_cast(iter.Next()))) { + aVol = dynamic_cast(node); + if (node->isSensitive()) { + fSensNodes->AddLast(aVol); + } else { + fPassNodes->AddLast(aVol); + } + } + ProcessNodes(volList); + par->setChanged(); + par->setInputVersion(fRun->GetRunId(), 1); + } } - -#endif //FAIRMODULE_H +#endif // FAIRMODULE_H diff --git a/base/sim/FairParticle.cxx b/base/sim/FairParticle.cxx index 101b84cc41..9df85a22b0 100644 --- a/base/sim/FairParticle.cxx +++ b/base/sim/FairParticle.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -14,263 +14,260 @@ #include "FairParticle.h" -#include // for TDatabasePDG -#include // for TMCParticleType::kPTIon, etc -#include // for TParticle -#include // for TParticlePDG - -#include // for operator<<, basic_ostream, etc +#include // for TDatabasePDG +#include // for TMCParticleType::kPTIon, etc +#include // for TParticle +#include // for TParticlePDG +#include // for operator<<, basic_ostream, etc using std::cout; using std::endl; -ClassImp(FairParticle) +ClassImp(FairParticle); FairParticle::FairParticle(Int_t id, TParticle* particle) - : TObject(), - fpdg(id), - fParticle(particle), - fMother(0), - fDaughters(0), - fname(particle->GetName()), - fmcType(kPTIon), - fmass(particle->GetMass()), - fcharge(particle->GetPDG()->Charge()), - fDecayTime(particle->GetPDG()->Lifetime()), - fpType("Ion"), - fwidth(particle->GetPDG()->Width()), - fiSpin(static_cast(particle->GetPDG()->Spin())), - fiParity(particle->GetPDG()->Parity()), - fiConjugation(0), - fiIsospin(static_cast(particle->GetPDG()->Isospin())), - fiIsospinZ(0), - fgParity(0), - flepton(0), - fbaryon(0), - fstable(particle->GetPDG()->Stable()) -{ -} - -FairParticle::FairParticle(const char* name, Int_t z, Int_t a, Int_t s,Double_t mass ,Int_t q, Bool_t stable, Double_t decaytime) - : TObject(), - fpdg(1000000000+10000000*s+10000* z +10 * a), - fParticle(0), - fMother(0), - fDaughters(0), - fname(name), - fmcType(kPTIon), - fmass(0), - fcharge(0), - fDecayTime(decaytime), - fpType("Ion"), - fwidth(0), - fiSpin(0), - fiParity(0), - fiConjugation(0), - fiIsospin(0), - fiIsospinZ(0), - fgParity(0), - flepton(0), - fbaryon(0), - fstable(stable) + : TObject() + , fpdg(id) + , fParticle(particle) + , fMother(0) + , fDaughters(0) + , fname(particle->GetName()) + , fmcType(kPTIon) + , fmass(particle->GetMass()) + , fcharge(particle->GetPDG()->Charge()) + , fDecayTime(particle->GetPDG()->Lifetime()) + , fpType("Ion") + , fwidth(particle->GetPDG()->Width()) + , fiSpin(static_cast(particle->GetPDG()->Spin())) + , fiParity(particle->GetPDG()->Parity()) + , fiConjugation(0) + , fiIsospin(static_cast(particle->GetPDG()->Isospin())) + , fiIsospinZ(0) + , fgParity(0) + , flepton(0) + , fbaryon(0) + , fstable(particle->GetPDG()->Stable()) +{} + +FairParticle::FairParticle(const char* name, + Int_t z, + Int_t a, + Int_t s, + Double_t mass, + Int_t q, + Bool_t stable, + Double_t decaytime) + : TObject() + , fpdg(1000000000 + 10000000 * s + 10000 * z + 10 * a) + , fParticle(0) + , fMother(0) + , fDaughters(0) + , fname(name) + , fmcType(kPTIon) + , fmass(0) + , fcharge(0) + , fDecayTime(decaytime) + , fpType("Ion") + , fwidth(0) + , fiSpin(0) + , fiParity(0) + , fiConjugation(0) + , fiIsospin(0) + , fiIsospinZ(0) + , fgParity(0) + , flepton(0) + , fbaryon(0) + , fstable(stable) { - TDatabasePDG* pdgDB = TDatabasePDG::Instance(); - if (!pdgDB->GetParticle(fpdg)) { - if(mass == 0 ) { - TParticlePDG* kProton = pdgDB->GetParticle(2212); - Double_t kProtonMass=kProton->Mass(); - mass = a*kProtonMass; + TDatabasePDG* pdgDB = TDatabasePDG::Instance(); + if (!pdgDB->GetParticle(fpdg)) { + if (mass == 0) { + TParticlePDG* kProton = pdgDB->GetParticle(2212); + Double_t kProtonMass = kProton->Mass(); + mass = a * kProtonMass; + } + pdgDB->AddParticle(name, name, mass, stable, 0, q, "kPTHadron", fpdg); } - pdgDB->AddParticle(name, name, mass, stable, 0, q, "kPTHadron", fpdg); - - } - - fParticle = new TParticle(); - fParticle->SetPdgCode(fpdg); - - fmcType= kPTHadron; - fmass= mass; - fcharge= fParticle->GetPDG()->Charge(); - fDecayTime=decaytime ; - fwidth= fParticle->GetPDG()->Width(); - fiSpin= static_cast(fParticle->GetPDG()->Spin()); - fiParity= fParticle->GetPDG()->Parity(); - fiConjugation= 0; - fiIsospin= static_cast(fParticle->GetPDG()->Isospin()); - fiIsospinZ= 0; - fgParity= 0; - flepton= 0; - fbaryon= 0; - fstable= fParticle->GetPDG()->Stable(); - + fParticle = new TParticle(); + fParticle->SetPdgCode(fpdg); + + fmcType = kPTHadron; + fmass = mass; + fcharge = fParticle->GetPDG()->Charge(); + fDecayTime = decaytime; + fwidth = fParticle->GetPDG()->Width(); + fiSpin = static_cast(fParticle->GetPDG()->Spin()); + fiParity = fParticle->GetPDG()->Parity(); + fiConjugation = 0; + fiIsospin = static_cast(fParticle->GetPDG()->Isospin()); + fiIsospinZ = 0; + fgParity = 0; + flepton = 0; + fbaryon = 0; + fstable = fParticle->GetPDG()->Stable(); } -FairParticle::FairParticle(const char* name, Int_t z, Int_t a, Double_t mass ,Int_t q, Bool_t stable, Double_t decaytime) - : TObject(), - fpdg(10000000+10000* z +10 * a), - fParticle(0), - fMother(0), - fDaughters(0), - fname(name), - fmcType(kPTIon), - fmass(0), - fcharge(0), - fDecayTime(decaytime), - fpType("Ion"), - fwidth(0), - fiSpin(0), - fiParity(0), - fiConjugation(0), - fiIsospin(0), - fiIsospinZ(0), - fgParity(0), - flepton(0), - fbaryon(0), - fstable(stable) +FairParticle::FairParticle(const char* name, + Int_t z, + Int_t a, + Double_t mass, + Int_t q, + Bool_t stable, + Double_t decaytime) + : TObject() + , fpdg(10000000 + 10000 * z + 10 * a) + , fParticle(0) + , fMother(0) + , fDaughters(0) + , fname(name) + , fmcType(kPTIon) + , fmass(0) + , fcharge(0) + , fDecayTime(decaytime) + , fpType("Ion") + , fwidth(0) + , fiSpin(0) + , fiParity(0) + , fiConjugation(0) + , fiIsospin(0) + , fiIsospinZ(0) + , fgParity(0) + , flepton(0) + , fbaryon(0) + , fstable(stable) { - // fpdg= 10000000+10000* z +10 * a; - - // fDecayTime= decaytime; - TDatabasePDG* pdgDB = TDatabasePDG::Instance(); - - if (!pdgDB->GetParticle(fpdg)) { - if(mass == 0 ) { - TParticlePDG* kProton = pdgDB->GetParticle(2212); - Double_t kProtonMass=kProton->Mass(); - mass = a*kProtonMass; + // fpdg= 10000000+10000* z +10 * a; + + // fDecayTime= decaytime; + TDatabasePDG* pdgDB = TDatabasePDG::Instance(); + + if (!pdgDB->GetParticle(fpdg)) { + if (mass == 0) { + TParticlePDG* kProton = pdgDB->GetParticle(2212); + Double_t kProtonMass = kProton->Mass(); + mass = a * kProtonMass; + } + pdgDB->AddParticle(name, name, mass, stable, 0, q, "kPTHadron", fpdg); } - pdgDB->AddParticle(name, name, mass, stable, 0, q, "kPTHadron", fpdg); - - } - - fParticle = new TParticle(); - fParticle->SetPdgCode(fpdg); - - fmcType= kPTHadron; - fmass= mass; - fcharge= fParticle->GetPDG()->Charge(); - fDecayTime=decaytime ; - fwidth= fParticle->GetPDG()->Width(); - fiSpin= static_cast(fParticle->GetPDG()->Spin()); - fiParity= fParticle->GetPDG()->Parity(); - fiConjugation= 0; - fiIsospin= static_cast(fParticle->GetPDG()->Isospin()); - fiIsospinZ= 0; - fgParity= 0; - flepton= 0; - fbaryon= 0; - fstable= fParticle->GetPDG()->Stable(); - + fParticle = new TParticle(); + fParticle->SetPdgCode(fpdg); + + fmcType = kPTHadron; + fmass = mass; + fcharge = fParticle->GetPDG()->Charge(); + fDecayTime = decaytime; + fwidth = fParticle->GetPDG()->Width(); + fiSpin = static_cast(fParticle->GetPDG()->Spin()); + fiParity = fParticle->GetPDG()->Parity(); + fiConjugation = 0; + fiIsospin = static_cast(fParticle->GetPDG()->Isospin()); + fiIsospinZ = 0; + fgParity = 0; + flepton = 0; + fbaryon = 0; + fstable = fParticle->GetPDG()->Stable(); } FairParticle::FairParticle(Int_t id, TParticle* particle, FairParticle* mother) - : TObject(), - fpdg(id), - fParticle(particle), - fMother(mother), - fDaughters(), - fname(particle->GetName()), - fmcType (kPTIon), - fmass (0), - fcharge(0), - fDecayTime(0), - fpType("Ion"), - fwidth(0), - fiSpin(0), - fiParity(0), - fiConjugation(0), - fiIsospin(0), - fiIsospinZ(0), - fgParity(0), - flepton(0), - fbaryon(0), - fstable(kTRUE) - + : TObject() + , fpdg(id) + , fParticle(particle) + , fMother(mother) + , fDaughters() + , fname(particle->GetName()) + , fmcType(kPTIon) + , fmass(0) + , fcharge(0) + , fDecayTime(0) + , fpType("Ion") + , fwidth(0) + , fiSpin(0) + , fiParity(0) + , fiConjugation(0) + , fiIsospin(0) + , fiIsospinZ(0) + , fgParity(0) + , flepton(0) + , fbaryon(0) + , fstable(kTRUE) + +{} + +FairParticle::FairParticle(Int_t pdg, + const TString name, + TMCParticleType mcType, + Double_t mass, + Double_t charge, + Double_t lifetime, + const TString pType, + Double_t width, + Int_t iSpin, + Int_t iParity, + Int_t iConjugation, + Int_t iIsospin, + Int_t iIsospinZ, + Int_t gParity, + Int_t lepton, + Int_t baryon, + Bool_t stable) + : TObject() + , fpdg(pdg) + , fParticle(new TParticle()) + , fMother(0) + , fDaughters(0) + , fname(name) + , fmcType(mcType) + , fmass(mass) + , fcharge(charge) + , fDecayTime(lifetime) + , fpType(pType) + , fwidth(width) + , fiSpin(iSpin) + , fiParity(iParity) + , fiConjugation(iConjugation) + , fiIsospin(iIsospin) + , fiIsospinZ(iIsospinZ) + , fgParity(gParity) + , flepton(lepton) + , fbaryon(baryon) + , fstable(stable) { -} -FairParticle::FairParticle( Int_t pdg, - const TString name, - TMCParticleType mcType, - Double_t mass, - Double_t charge, - Double_t lifetime, - const TString pType, - Double_t width, - Int_t iSpin, - Int_t iParity, - Int_t iConjugation, - Int_t iIsospin, - Int_t iIsospinZ, - Int_t gParity, - Int_t lepton, - Int_t baryon, - Bool_t stable ) - : TObject(), - fpdg (pdg), - fParticle( new TParticle()), - fMother(0), - fDaughters(0), - fname(name), - fmcType (mcType), - fmass (mass), - fcharge( charge), - fDecayTime( lifetime), - fpType( pType), - fwidth( width), - fiSpin( iSpin), - fiParity( iParity), - fiConjugation( iConjugation), - fiIsospin( iIsospin), - fiIsospinZ( iIsospinZ), - fgParity( gParity), - flepton( lepton), - fbaryon( baryon), - fstable( stable) -{ - - if (!TDatabasePDG::Instance()->GetParticle(fpdg)) { - TDatabasePDG::Instance() - ->AddParticle(fname, fname, fmass, fstable, fwidth,fcharge ,pType, fpdg); - - } - - fParticle->SetPdgCode(fpdg); + if (!TDatabasePDG::Instance()->GetParticle(fpdg)) { + TDatabasePDG::Instance()->AddParticle(fname, fname, fmass, fstable, fwidth, fcharge, pType, fpdg); + } + fParticle->SetPdgCode(fpdg); } FairParticle::FairParticle() - : TObject(), - fpdg(0), - fParticle(0), - fMother(0), - fDaughters(), - fname("ion"), - fmcType (kPTIon), - fmass (0), - fcharge(0), - fDecayTime(0), - fpType("Ion"), - fwidth(0), - fiSpin(0), - fiParity(0), - fiConjugation(0), - fiIsospin(0), - fiIsospinZ(0), - fgParity(0), - flepton(0), - fbaryon(0), - fstable(kTRUE) -{ -} - -FairParticle::~FairParticle() -{ - delete fParticle; -} + : TObject() + , fpdg(0) + , fParticle(0) + , fMother(0) + , fDaughters() + , fname("ion") + , fmcType(kPTIon) + , fmass(0) + , fcharge(0) + , fDecayTime(0) + , fpType("Ion") + , fwidth(0) + , fiSpin(0) + , fiParity(0) + , fiConjugation(0) + , fiIsospin(0) + , fiIsospinZ(0) + , fgParity(0) + , flepton(0) + , fbaryon(0) + , fstable(kTRUE) +{} + +FairParticle::~FairParticle() { delete fParticle; } // // public methods @@ -278,94 +275,92 @@ FairParticle::~FairParticle() void FairParticle::SetMother(FairParticle* particle) { -// Adds particles daughter -// --- + // Adds particles daughter + // --- - fMother.SetObject(particle); + fMother.SetObject(particle); } void FairParticle::AddDaughter(FairParticle* particle) { -// Adds particles daughter -// --- + // Adds particles daughter + // --- - fDaughters.Add(particle); + fDaughters.Add(particle); } void FairParticle::Print(Option_t*) const { -// Prints particle properties. -// --- -// return; + // Prints particle properties. + // --- + // return; - cout << "Particle: " << fParticle->GetName() << " with ID: " << fpdg << endl; + cout << "Particle: " << fParticle->GetName() << " with ID: " << fpdg << endl; - // fParticle->Print(); + // fParticle->Print(); - if (GetMother()) { - cout << "Mother: " << GetMother()->GetParticle()->GetName() - << " with ID: " << GetMother()->GetPDG() << endl; - } else { - cout << "Primary " << endl; - } + if (GetMother()) { + cout << "Mother: " << GetMother()->GetParticle()->GetName() << " with ID: " << GetMother()->GetPDG() + << endl; + } else { + cout << "Primary " << endl; + } - cout << "Number of daughters: " << GetNofDaughters() << endl; - cout << endl; + cout << "Number of daughters: " << GetNofDaughters() << endl; + cout << endl; } void FairParticle::PrintDaughters() const { -// Prints particles daughters. -// --- + // Prints particles daughters. + // --- - for (Int_t i=0; iPrint(); - } + for (Int_t i = 0; i < GetNofDaughters(); i++) { + cout << i << "th daughter: " << endl; + GetDaughter(i)->Print(); + } } -Int_t FairParticle::GetPDG() const +Int_t FairParticle::GetPDG() const { -// Returs particle ID. -// --- + // Returs particle ID. + // --- - return fpdg; + return fpdg; } - -TParticle* FairParticle::GetParticle() const +TParticle* FairParticle::GetParticle() const { -// Returns particle definition (TParticle). -// --- + // Returns particle definition (TParticle). + // --- - return fParticle; + return fParticle; } FairParticle* FairParticle::GetMother() const { -// Returns particle definition (TParticle). -// --- + // Returns particle definition (TParticle). + // --- - return static_cast(fMother.GetObject()); + return static_cast(fMother.GetObject()); } Int_t FairParticle::GetNofDaughters() const { -// Returns number of daughters. -// --- + // Returns number of daughters. + // --- - return fDaughters.GetEntriesFast(); + return fDaughters.GetEntriesFast(); } FairParticle* FairParticle::GetDaughter(Int_t i) const { -// Returns i-th daughter. -// --- + // Returns i-th daughter. + // --- - if (i < 0 || i >= GetNofDaughters()) { - Fatal("GetDaughter", "Index out of range"); - } + if (i < 0 || i >= GetNofDaughters()) { + Fatal("GetDaughter", "Index out of range"); + } - return static_cast(fDaughters.At(i)); + return static_cast(fDaughters.At(i)); } - diff --git a/base/sim/FairParticle.h b/base/sim/FairParticle.h index 16531acd74..10385000b9 100644 --- a/base/sim/FairParticle.h +++ b/base/sim/FairParticle.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /// Class FAIRParticle @@ -14,12 +14,12 @@ #ifndef FAIR_PARTICLE_H #define FAIR_PARTICLE_H -#include // for TObject -#include // for Int_t, Double_t, Bool_t, etc -#include // for TMCParticleType -#include // for TRef -#include // for TRefArray -#include // for TString +#include // for Int_t, Double_t, Bool_t, etc +#include // for TMCParticleType +#include // for TObject +#include // for TRef +#include // for TRefArray +#include // for TString class TParticle; @@ -28,12 +28,32 @@ class FairParticle : public TObject public: FairParticle(Int_t id, TParticle* particle); FairParticle(Int_t id, TParticle* particle, FairParticle* mother); - FairParticle(const char* name, Int_t z, Int_t a, Int_t s,Double_t mass , Int_t q, Bool_t stable, Double_t decaytime); - FairParticle(const char* name, Int_t z, Int_t a, Double_t mass , Int_t q, Bool_t stable, Double_t decaytime); - FairParticle( Int_t pdg , const TString name, TMCParticleType mcType, Double_t mass, Double_t charge, - Double_t lifetime, const TString pType="Ion", Double_t width=0, Int_t iSpin=0, Int_t iParity=0, - Int_t iConjugation=0, Int_t iIsospin=0, Int_t iIsospinZ=0, Int_t gParity=0, Int_t lepton=0, - Int_t baryon=0,Bool_t stable=kFALSE); + FairParticle(const char* name, + Int_t z, + Int_t a, + Int_t s, + Double_t mass, + Int_t q, + Bool_t stable, + Double_t decaytime); + FairParticle(const char* name, Int_t z, Int_t a, Double_t mass, Int_t q, Bool_t stable, Double_t decaytime); + FairParticle(Int_t pdg, + const TString name, + TMCParticleType mcType, + Double_t mass, + Double_t charge, + Double_t lifetime, + const TString pType = "Ion", + Double_t width = 0, + Int_t iSpin = 0, + Int_t iParity = 0, + Int_t iConjugation = 0, + Int_t iIsospin = 0, + Int_t iIsospinZ = 0, + Int_t gParity = 0, + Int_t lepton = 0, + Int_t baryon = 0, + Bool_t stable = kFALSE); FairParticle(); @@ -42,59 +62,58 @@ class FairParticle : public TObject // methods void SetMother(FairParticle* particle); void AddDaughter(FairParticle* particle); - virtual void Print(Option_t* option = "") const; + virtual void Print(Option_t* option = "") const; void PrintDaughters() const; // get methods - Int_t GetPDG() const; - TParticle* GetParticle() const; - FairParticle* GetMother() const; - Int_t GetNofDaughters() const; - FairParticle* GetDaughter(Int_t i) const; - virtual const char* GetName() const {return fname.Data();} - TMCParticleType GetMCType() {return fmcType;} - Double_t GetMass() {return fmass;} - Double_t GetCharge() {return fcharge;} - Double_t GetDecayTime() {return fDecayTime;} - const TString& GetPType() {return fpType;} - Double_t GetWidth() {return fwidth;} - Int_t GetSpin() {return fiSpin;} - Int_t GetiParity() {return fiParity;} - Int_t GetConjugation() {return fiConjugation;} - Int_t GetIsospin() {return fiIsospin;} - Int_t GetIsospinZ() {return fiIsospinZ;} - Int_t GetgParity() {return fgParity;} - Int_t GetLepton() {return flepton;} - Int_t GetBaryon() {return fbaryon;} - Bool_t IsStable() {return fstable;} + Int_t GetPDG() const; + TParticle* GetParticle() const; + FairParticle* GetMother() const; + Int_t GetNofDaughters() const; + FairParticle* GetDaughter(Int_t i) const; + virtual const char* GetName() const { return fname.Data(); } + TMCParticleType GetMCType() { return fmcType; } + Double_t GetMass() { return fmass; } + Double_t GetCharge() { return fcharge; } + Double_t GetDecayTime() { return fDecayTime; } + const TString& GetPType() { return fpType; } + Double_t GetWidth() { return fwidth; } + Int_t GetSpin() { return fiSpin; } + Int_t GetiParity() { return fiParity; } + Int_t GetConjugation() { return fiConjugation; } + Int_t GetIsospin() { return fiIsospin; } + Int_t GetIsospinZ() { return fiIsospinZ; } + Int_t GetgParity() { return fgParity; } + Int_t GetLepton() { return flepton; } + Int_t GetBaryon() { return fbaryon; } + Bool_t IsStable() { return fstable; } private: - FairParticle(const FairParticle& P); - FairParticle& operator= (const FairParticle&) {return *this;} + FairParticle& operator=(const FairParticle&) { return *this; } // data members - Int_t fpdg; - TParticle* fParticle; - TRef fMother; - TRefArray fDaughters; - const TString fname; - TMCParticleType fmcType; - Double_t fmass; - Double_t fcharge; - Double_t fDecayTime; - const TString fpType; - Double_t fwidth; - Int_t fiSpin; - Int_t fiParity; - Int_t fiConjugation; - Int_t fiIsospin; - Int_t fiIsospinZ; - Int_t fgParity; - Int_t flepton; - Int_t fbaryon; - Bool_t fstable; + Int_t fpdg; + TParticle* fParticle; + TRef fMother; + TRefArray fDaughters; + const TString fname; + TMCParticleType fmcType; + Double_t fmass; + Double_t fcharge; + Double_t fDecayTime; + const TString fpType; + Double_t fwidth; + Int_t fiSpin; + Int_t fiParity; + Int_t fiConjugation; + Int_t fiIsospin; + Int_t fiIsospinZ; + Int_t fgParity; + Int_t flepton; + Int_t fbaryon; + Bool_t fstable; - ClassDef(FairParticle,3) // Extended TParticle + ClassDef(FairParticle, 3) // Extended TParticle }; -#endif //FAIR_PARTICLE_H +#endif // FAIR_PARTICLE_H diff --git a/base/sim/FairPrimaryGenerator.cxx b/base/sim/FairPrimaryGenerator.cxx index cf438d51ec..55aa1770dc 100644 --- a/base/sim/FairPrimaryGenerator.cxx +++ b/base/sim/FairPrimaryGenerator.cxx @@ -2,443 +2,543 @@ * 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, * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "FairPrimaryGenerator.h" -#include "FairGenerator.h" // for FairGenerator -#include "FairGenericStack.h" // for FairGenericStack -#include "FairLogger.h" // for FairLogger, MESSAGE_ORIGIN -#include "FairMCEventHeader.h" // for FairMCEventHeader +#include "FairGenerator.h" // for FairGenerator +#include "FairGenericStack.h" // for FairGenericStack +#include "FairLogger.h" // for FairLogger, MESSAGE_ORIGIN +#include "FairMCEventHeader.h" // for FairMCEventHeader -#include // for TDatabasePDG -#include // for TIterator -#include // for Sqrt -#include // for TObject -#include // for TParticlePDG -#include // for TRandom, gRandom +#include // for TDatabasePDG +#include // for TIterator +#include // for Sqrt +#include // for TObject +#include // for TParticlePDG +#include // for TRandom, gRandom +#include // for operator<<, basic_ostream, etc -#include // for operator<<, basic_ostream, etc - -using std::cout; using std::cerr; +using std::cout; using std::endl; Int_t FairPrimaryGenerator::fTotPrim = 0; FairPrimaryGenerator::FairPrimaryGenerator() - : TNamed(), fBeamX0(0.), fBeamY0(0.), fBeamSigmaX(0.), fBeamSigmaY(0.), - fBeamAngleX0(0.), fBeamAngleY0(0.), fBeamAngleX(0.), fBeamAngleY(0.), - fBeamAngleSigmaX(0.), fBeamAngleSigmaY(0.), - fBeamDirection(TVector3(0., 0., 1.)), fPhiMin(0.), fPhiMax(0.), fPhi(0.), - fTargetZ(new Double_t[1]), fNrTargets(1), fTargetDz(0), - fVertex(TVector3(0., 0., 0.)), fNTracks(0), fSmearVertexZ(kFALSE), - fSmearGausVertexZ(kFALSE), fSmearVertexXY(kFALSE), - fSmearGausVertexXY(kFALSE), fBeamAngle(kFALSE), fEventPlane(kFALSE), - fStack(nullptr), fGenList(new TObjArray()), - fListIter(fGenList->MakeIterator()), fEvent(nullptr), fdoTracking(kTRUE), - fMCIndexOffset(0), fEventNr(0) { - fTargetZ[0] = 0.; + : TNamed() + , fBeamX0(0.) + , fBeamY0(0.) + , fBeamSigmaX(0.) + , fBeamSigmaY(0.) + , fBeamAngleX0(0.) + , fBeamAngleY0(0.) + , fBeamAngleX(0.) + , fBeamAngleY(0.) + , fBeamAngleSigmaX(0.) + , fBeamAngleSigmaY(0.) + , fBeamDirection(TVector3(0., 0., 1.)) + , fPhiMin(0.) + , fPhiMax(0.) + , fPhi(0.) + , fTargetZ(new Double_t[1]) + , fNrTargets(1) + , fTargetDz(0) + , fVertex(TVector3(0., 0., 0.)) + , fNTracks(0) + , fSmearVertexZ(kFALSE) + , fSmearGausVertexZ(kFALSE) + , fSmearVertexXY(kFALSE) + , fSmearGausVertexXY(kFALSE) + , fBeamAngle(kFALSE) + , fEventPlane(kFALSE) + , fStack(nullptr) + , fGenList(new TObjArray()) + , fListIter(fGenList->MakeIterator()) + , fEvent(nullptr) + , fdoTracking(kTRUE) + , fMCIndexOffset(0) + , fEventNr(0) +{ + fTargetZ[0] = 0.; } FairPrimaryGenerator::FairPrimaryGenerator(const char *name, const char *title) - : TNamed(name, title), fBeamX0(0), fBeamY0(0), fBeamSigmaX(0), - fBeamSigmaY(0), fBeamAngleX0(0), fBeamAngleY0(0), fBeamAngleX(0), - fBeamAngleY(0), fBeamAngleSigmaX(0), fBeamAngleSigmaY(0), - fBeamDirection(TVector3(0., 0., 1.)), fPhiMin(0.), fPhiMax(0.), fPhi(0.), - fTargetZ(new Double_t[1]), fNrTargets(1), fTargetDz(0), - fVertex(TVector3(0., 0., 0.)), fNTracks(0), fSmearVertexZ(kFALSE), - fSmearGausVertexZ(kFALSE), fSmearVertexXY(kFALSE), - fSmearGausVertexXY(kFALSE), fBeamAngle(kFALSE), fEventPlane(kFALSE), - fStack(nullptr), fGenList(new TObjArray()), - fListIter(fGenList->MakeIterator()), fEvent(nullptr), fdoTracking(kTRUE), - fMCIndexOffset(0), fEventNr(0) { - fTargetZ[0] = 0.; + : TNamed(name, title) + , fBeamX0(0) + , fBeamY0(0) + , fBeamSigmaX(0) + , fBeamSigmaY(0) + , fBeamAngleX0(0) + , fBeamAngleY0(0) + , fBeamAngleX(0) + , fBeamAngleY(0) + , fBeamAngleSigmaX(0) + , fBeamAngleSigmaY(0) + , fBeamDirection(TVector3(0., 0., 1.)) + , fPhiMin(0.) + , fPhiMax(0.) + , fPhi(0.) + , fTargetZ(new Double_t[1]) + , fNrTargets(1) + , fTargetDz(0) + , fVertex(TVector3(0., 0., 0.)) + , fNTracks(0) + , fSmearVertexZ(kFALSE) + , fSmearGausVertexZ(kFALSE) + , fSmearVertexXY(kFALSE) + , fSmearGausVertexXY(kFALSE) + , fBeamAngle(kFALSE) + , fEventPlane(kFALSE) + , fStack(nullptr) + , fGenList(new TObjArray()) + , fListIter(fGenList->MakeIterator()) + , fEvent(nullptr) + , fdoTracking(kTRUE) + , fMCIndexOffset(0) + , fEventNr(0) +{ + fTargetZ[0] = 0.; } FairPrimaryGenerator::FairPrimaryGenerator(const FairPrimaryGenerator &rhs) - : TNamed(rhs), fBeamX0(rhs.fBeamX0), fBeamY0(rhs.fBeamY0), - fBeamSigmaX(rhs.fBeamSigmaX), fBeamSigmaY(rhs.fBeamSigmaY), - fBeamAngleX0(rhs.fBeamAngleX0), fBeamAngleY0(rhs.fBeamAngleY0), - fBeamAngleX(rhs.fBeamAngleX), fBeamAngleY(rhs.fBeamAngleY), - fBeamAngleSigmaX(rhs.fBeamAngleSigmaX), fBeamAngleSigmaY(rhs.fBeamAngleSigmaY), - fBeamDirection(rhs.fBeamDirection), - fPhiMin(rhs.fPhiMin), fPhiMax(rhs.fPhiMax), fPhi(rhs.fPhi), - fTargetZ(new Double_t[1]), fNrTargets(rhs.fNrTargets), - fTargetDz(rhs.fTargetDz), fVertex(rhs.fVertex), fNTracks(rhs.fNTracks), - fSmearVertexZ(rhs.fSmearVertexZ), fSmearGausVertexZ(rhs.fSmearGausVertexZ), - fSmearVertexXY(rhs.fSmearVertexXY), fSmearGausVertexXY(rhs.fSmearGausVertexXY), - fBeamAngle(rhs.fBeamAngle), fEventPlane(rhs.fEventPlane), - fStack(nullptr), fGenList(new TObjArray()), - fListIter(fGenList->MakeIterator()), fEvent(nullptr), fdoTracking(rhs.fdoTracking), - fMCIndexOffset(rhs.fMCIndexOffset), fEventNr(rhs.fEventNr) { - fTargetZ[0] = rhs.fTargetZ[0]; + : TNamed(rhs) + , fBeamX0(rhs.fBeamX0) + , fBeamY0(rhs.fBeamY0) + , fBeamSigmaX(rhs.fBeamSigmaX) + , fBeamSigmaY(rhs.fBeamSigmaY) + , fBeamAngleX0(rhs.fBeamAngleX0) + , fBeamAngleY0(rhs.fBeamAngleY0) + , fBeamAngleX(rhs.fBeamAngleX) + , fBeamAngleY(rhs.fBeamAngleY) + , fBeamAngleSigmaX(rhs.fBeamAngleSigmaX) + , fBeamAngleSigmaY(rhs.fBeamAngleSigmaY) + , fBeamDirection(rhs.fBeamDirection) + , fPhiMin(rhs.fPhiMin) + , fPhiMax(rhs.fPhiMax) + , fPhi(rhs.fPhi) + , fTargetZ(new Double_t[1]) + , fNrTargets(rhs.fNrTargets) + , fTargetDz(rhs.fTargetDz) + , fVertex(rhs.fVertex) + , fNTracks(rhs.fNTracks) + , fSmearVertexZ(rhs.fSmearVertexZ) + , fSmearGausVertexZ(rhs.fSmearGausVertexZ) + , fSmearVertexXY(rhs.fSmearVertexXY) + , fSmearGausVertexXY(rhs.fSmearGausVertexXY) + , fBeamAngle(rhs.fBeamAngle) + , fEventPlane(rhs.fEventPlane) + , fStack(nullptr) + , fGenList(new TObjArray()) + , fListIter(fGenList->MakeIterator()) + , fEvent(nullptr) + , fdoTracking(rhs.fdoTracking) + , fMCIndexOffset(rhs.fMCIndexOffset) + , fEventNr(rhs.fEventNr) +{ + fTargetZ[0] = rhs.fTargetZ[0]; } -Bool_t FairPrimaryGenerator::Init() { - /** Initialize list of generators*/ - for (Int_t i = 0; i < fGenList->GetEntries(); i++) { - FairGenerator *gen = static_cast(fGenList->At(i)); - if (gen) { - gen->Init(); +Bool_t FairPrimaryGenerator::Init() +{ + /** Initialize list of generators*/ + for (Int_t i = 0; i < fGenList->GetEntries(); i++) { + FairGenerator *gen = static_cast(fGenList->At(i)); + if (gen) { + gen->Init(); + } } - } - return kTRUE; + return kTRUE; } -FairPrimaryGenerator::~FairPrimaryGenerator() { - - delete[] fTargetZ; - fGenList->Delete(); - delete fGenList; - delete fListIter; +FairPrimaryGenerator::~FairPrimaryGenerator() +{ + delete[] fTargetZ; + fGenList->Delete(); + delete fGenList; + delete fListIter; } -FairPrimaryGenerator& FairPrimaryGenerator::operator=(const FairPrimaryGenerator& rhs) +FairPrimaryGenerator &FairPrimaryGenerator::operator=(const FairPrimaryGenerator &rhs) { - // check assignment to self - if (this != &rhs) { - - // base class assignment - TNamed::operator=(rhs); - - // assignment operator - fBeamX0 = rhs.fBeamX0; - fBeamY0 = rhs.fBeamY0; - fBeamSigmaX = rhs.fBeamSigmaX; - fBeamSigmaY = rhs.fBeamSigmaY; - fBeamAngleX0 = rhs.fBeamAngleX0; - fBeamAngleY0 = rhs.fBeamAngleY0; - fBeamAngleX = rhs.fBeamAngleX; - fBeamAngleY = rhs.fBeamAngleY; - fBeamAngleSigmaX = rhs.fBeamAngleSigmaX; - fBeamAngleSigmaY = rhs.fBeamAngleSigmaY; - fBeamDirection = rhs.fBeamDirection; - fPhiMin = rhs.fPhiMin; - fPhiMax = rhs.fPhiMax; - fPhi = rhs.fPhi; - fTargetZ = new Double_t[1]; - fNrTargets = rhs.fNrTargets; - fTargetDz = rhs.fTargetDz; - fVertex = rhs.fVertex; - fNTracks = rhs.fNTracks; - fSmearVertexZ = rhs.fSmearVertexZ; - fSmearGausVertexZ = rhs.fSmearGausVertexZ; - fSmearVertexXY = rhs.fSmearVertexXY; - fSmearGausVertexXY = rhs.fSmearGausVertexXY; - fBeamAngle = rhs.fBeamAngle; - fEventPlane = rhs.fEventPlane; - fStack = nullptr; - fGenList =new TObjArray(); - fListIter = fGenList->MakeIterator(); - fEvent = nullptr; - fdoTracking = rhs.fdoTracking; - fMCIndexOffset = rhs.fMCIndexOffset; - fEventNr = rhs.fEventNr; - fTargetZ[0] = rhs.fTargetZ[0]; - } + // check assignment to self + if (this != &rhs) { + + // base class assignment + TNamed::operator=(rhs); + + // assignment operator + fBeamX0 = rhs.fBeamX0; + fBeamY0 = rhs.fBeamY0; + fBeamSigmaX = rhs.fBeamSigmaX; + fBeamSigmaY = rhs.fBeamSigmaY; + fBeamAngleX0 = rhs.fBeamAngleX0; + fBeamAngleY0 = rhs.fBeamAngleY0; + fBeamAngleX = rhs.fBeamAngleX; + fBeamAngleY = rhs.fBeamAngleY; + fBeamAngleSigmaX = rhs.fBeamAngleSigmaX; + fBeamAngleSigmaY = rhs.fBeamAngleSigmaY; + fBeamDirection = rhs.fBeamDirection; + fPhiMin = rhs.fPhiMin; + fPhiMax = rhs.fPhiMax; + fPhi = rhs.fPhi; + fTargetZ = new Double_t[1]; + fNrTargets = rhs.fNrTargets; + fTargetDz = rhs.fTargetDz; + fVertex = rhs.fVertex; + fNTracks = rhs.fNTracks; + fSmearVertexZ = rhs.fSmearVertexZ; + fSmearGausVertexZ = rhs.fSmearGausVertexZ; + fSmearVertexXY = rhs.fSmearVertexXY; + fSmearGausVertexXY = rhs.fSmearGausVertexXY; + fBeamAngle = rhs.fBeamAngle; + fEventPlane = rhs.fEventPlane; + fStack = nullptr; + fGenList = new TObjArray(); + fListIter = fGenList->MakeIterator(); + fEvent = nullptr; + fdoTracking = rhs.fdoTracking; + fMCIndexOffset = rhs.fMCIndexOffset; + fEventNr = rhs.fEventNr; + fTargetZ[0] = rhs.fTargetZ[0]; + } - return *this; + return *this; } -Bool_t FairPrimaryGenerator::GenerateEvent(FairGenericStack *pStack) { - // Check for MCEventHeader - if (!fEvent) { - LOG(fatal) << "No MCEventHeader branch!"; - return kFALSE; - } else { - // Initialise - fStack = pStack; - fNTracks = 0; - fEvent->Reset(); - - // Create beam angle - // Here we only randomly generate two angles (anglex, angley) - // for the event and later on (in AddTrack()) - // all our particles will be rotated accordingly. - if (fBeamAngle) { - MakeBeamAngle(); +Bool_t FairPrimaryGenerator::GenerateEvent(FairGenericStack *pStack) +{ + // Check for MCEventHeader + if (!fEvent) { + LOG(fatal) << "No MCEventHeader branch!"; + return kFALSE; + } else { + // Initialise + fStack = pStack; + fNTracks = 0; + fEvent->Reset(); + + // Create beam angle + // Here we only randomly generate two angles (anglex, angley) + // for the event and later on (in AddTrack()) + // all our particles will be rotated accordingly. + if (fBeamAngle) { + MakeBeamAngle(); + } + + // Create event vertex + MakeVertex(); + fEvent->SetVertex(fVertex); + + // Create event plane + // Randomly generate an angle by which each track added (in AddTrack()) + // to the event is rotated around the z-axis + if (fEventPlane) { + MakeEventPlane(); + } + + // Call the ReadEvent methods from all registered generators + fListIter->Reset(); + TObject *obj = 0; + FairGenerator *gen = 0; + while ((obj = fListIter->Next())) { + gen = dynamic_cast(obj); + if (!gen) { + return kFALSE; + } + const char *genName = gen->GetName(); + fMCIndexOffset = fNTracks; // number tracks before generator is called + Bool_t test = gen->ReadEvent(this); + if (!test) { + LOG(error) << "ReadEvent failed for generator " << genName; + return kFALSE; + } + } + + fTotPrim += fNTracks; + // Screen output + + // Set the event number if not set already by one of the dedicated generators + if (-1 == fEvent->GetEventID()) { + fEventNr++; + fEvent->SetEventID(fEventNr); + } + LOG(debug) << "(Event " << fEvent->GetEventID() << ") " << fNTracks << " primary tracks from vertex (" + << fVertex.X() << ", " << fVertex.Y() << ", " << fVertex.Z() << ") with beam angle (" << fBeamAngleX + << ", " << fBeamAngleY << ") "; + + fEvent->SetNPrim(fNTracks); + + return kTRUE; } +} + +void FairPrimaryGenerator::AddTrack(Int_t pdgid, + Double_t px_raw, + Double_t py_raw, + Double_t pz_raw, + Double_t vx, + Double_t vy, + Double_t vz, + Int_t parent, + Bool_t wanttracking, + Double_t e, + Double_t tof, + Double_t weight, + TMCProcess proc) +{ + // ---> Add event vertex to track vertex + vx += fVertex.X(); + vy += fVertex.Y(); + vz += fVertex.Z(); - // Create event vertex - MakeVertex(); - fEvent->SetVertex(fVertex); + // cout << "FairPrimaryGenerator::AddTrack +Z" << fVertex.Z() << " pdgid " << + // pdgid << "?"<< wanttracking << endl; + TVector3 mom(px_raw, py_raw, pz_raw); - // Create event plane - // Randomly generate an angle by which each track added (in AddTrack()) - // to the event is rotated around the z-axis if (fEventPlane) { - MakeEventPlane(); + // Rotate the track (event) by the randomly generated angle which is fixed + // for the complete event. + // The coordinate system is not changed by this rotation. + mom.RotateZ(fPhi); } - // Call the ReadEvent methods from all registered generators - fListIter->Reset(); - TObject *obj = 0; - FairGenerator *gen = 0; - while ((obj = fListIter->Next())) { - gen = dynamic_cast(obj); - if (!gen) { - return kFALSE; - } - const char *genName = gen->GetName(); - fMCIndexOffset = fNTracks; // number tracks before generator is called - Bool_t test = gen->ReadEvent(this); - if (!test) { - LOG(error) << "ReadEvent failed for generator " << genName; - return kFALSE; - } + if (fBeamAngle) { + // Rotate the track (event) from the rotated beam direction system into + // the fixed global experiment coordinate system + mom.RotateUz(fBeamDirection.Unit()); } - - fTotPrim += fNTracks; - // Screen output - - // Set the event number if not set already by one of the dedicated generators - if (-1 == fEvent->GetEventID()) { - fEventNr++; - fEvent->SetEventID(fEventNr); + // ---> Convert K0 and AntiK0 into K0s and K0L + if (pdgid == 311 || pdgid == -311) { + Double_t test = gRandom->Uniform(0., 1.); + if (test >= 0.5) { + pdgid = 310; + } // K0S + else { + pdgid = 130; + } // K0L } - LOG(debug) << "(Event " << fEvent->GetEventID() << ") " << fNTracks - << " primary tracks from vertex (" << fVertex.X() << ", " - << fVertex.Y() << ", " << fVertex.Z() << ") with beam angle (" - << fBeamAngleX << ", " << fBeamAngleY << ") "; - - fEvent->SetNPrim(fNTracks); - return kTRUE; - } -} - -void FairPrimaryGenerator::AddTrack(Int_t pdgid, Double_t px_raw, - Double_t py_raw, Double_t pz_raw, - Double_t vx, Double_t vy, Double_t vz, - Int_t parent, Bool_t wanttracking, - Double_t e, Double_t tof, - Double_t weight, TMCProcess proc) { - // ---> Add event vertex to track vertex - vx += fVertex.X(); - vy += fVertex.Y(); - vz += fVertex.Z(); - - // cout << "FairPrimaryGenerator::AddTrack +Z" << fVertex.Z() << " pdgid " << - // pdgid << "?"<< wanttracking << endl; - - TVector3 mom(px_raw, py_raw, pz_raw); - - if (fEventPlane) { - // Rotate the track (event) by the randomly generated angle which is fixed - // for the complete event. - // The coordinate system is not changed by this rotation. - mom.RotateZ(fPhi); - } - - if (fBeamAngle) { - // Rotate the track (event) from the rotated beam direction system into - // the fixed global experiment coordinate system - mom.RotateUz(fBeamDirection.Unit()); - } - - // ---> Convert K0 and AntiK0 into K0s and K0L - if (pdgid == 311 || pdgid == -311) { - Double_t test = gRandom->Uniform(0., 1.); - if (test >= 0.5) { - pdgid = 310; - } // K0S - else { - pdgid = 130; - } // K0L - } - - // ---> Check whether particle type is in PDG Database - TDatabasePDG *pdgBase = TDatabasePDG::Instance(); - if (!pdgBase) { - Fatal("FairPrimaryGenerator", "No TDatabasePDG instantiated"); - } else { - TParticlePDG *pdgPart = pdgBase->GetParticle(pdgid); - if (!pdgPart) { - if (e < 0) { - cerr << "\033[5m\033[31m -E FairPrimaryGenerator: PDG code " << pdgid - << " not found in database.\033[0m " << endl; - cerr << "\033[5m\033[31m -E FairPrimaryGenerator: Discarding particle " - "\033[0m " << endl; - cerr << "\033[5m\033[31m -E FairPrimaryGenerator: now MC Index is " - "corrupted \033[0m " << endl; - return; - } else { - cout << "\033[5m\033[31m -W FairPrimaryGenerator: PDG code " << pdgid - << " not found in database. This warning can be savely " - "ignored.\033[0m " << endl; - } + // ---> Check whether particle type is in PDG Database + TDatabasePDG *pdgBase = TDatabasePDG::Instance(); + if (!pdgBase) { + Fatal("FairPrimaryGenerator", "No TDatabasePDG instantiated"); + } else { + TParticlePDG *pdgPart = pdgBase->GetParticle(pdgid); + if (!pdgPart) { + if (e < 0) { + cerr << "\033[5m\033[31m -E FairPrimaryGenerator: PDG code " << pdgid + << " not found in database.\033[0m " << endl; + cerr << "\033[5m\033[31m -E FairPrimaryGenerator: Discarding particle " + "\033[0m " + << endl; + cerr << "\033[5m\033[31m -E FairPrimaryGenerator: now MC Index is " + "corrupted \033[0m " + << endl; + return; + } else { + cout << "\033[5m\033[31m -W FairPrimaryGenerator: PDG code " << pdgid + << " not found in database. This warning can be savely " + "ignored.\033[0m " + << endl; + } + } + } + // ---> Get mass and calculate energy of particle + if (e < 0) { + Double_t mass = pdgBase->GetParticle(pdgid)->Mass(); + e = TMath::Sqrt(mom.Mag2() + mass * mass); + } // else, use the value of e given to the function + + // ---> Set all other parameters required by PushTrack + Int_t doTracking = 0; // Go to tracking + if (fdoTracking && wanttracking) { + doTracking = 1; } - } - // ---> Get mass and calculate energy of particle - if (e < 0) { - Double_t mass = pdgBase->GetParticle(pdgid)->Mass(); - e = TMath::Sqrt(mom.Mag2() + mass * mass); - } // else, use the value of e given to the function - - // ---> Set all other parameters required by PushTrack - Int_t doTracking = 0; // Go to tracking - if (fdoTracking && wanttracking) { - doTracking = 1; - } - Int_t dummyparent = -1; // Primary particle (now the value is -1 by default) - Double_t polx = 0.; // Polarisation - Double_t poly = 0.; - Double_t polz = 0.; - Int_t ntr = 0; // Track number; to be filled by the stack - Int_t status = 0; // Generation status - - if (parent != -1) { - parent += fMCIndexOffset; - } // correct for tracks which are in list before generator is called - // Add track to stack - fStack->PushTrack(doTracking, dummyparent, pdgid, mom.X(), mom.Y(), mom.Z(), - e, vx, vy, vz, tof, polx, poly, polz, proc, ntr, - weight, status, parent); - fNTracks++; + Int_t dummyparent = -1; // Primary particle (now the value is -1 by default) + Double_t polx = 0.; // Polarisation + Double_t poly = 0.; + Double_t polz = 0.; + Int_t ntr = 0; // Track number; to be filled by the stack + Int_t status = 0; // Generation status + + if (parent != -1) { + parent += fMCIndexOffset; + } // correct for tracks which are in list before generator is called + // Add track to stack + fStack->PushTrack(doTracking, + dummyparent, + pdgid, + mom.X(), + mom.Y(), + mom.Z(), + e, + vx, + vy, + vz, + tof, + polx, + poly, + polz, + proc, + ntr, + weight, + status, + parent); + fNTracks++; } -FairPrimaryGenerator* FairPrimaryGenerator::ClonePrimaryGenerator() const +FairPrimaryGenerator *FairPrimaryGenerator::ClonePrimaryGenerator() const { - FairPrimaryGenerator* newPrimaryGenerator = new FairPrimaryGenerator(*this); - - /** Clone generators in the list*/ - for (Int_t i = 0; i < fGenList->GetEntries(); i++) { - FairGenerator *gen = static_cast(fGenList->At(i)); - if (gen) { - newPrimaryGenerator->AddGenerator(gen->CloneGenerator()); + FairPrimaryGenerator *newPrimaryGenerator = new FairPrimaryGenerator(*this); + + /** Clone generators in the list*/ + for (Int_t i = 0; i < fGenList->GetEntries(); i++) { + FairGenerator *gen = static_cast(fGenList->At(i)); + if (gen) { + newPrimaryGenerator->AddGenerator(gen->CloneGenerator()); + } } - } - return newPrimaryGenerator; + return newPrimaryGenerator; } -void FairPrimaryGenerator::SetBeam(Double_t x0, Double_t y0, Double_t sigmaX, - Double_t sigmaY) { - fBeamX0 = x0; - fBeamY0 = y0; - fBeamSigmaX = sigmaX; - fBeamSigmaY = sigmaY; +void FairPrimaryGenerator::SetBeam(Double_t x0, Double_t y0, Double_t sigmaX, Double_t sigmaY) +{ + fBeamX0 = x0; + fBeamY0 = y0; + fBeamSigmaX = sigmaX; + fBeamSigmaY = sigmaY; } void FairPrimaryGenerator::SetBeamAngle(Double_t beamAngleX0, Double_t beamAngleY0, Double_t beamAngleSigmaX, - Double_t beamAngleSigmaY) { - fBeamAngleX0 = beamAngleX0; - fBeamAngleY0 = beamAngleY0; - fBeamAngleSigmaX = beamAngleSigmaX; - fBeamAngleSigmaY = beamAngleSigmaY; - fBeamAngle = kTRUE; + Double_t beamAngleSigmaY) +{ + fBeamAngleX0 = beamAngleX0; + fBeamAngleY0 = beamAngleY0; + fBeamAngleSigmaX = beamAngleSigmaX; + fBeamAngleSigmaY = beamAngleSigmaY; + fBeamAngle = kTRUE; } -void FairPrimaryGenerator::SetEventPlane(Double_t phiMin, Double_t phiMax) { - fPhiMin = phiMin; - fPhiMax = phiMax; - fEventPlane = kTRUE; +void FairPrimaryGenerator::SetEventPlane(Double_t phiMin, Double_t phiMax) +{ + fPhiMin = phiMin; + fPhiMax = phiMax; + fEventPlane = kTRUE; } -void FairPrimaryGenerator::SetTarget(Double_t z, Double_t dz) { +void FairPrimaryGenerator::SetTarget(Double_t z, Double_t dz) +{ - fTargetZ[0] = z; - fTargetDz = dz; + fTargetZ[0] = z; + fTargetDz = dz; } -void FairPrimaryGenerator::SetMultTarget(Int_t nroftargets, Double_t *targetpos, - Double_t dz) { +void FairPrimaryGenerator::SetMultTarget(Int_t nroftargets, Double_t *targetpos, Double_t dz) +{ - delete[] fTargetZ; + delete[] fTargetZ; - fNrTargets = nroftargets; + fNrTargets = nroftargets; - fTargetZ = new Double_t[nroftargets]; - for (Int_t i = 0; i < nroftargets; i++) { - fTargetZ[i] = targetpos[i]; - } - fTargetDz = dz; + fTargetZ = new Double_t[nroftargets]; + for (Int_t i = 0; i < nroftargets; i++) { + fTargetZ[i] = targetpos[i]; + } + fTargetDz = dz; } -void FairPrimaryGenerator::MakeVertex() { - Double_t vx = fBeamX0; - Double_t vy = fBeamY0; - Double_t vz; - if (1 == fNrTargets) { - vz = fTargetZ[0]; - } else { - Int_t Target = static_cast(gRandom->Uniform(fNrTargets)); - vz = fTargetZ[Target]; - } - - if (fSmearVertexZ) - vz = gRandom->Uniform(vz - fTargetDz / 2., vz + fTargetDz / 2.); - - if (fSmearGausVertexZ) { - vz = gRandom->Gaus(vz, fTargetDz); - } - - if (fSmearGausVertexXY) { - if (fBeamSigmaX != 0.) { - vx = gRandom->Gaus(fBeamX0, fBeamSigmaX); +void FairPrimaryGenerator::MakeVertex() +{ + Double_t vx = fBeamX0; + Double_t vy = fBeamY0; + Double_t vz; + if (1 == fNrTargets) { + vz = fTargetZ[0]; + } else { + Int_t Target = static_cast(gRandom->Uniform(fNrTargets)); + vz = fTargetZ[Target]; } - if (fBeamSigmaY != 0.) { - vy = gRandom->Gaus(fBeamY0, fBeamSigmaY); + + if (fSmearVertexZ) + vz = gRandom->Uniform(vz - fTargetDz / 2., vz + fTargetDz / 2.); + + if (fSmearGausVertexZ) { + vz = gRandom->Gaus(vz, fTargetDz); } - } - if (fSmearVertexXY) { - if (fBeamSigmaX != 0.) { - vx = gRandom->Uniform(vx - fBeamSigmaX / 2., vx + fBeamSigmaX / 2.); + if (fSmearGausVertexXY) { + if (fBeamSigmaX != 0.) { + vx = gRandom->Gaus(fBeamX0, fBeamSigmaX); + } + if (fBeamSigmaY != 0.) { + vy = gRandom->Gaus(fBeamY0, fBeamSigmaY); + } } - if (fBeamSigmaY != 0.) { - vy = gRandom->Uniform(vy - fBeamSigmaY / 2., vy + fBeamSigmaY / 2.); + + if (fSmearVertexXY) { + if (fBeamSigmaX != 0.) { + vx = gRandom->Uniform(vx - fBeamSigmaX / 2., vx + fBeamSigmaX / 2.); + } + if (fBeamSigmaY != 0.) { + vy = gRandom->Uniform(vy - fBeamSigmaY / 2., vy + fBeamSigmaY / 2.); + } } - } - fVertex = TVector3(vx, vy, vz); + fVertex = TVector3(vx, vy, vz); } -void FairPrimaryGenerator::MakeBeamAngle() { - fBeamAngleX = gRandom->Gaus(fBeamAngleX0, fBeamAngleSigmaX); - fBeamAngleY = gRandom->Gaus(fBeamAngleY0, fBeamAngleSigmaY); - fBeamDirection.SetXYZ(TMath::Tan(fBeamAngleX), TMath::Tan(fBeamAngleY), 1.); - fEvent->SetRotX(fBeamAngleX); - fEvent->SetRotY(fBeamAngleY); +void FairPrimaryGenerator::MakeBeamAngle() +{ + fBeamAngleX = gRandom->Gaus(fBeamAngleX0, fBeamAngleSigmaX); + fBeamAngleY = gRandom->Gaus(fBeamAngleY0, fBeamAngleSigmaY); + fBeamDirection.SetXYZ(TMath::Tan(fBeamAngleX), TMath::Tan(fBeamAngleY), 1.); + fEvent->SetRotX(fBeamAngleX); + fEvent->SetRotY(fBeamAngleY); } -void FairPrimaryGenerator::MakeEventPlane() { - fPhi = gRandom->Uniform(fPhiMin, fPhiMax); - fEvent->SetRotZ(fPhi); +void FairPrimaryGenerator::MakeEventPlane() +{ + fPhi = gRandom->Uniform(fPhiMin, fPhiMax); + fEvent->SetRotZ(fPhi); } -void FairPrimaryGenerator::SmearVertexZ(Bool_t flag) { - fSmearVertexZ = flag; - if (fSmearVertexZ && fSmearGausVertexZ) { - fSmearGausVertexZ = kFALSE; - } +void FairPrimaryGenerator::SmearVertexZ(Bool_t flag) +{ + fSmearVertexZ = flag; + if (fSmearVertexZ && fSmearGausVertexZ) { + fSmearGausVertexZ = kFALSE; + } } -void FairPrimaryGenerator::SmearGausVertexZ(Bool_t flag) { - fSmearGausVertexZ = flag; - if (fSmearGausVertexZ && fSmearVertexZ) { - fSmearVertexZ = kFALSE; - } +void FairPrimaryGenerator::SmearGausVertexZ(Bool_t flag) +{ + fSmearGausVertexZ = flag; + if (fSmearGausVertexZ && fSmearVertexZ) { + fSmearVertexZ = kFALSE; + } } -void FairPrimaryGenerator::SmearVertexXY(Bool_t flag) { - fSmearVertexXY = flag; - if (fSmearVertexXY && fSmearGausVertexXY) { - fSmearGausVertexXY = kFALSE; - } +void FairPrimaryGenerator::SmearVertexXY(Bool_t flag) +{ + fSmearVertexXY = flag; + if (fSmearVertexXY && fSmearGausVertexXY) { + fSmearGausVertexXY = kFALSE; + } } -void FairPrimaryGenerator::SmearGausVertexXY(Bool_t flag) { - fSmearGausVertexXY = flag; - if (fSmearGausVertexXY && fSmearVertexXY) { - fSmearVertexXY = kFALSE; - } +void FairPrimaryGenerator::SmearGausVertexXY(Bool_t flag) +{ + fSmearGausVertexXY = flag; + if (fSmearGausVertexXY && fSmearVertexXY) { + fSmearVertexXY = kFALSE; + } } -ClassImp(FairPrimaryGenerator) +ClassImp(FairPrimaryGenerator); diff --git a/base/sim/FairPrimaryGenerator.h b/base/sim/FairPrimaryGenerator.h index 2759717fc3..662560fc8b 100644 --- a/base/sim/FairPrimaryGenerator.h +++ b/base/sim/FairPrimaryGenerator.h @@ -2,7 +2,7 @@ * 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, * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ @@ -23,220 +23,222 @@ the tracking from the macro (M. Al-Turany) #ifndef FAIRPRIMARYGENERATOR_H #define FAIRPRIMARYGENERATOR_H +#include "FairGenerator.h" // for FairGenerator -#include "FairGenerator.h" // for FairGenerator - -#include // for TNamed -#include // for Double_t, Bool_t, Int_t, etc -#include // for TObjArray -#include // for TVector3 +#include // for Double_t, Bool_t, Int_t, etc #include - -#include // for cout +#include // for TNamed +#include // for TObjArray +#include // for TVector3 +#include // for cout class FairGenericStack; class FairMCEventHeader; class TIterator; -class FairPrimaryGenerator : public TNamed { +class FairPrimaryGenerator : public TNamed +{ -public: - /** Default constructor. **/ - FairPrimaryGenerator(); + public: + /** Default constructor. **/ + FairPrimaryGenerator(); - /** Constructor with name and title **/ - FairPrimaryGenerator(const char *name, const char *title = "FAIR Generator"); + /** Constructor with name and title **/ + FairPrimaryGenerator(const char *name, const char *title = "FAIR Generator"); - /** Destructor. **/ - virtual ~FairPrimaryGenerator(); + /** Destructor. **/ + virtual ~FairPrimaryGenerator(); - /** Initialize the generater (if needed!)*/ - virtual Bool_t Init(); + /** Initialize the generater (if needed!)*/ + virtual Bool_t Init(); - /** Register a generator derived from FairGenerator. **/ - void AddGenerator(FairGenerator *generator) { - if (!fGenList) { - std::cout << "Empty fGenList pointer ! " << std::endl; - return; + /** Register a generator derived from FairGenerator. **/ + void AddGenerator(FairGenerator *generator) + { + if (!fGenList) { + std::cout << "Empty fGenList pointer ! " << std::endl; + return; + } + fGenList->Add(generator); } - fGenList->Add(generator); - } - void SetEventNr(Int_t evtNr) { fEventNr = evtNr; } + void SetEventNr(Int_t evtNr) { fEventNr = evtNr; } - /** Public method GenerateEvent + /** Public method GenerateEvent To be called at the beginning of each event from FairMCApplication. Generates an event vertex and calls the ReadEvent methods from the registered generators. *@param pStack The particle stack *@return kTRUE if successful, kFALSE if not **/ - virtual Bool_t GenerateEvent(FairGenericStack *pStack); + virtual Bool_t GenerateEvent(FairGenericStack *pStack); - /** Public method AddTrack + /** Public method AddTrack Adding a track to the MC stack. To be called within the ReadEvent methods of the registered generators. *@param pdgid Particle ID (PDG code) *@param px,py,pz Momentum coordinates [GeV] *@param vx,vy,vz Track origin relative to event vertex **/ - virtual void AddTrack(Int_t pdgid, Double_t px, Double_t py, Double_t pz, - Double_t vx, Double_t vy, Double_t vz, - Int_t parent = -1, Bool_t wanttracking = true, - Double_t e = -9e9, Double_t tof = 0., - Double_t weight = 0., TMCProcess proc = kPPrimary); - - /** Clone this object (used in MT mode only) */ - virtual FairPrimaryGenerator* ClonePrimaryGenerator() const; - - /** Set beam position and widths. - *@param beamX0 mean x position of beam at target - *@param beamY0 mean y position of beam at target - *@param beamSigmaX Gaussian beam width in x - *@param beamSigmaY Gaussian beam width in y - **/ - void SetBeam(Double_t beamX0, Double_t beamY0, Double_t beamSigmaX, - Double_t beamSigmaY); - - /** Set nominal beam angle and angle widths. - *@param beamAngleX0 mean x angle of beam at target - *@param beamAngleY0 mean y angle of beam at target - *@param beamAngleSigmaX Gaussian beam angle width in x - *@param beamAngleSigmaY Gaussian beam angle width in y - **/ - void SetBeamAngle(Double_t beamAngleX0, Double_t beamAngleY0, - Double_t beamAngleSigmaX, Double_t beamAngleSigmaY); - - /** Public method SetEventPlane - **@param phiMin Lower limit for event plane angle [rad] - **@param phiMax Upper limit for event plane angle [rad] - **If set, an event plane angle will be generated with flat - **distrtibution between phiMin and phiMax. - **/ - void SetEventPlane(Double_t phiMin, Double_t phiMax); - - /** Set target position and thickness. - *@param targetZ z position of target center - *@param targetDz full target thickness - **/ - void SetTarget(Double_t targetZ, Double_t targetDz); - - /** Set target position for multiple tagets. The thickness - * is the same for all targets. - *@param nroftargets number of targets - *@param *targetZ z positions of target center - *@param targetDz full target thickness - **/ - void SetMultTarget(Int_t nroftargets, Double_t *targetZ, Double_t targetDz); - - /** Enable vertex smearing in z and/or xy direction **/ - void SmearVertexZ(Bool_t flag); - void SmearGausVertexZ(Bool_t flag); - void SmearVertexXY(Bool_t flag); - void SmearGausVertexXY(Bool_t flag); - - TObjArray *GetListOfGenerators() { return fGenList; } - - /** Set the pointer to the MCEvent **/ - void SetEvent(FairMCEventHeader *event) { - fEvent = event; - }; - - /** Accessor to the MCEvent **/ - FairMCEventHeader *GetEvent() { - return fEvent; - }; - - /** Swich on/off the tracking of a particle*/ - - void DoTracking(Bool_t doTracking = kTRUE) { fdoTracking = doTracking; } - - Int_t GetTotPrimary() { return fTotPrim; } - -protected: - /** Copy constructor */ - FairPrimaryGenerator(const FairPrimaryGenerator&); - /** Assignment operator */ - FairPrimaryGenerator &operator=(const FairPrimaryGenerator&); - - /** Nominal beam position at target in x [cm] */ - Double_t fBeamX0; - /** Nominal beam position at target in y [cm]*/ - Double_t fBeamY0; - /** Beam width (Gaussian) in x [cm]*/ - Double_t fBeamSigmaX; - /** Beam width (Gaussian) in y [cm]*/ - Double_t fBeamSigmaY; - - /** Nominal beam angle at target in x [rad] */ - Double_t fBeamAngleX0; - /** Nominal beam angle at target in y [rad] */ - Double_t fBeamAngleY0; - /** Actual beam angle at target in x [rad] */ - Double_t fBeamAngleX; - /** Actual beam angle at target in y [rad] */ - Double_t fBeamAngleY; - /** Beam angle width (Gaussian) in x [rad]*/ - Double_t fBeamAngleSigmaX; - /** Beam angle width (Gaussian) in y [rad]*/ - Double_t fBeamAngleSigmaY; - /** Actual beam direction at the vertex */ - TVector3 fBeamDirection; - - /** Lower limit for the event plane rotation angle [rad] */ - Double_t fPhiMin; - /** Upper limit for the event plane rotation angle [rad] */ - Double_t fPhiMax; - /** Actual event plane rotation angle [rad] */ - Double_t fPhi; - - /** Nominal z position of center of targets [cm]*/ - Double_t *fTargetZ; //! - /** Number of targets;*/ - Int_t fNrTargets; - /** Full target thickness [cm]*/ - Double_t fTargetDz; - - /** Vertex position of current event [cm]*/ - TVector3 fVertex; - - /** Number of primary tracks in current event*/ - Int_t fNTracks; - - /** Flag for uniform vertex smearing in z*/ - Bool_t fSmearVertexZ; - /** Flag for gaus vertex smearing in z*/ - Bool_t fSmearGausVertexZ; - /** Flag for vertex smearing in xy*/ - Bool_t fSmearVertexXY; - /** Flag for gaus vertex smearing in xy*/ - Bool_t fSmearGausVertexXY; - /** Flag for beam gradient calculation*/ - Bool_t fBeamAngle; - /** Flag for event plane rotation*/ - Bool_t fEventPlane; - - /** Pointer to MC stack*/ - FairGenericStack *fStack; //! - /** List of registered generators */ - TObjArray *fGenList; - /** Iterator over generator list */ - TIterator *fListIter; //! - /** Pointer to MCEventHeader */ - FairMCEventHeader *fEvent; //! - /** go to tracking */ - Bool_t fdoTracking; //! - /** Number of MC tracks before a Generator is called, needed for MC index - * update */ - Int_t fMCIndexOffset; //! - /** Number of all primaries of this run*/ - static Int_t fTotPrim; //! - /** Event number (Set by the primary generator if not set already by one of + virtual void AddTrack(Int_t pdgid, + Double_t px, + Double_t py, + Double_t pz, + Double_t vx, + Double_t vy, + Double_t vz, + Int_t parent = -1, + Bool_t wanttracking = true, + Double_t e = -9e9, + Double_t tof = 0., + Double_t weight = 0., + TMCProcess proc = kPPrimary); + + /** Clone this object (used in MT mode only) */ + virtual FairPrimaryGenerator *ClonePrimaryGenerator() const; + + /** Set beam position and widths. + *@param beamX0 mean x position of beam at target + *@param beamY0 mean y position of beam at target + *@param beamSigmaX Gaussian beam width in x + *@param beamSigmaY Gaussian beam width in y + **/ + void SetBeam(Double_t beamX0, Double_t beamY0, Double_t beamSigmaX, Double_t beamSigmaY); + + /** Set nominal beam angle and angle widths. + *@param beamAngleX0 mean x angle of beam at target + *@param beamAngleY0 mean y angle of beam at target + *@param beamAngleSigmaX Gaussian beam angle width in x + *@param beamAngleSigmaY Gaussian beam angle width in y + **/ + void SetBeamAngle(Double_t beamAngleX0, Double_t beamAngleY0, Double_t beamAngleSigmaX, Double_t beamAngleSigmaY); + + /** Public method SetEventPlane + **@param phiMin Lower limit for event plane angle [rad] + **@param phiMax Upper limit for event plane angle [rad] + **If set, an event plane angle will be generated with flat + **distrtibution between phiMin and phiMax. + **/ + void SetEventPlane(Double_t phiMin, Double_t phiMax); + + /** Set target position and thickness. + *@param targetZ z position of target center + *@param targetDz full target thickness + **/ + void SetTarget(Double_t targetZ, Double_t targetDz); + + /** Set target position for multiple tagets. The thickness + * is the same for all targets. + *@param nroftargets number of targets + *@param *targetZ z positions of target center + *@param targetDz full target thickness + **/ + void SetMultTarget(Int_t nroftargets, Double_t *targetZ, Double_t targetDz); + + /** Enable vertex smearing in z and/or xy direction **/ + void SmearVertexZ(Bool_t flag); + void SmearGausVertexZ(Bool_t flag); + void SmearVertexXY(Bool_t flag); + void SmearGausVertexXY(Bool_t flag); + + TObjArray *GetListOfGenerators() { return fGenList; } + + /** Set the pointer to the MCEvent **/ + void SetEvent(FairMCEventHeader *event) { fEvent = event; }; + + /** Accessor to the MCEvent **/ + FairMCEventHeader *GetEvent() { return fEvent; }; + + /** Swich on/off the tracking of a particle*/ + + void DoTracking(Bool_t doTracking = kTRUE) { fdoTracking = doTracking; } + + Int_t GetTotPrimary() { return fTotPrim; } + + protected: + /** Copy constructor */ + FairPrimaryGenerator(const FairPrimaryGenerator &); + /** Assignment operator */ + FairPrimaryGenerator &operator=(const FairPrimaryGenerator &); + + /** Nominal beam position at target in x [cm] */ + Double_t fBeamX0; + /** Nominal beam position at target in y [cm]*/ + Double_t fBeamY0; + /** Beam width (Gaussian) in x [cm]*/ + Double_t fBeamSigmaX; + /** Beam width (Gaussian) in y [cm]*/ + Double_t fBeamSigmaY; + + /** Nominal beam angle at target in x [rad] */ + Double_t fBeamAngleX0; + /** Nominal beam angle at target in y [rad] */ + Double_t fBeamAngleY0; + /** Actual beam angle at target in x [rad] */ + Double_t fBeamAngleX; + /** Actual beam angle at target in y [rad] */ + Double_t fBeamAngleY; + /** Beam angle width (Gaussian) in x [rad]*/ + Double_t fBeamAngleSigmaX; + /** Beam angle width (Gaussian) in y [rad]*/ + Double_t fBeamAngleSigmaY; + /** Actual beam direction at the vertex */ + TVector3 fBeamDirection; + + /** Lower limit for the event plane rotation angle [rad] */ + Double_t fPhiMin; + /** Upper limit for the event plane rotation angle [rad] */ + Double_t fPhiMax; + /** Actual event plane rotation angle [rad] */ + Double_t fPhi; + + /** Nominal z position of center of targets [cm]*/ + Double_t *fTargetZ; //! + /** Number of targets;*/ + Int_t fNrTargets; + /** Full target thickness [cm]*/ + Double_t fTargetDz; + + /** Vertex position of current event [cm]*/ + TVector3 fVertex; + + /** Number of primary tracks in current event*/ + Int_t fNTracks; + + /** Flag for uniform vertex smearing in z*/ + Bool_t fSmearVertexZ; + /** Flag for gaus vertex smearing in z*/ + Bool_t fSmearGausVertexZ; + /** Flag for vertex smearing in xy*/ + Bool_t fSmearVertexXY; + /** Flag for gaus vertex smearing in xy*/ + Bool_t fSmearGausVertexXY; + /** Flag for beam gradient calculation*/ + Bool_t fBeamAngle; + /** Flag for event plane rotation*/ + Bool_t fEventPlane; + + /** Pointer to MC stack*/ + FairGenericStack *fStack; //! + /** List of registered generators */ + TObjArray *fGenList; + /** Iterator over generator list */ + TIterator *fListIter; //! + /** Pointer to MCEventHeader */ + FairMCEventHeader *fEvent; //! + /** go to tracking */ + Bool_t fdoTracking; //! + /** Number of MC tracks before a Generator is called, needed for MC index + * update */ + Int_t fMCIndexOffset; //! + /** Number of all primaries of this run*/ + static Int_t fTotPrim; //! + /** Event number (Set by the primary generator if not set already by one of the specific generators **/ - Int_t fEventNr; + Int_t fEventNr; - /** Private method MakeVertex. If vertex smearing in xy is switched on, + /** Private method MakeVertex. If vertex smearing in xy is switched on, the event vertex is smeared Gaussianlike in x and y direction according to the mean beam positions and widths set by the SetBeam method. If vertex smearing in z is switched on, the z @@ -245,27 +247,27 @@ class FairPrimaryGenerator : public TNamed { To be called at the beginning of the event from the GenerateEvent method. **/ - virtual void MakeVertex(); + virtual void MakeVertex(); - /** Private method MakeBeamAngle. If beam angle smearing in xy + /** Private method MakeBeamAngle. If beam angle smearing in xy is switched on, all tracks in an event are rotated by a Gaussianlike angle distribution around the x and y axis according to the mean beam angle and angle widths set by the SetBeamAngle method. To be called at the beginning of the event from the GenerateEvent method. **/ - virtual void MakeBeamAngle(); + virtual void MakeBeamAngle(); - /** Private method MakeEventPlane. If the rotation of the event around the + /** Private method MakeEventPlane. If the rotation of the event around the z-axis by a random angle is switched on, the complete event is rotated by the chosen angle. This function is called at the beginning of the event from the GenerateEvent method. The function pick a random rotation angle between fPhiMin and fPhiMax which are set using the function SetEventPlane. **/ - void MakeEventPlane(); + void MakeEventPlane(); - ClassDef(FairPrimaryGenerator, 5); + ClassDef(FairPrimaryGenerator, 5); }; #endif diff --git a/base/sim/FairRunIdGenerator.cxx b/base/sim/FairRunIdGenerator.cxx index 33b07f0947..67114c4760 100644 --- a/base/sim/FairRunIdGenerator.cxx +++ b/base/sim/FairRunIdGenerator.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* @@ -24,17 +24,18 @@ #define _DEFAULT_SOURCE #include "FairRunIdGenerator.h" -#include // for errno, EAGAIN, EINTR -#include // for open, O_RDONLY, O_NONBLOCK -#include // for rand, srand -#include // for memcpy -#include // for gettimeofday -#include // for getpid, getuid, read -#define srand(x) srandom(x) -#define rand() random() +#include // for rand, srand +#include // for memcpy +#include // for errno, EAGAIN, EINTR +#include // for open, O_RDONLY, O_NONBLOCK +#include // for gettimeofday +#include // for getpid, getuid, read -//using namespace std; +#define srand(x) srandom(x) +#define rand() random() + +// using namespace std; //#include "genid32.h" replaced by hrunidgenerator.h @@ -49,69 +50,66 @@ * %End-Header% */ - /* * Offset between 15-Oct-1582 and 1-Jan-70 */ #define TIME_OFFSET_HIGH 0x01B21DD2 -#define TIME_OFFSET_LOW 0x13814000 +#define TIME_OFFSET_LOW 0x13814000 int FairRunIdGenerator::get_random_fd(void) { - struct timeval tv; - static int fd = -2; - int i; - - if (fd == -2) { + struct timeval tv; + static int fd = -2; + int i; + + if (fd == -2) { + gettimeofday(&tv, 0); + fd = open("/dev/urandom", O_RDONLY); + if (fd == -1) { + fd = open("/dev/random", O_RDONLY | O_NONBLOCK); + } + srand((getpid() << 16) ^ getuid() ^ tv.tv_sec ^ tv.tv_usec); + } + /* Crank the random number generator a few times */ gettimeofday(&tv, 0); - fd = open("/dev/urandom", O_RDONLY); - if (fd == -1) { - fd = open("/dev/random", O_RDONLY | O_NONBLOCK); + for (i = (tv.tv_sec ^ tv.tv_usec) & 0x1F; i > 0; i--) { + rand(); } - srand((getpid() << 16) ^ getuid() ^ tv.tv_sec ^ tv.tv_usec); - } - /* Crank the random number generator a few times */ - gettimeofday(&tv, 0); - for (i = (tv.tv_sec ^ tv.tv_usec) & 0x1F; i > 0; i--) { - rand(); - } - return fd; + return fd; } - /* * Generate a series of random bytes. Use /dev/urandom if possible, * and if not, use srandom/random. */ void FairRunIdGenerator::get_random_bytes(void* buf, int nbytes) { - int i, fd = get_random_fd(); - int lose_counter = 0; - char* cp = static_cast(buf); - - if (fd >= 0) { - while (nbytes > 0) { - i = read(fd, cp, nbytes); - if ((i < 0) && - ((errno == EINTR) || (errno == EAGAIN))) { - continue; - } - if (i <= 0) { - if (lose_counter++ == 8) { - break; + int i, fd = get_random_fd(); + int lose_counter = 0; + char* cp = static_cast(buf); + + if (fd >= 0) { + while (nbytes > 0) { + i = read(fd, cp, nbytes); + if ((i < 0) && ((errno == EINTR) || (errno == EAGAIN))) { + continue; + } + if (i <= 0) { + if (lose_counter++ == 8) { + break; + } + continue; + } + nbytes -= i; + cp += i; + lose_counter = 0; } - continue; - } - nbytes -= i; - cp += i; - lose_counter = 0; } - } - /* XXX put something better here if no /dev/random! */ - for (i = 0; i < nbytes; i++) { - *cp++ = rand() & 0xFF; - } - return; + /* XXX put something better here if no /dev/random! */ + for (i = 0; i < nbytes; i++) { + *cp++ = rand() & 0xFF; + } + return; } /* @@ -120,76 +118,75 @@ void FairRunIdGenerator::get_random_bytes(void* buf, int nbytes) int FairRunIdGenerator::get_node_id(unsigned char* /*node_id*/) { #ifdef HAVE_NET_IF_H - int sd; - struct ifreq ifr, *ifrp; - struct ifconf ifc; - char buf[1024]; - int n, i; - unsigned char* a; - - /* - * BSD 4.4 defines the size of an ifreq to be - * max(sizeof(ifreq), sizeof(ifreq.ifr_name)+ifreq.ifr_addr.sa_len - * However, under earlier systems, sa_len isn't present, so the size is - * just sizeof(struct ifreq) - */ + int sd; + struct ifreq ifr, *ifrp; + struct ifconf ifc; + char buf[1024]; + int n, i; + unsigned char* a; + + /* + * BSD 4.4 defines the size of an ifreq to be + * max(sizeof(ifreq), sizeof(ifreq.ifr_name)+ifreq.ifr_addr.sa_len + * However, under earlier systems, sa_len isn't present, so the size is + * just sizeof(struct ifreq) + */ #ifdef HAVE_SA_LEN #ifndef max -#define max(a,b) ((a) > (b) ? (a) : (b)) +#define max(a, b) ((a) > (b) ? (a) : (b)) #endif -#define ifreq_size(i) max(sizeof(struct ifreq),\ - sizeof((i).ifr_name)+(i).ifr_addr.sa_len) +#define ifreq_size(i) max(sizeof(struct ifreq), sizeof((i).ifr_name) + (i).ifr_addr.sa_len) #else #define ifreq_size(i) sizeof(struct ifreq) -#endif /* HAVE_SA_LEN*/ +#endif /* HAVE_SA_LEN*/ - sd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP); - if (sd < 0) { - return -1; - } - memset(buf, 0, sizeof(buf)); - ifc.ifc_len = sizeof(buf); - ifc.ifc_buf = buf; - if (ioctl(sd, SIOCGIFCONF, (char*) &ifc) < 0) { - close(sd); - return -1; - } - n = ifc.ifc_len; - for (i = 0; i < n; i += ifreq_size(*ifr)) { - ifrp = (struct ifreq*) ((char*) ifc.ifc_buf + i); - strncpy(ifr.ifr_name, ifrp->ifr_name, IFNAMSIZ); -#ifdef SIOCGIFHWADDR - if (ioctl(sd, SIOCGIFHWADDR, &ifr) < 0) { - continue; + sd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP); + if (sd < 0) { + return -1; } - a = (unsigned char*) &ifr.ifr_hwaddr.sa_data; + memset(buf, 0, sizeof(buf)); + ifc.ifc_len = sizeof(buf); + ifc.ifc_buf = buf; + if (ioctl(sd, SIOCGIFCONF, (char*)&ifc) < 0) { + close(sd); + return -1; + } + n = ifc.ifc_len; + for (i = 0; i < n; i += ifreq_size(*ifr)) { + ifrp = (struct ifreq*)((char*)ifc.ifc_buf + i); + strncpy(ifr.ifr_name, ifrp->ifr_name, IFNAMSIZ); +#ifdef SIOCGIFHWADDR + if (ioctl(sd, SIOCGIFHWADDR, &ifr) < 0) { + continue; + } + a = (unsigned char*)&ifr.ifr_hwaddr.sa_data; #else #ifdef SIOCGENADDR - if (ioctl(sd, SIOCGENADDR, &ifr) < 0) { - continue; - } - a = (unsigned char*) ifr.ifr_enaddr; + if (ioctl(sd, SIOCGENADDR, &ifr) < 0) { + continue; + } + a = (unsigned char*)ifr.ifr_enaddr; #else - /* - * XXX we don't have a way of getting the hardware - * address - */ - close(sd); - return 0; -#endif /* SIOCGENADDR */ -#endif /* SIOCGIFHWADDR */ - if (!a[0] && !a[1] && !a[2] && !a[3] && !a[4] && !a[5]) { - continue; - } - if (node_id) { - memcpy(node_id, a, 6); - close(sd); - return 1; + /* + * XXX we don't have a way of getting the hardware + * address + */ + close(sd); + return 0; +#endif /* SIOCGENADDR */ +#endif /* SIOCGIFHWADDR */ + if (!a[0] && !a[1] && !a[2] && !a[3] && !a[4] && !a[5]) { + continue; + } + if (node_id) { + memcpy(node_id, a, 6); + close(sd); + return 1; + } } - } - close(sd); + close(sd); #endif - return 0; + return 0; } /* Assume that the gettimeofday() has microsecond granularity */ @@ -197,91 +194,87 @@ int FairRunIdGenerator::get_node_id(unsigned char* /*node_id*/) int FairRunIdGenerator::get_clock(uint32_t* clock_high, uint32_t* clock_low, uint16_t* ret_clock_seq) { - static int adjustment = 0; - static struct timeval last = - {0, 0}; - static uint16_t clock_seq; - struct timeval tv; - unsigned long long clock_reg; + static int adjustment = 0; + static struct timeval last = {0, 0}; + static uint16_t clock_seq; + struct timeval tv; + unsigned long long clock_reg; try_again: - gettimeofday(&tv, 0); - if ((last.tv_sec == 0) && (last.tv_usec == 0)) { - get_random_bytes(&clock_seq, sizeof(clock_seq)); - clock_seq &= 0x1FFF; - last = tv; - last.tv_sec--; - } - if ((tv.tv_sec < last.tv_sec) || - ((tv.tv_sec == last.tv_sec) && - (tv.tv_usec < last.tv_usec))) { - clock_seq = (clock_seq + 1) & 0x1FFF; - adjustment = 0; - last = tv; - } else if ((tv.tv_sec == last.tv_sec) && - (tv.tv_usec == last.tv_usec)) { - if (adjustment >= MAX_ADJUSTMENT) { - goto try_again; + gettimeofday(&tv, 0); + if ((last.tv_sec == 0) && (last.tv_usec == 0)) { + get_random_bytes(&clock_seq, sizeof(clock_seq)); + clock_seq &= 0x1FFF; + last = tv; + last.tv_sec--; + } + if ((tv.tv_sec < last.tv_sec) || ((tv.tv_sec == last.tv_sec) && (tv.tv_usec < last.tv_usec))) { + clock_seq = (clock_seq + 1) & 0x1FFF; + adjustment = 0; + last = tv; + } else if ((tv.tv_sec == last.tv_sec) && (tv.tv_usec == last.tv_usec)) { + if (adjustment >= MAX_ADJUSTMENT) { + goto try_again; + } + adjustment++; + } else { + adjustment = 0; + last = tv; } - adjustment++; - } else { - adjustment = 0; - last = tv; - } - clock_reg = tv.tv_usec * 10 + adjustment; - clock_reg += (static_cast(tv.tv_sec)) * 10000000; - clock_reg += ((static_cast(0x01B21DD2)) << 32) + 0x13814000; + clock_reg = tv.tv_usec * 10 + adjustment; + clock_reg += (static_cast(tv.tv_sec)) * 10000000; + clock_reg += ((static_cast(0x01B21DD2)) << 32) + 0x13814000; - *clock_high = clock_reg >> 32; - *clock_low = clock_reg; - *ret_clock_seq = clock_seq; + *clock_high = clock_reg >> 32; + *clock_low = clock_reg; + *ret_clock_seq = clock_seq; - fTimeSpec.tv_sec = last.tv_sec; - // fTimeSpec.tv_nsec = last.tv_usec*1000.; - fTimeSpec.tv_nsec = 0.; + fTimeSpec.tv_sec = last.tv_sec; + // fTimeSpec.tv_nsec = last.tv_usec*1000.; + fTimeSpec.tv_nsec = 0.; - return 0; + return 0; } void FairRunIdGenerator::uuid_generate_time(uuid_t out) { - static unsigned char node_id[6]; - static int has_init = 0; - struct uuid uu; - uint32_t clock_mid; - - if (!has_init) { - if (get_node_id(node_id) <= 0) { - get_random_bytes(node_id, 6); - /* - * Set multicast bit, to prevent conflicts - * with IEEE 802 addresses obtained from - * network cards - */ - node_id[0] |= 0x80; + static unsigned char node_id[6]; + static int has_init = 0; + struct uuid uu; + uint32_t clock_mid; + + if (!has_init) { + if (get_node_id(node_id) <= 0) { + get_random_bytes(node_id, 6); + /* + * Set multicast bit, to prevent conflicts + * with IEEE 802 addresses obtained from + * network cards + */ + node_id[0] |= 0x80; + } + has_init = 1; } - has_init = 1; - } - get_clock(&clock_mid, &uu.time_low, &uu.clock_seq); - uu.clock_seq |= 0x8000; - uu.time_mid = static_cast(clock_mid); - uu.time_hi_and_version = (clock_mid >> 16) | 0x1000; - memcpy(uu.node, node_id, 6); - uuid_pack(&uu, out); + get_clock(&clock_mid, &uu.time_low, &uu.clock_seq); + uu.clock_seq |= 0x8000; + uu.time_mid = static_cast(clock_mid); + uu.time_hi_and_version = (clock_mid >> 16) | 0x1000; + memcpy(uu.node, node_id, 6); + uuid_pack(&uu, out); } void FairRunIdGenerator::uuid_generate_random(uuid_t out) { - uuid_t buf; - struct uuid uu; + uuid_t buf; + struct uuid uu; - get_random_bytes(buf, sizeof(buf)); - uuid_unpack(buf, &uu); + get_random_bytes(buf, sizeof(buf)); + uuid_unpack(buf, &uu); - uu.clock_seq = (uu.clock_seq & 0x3FFF) | 0x8000; - uu.time_hi_and_version = (uu.time_hi_and_version & 0x0FFF) | 0x4000; - uuid_pack(&uu, out); + uu.clock_seq = (uu.clock_seq & 0x3FFF) | 0x8000; + uu.time_hi_and_version = (uu.time_hi_and_version & 0x0FFF) | 0x4000; + uuid_pack(&uu, out); } /* @@ -292,15 +285,14 @@ void FairRunIdGenerator::uuid_generate_random(uuid_t out) */ void FairRunIdGenerator::uuid_generate(uuid_t out) { - /* + /* if (get_random_fd() >= 0) { uuid_generate_random(out); } else { uuid_generate_time(out); } */ - uuid_generate_time(out); - + uuid_generate_time(out); } /* @@ -316,37 +308,36 @@ void FairRunIdGenerator::uuid_generate(uuid_t out) void FairRunIdGenerator::uuid_pack(const struct uuid* uu, uuid_t ptr) { - uint32_t tmp; - unsigned char* out = ptr; - - tmp = uu->time_low; - out[3] = static_cast(tmp); - tmp >>= 8; - out[2] = static_cast(tmp); - tmp >>= 8; - out[1] = static_cast(tmp); - tmp >>= 8; - out[0] = static_cast(tmp); - - tmp = uu->time_mid; - out[5] = static_cast(tmp); - tmp >>= 8; - out[4] = static_cast(tmp); - - tmp = uu->time_hi_and_version; - out[7] = static_cast(tmp); - tmp >>= 8; - out[6] = static_cast(tmp); - - tmp = uu->clock_seq; - out[9] = static_cast(tmp); - tmp >>= 8; - out[8] = static_cast(tmp); - - memcpy(out + 10, uu->node, 6); + uint32_t tmp; + unsigned char* out = ptr; + + tmp = uu->time_low; + out[3] = static_cast(tmp); + tmp >>= 8; + out[2] = static_cast(tmp); + tmp >>= 8; + out[1] = static_cast(tmp); + tmp >>= 8; + out[0] = static_cast(tmp); + + tmp = uu->time_mid; + out[5] = static_cast(tmp); + tmp >>= 8; + out[4] = static_cast(tmp); + + tmp = uu->time_hi_and_version; + out[7] = static_cast(tmp); + tmp >>= 8; + out[6] = static_cast(tmp); + + tmp = uu->clock_seq; + out[9] = static_cast(tmp); + tmp >>= 8; + out[8] = static_cast(tmp); + + memcpy(out + 10, uu->node, 6); } - /* * Internal routine for unpacking UUID * @@ -360,59 +351,54 @@ void FairRunIdGenerator::uuid_pack(const struct uuid* uu, uuid_t ptr) void FairRunIdGenerator::uuid_unpack(const uuid_t in, struct uuid* uu) { - const uint8_t* ptr = in; - uint32_t tmp; + const uint8_t* ptr = in; + uint32_t tmp; - tmp = *ptr++; - tmp = (tmp << 8) | *ptr++; - tmp = (tmp << 8) | *ptr++; - tmp = (tmp << 8) | *ptr++; - uu->time_low = tmp; + tmp = *ptr++; + tmp = (tmp << 8) | *ptr++; + tmp = (tmp << 8) | *ptr++; + tmp = (tmp << 8) | *ptr++; + uu->time_low = tmp; - tmp = *ptr++; - tmp = (tmp << 8) | *ptr++; - uu->time_mid = tmp; + tmp = *ptr++; + tmp = (tmp << 8) | *ptr++; + uu->time_mid = tmp; - tmp = *ptr++; - tmp = (tmp << 8) | *ptr++; - uu->time_hi_and_version = tmp; + tmp = *ptr++; + tmp = (tmp << 8) | *ptr++; + uu->time_hi_and_version = tmp; - tmp = *ptr++; - tmp = (tmp << 8) | *ptr++; - uu->clock_seq = tmp; + tmp = *ptr++; + tmp = (tmp << 8) | *ptr++; + uu->clock_seq = tmp; - memcpy(uu->node, ptr, 6); + memcpy(uu->node, ptr, 6); } unsigned int FairRunIdGenerator::generateId(void) { - uuid_t uu; -// unsigned int v; -// struct timeval ret_tv; - uuid_generate(uu); + uuid_t uu; + // unsigned int v; + // struct timeval ret_tv; + uuid_generate(uu); -/* + /* v = ((uu[0] ^ uu[4] ^ uu[8] ^ uu[12]) << 0) | ((uu[1] ^ uu[5] ^ uu[9] ^ uu[13]) << 8) | ((uu[2] ^ uu[6] ^ uu[10] ^ uu[14]) << 16) | ((uu[3] ^ uu[7] ^ uu[11] ^ uu[15]) << 24); */ - // return v & 0x7fffffff; - return getTID(); + // return v & 0x7fffffff; + return getTID(); } -unsigned int FairRunIdGenerator::getTID() -{ - return (fTimeSpec.tv_sec ); -} +unsigned int FairRunIdGenerator::getTID() { return (fTimeSpec.tv_sec); } -struct timespec FairRunIdGenerator::getTimeSpecFromTID( unsigned int ms) { - struct timespec ret_tv; - ret_tv.tv_sec = ms; - ret_tv.tv_nsec = 0. ; // truncate the ns resolution - return ret_tv; +struct timespec FairRunIdGenerator::getTimeSpecFromTID(unsigned int ms) +{ + struct timespec ret_tv; + ret_tv.tv_sec = ms; + ret_tv.tv_nsec = 0.; // truncate the ns resolution + return ret_tv; } - - - diff --git a/base/sim/FairRunIdGenerator.h b/base/sim/FairRunIdGenerator.h index 96c62bd4a1..a282952ed8 100644 --- a/base/sim/FairRunIdGenerator.h +++ b/base/sim/FairRunIdGenerator.h @@ -1,29 +1,30 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRRUNIDGENERATOR_H #define FAIRRUNIDGENERATOR_H -#include // IWYU pragma: keep for timespec +#include // IWYU pragma: keep for timespec // IWYU pragma: no_include -typedef unsigned char uint8_t; +typedef unsigned char uint8_t; typedef unsigned short int uint16_t; -typedef unsigned int uint32_t; -typedef unsigned char uuid_t[16]; +typedef unsigned int uint32_t; +typedef unsigned char uuid_t[16]; class FairRunIdGenerator { - struct uuid { - uint32_t time_low; - uint16_t time_mid; - uint16_t time_hi_and_version; - uint16_t clock_seq; - uint8_t node[6]; + struct uuid + { + uint32_t time_low; + uint16_t time_mid; + uint16_t time_hi_and_version; + uint16_t clock_seq; + uint8_t node[6]; }; struct timespec fTimeSpec; @@ -37,18 +38,18 @@ class FairRunIdGenerator void uuid_generate(uuid_t); void uuid_pack(const struct uuid*, uuid_t); void uuid_unpack(const uuid_t, struct uuid*); + public: - struct timespec getTimeSpec() {return fTimeSpec;} - struct timespec getTimeSpecFromTID( unsigned int ms); - unsigned int getTID(); + struct timespec getTimeSpec() { return fTimeSpec; } + struct timespec getTimeSpecFromTID(unsigned int ms); + unsigned int getTID(); public: - FairRunIdGenerator() : fTimeSpec() {} + FairRunIdGenerator() + : fTimeSpec() + {} ~FairRunIdGenerator() {} unsigned int generateId(void); - - - }; #endif diff --git a/base/sim/FairVolume.cxx b/base/sim/FairVolume.cxx index c624974e3b..8e56b02ac4 100644 --- a/base/sim/FairVolume.cxx +++ b/base/sim/FairVolume.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -13,42 +13,57 @@ #include "FairVolume.h" FairVolume::FairVolume() - : TNamed(), + : TNamed() + , // fName(""), /**Volume Name in MC*/ - fRealName(""), /**Volume Name in ASCII file*/ - fVolumeId(-1), /**Volume Id in GeoManager*/ - fModId(-1), /**Module Id in which this volume exist*/ - fMCid(-1), /**Volume Id in MC*/ - fCopyNo(-1), /**Volume Copy No*/ - fMotherId(-1), /**Mother Volume Id*/ - fMotherCopyNo(-1), /**Mother Volume Copy No*/ - fDetector(0), - fModule(nullptr), /**The Module (detector) which will proccess the hits for this volume*/ - fNode(nullptr) /**Node corre*/ -{ -} + fRealName("") + , /**Volume Name in ASCII file*/ + fVolumeId(-1) + , /**Volume Id in GeoManager*/ + fModId(-1) + , /**Module Id in which this volume exist*/ + fMCid(-1) + , /**Volume Id in MC*/ + fCopyNo(-1) + , /**Volume Copy No*/ + fMotherId(-1) + , /**Mother Volume Id*/ + fMotherCopyNo(-1) + , /**Mother Volume Copy No*/ + fDetector(0) + , fModule(nullptr) + , /**The Module (detector) which will proccess the hits for this volume*/ + fNode(nullptr) /**Node corre*/ +{} FairVolume::FairVolume(TString name, Int_t id, Int_t ModId, FairModule* fMod) - :TNamed(name,name), - // fName(name), - fRealName(""), /**Volume Name in ASCII file*/ - fVolumeId(id), /**Volume Id in GeoManager*/ - fModId(ModId), /**Module Id in which this volume exist*/ - fMCid(-1), /**Volume Id in MC*/ - fCopyNo(-1), /**Volume Copy No*/ - fMotherId(0), /**Mother Volume Id*/ - fMotherCopyNo(0), /**Mother Volume Copy No*/ - fDetector(0), - fModule(fMod), /**The Module (detector) which will proccess the hits for this volume*/ - fNode(nullptr) /**Node corre*/ + : TNamed(name, name) + , + // fName(name), + fRealName("") + , /**Volume Name in ASCII file*/ + fVolumeId(id) + , /**Volume Id in GeoManager*/ + fModId(ModId) + , /**Module Id in which this volume exist*/ + fMCid(-1) + , /**Volume Id in MC*/ + fCopyNo(-1) + , /**Volume Copy No*/ + fMotherId(0) + , /**Mother Volume Id*/ + fMotherCopyNo(0) + , /**Mother Volume Copy No*/ + fDetector(0) + , fModule(fMod) + , /**The Module (detector) which will proccess the hits for this volume*/ + fNode(nullptr) /**Node corre*/ { - if (fModule && fModule->InheritsFrom("FairDetector")){ - fDetector=dynamic_cast(fModule); + if (fModule && fModule->InheritsFrom("FairDetector")) { + fDetector = dynamic_cast(fModule); } } -FairVolume::~FairVolume() -{ -} +FairVolume::~FairVolume() {} -ClassImp(FairVolume) +ClassImp(FairVolume); diff --git a/base/sim/FairVolume.h b/base/sim/FairVolume.h index 37a13fd8ef..3b224aedf8 100644 --- a/base/sim/FairVolume.h +++ b/base/sim/FairVolume.h @@ -1,19 +1,19 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIR_VOLUME_H #define FAIR_VOLUME_H -#include // for TNamed -#include // for Int_t, FairVolume::Class, etc -#include // for TString - -#include "FairModule.h" #include "FairDetector.h" +#include "FairModule.h" + +#include // for Int_t, FairVolume::Class, etc +#include // for TNamed +#include // for TString class FairGeoNode; /** @@ -27,57 +27,57 @@ class FairVolume : public TNamed { public: FairVolume(); - FairVolume(TString name, Int_t id=0, Int_t detid=0,FairModule* fMod=0); + FairVolume(TString name, Int_t id = 0, Int_t detid = 0, FairModule* fMod = 0); virtual ~FairVolume(); // const char* GetName() { return fName.Data();} // TString getName() { return fName;} - void setRealName(TString name) { fRealName = name;} - const char* getRealName() { return fRealName.Data();} - Int_t getVolumeId() { return fVolumeId;} - Int_t getModId() { return fModId;} - void setModId(Int_t id) { fModId=id;} - void setCopyNo(Int_t id) { fCopyNo=id;} - void setVolumeId (Int_t id) {fVolumeId= id;} - void setGeoNode(FairGeoNode* d) {fNode=d;} - void setMotherId(Int_t fM) {fMotherId=fM;} - void setMotherCopyNo(Int_t CopyNo) {fMotherCopyNo=CopyNo;} + void setRealName(TString name) { fRealName = name; } + const char* getRealName() { return fRealName.Data(); } + Int_t getVolumeId() { return fVolumeId; } + Int_t getModId() { return fModId; } + void setModId(Int_t id) { fModId = id; } + void setCopyNo(Int_t id) { fCopyNo = id; } + void setVolumeId(Int_t id) { fVolumeId = id; } + void setGeoNode(FairGeoNode* d) { fNode = d; } + void setMotherId(Int_t fM) { fMotherId = fM; } + void setMotherCopyNo(Int_t CopyNo) { fMotherCopyNo = CopyNo; } - FairModule* GetModule() {return fModule;} - FairDetector* GetDetector() { return fDetector;} - void SetModule(FairModule* mod) { - fModule=mod; - if (mod->InheritsFrom("FairDetector")){ - fDetector=dynamic_cast(mod); + FairModule* GetModule() { return fModule; } + FairDetector* GetDetector() { return fDetector; } + void SetModule(FairModule* mod) + { + fModule = mod; + if (mod->InheritsFrom("FairDetector")) { + fDetector = dynamic_cast(mod); } } - Int_t getMCid() {return fMCid;} - Int_t getCopyNo() { return fCopyNo;} - void setMCid(Int_t id) {fMCid=id;} - FairGeoNode* getGeoNode() {return fNode;} - Int_t getMotherId() { return fMotherId;} - Int_t getMotherCopyNo() {return fMotherCopyNo;} - + Int_t getMCid() { return fMCid; } + Int_t getCopyNo() { return fCopyNo; } + void setMCid(Int_t id) { fMCid = id; } + FairGeoNode* getGeoNode() { return fNode; } + Int_t getMotherId() { return fMotherId; } + Int_t getMotherCopyNo() { return fMotherCopyNo; } private: FairVolume(const FairVolume&); FairVolume& operator=(const FairVolume&); // TString fName; /**Volume Name in MC*/ - TString fRealName; /**Volume Name in ASCII file*/ - Int_t fVolumeId; /**Volume Id in GeoManager*/ - Int_t fModId; /**Module Id in which this volume exist*/ - Int_t fMCid; /**Volume Id in MC*/ - Int_t fCopyNo; /**Volume Copy No*/ - Int_t fMotherId; /**Mother Volume Id*/ - Int_t fMotherCopyNo; /**Mother Volume Copy No*/ + TString fRealName; /**Volume Name in ASCII file*/ + Int_t fVolumeId; /**Volume Id in GeoManager*/ + Int_t fModId; /**Module Id in which this volume exist*/ + Int_t fMCid; /**Volume Id in MC*/ + Int_t fCopyNo; /**Volume Copy No*/ + Int_t fMotherId; /**Mother Volume Id*/ + Int_t fMotherCopyNo; /**Mother Volume Copy No*/ FairDetector* fDetector; /** The Detector which will proccess the hits for this volume*/ - FairModule* fModule; /**The Module in which the volume is */ - FairGeoNode* fNode; /**Node corresponding to this volume*/ + FairModule* fModule; /**The Module in which the volume is */ + FairGeoNode* fNode; /**Node corresponding to this volume*/ - ClassDef(FairVolume,2) // Volume Definition + ClassDef(FairVolume, 2) // Volume Definition }; #endif diff --git a/base/sim/FairVolumeList.cxx b/base/sim/FairVolumeList.cxx index fa502ea807..3a481331d2 100644 --- a/base/sim/FairVolumeList.cxx +++ b/base/sim/FairVolumeList.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -12,73 +12,70 @@ #include "FairVolumeList.h" -#include "FairVolume.h" // for FairVolume -#include "FairLogger.h" // for logging - +#include "FairLogger.h" // for logging +#include "FairVolume.h" // for FairVolume FairVolumeList::FairVolumeList() - :TObject(), - fData(new TObjArray()) -{ -} + : TObject() + , fData(new TObjArray()) +{} FairVolumeList::~FairVolumeList() { - if (fData) { - fData->Delete(); - delete fData; - } + if (fData) { + fData->Delete(); + delete fData; + } } FairVolume* FairVolumeList::getVolume(TString* name) { - TObject* obj = findObject(* name); - if (obj) { - LOG(info) << "FairVolume getVolume " << name->Data() << "found"; - } + TObject* obj = findObject(*name); + if (obj) { + LOG(info) << "FairVolume getVolume " << name->Data() << "found"; + } - return static_cast(obj); + return static_cast(obj); } Int_t FairVolumeList::getVolumeId(TString* name) { - FairVolume* vol = getVolume(name); + FairVolume* vol = getVolume(name); - if (vol) { - return vol->getVolumeId(); - } else { - return -111; - } + if (vol) { + return vol->getVolumeId(); + } else { + return -111; + } } FairVolume* FairVolumeList::findObject(TString name) { - FairVolume* obj = nullptr; - - for (int i = 0; i < fData->GetEntriesFast(); i++) { - obj = static_cast(fData->At(i)); - if (obj) { - if (obj->GetName() == name) { - return static_cast(obj); - } + FairVolume* obj = nullptr; + + for (int i = 0; i < fData->GetEntriesFast(); i++) { + obj = static_cast(fData->At(i)); + if (obj) { + if (obj->GetName() == name) { + return static_cast(obj); + } + } } - } - return nullptr; + return nullptr; } void FairVolumeList::addVolume(FairVolume* elem) { - FairVolume* v = static_cast(findObject(elem->GetName())); + FairVolume* v = static_cast(findObject(elem->GetName())); - if (v) { - LOG(error) << "FairVolumeList element: " << elem->GetName() - << " VolId : " << elem->getVolumeId() - << " already defined " << v->getVolumeId(); - } else { - fData->Add(elem); - } + if (v) { + LOG(error) << "FairVolumeList element: " << elem->GetName() << " VolId : " << elem->getVolumeId() + << " already defined " << v->getVolumeId(); + } else { + fData->Add(elem); + } } -ClassImp(FairVolumeList) +ClassImp(FairVolumeList); diff --git a/base/sim/FairVolumeList.h b/base/sim/FairVolumeList.h index f2ba567fed..873f00cdc8 100644 --- a/base/sim/FairVolumeList.h +++ b/base/sim/FairVolumeList.h @@ -1,29 +1,28 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIR_VOLUMELIST_H #define FAIR_VOLUMELIST_H - #include "FairVolume.h" -#include // for TObject -#include // for Int_t, etc -#include // for TObjArray -#include // for TString +#include // for Int_t, etc +#include // for TObjArray +#include // for TObject +#include // for TString -//class FairVolume; +// class FairVolume; /** -* This Object is only used for internal book keeping! -* @author M. Al-Turany, D. Bertini -* @version 0.1 -* @since 12.01.04 -*/ + * This Object is only used for internal book keeping! + * @author M. Al-Turany, D. Bertini + * @version 0.1 + * @since 12.01.04 + */ class FairVolumeList : public TObject { @@ -42,12 +41,10 @@ class FairVolumeList : public TObject FairVolume* findObject(TString name); void addVolume(FairVolume* elem); - Int_t getEntries () { return fData->GetEntries();} + Int_t getEntries() { return fData->GetEntries(); } FairVolume* At(Int_t pos) { return (dynamic_cast(fData->At(pos))); } - ClassDef(FairVolumeList,1) // Volume List + ClassDef(FairVolumeList, 1) // Volume List }; -#endif //FAIR_VOLUMELIST_H - - +#endif // FAIR_VOLUMELIST_H diff --git a/base/sim/fastsim/FairFastSimDetector.cxx b/base/sim/fastsim/FairFastSimDetector.cxx index 8cb64d28e3..f574d92e77 100644 --- a/base/sim/fastsim/FairFastSimDetector.cxx +++ b/base/sim/fastsim/FairFastSimDetector.cxx @@ -6,32 +6,30 @@ * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "FairFastSimDetector.h" -#include "FairGeoMedia.h" + #include "FairGeoBuilder.h" -#include "FairGeoInterface.h" // for FairGeoInterface -#include "FairGeoLoader.h" // for FairGeoLoader -#include "FairGeoMedium.h" // for FairGeoMedium +#include "FairGeoInterface.h" // for FairGeoInterface +#include "FairGeoLoader.h" // for FairGeoLoader +#include "FairGeoMedia.h" +#include "FairGeoMedium.h" // for FairGeoMedium // #include -#include // gGeoManager +#include // gGeoManager FairFastSimDetector::FairFastSimDetector() : FairDetector("FastSimulation", kTRUE) , fFastSimMedium(nullptr) -{ -} +{} FairFastSimDetector::FairFastSimDetector(const char* name, Int_t DetId) : FairDetector(name, kTRUE, DetId) , fFastSimMedium(nullptr) -{ -} +{} FairFastSimDetector::FairFastSimDetector(const FairFastSimDetector& right) : FairDetector(right) , fFastSimMedium(right.fFastSimMedium) -{ -} +{} FairFastSimDetector::~FairFastSimDetector() {} @@ -43,11 +41,9 @@ void FairFastSimDetector::ConstructGeometry() FairGeoBuilder* geoBuild = geoLoad->getGeoBuilder(); TGeoMedium* medium = gGeoManager->GetMedium("FastSimMedium"); - if (!medium) - { + if (!medium) { FairGeoMedium* fairMedium = geoMedia->getMedium("FastSimMedium"); - if (!fairMedium) - { + if (!fairMedium) { fairMedium = new FairGeoMedium("FastSimMedium"); fairMedium->setMediumIndex(geoMedia->getListOfMedia()->GetEntries()); fairMedium->setNComponents(1); @@ -58,9 +54,7 @@ void FairFastSimDetector::ConstructGeometry() } geoBuild->createMedium(fairMedium); fFastSimMedium = gGeoManager->GetMedium("FastSimMedium"); - } - else - { + } else { fFastSimMedium = medium; } } @@ -72,4 +66,4 @@ Bool_t FairFastSimDetector::ProcessHits(FairVolume*) return kTRUE; } -ClassImp(FairFastSimDetector) +ClassImp(FairFastSimDetector); diff --git a/base/sim/fastsim/FairFastSimDetector.h b/base/sim/fastsim/FairFastSimDetector.h index 2f8a52a59c..1e776ff31f 100644 --- a/base/sim/fastsim/FairFastSimDetector.h +++ b/base/sim/fastsim/FairFastSimDetector.h @@ -51,4 +51,4 @@ class FairFastSimDetector : public FairDetector ClassDef(FairFastSimDetector, 1) }; -#endif //! FAIRFASTSIMDETECTOR_H +#endif //! FAIRFASTSIMDETECTOR_H diff --git a/base/sim/fastsim/FairFastSimModel.cxx b/base/sim/fastsim/FairFastSimModel.cxx index 1b12c74bf3..ce8469b93e 100644 --- a/base/sim/fastsim/FairFastSimModel.cxx +++ b/base/sim/fastsim/FairFastSimModel.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -11,40 +11,37 @@ // ------------------------------------------------------------------------- #include "FairFastSimModel.h" + #include "FairGenericStack.h" #include "FairLogger.h" #include "FairMCApplication.h" #include "FairTrajFilter.h" - -#include "G4VPhysicalVolume.hh" #include "G4Electron.hh" #include "G4Gamma.hh" #include "G4ParticleTable.hh" #include "G4StackManager.hh" #include "G4SystemOfUnits.hh" +#include "G4VPhysicalVolume.hh" +#include // for TClonesArray #include #include +#include // for TVector3 #include -#include // for TClonesArray -#include // for TVector3 - -#include // for tie, tuple +#include // for tie, tuple // I.H. make this optional // #include "G4GDMLParser.hh" -FairFastSimModel::FairFastSimModel(G4String modelName, - G4Region* envelope) : - G4VFastSimulationModel(modelName, envelope) { -} +FairFastSimModel::FairFastSimModel(G4String modelName, G4Region* envelope) + : G4VFastSimulationModel(modelName, envelope) +{} -FairFastSimModel::FairFastSimModel(G4String modelName) : - G4VFastSimulationModel(modelName) { -} +FairFastSimModel::FairFastSimModel(G4String modelName) + : G4VFastSimulationModel(modelName) +{} -FairFastSimModel::~FairFastSimModel() { -} +FairFastSimModel::~FairFastSimModel() {} // I.H. make this optional // void FairFastSimModel::WriteGeometryToGDML( @@ -56,18 +53,12 @@ FairFastSimModel::~FairFastSimModel() { // delete parser; // } -G4bool FairFastSimModel::IsApplicable( - const G4ParticleDefinition& particleType) { - return true; -} +G4bool FairFastSimModel::IsApplicable(const G4ParticleDefinition& particleType) { return true; } -G4bool FairFastSimModel::ModelTrigger( - const G4FastTrack& fastTrack) { - return true; -} +G4bool FairFastSimModel::ModelTrigger(const G4FastTrack& fastTrack) { return true; } -void FairFastSimModel::DoIt(const G4FastTrack& fastTrack, - G4FastStep& fastStep) { +void FairFastSimModel::DoIt(const G4FastTrack& fastTrack, G4FastStep& fastStep) +{ LOG(debug) << "FairFastSimModel::DoIt() called"; // G4TouchableHandle theTouchable = @@ -77,69 +68,76 @@ void FairFastSimModel::DoIt(const G4FastTrack& fastTrack, int firstSecondary(0); int nofSecondaries(0); int movedParticleIndex(0); - std::tie(movedParticleIndex,firstSecondary,nofSecondaries) = ((FairGenericStack*)(gMC->GetStack()))->FastSimGetMovedIndex(); - if ( movedParticleIndex == -2 ) { + std::tie(movedParticleIndex, firstSecondary, nofSecondaries) = + ((FairGenericStack*)(gMC->GetStack()))->FastSimGetMovedIndex(); + if (movedParticleIndex == -2) { FairMCApplication::Instance()->Stepping(); - std::tie(movedParticleIndex,firstSecondary,nofSecondaries) = ((FairGenericStack*)(gMC->GetStack()))->FastSimGetMovedIndex(); + std::tie(movedParticleIndex, firstSecondary, nofSecondaries) = + ((FairGenericStack*)(gMC->GetStack()))->FastSimGetMovedIndex(); } TClonesArray* particles = ((FairGenericStack*)(gMC->GetStack()))->GetListOfParticles(); - if ( nofSecondaries != 0 ) { + if (nofSecondaries != 0) { fastStep.SetNumberOfSecondaryTracks(nofSecondaries); int addedParticleIndex = firstSecondary; G4ParticleTable* particleTable = G4ParticleTable::GetParticleTable(); - for ( int ipart = 0 ; ipart < nofSecondaries ; ipart++ ) { - if ( addedParticleIndex == movedParticleIndex ) addedParticleIndex++; // added protection in case user adds, moves and adds again + for (int ipart = 0; ipart < nofSecondaries; ipart++) { + if (addedParticleIndex == movedParticleIndex) + addedParticleIndex++; // added protection in case user adds, moves and adds again TParticle* particle = (TParticle*)particles->At(addedParticleIndex); G4ParticleDefinition* particleDefinition = 0; particleDefinition = particleTable->FindParticle(particle->GetPdgCode()); - if ( !particleDefinition ) + if (!particleDefinition) LOG(fatal) << "FairFastSimModel::DoIt() PDG " << particle->GetPdgCode() << " unknown!"; - G4ThreeVector pos(particle->Vx()*10.,particle->Vy()*10.,particle->Vz()*10.); //change from cm to mm - G4ThreeVector mom(particle->Px()*1000.,particle->Py()*1000.,particle->Pz()*1000.); + G4ThreeVector pos( + particle->Vx() * 10., particle->Vy() * 10., particle->Vz() * 10.); // change from cm to mm + G4ThreeVector mom(particle->Px() * 1000., particle->Py() * 1000., particle->Pz() * 1000.); TVector3 polVect; particle->GetPolarisation(polVect); - G4ThreeVector pol(polVect.X(),polVect.Y(),polVect.Z()); // get polarisation - G4double tim = particle->T()*10.e9; // change from ns to s - G4double len = 0.; - G4double ek = particle->Ek()*1000.; - G4DynamicParticle dynParticle(particleDefinition,mom.unit(),ek); - G4Track* tempTrack = - fastStep.CreateSecondaryTrack(dynParticle, pos, tim, false); + G4ThreeVector pol(polVect.X(), polVect.Y(), polVect.Z()); // get polarisation + G4double tim = particle->T() * 10.e9; // change from ns to s + G4double len = 0.; + G4double ek = particle->Ek() * 1000.; + G4DynamicParticle dynParticle(particleDefinition, mom.unit(), ek); + G4Track* tempTrack = fastStep.CreateSecondaryTrack(dynParticle, pos, tim, false); tempTrack->SetTouchableHandle(fastTrack.GetPrimaryTrack()->GetTouchableHandle()); addedParticleIndex++; } } - - LOG(debug) << "FairFastSimModel::DoIt() moving particle " << gMC->GetStack()->GetCurrentTrackNumber() << " (pos #" << movedParticleIndex << ")."; - if ( movedParticleIndex != -1 ) { + + LOG(debug) << "FairFastSimModel::DoIt() moving particle " << gMC->GetStack()->GetCurrentTrackNumber() << " (pos #" + << movedParticleIndex << ")."; + if (movedParticleIndex != -1) { TParticle* particle = (TParticle*)particles->At(movedParticleIndex); - LOG(debug) << "FAST SIM (moving particle to <" << particle->Vx() << "," << particle->Vy() << "," << particle->Vz() << "," << particle->T() << "> with p=<" - << particle->Px() << "," << particle->Py() << "," << particle->Pz() << "," << particle->Ek() << ">)"; - - G4ThreeVector pos(particle->Vx()*10.,particle->Vy()*10.,particle->Vz()*10.); //change from cm to mm - G4ThreeVector mom(particle->Px()*1000.,particle->Py()*1000.,particle->Pz()*1000.); - G4ThreeVector pol(0.,0.,0.); // get polarisation - G4double tim = particle->T()*10.e9; // change from ns to s - G4double len = 0.; - G4double ek = particle->Ek()*1000.; - - fastStep.SetPrimaryTrackFinalPosition (pos,false); - fastStep.SetPrimaryTrackFinalTime (tim); - fastStep.SetPrimaryTrackFinalProperTime (tim); - fastStep.SetPrimaryTrackFinalMomentum (mom,false); - fastStep.SetPrimaryTrackFinalKineticEnergy (ek); - // fastStep.SetPrimaryTrackFinalKineticEnergyAndDirection (G4double, const G4ThreeVector &, G4bool localCoordinates=true); - fastStep.SetPrimaryTrackFinalPolarization (pol,false); - fastStep.SetPrimaryTrackPathLength (len); - - if ( FairTrajFilter::Instance()->IsAccepted(particle) ) { - FairTrajFilter::Instance()->GetCurrentTrk()->AddPoint(particle->Vx(),particle->Vy(),particle->Vz(),particle->T()); + LOG(debug) << "FAST SIM (moving particle to <" << particle->Vx() << "," << particle->Vy() << "," + << particle->Vz() << "," << particle->T() << "> with p=<" << particle->Px() << "," << particle->Py() + << "," << particle->Pz() << "," << particle->Ek() << ">)"; + + G4ThreeVector pos(particle->Vx() * 10., particle->Vy() * 10., particle->Vz() * 10.); // change from cm to mm + G4ThreeVector mom(particle->Px() * 1000., particle->Py() * 1000., particle->Pz() * 1000.); + G4ThreeVector pol(0., 0., 0.); // get polarisation + G4double tim = particle->T() * 10.e9; // change from ns to s + G4double len = 0.; + G4double ek = particle->Ek() * 1000.; + + fastStep.SetPrimaryTrackFinalPosition(pos, false); + fastStep.SetPrimaryTrackFinalTime(tim); + fastStep.SetPrimaryTrackFinalProperTime(tim); + fastStep.SetPrimaryTrackFinalMomentum(mom, false); + fastStep.SetPrimaryTrackFinalKineticEnergy(ek); + // fastStep.SetPrimaryTrackFinalKineticEnergyAndDirection (G4double, const G4ThreeVector &, G4bool + // localCoordinates=true); + fastStep.SetPrimaryTrackFinalPolarization(pol, false); + fastStep.SetPrimaryTrackPathLength(len); + + if (FairTrajFilter::Instance()->IsAccepted(particle)) { + FairTrajFilter::Instance()->GetCurrentTrk()->AddPoint( + particle->Vx(), particle->Vy(), particle->Vz(), particle->T()); } - - gGeoManager->SetCurrentPoint(particle->Vx(),particle->Vy(),particle->Vz()); + + gGeoManager->SetCurrentPoint(particle->Vx(), particle->Vy(), particle->Vz()); } ((FairGenericStack*)(gMC->GetStack()))->FastSimClearMovedIndex(); } diff --git a/base/sim/fastsim/FairFastSimModel.h b/base/sim/fastsim/FairFastSimModel.h index ecfe630992..0c0f11e138 100644 --- a/base/sim/fastsim/FairFastSimModel.h +++ b/base/sim/fastsim/FairFastSimModel.h @@ -12,9 +12,9 @@ #ifndef FAIR_FASTSIM_MODEL_H_ #define FAIR_FASTSIM_MODEL_H_ +#include "G4String.hh" // for G4String +#include "G4Types.hh" // for G4bool #include "G4VFastSimulationModel.hh" -#include "G4String.hh" // for G4String -#include "G4Types.hh" // for G4bool class G4FastStep; class G4FastTrack; class G4ParticleDefinition; @@ -23,16 +23,16 @@ class G4Region; class FairFastSimModel : public G4VFastSimulationModel { public: - //------------------------- - // Constructor, destructor - //------------------------- - FairFastSimModel (G4String, G4Region*); - FairFastSimModel (G4String); - ~FairFastSimModel (); + //------------------------- + // Constructor, destructor + //------------------------- + FairFastSimModel(G4String, G4Region *); + FairFastSimModel(G4String); + ~FairFastSimModel(); - virtual G4bool IsApplicable(const G4ParticleDefinition&); + virtual G4bool IsApplicable(const G4ParticleDefinition &); virtual G4bool ModelTrigger(const G4FastTrack &); - virtual void DoIt(const G4FastTrack&, G4FastStep&); + virtual void DoIt(const G4FastTrack &, G4FastStep &); }; #endif /* FAIR_FASTSIM_MODEL_H_ */ diff --git a/base/sim/fastsim/FairFastSimRunConfiguration.cxx b/base/sim/fastsim/FairFastSimRunConfiguration.cxx index 6ed0fb04fb..39eafa2b5a 100644 --- a/base/sim/fastsim/FairFastSimRunConfiguration.cxx +++ b/base/sim/fastsim/FairFastSimRunConfiguration.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -10,35 +10,35 @@ // ----- Created 2019/01/30 by R. Karabowicz ----- // ------------------------------------------------------------------------- #include "FairFastSimRunConfiguration.h" -#include "FairFastSimulation.h" +#include "FairFastSimulation.h" #include "FairLogger.h" -#include // for TG4RunConfiguration +#include // for TG4RunConfiguration FairFastSimRunConfiguration::FairFastSimRunConfiguration(const TString& geometry, const TString& physicsList, const TString& specialProcess, - const bool specialStacking, - const bool isMT) + const bool specialStacking, + const bool isMT) : TG4RunConfiguration(geometry, physicsList, specialProcess, specialStacking, isMT) { -/// Standard constructor -/// \param geometry Selection of geometry option -/// \param physicsList Selection of physics -/// \param specialProcess Selection of the special processes + /// Standard constructor + /// \param geometry Selection of geometry option + /// \param physicsList Selection of physics + /// \param specialProcess Selection of the special processes } FairFastSimRunConfiguration::~FairFastSimRunConfiguration() { -/// Destructor + /// Destructor } // // protected methods // -TG4VUserFastSimulation* FairFastSimRunConfiguration::CreateUserFastSimulation() +TG4VUserFastSimulation* FairFastSimRunConfiguration::CreateUserFastSimulation() { LOG(info) << "Going to create FairFastSimulation"; return new FairFastSimulation(); diff --git a/base/sim/fastsim/FairFastSimRunConfiguration.h b/base/sim/fastsim/FairFastSimRunConfiguration.h index 8441b70ca1..247b099683 100644 --- a/base/sim/fastsim/FairFastSimRunConfiguration.h +++ b/base/sim/fastsim/FairFastSimRunConfiguration.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -12,8 +12,7 @@ #ifndef FAIR_FASTSIM_RUN_CONFIGURATION_H #define FAIR_FASTSIM_RUN_CONFIGURATION_H #include - -#include // for TString +#include // for TString class TG4VUserFastSimulation; class FairFastSimRunConfiguration : public TG4RunConfiguration @@ -22,13 +21,12 @@ class FairFastSimRunConfiguration : public TG4RunConfiguration FairFastSimRunConfiguration(const TString& geometry, const TString& physicsList = "FTFP_BERT", const TString& specialProcess = "stepLimiter", - const bool specialStacking = false, - const bool isMT = false); + const bool specialStacking = false, + const bool isMT = false); virtual ~FairFastSimRunConfiguration(); // methods - virtual TG4VUserFastSimulation* CreateUserFastSimulation(); + virtual TG4VUserFastSimulation* CreateUserFastSimulation(); }; -#endif //FAIR_FASTSIM_RUN_CONFIGURATION_H - +#endif // FAIR_FASTSIM_RUN_CONFIGURATION_H diff --git a/base/sim/fastsim/FairFastSimulation.cxx b/base/sim/fastsim/FairFastSimulation.cxx index e53075b968..1c0bd8b49a 100644 --- a/base/sim/fastsim/FairFastSimulation.cxx +++ b/base/sim/fastsim/FairFastSimulation.cxx @@ -11,14 +11,14 @@ // ------------------------------------------------------------------------- #include "FairFastSimulation.h" -#include "FairFastSimModel.h" - -#include // for TG4VUserFastSimulation +#include "FairFastSimModel.h" #include "FairLogger.h" +#include // for TG4VUserFastSimulation + FairFastSimulation::FairFastSimulation() - : TG4VUserFastSimulation() + : TG4VUserFastSimulation() { SetModel("fairFastSimModel"); LOG(info) << "FairFastSimulation::FairFastSimulation() model set"; @@ -29,18 +29,16 @@ FairFastSimulation::FairFastSimulation() LOG(info) << "FairFastSimulation::FairFastSimulation() finished"; } -FairFastSimulation::~FairFastSimulation() -{ -} +FairFastSimulation::~FairFastSimulation() {} // // protected methods // -void FairFastSimulation::Construct() +void FairFastSimulation::Construct() { -/// This function must be overriden in user class and users should create -/// the simulation models and register them to VMC framework + /// This function must be overriden in user class and users should create + /// the simulation models and register them to VMC framework LOG(info) << "Construct FairFastSimulation model."; @@ -51,6 +49,6 @@ void FairFastSimulation::Construct() Register(fairFastSimModel); LOG(info) << "end construct FairFastSimulation model."; - // - // end Initializing shower model + // + // end Initializing shower model } diff --git a/base/sim/fastsim/FairFastSimulation.h b/base/sim/fastsim/FairFastSimulation.h index d913e2f555..758726a675 100644 --- a/base/sim/fastsim/FairFastSimulation.h +++ b/base/sim/fastsim/FairFastSimulation.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -24,4 +24,4 @@ class FairFastSimulation : public TG4VUserFastSimulation virtual void Construct(); }; -#endif //FAIR_FAST_SIMULATION_H +#endif // FAIR_FAST_SIMULATION_H diff --git a/base/sink/FairRootFileSink.cxx b/base/sink/FairRootFileSink.cxx index c7bfae552a..757762ac74 100644 --- a/base/sink/FairRootFileSink.cxx +++ b/base/sink/FairRootFileSink.cxx @@ -12,18 +12,18 @@ // ----- ----- // ----------------------------------------------------------------------------- +#include "FairRootFileSink.h" + #include "FairEventHeader.h" #include "FairLogger.h" -#include "FairMonitor.h" // to store histograms at the end -#include "FairRootFileSink.h" -#include "FairRootManager.h" // to GetTreeName() +#include "FairMonitor.h" // to store histograms at the end +#include "FairRootManager.h" // to GetTreeName() #include #include #include #include -#include -#include // for TGeoManager, gGeoManager +#include // for TGeoManager, gGeoManager #include #include #include @@ -31,74 +31,73 @@ #include #include #include - -#include // free -#include // __cxa_demangle -#include // unique_ptr -#include // string - -FairRootFileSink::FairRootFileSink(TFile *f, const char* Title) - : FairSink() - , fOutputTitle(Title) - , fRootFile(f) - , fOutTree(0) - , fListFolder(new TObjArray(16)) - , fCbmout(0) - , fIsInitialized(kFALSE) - , fFileHeader(0) +#include // free +#include // __cxa_demangle +#include // unique_ptr +#include // string + +FairRootFileSink::FairRootFileSink(TFile* f, const char* Title) + : FairSink() + , fOutputTitle(Title) + , fRootFile(f) + , fOutTree(0) + , fListFolder(new TObjArray(16)) + , fCbmout(0) + , fIsInitialized(kFALSE) + , fFileHeader(0) { if (fRootFile->IsZombie()) { - LOG(fatal) << "Error opening the Input file"; + LOG(fatal) << "Error opening the Input file"; } LOG(debug) << "FairRootFileSink created------------"; } FairRootFileSink::FairRootFileSink(const TString* RootFileName, const char* Title) - : FairSink() - , fOutputTitle(Title) - , fRootFile(0) - , fOutTree(0) - , fListFolder(new TObjArray(16)) - , fCbmout(0) - , fIsInitialized(kFALSE) - , fFileHeader(0) + : FairSink() + , fOutputTitle(Title) + , fRootFile(0) + , fOutTree(0) + , fListFolder(new TObjArray(16)) + , fCbmout(0) + , fIsInitialized(kFALSE) + , fFileHeader(0) { - fRootFile = TFile::Open(RootFileName->Data(),"recreate"); + fRootFile = TFile::Open(RootFileName->Data(), "recreate"); if (fRootFile->IsZombie()) { - LOG(fatal) << "Error opening the Output file"; + LOG(fatal) << "Error opening the Output file"; } LOG(debug) << "FairRootFileSink created------------"; } FairRootFileSink::FairRootFileSink(const TString RootFileName, const char* Title) - : FairSink() - , fOutputTitle(Title) - , fRootFile(0) - , fOutTree(0) - , fListFolder(new TObjArray(16)) - , fCbmout(0) - , fIsInitialized(kFALSE) - , fFileHeader(0) + : FairSink() + , fOutputTitle(Title) + , fRootFile(0) + , fOutTree(0) + , fListFolder(new TObjArray(16)) + , fCbmout(0) + , fIsInitialized(kFALSE) + , fFileHeader(0) { - fRootFile = TFile::Open(RootFileName.Data(),"recreate"); - if (fRootFile->IsZombie()) { - LOG(fatal) << "Error opening the Input file"; - } - LOG(debug) << "FairRootFileSink created------------"; + fRootFile = TFile::Open(RootFileName.Data(), "recreate"); + if (fRootFile->IsZombie()) { + LOG(fatal) << "Error opening the Input file"; + } + LOG(debug) << "FairRootFileSink created------------"; } -FairRootFileSink::~FairRootFileSink() -{ -} +FairRootFileSink::~FairRootFileSink() {} -TFile* FairRootFileSink::OpenRootFile(TString fileName) { - if ( fileName.Length() <= 5 ) return nullptr; - return TFile::Open(fileName.Data(),"recreate"); +TFile* FairRootFileSink::OpenRootFile(TString fileName) +{ + if (fileName.Length() <= 5) + return nullptr; + return TFile::Open(fileName.Data(), "recreate"); } Bool_t FairRootFileSink::InitSink() { - if (fIsInitialized){ + if (fIsInitialized) { LOG(info) << "FairRootFileSink already initialized"; return kTRUE; } @@ -106,9 +105,10 @@ Bool_t FairRootFileSink::InitSink() fRootFile->cd(); - //FairRun* fRun = FairRun::Instance(); + // FairRun* fRun = FairRun::Instance(); /**Check if a simulation run!*/ - fOutFolder= gROOT->GetRootFolder()->AddFolder(Form("%s_%d",FairRootManager::GetFolderName(),FairRootManager::Instance()->GetInstanceId()), "Main Folder"); + fOutFolder = gROOT->GetRootFolder()->AddFolder( + Form("%s_%d", FairRootManager::GetFolderName(), FairRootManager::Instance()->GetInstanceId()), "Main Folder"); gROOT->GetListOfBrowsables()->Add(fOutFolder); LOG(info) << "FairRootFileSink initialized."; @@ -120,236 +120,240 @@ Bool_t FairRootFileSink::InitSink() void FairRootFileSink::TruncateBranchNames() { - /** If a object is created in a folder the corresponding branch - * in the tree is crated with a wrong name. - * The name of the branch is created as follows - * mainFolder.subFolder.nameOfStoredObject - * e.g. cbmroot.Event.ExampleClass. - * The name which is wanted is only nameOfStoredObject - * e.g. ExampleClass. - * This is corrected in this function - * If the folder does not exist don't do anything - */ - TCollection* lf = fOutFolder->GetListOfFolders(); - TIterator* iter= lf->MakeIterator(); - TObjArray* Br= fOutTree->GetListOfBranches(); - TIterator* BrIter= Br->MakeIterator(); - TObject* obj; - TObject* BrObj; - - /** correct branch names in all folders below the main output folder*/ - while ((obj=iter->Next())) { - /** Create TString with the part of the branch name which should be - * removed. This is mainFolderName.folderName. e.g. cbmroot.Event. - * This part of the branch name is obsolete, so it is removed from - * the branch name. - */ - TString ffn=(fOutFolder->GetName()); - ffn=ffn+"."; - ffn=ffn+obj->GetName(); - ffn=ffn+"."; - - /** Correct name of all branches and leaves which correspond to - * the subfolder. To do so loop over all branches and check - * if the branch corresponds with the folder. If it corresponds - * correct the branch names of all sub branches. - * Only correct branch names for up to now uncorrected branches. + /** If a object is created in a folder the corresponding branch + * in the tree is crated with a wrong name. + * The name of the branch is created as follows + * mainFolder.subFolder.nameOfStoredObject + * e.g. cbmroot.Event.ExampleClass. + * The name which is wanted is only nameOfStoredObject + * e.g. ExampleClass. + * This is corrected in this function + * If the folder does not exist don't do anything */ - BrIter->Reset(); - - while ((BrObj=BrIter->Next())) { - TBranch* b=static_cast(BrObj); - TruncateBranchNames(b, ffn); + TCollection* lf = fOutFolder->GetListOfFolders(); + TIterator* iter = lf->MakeIterator(); + TObjArray* Br = fOutTree->GetListOfBranches(); + TIterator* BrIter = Br->MakeIterator(); + TObject* obj; + TObject* BrObj; + + /** correct branch names in all folders below the main output folder*/ + while ((obj = iter->Next())) { + /** Create TString with the part of the branch name which should be + * removed. This is mainFolderName.folderName. e.g. cbmroot.Event. + * This part of the branch name is obsolete, so it is removed from + * the branch name. + */ + TString ffn = (fOutFolder->GetName()); + ffn = ffn + "."; + ffn = ffn + obj->GetName(); + ffn = ffn + "."; + + /** Correct name of all branches and leaves which correspond to + * the subfolder. To do so loop over all branches and check + * if the branch corresponds with the folder. If it corresponds + * correct the branch names of all sub branches. + * Only correct branch names for up to now uncorrected branches. + */ + BrIter->Reset(); + + while ((BrObj = BrIter->Next())) { + TBranch* b = static_cast(BrObj); + TruncateBranchNames(b, ffn); + } } - } - - // Remove all occurence of FairMCEventHeader and from - // all branches containing that string. - // This is not the correct way to do it, but up tonow we don't understand - // why this part comes in when storing a derrived class from - // FairMCEventHeader or FairEventHeader. - iter->Reset(); - while ((obj=iter->Next())) { - TString ffn=".FairMCEventHeader"; - BrIter->Reset(); - - while ((BrObj=BrIter->Next())) { - TBranch* b=static_cast(BrObj); - TruncateBranchNames(b, ffn); + // Remove all occurence of FairMCEventHeader and from + // all branches containing that string. + // This is not the correct way to do it, but up tonow we don't understand + // why this part comes in when storing a derrived class from + // FairMCEventHeader or FairEventHeader. + + iter->Reset(); + while ((obj = iter->Next())) { + TString ffn = ".FairMCEventHeader"; + BrIter->Reset(); + + while ((BrObj = BrIter->Next())) { + TBranch* b = static_cast(BrObj); + TruncateBranchNames(b, ffn); + } } - } - iter->Reset(); - while ((obj=iter->Next())) { - TString ffn=".FairEventHeader"; - BrIter->Reset(); + iter->Reset(); + while ((obj = iter->Next())) { + TString ffn = ".FairEventHeader"; + BrIter->Reset(); - while ((BrObj=BrIter->Next())) { - TBranch* b=static_cast(BrObj); - TruncateBranchNames(b, ffn); + while ((BrObj = BrIter->Next())) { + TBranch* b = static_cast(BrObj); + TruncateBranchNames(b, ffn); + } } - } - delete iter; - delete BrIter; + delete iter; + delete BrIter; } void FairRootFileSink::TruncateBranchNames(TBranch* b, TString ffn) { - /** Get the branch name from the branch object, remove common - * and wrong part of the name and and set branch name to - * the new corrected name. This has to be done recursivly for - * all subbranches/leaves - * Remove wrong part of branch name - */ - TObject* BrObj; - TString nn= b->GetName(); - LOG(debug) << "nn.Data before: " << nn.Data(); - nn.ReplaceAll(ffn.Data(),""); - LOG(debug) << "nn.Data after: " << nn.Data(); - LOG(debug) << "##################"; - b->SetName(nn.Data()); - TObjArray* Br= b->GetListOfBranches(); - TIterator* BrIter= Br->MakeIterator(); - BrIter->Reset(); - - while ((BrObj=BrIter->Next())) { - TBranch* bb=static_cast(BrObj); - TruncateBranchNames(bb, ffn); - } - delete BrIter; + /** Get the branch name from the branch object, remove common + * and wrong part of the name and and set branch name to + * the new corrected name. This has to be done recursivly for + * all subbranches/leaves + * Remove wrong part of branch name + */ + TObject* BrObj; + TString nn = b->GetName(); + LOG(debug) << "nn.Data before: " << nn.Data(); + nn.ReplaceAll(ffn.Data(), ""); + LOG(debug) << "nn.Data after: " << nn.Data(); + LOG(debug) << "##################"; + b->SetName(nn.Data()); + TObjArray* Br = b->GetListOfBranches(); + TIterator* BrIter = Br->MakeIterator(); + BrIter->Reset(); + + while ((BrObj = BrIter->Next())) { + TBranch* bb = static_cast(BrObj); + TruncateBranchNames(bb, ffn); + } + delete BrIter; } void FairRootFileSink::Close() { - if (fRootFile) { - fRootFile->Close(); - } + if (fRootFile) { + fRootFile->Close(); + } } -void FairRootFileSink::Reset() -{ -} +void FairRootFileSink::Reset() {} -void FairRootFileSink::FillEventHeader(FairEventHeader* /* feh */) -{ - return; -} +void FairRootFileSink::FillEventHeader(FairEventHeader* /* feh */) { return; } -void FairRootFileSink::RegisterImpl(const char* /* name */, const char *folderName, void* obj) { - TFolder* folder=0; - TFolder* f=0; - f=static_cast(fOutFolder->FindObjectAny(folderName)); - if (f==0) { - folder= fOutFolder->AddFolder(folderName,folderName); - } else { - folder=f; - } +void FairRootFileSink::RegisterImpl(const char* /* name */, const char* folderName, void* obj) +{ + TFolder* folder = 0; + TFolder* f = 0; + f = static_cast(fOutFolder->FindObjectAny(folderName)); + if (f == 0) { + folder = fOutFolder->AddFolder(folderName, folderName); + } else { + folder = f; + } // ((TNamed*)obj)->SetName(name); - folder->Add((TNamed*)obj); + folder->Add((TNamed*)obj); } -void FairRootFileSink::RegisterAny(const char* brname, const std::type_info &oi, const std::type_info &pi, void* obj) { - fPersistentBranchesMap[brname]=std::unique_ptr (new TypeAddressPair(oi, pi,obj)); +void FairRootFileSink::RegisterAny(const char* brname, const std::type_info& oi, const std::type_info& pi, void* obj) +{ + fPersistentBranchesMap[brname] = std::unique_ptr(new TypeAddressPair(oi, pi, obj)); } -void FairRootFileSink::WriteFolder() { - fRootFile->cd(); - if(fOutFolder!=0) { - fOutFolder->Write(FairRootManager::GetFolderName()); - - //FairRun* fRun = FairRun::Instance(); - fOutTree =new TTree(FairRootManager::GetTreeName(), Form("/%s_%d",FairRootManager::GetFolderName(),FairRootManager::Instance()->GetInstanceId()), 99); - TruncateBranchNames(); - CreatePersistentBranchesAny(); - } +void FairRootFileSink::WriteFolder() +{ + fRootFile->cd(); + if (fOutFolder != 0) { + fOutFolder->Write(FairRootManager::GetFolderName()); + + // FairRun* fRun = FairRun::Instance(); + fOutTree = + new TTree(FairRootManager::GetTreeName(), + Form("/%s_%d", FairRootManager::GetFolderName(), FairRootManager::Instance()->GetInstanceId()), + 99); + TruncateBranchNames(); + CreatePersistentBranchesAny(); + } } -namespace impl +namespace impl { +// a helper function to demangle a type_name +inline std::string demangle(const char* name) { - // a helper function to demangle a type_name - inline std::string demangle(const char* name) - { - int status = -4; // some arbitrary value to eliminate the compiler warning - std::unique_ptr res{ abi::__cxa_demangle(name, nullptr, nullptr, &status), std::free }; + int status = -4; // some arbitrary value to eliminate the compiler warning + std::unique_ptr res{abi::__cxa_demangle(name, nullptr, nullptr, &status), std::free}; return (status == 0) ? res.get() : name; - } } +} // namespace impl bool FairRootFileSink::CreatePersistentBranchesAny() { - for(auto& iter : fPersistentBranchesMap) { - LOG(info) << "CREATING BRANCH " << iter.first; - auto &tinfo = iter.second->persistenttypeinfo; - auto tname = impl::demangle(tinfo.name()); - - // for the branch creation we need a TClass describing the object - // get it from ROOT via the type name - auto cl = TClass::GetClass(tinfo); - if (!cl) { - LOG(fatal) << "No TClass found for " << tname << "\n"; - return false; - } - - if (!cl->HasDictionary()) { - LOG(fatal) << "No dictionary found for " << tname << "\n"; - return false; + for (auto& iter : fPersistentBranchesMap) { + LOG(info) << "CREATING BRANCH " << iter.first; + auto& tinfo = iter.second->persistenttypeinfo; + auto tname = impl::demangle(tinfo.name()); + + // for the branch creation we need a TClass describing the object + // get it from ROOT via the type name + auto cl = TClass::GetClass(tinfo); + if (!cl) { + LOG(fatal) << "No TClass found for " << tname << "\n"; + return false; + } + + if (!cl->HasDictionary()) { + LOG(fatal) << "No dictionary found for " << tname << "\n"; + return false; + } + + // create the branch + auto obj = iter.second->ptraddr; + + LOG(info) << "Creating branch for " << iter.first.c_str() << " with address " << obj; + fOutTree->Branch(iter.first.c_str(), tname.c_str(), obj); } - - // create the branch - auto obj = iter.second->ptraddr; - - LOG(info) << "Creating branch for " << iter.first.c_str() << " with address " << obj; - fOutTree->Branch(iter.first.c_str(), tname.c_str(), obj); - } - return true; + return true; } -void FairRootFileSink::WriteObject(TObject* f, const char* name, Int_t option) { - fRootFile->cd(); - f->Write(name, option); +void FairRootFileSink::WriteObject(TObject* f, const char* name, Int_t option) +{ + fRootFile->cd(); + f->Write(name, option); } -void FairRootFileSink::WriteGeometry() { - fRootFile->cd(); - gGeoManager->Write(); +void FairRootFileSink::WriteGeometry() +{ + fRootFile->cd(); + gGeoManager->Write(); } -void FairRootFileSink::Fill() { - if (fOutTree != 0) { - fOutTree->Fill(); - } else { - LOG(info) << " No Output Tree"; - } +void FairRootFileSink::Fill() +{ + if (fOutTree != 0) { + fOutTree->Fill(); + } else { + LOG(info) << " No Output Tree"; + } } Int_t FairRootFileSink::Write(const char*, Int_t, Int_t) { - /** Writes the tree in the file.*/ - if (fOutTree!=0) { - /** Get the file handle to the current output file from the tree. - * If ROOT splits the file (due to the size of the file) the file - * handle fOutFile is lost and the program crash while writing the - * last part of the last file. - */ - - // fOutTree->Print(); - - fRootFile = fOutTree->GetCurrentFile(); - FairMonitor::GetMonitor()->StoreHistograms(fRootFile); - LOG(debug) << "FairRootFileSink::Write to file: " << fRootFile->GetName(); - fRootFile->cd(); - fOutTree->Write(); - } else { - LOG(info) << "No Output Tree"; - } - return 0; + /** Writes the tree in the file.*/ + if (fOutTree != 0) { + /** Get the file handle to the current output file from the tree. + * If ROOT splits the file (due to the size of the file) the file + * handle fOutFile is lost and the program crash while writing the + * last part of the last file. + */ + + // fOutTree->Print(); + + fRootFile = fOutTree->GetCurrentFile(); + FairMonitor::GetMonitor()->StoreHistograms(fRootFile); + LOG(debug) << "FairRootFileSink::Write to file: " << fRootFile->GetName(); + fRootFile->cd(); + fOutTree->Write(); + } else { + LOG(info) << "No Output Tree"; + } + return 0; } //_____________________________________________________________________________ //_____________________________________________________________________________ -FairSink* FairRootFileSink::CloneSink() { +FairSink* FairRootFileSink::CloneSink() +{ FairRootManager* tempMan = FairRootManager::Instance(); TString workerFileName = fRootFile->GetName(); @@ -361,4 +365,4 @@ FairSink* FairRootFileSink::CloneSink() { } //_____________________________________________________________________________ -ClassImp(FairRootFileSink) +ClassImp(FairRootFileSink); diff --git a/base/sink/FairRootFileSink.h b/base/sink/FairRootFileSink.h index d7fac4601a..4bf72bc91d 100644 --- a/base/sink/FairRootFileSink.h +++ b/base/sink/FairRootFileSink.h @@ -20,7 +20,6 @@ #include #include #include - #include class FairEventHeader; @@ -34,43 +33,43 @@ class TFolder; class FairRootFileSink : public FairSink { public: - FairRootFileSink(TFile *f, const char* Title="OutputRootFile"); - FairRootFileSink(const TString* RootFileName, const char* Title="OutputRootFile"); - FairRootFileSink(const TString RootFileName, const char* Title="OutputRootFile"); + FairRootFileSink(TFile* f, const char* Title = "OutputRootFile"); + FairRootFileSink(const TString* RootFileName, const char* Title = "OutputRootFile"); + FairRootFileSink(const TString RootFileName, const char* Title = "OutputRootFile"); // FairRootFileSink(const FairRootFileSink& file); virtual ~FairRootFileSink(); - virtual Bool_t InitSink(); - virtual void Close(); - virtual void Reset(); + virtual Bool_t InitSink(); + virtual void Close(); + virtual void Reset(); virtual Sink_Type GetSinkType() { return kFILESINK; } - virtual void FillEventHeader(FairEventHeader* feh); + virtual void FillEventHeader(FairEventHeader* feh); - virtual TFile* OpenRootFile(TString fileName=""); - TFile* GetRootFile (){return fRootFile;} - virtual TString GetFileName (){return (fRootFile?fRootFile->GetName():"");} + virtual TFile* OpenRootFile(TString fileName = ""); + TFile* GetRootFile() { return fRootFile; } + virtual TString GetFileName() { return (fRootFile ? fRootFile->GetName() : ""); } - virtual void SetOutTree(TTree* fTree) { fOutTree=fTree;} - TTree* GetOutTree() { return fOutTree; } + virtual void SetOutTree(TTree* fTree) { fOutTree = fTree; } + TTree* GetOutTree() { return fOutTree; } - virtual void Fill(); + virtual void Fill(); - virtual Int_t Write(const char* name=0, Int_t option=0, Int_t bufsize=0); + virtual Int_t Write(const char* name = 0, Int_t option = 0, Int_t bufsize = 0); - virtual void RegisterImpl(const char* , const char* , void* ); - virtual void RegisterAny(const char* brname, const std::type_info &oi, const std::type_info &pi, void* obj); + virtual void RegisterImpl(const char*, const char*, void*); + virtual void RegisterAny(const char* brname, const std::type_info& oi, const std::type_info& pi, void* obj); - virtual void WriteFolder(); - virtual bool CreatePersistentBranchesAny(); + virtual void WriteFolder(); + virtual bool CreatePersistentBranchesAny(); - virtual void WriteObject(TObject* f, const char*, Int_t option = 0); - virtual void WriteGeometry(); + virtual void WriteObject(TObject* f, const char*, Int_t option = 0); + virtual void WriteGeometry(); - virtual FairSink* CloneSink(); + virtual FairSink* CloneSink(); - private: + private: /** Title of input sink, could be input, background or signal*/ TString fOutputTitle; /** ROOT file */ @@ -78,7 +77,7 @@ class FairRootFileSink : public FairSink /** Output Tree */ TTree* fOutTree; /** list of folders from all input (and friends) files */ - TObjArray *fListFolder; //! + TObjArray* fListFolder; //! /** folder structure of output */ TFolder* fCbmout; /** Initialization flag, true if initialized */ @@ -92,7 +91,7 @@ class FairRootFileSink : public FairSink // bool CreatePersistentBranchesAny(); /**File Header*/ - FairFileHeader* fFileHeader; //! + FairFileHeader* fFileHeader; //! ClassDef(FairRootFileSink, 1) }; diff --git a/base/sink/FairSink.cxx b/base/sink/FairSink.cxx index cdec1ea780..5e36b08bab 100644 --- a/base/sink/FairSink.cxx +++ b/base/sink/FairSink.cxx @@ -13,23 +13,20 @@ // ----------------------------------------------------------------------------- #include "FairSink.h" + #include #include FairSink::FairSink() - : fRunId(0) - , fOutFolder(0) -{ -} + : fRunId(0) + , fOutFolder(0) +{} FairSink::FairSink(const FairSink& sink) - : fRunId(sink.fRunId) - , fOutFolder(0) -{ -} + : fRunId(sink.fRunId) + , fOutFolder(0) +{} -FairSink::~FairSink() -{ -} +FairSink::~FairSink() {} -ClassImp(FairSink) +ClassImp(FairSink); diff --git a/base/sink/FairSink.h b/base/sink/FairSink.h index cd4041e6f3..aa19dfdff0 100644 --- a/base/sink/FairSink.h +++ b/base/sink/FairSink.h @@ -17,17 +17,20 @@ #include #include - -#include // map -#include // unique_ptr -#include // string -#include // type_info +#include // map +#include // unique_ptr +#include // string +#include // type_info class TObject; class TFolder; class TTree; -enum Sink_Type {kONLINESINK, kFILESINK}; +enum Sink_Type +{ + kONLINESINK, + kFILESINK +}; class FairSink { @@ -41,7 +44,7 @@ class FairSink virtual void Reset() = 0; virtual Sink_Type GetSinkType() = 0; - virtual TString GetFileName () { return ""; } + virtual TString GetFileName() { return ""; } void SetRunId(Int_t runId) { fRunId = runId; } Int_t GetRunId() const { return fRunId; } @@ -61,14 +64,19 @@ class FairSink virtual void WriteObject(TObject* f, const char*, Int_t option = 0) = 0; virtual void WriteGeometry() = 0; - virtual FairSink* CloneSink() = 0; + virtual FairSink* CloneSink() = 0; protected: - struct TypeAddressPair { - TypeAddressPair(const std::type_info& oi, const std::type_info& pi, void* a) : origtypeinfo(oi), persistenttypeinfo(pi), ptraddr(a) {} - const std::type_info &origtypeinfo; // type_info of type addr points to - const std::type_info &persistenttypeinfo; // type_info of ROOT persistent branch (drops pointers) - void* ptraddr; // address of a pointer (pointing to origtypeinfo); + struct TypeAddressPair + { + TypeAddressPair(const std::type_info& oi, const std::type_info& pi, void* a) + : origtypeinfo(oi) + , persistenttypeinfo(pi) + , ptraddr(a) + {} + const std::type_info& origtypeinfo; // type_info of type addr points to + const std::type_info& persistenttypeinfo; // type_info of ROOT persistent branch (drops pointers) + void* ptraddr; // address of a pointer (pointing to origtypeinfo); }; Int_t fRunId; @@ -78,7 +86,7 @@ class FairSink /// A map of branchnames to typeinformation + memory address; /// used for branches registered to bes stored; use of ptr here /// since type_info cannot be copied - std::map> fPersistentBranchesMap; //! + std::map> fPersistentBranchesMap; //! public: ClassDef(FairSink, 1) diff --git a/base/source/FairFileSource.cxx b/base/source/FairFileSource.cxx index 5fe48aa9c5..76fd3772d2 100644 --- a/base/source/FairFileSource.cxx +++ b/base/source/FairFileSource.cxx @@ -13,75 +13,74 @@ // Created by Mohammad Al-Turany on 08/02/14. // // -#include "FairEventHeader.h" #include "FairFileSource.h" + +#include "FairEventHeader.h" #include "FairLogger.h" #include "FairMCEventHeader.h" #include "FairRootManager.h" -#include "FairRuntimeDb.h" // for FairRuntimeDb +#include "FairRuntimeDb.h" // for FairRuntimeDb +#include #include #include -#include // for TIter +#include // for TIter #include #include #include #include -#include #include -#include // for TRandom, gRandom +#include #include +#include // for TRandom, gRandom #include #include -#include -#include - -#include // for find -#include // fmod -#include // exit -#include // for _List_iterator, list, etc -#include // multimap +#include // for find +#include // fmod +#include // exit +#include // for _List_iterator, list, etc +#include // multimap #include #include #include using std::set; -FairFileSource::FairFileSource(TFile *f, const char* Title, UInt_t) - : FairSource() - , fInputTitle(Title) - , fRootFile(f) - , fCurrentEntryNr(0) - , fFriendFileList() - , fInputChainList() - , fFriendTypeList() - , fCheckInputBranches() - , fInputLevel() - , fRunIdInfoAll() - , fInChain(0) - , fInTree(0) - , fListFolder(new TObjArray(16)) - , fRtdb(FairRuntimeDb::instance()) - , fCbmout(0) - , fCbmroot(0) - , fSourceIdentifier(0) - , fNoOfEntries(-1) - , IsInitialized(kFALSE) - , fMCHeader(0) - , fEvtHeader(0) - , fFileHeader(0) - , fEventTimeInMCHeader(kTRUE) - , fEvtHeaderIsNew(kFALSE) - , fCurrentEntryNo(0) - , fTimeforEntryNo(-1) - , fEventTimeMin(0.) - , fEventTimeMax(0.) - , fEventTime(0.) - , fBeamTime(-1.) - , fGapTime(-1.) - , fEventMeanTime(0.) - , fTimeProb(0) - , fCheckFileLayout(kTRUE) +FairFileSource::FairFileSource(TFile* f, const char* Title, UInt_t) + : FairSource() + , fInputTitle(Title) + , fRootFile(f) + , fCurrentEntryNr(0) + , fFriendFileList() + , fInputChainList() + , fFriendTypeList() + , fCheckInputBranches() + , fInputLevel() + , fRunIdInfoAll() + , fInChain(0) + , fInTree(0) + , fListFolder(new TObjArray(16)) + , fRtdb(FairRuntimeDb::instance()) + , fCbmout(0) + , fCbmroot(0) + , fSourceIdentifier(0) + , fNoOfEntries(-1) + , IsInitialized(kFALSE) + , fMCHeader(0) + , fEvtHeader(0) + , fFileHeader(0) + , fEventTimeInMCHeader(kTRUE) + , fEvtHeaderIsNew(kFALSE) + , fCurrentEntryNo(0) + , fTimeforEntryNo(-1) + , fEventTimeMin(0.) + , fEventTimeMax(0.) + , fEventTime(0.) + , fBeamTime(-1.) + , fGapTime(-1.) + , fEventMeanTime(0.) + , fTimeProb(0) + , fCheckFileLayout(kTRUE) { if (fRootFile->IsZombie()) { LOG(fatal) << "Error opening the Input file"; @@ -90,40 +89,40 @@ FairFileSource::FairFileSource(TFile *f, const char* Title, UInt_t) } FairFileSource::FairFileSource(const TString* RootFileName, const char* Title, UInt_t) - : FairSource() - , fInputTitle(Title) - , fRootFile(0) - , fCurrentEntryNr(0) - , fFriendFileList() - , fInputChainList() - , fFriendTypeList() - , fCheckInputBranches() - , fInputLevel() - , fRunIdInfoAll() - , fInChain(0) - , fInTree(0) - , fListFolder(new TObjArray(16)) - , fRtdb(FairRuntimeDb::instance()) - , fCbmout(0) - , fCbmroot(0) - , fSourceIdentifier(0) - , fNoOfEntries(-1) - , IsInitialized(kFALSE) - , fMCHeader(0) - , fEvtHeader(0) - , fFileHeader(0) - , fEventTimeInMCHeader(kTRUE) - , fEvtHeaderIsNew(kFALSE) - , fCurrentEntryNo(0) - , fTimeforEntryNo(-1) - , fEventTimeMin(0.) - , fEventTimeMax(0.) - , fEventTime(0.) - , fBeamTime(-1.) - , fGapTime(-1.) - , fEventMeanTime(0.) - , fTimeProb(0) - , fCheckFileLayout(kTRUE) + : FairSource() + , fInputTitle(Title) + , fRootFile(0) + , fCurrentEntryNr(0) + , fFriendFileList() + , fInputChainList() + , fFriendTypeList() + , fCheckInputBranches() + , fInputLevel() + , fRunIdInfoAll() + , fInChain(0) + , fInTree(0) + , fListFolder(new TObjArray(16)) + , fRtdb(FairRuntimeDb::instance()) + , fCbmout(0) + , fCbmroot(0) + , fSourceIdentifier(0) + , fNoOfEntries(-1) + , IsInitialized(kFALSE) + , fMCHeader(0) + , fEvtHeader(0) + , fFileHeader(0) + , fEventTimeInMCHeader(kTRUE) + , fEvtHeaderIsNew(kFALSE) + , fCurrentEntryNo(0) + , fTimeforEntryNo(-1) + , fEventTimeMin(0.) + , fEventTimeMax(0.) + , fEventTime(0.) + , fBeamTime(-1.) + , fGapTime(-1.) + , fEventMeanTime(0.) + , fTimeProb(0) + , fCheckFileLayout(kTRUE) { fRootFile = TFile::Open(RootFileName->Data()); if (fRootFile->IsZombie()) { @@ -133,40 +132,40 @@ FairFileSource::FairFileSource(const TString* RootFileName, const char* Title, U } FairFileSource::FairFileSource(const TString RootFileName, const char* Title, UInt_t) - : FairSource() - , fInputTitle(Title) - , fRootFile(0) - , fCurrentEntryNr(0) - , fFriendFileList() - , fInputChainList() - , fFriendTypeList() - , fCheckInputBranches() - , fInputLevel() - , fRunIdInfoAll() - , fInChain(0) - , fInTree(0) - , fListFolder(new TObjArray(16)) - , fRtdb(FairRuntimeDb::instance()) - , fCbmout(0) - , fCbmroot(0) - , fSourceIdentifier(0) - , fNoOfEntries(-1) - , IsInitialized(kFALSE) - , fMCHeader(0) - , fEvtHeader(0) - , fFileHeader(0) - , fEventTimeInMCHeader(kTRUE) - , fEvtHeaderIsNew(kFALSE) - , fCurrentEntryNo(0) - , fTimeforEntryNo(-1) - , fEventTimeMin(0.) - , fEventTimeMax(0.) - , fEventTime(0.) - , fBeamTime(-1.) - , fGapTime(-1.) - , fEventMeanTime(0.) - , fTimeProb(0) - , fCheckFileLayout(kTRUE) + : FairSource() + , fInputTitle(Title) + , fRootFile(0) + , fCurrentEntryNr(0) + , fFriendFileList() + , fInputChainList() + , fFriendTypeList() + , fCheckInputBranches() + , fInputLevel() + , fRunIdInfoAll() + , fInChain(0) + , fInTree(0) + , fListFolder(new TObjArray(16)) + , fRtdb(FairRuntimeDb::instance()) + , fCbmout(0) + , fCbmroot(0) + , fSourceIdentifier(0) + , fNoOfEntries(-1) + , IsInitialized(kFALSE) + , fMCHeader(0) + , fEvtHeader(0) + , fFileHeader(0) + , fEventTimeInMCHeader(kTRUE) + , fEvtHeaderIsNew(kFALSE) + , fCurrentEntryNo(0) + , fTimeforEntryNo(-1) + , fEventTimeMin(0.) + , fEventTimeMax(0.) + , fEventTime(0.) + , fBeamTime(-1.) + , fGapTime(-1.) + , fEventMeanTime(0.) + , fTimeProb(0) + , fCheckFileLayout(kTRUE) { fRootFile = TFile::Open(RootFileName.Data()); if (fRootFile->IsZombie()) { @@ -175,9 +174,7 @@ FairFileSource::FairFileSource(const TString RootFileName, const char* Title, UI LOG(debug) << "FairFileSource created------------"; } -FairFileSource::~FairFileSource() -{ -} +FairFileSource::~FairFileSource() {} Bool_t FairFileSource::Init() { @@ -186,7 +183,7 @@ Bool_t FairFileSource::Init() return kTRUE; } if (!fInChain) { - fInChain = new TChain(FairRootManager::GetTreeName(), Form("/%s",FairRootManager::GetFolderName())); + fInChain = new TChain(FairRootManager::GetTreeName(), Form("/%s", FairRootManager::GetFolderName())); LOG(debug) << "FairFileSource::Init() chain created"; FairRootManager::Instance()->SetInChain(fInChain); } @@ -219,7 +216,7 @@ Bool_t FairFileSource::Init() // branch structure. Without this check it is possible to add trees // with a different branch structure but the same tree name. ROOT // probably only checks if the name of the tree is the same. - TList* list= dynamic_cast(fRootFile->Get("BranchList")); + TList* list = dynamic_cast(fRootFile->Get("BranchList")); if (list == 0) { LOG(fatal) << "No Branch list in input file"; } @@ -233,7 +230,7 @@ Bool_t FairFileSource::Init() for (Int_t i = 0; i < list->GetEntries(); i++) { Obj = dynamic_cast(list->At(i)); if (Obj != 0) { - ObjName=Obj->GetString(); + ObjName = Obj->GetString(); LOG(debug) << "Branch name " << ObjName.Data(); fCheckInputBranches[chainName]->push_back(ObjName.Data()); @@ -263,50 +260,51 @@ Bool_t FairFileSource::Init() // is needed to bring the friend trees in the correct order TFile* inputFile = TFile::Open(fileName); if (inputFile->IsZombie()) { - LOG(fatal) << "Error opening the file " << fileName.Data() << " which should be added to the input chain or as friend chain"; + LOG(fatal) << "Error opening the file " << fileName.Data() + << " which should be added to the input chain or as friend chain"; } if (fCheckFileLayout) { - // Check if the branchlist is the same as for the first input file. - Bool_t isOk = CompareBranchList(inputFile, chainName); - if (!isOk) { - LOG(fatal) << "Branch structure of the input file " << fRootFile->GetName() << " and the file to be added " << fileName.Data() << " are different."; - return kFALSE; - } + // Check if the branchlist is the same as for the first input file. + Bool_t isOk = CompareBranchList(inputFile, chainName); + if (!isOk) { + LOG(fatal) << "Branch structure of the input file " << fRootFile->GetName() + << " and the file to be added " << fileName.Data() << " are different."; + return kFALSE; + } } // Add the runid information for all files in the chain. - //GetRunIdInfo(inputFile->GetName(), chainName); + // GetRunIdInfo(inputFile->GetName(), chainName); // Add the file to the input chain fInChain->Add(fileName); // Close the temporarly file and restore the gFile pointer. inputFile->Close(); gFile = temp; - } fNoOfEntries = fInChain->GetEntries(); LOG(debug) << "Entries in this Source " << fNoOfEntries; - for (Int_t i=0; iGetEntriesFast(); i++) { - TFolder* fold = static_cast(fListFolder->At(i)); - fEvtHeader = static_cast(fold->FindObjectAny("EventHeader.")); - fMCHeader = static_cast(fold->FindObjectAny("MCEventHeader.")); - if (fEvtHeader) { - ActivateObject(reinterpret_cast(&fEvtHeader),"EventHeader."); - } - if (fMCHeader) { - ActivateObject(reinterpret_cast(&fMCHeader),"MCEventHeader."); - } + for (Int_t i = 0; i < fListFolder->GetEntriesFast(); i++) { + TFolder* fold = static_cast(fListFolder->At(i)); + fEvtHeader = static_cast(fold->FindObjectAny("EventHeader.")); + fMCHeader = static_cast(fold->FindObjectAny("MCEventHeader.")); + if (fEvtHeader) { + ActivateObject(reinterpret_cast(&fEvtHeader), "EventHeader."); + } + if (fMCHeader) { + ActivateObject(reinterpret_cast(&fMCHeader), "MCEventHeader."); + } } FairRootManager::Instance()->SetListOfFolders(fListFolder); AddFriendsToChain(); - TList* timebasedlist= dynamic_cast(fRootFile->Get("TimeBasedBranchList")); - if (timebasedlist==0) { + TList* timebasedlist = dynamic_cast(fRootFile->Get("TimeBasedBranchList")); + if (timebasedlist == 0) { LOG(warn) << "No time based branch list in input file"; } else { FairRootManager::Instance()->SetTimeBasedBranchNameList(timebasedlist); @@ -315,13 +313,13 @@ Bool_t FairFileSource::Init() return kTRUE; } -void FairFileSource::SetInTree(TTree* tempTree) +void FairFileSource::SetInTree(TTree* tempTree) { fInTree = nullptr; - fInTree = tempTree; - fRootFile=static_cast(tempTree->GetCurrentFile()); + fInTree = tempTree; + fRootFile = static_cast(tempTree->GetCurrentFile()); fInChain->Reset(); - IsInitialized=kFALSE; + IsInitialized = kFALSE; Init(); } @@ -329,29 +327,19 @@ Int_t FairFileSource::ReadEvent(UInt_t i) { fCurrentEntryNo = i; fEventTime = GetEventTime(); - if (fInChain->GetEntry(i)) return 0; + if (fInChain->GetEntry(i)) + return 0; return 1; } -void FairFileSource::Close() -{ - CloseInFile(); -} +void FairFileSource::Close() { CloseInFile(); } -void FairFileSource::Reset() -{ -} +void FairFileSource::Reset() {} -void FairFileSource::AddFriend(TString fName) -{ - fFriendFileList.push_back(fName); -} +void FairFileSource::AddFriend(TString fName) { fFriendFileList.push_back(fName); } -void FairFileSource::AddFile(TString FileName) -{ - fInputChainList.push_back(FileName); -} +void FairFileSource::AddFile(TString FileName) { fInputChainList.push_back(FileName); } void FairFileSource::AddFriendsToChain() { @@ -396,7 +384,8 @@ void FairFileSource::AddFriendsToChain() inputFile = TFile::Open(fileName); if (inputFile->IsZombie()) { - LOG(fatal) << "Error opening the file " << level.Data() << " which should be added to the input chain or as friend chain"; + LOG(fatal) << "Error opening the file " << level.Data() + << " which should be added to the input chain or as friend chain"; } // Check if the branchlist is already stored in the map. If it is @@ -410,7 +399,7 @@ void FairFileSource::AddFriendsToChain() inputFile->Close(); } if (!inputLevelFound) { - inputLevel = Form("FriendTree_%i",friendType); + inputLevel = Form("FriendTree_%i", friendType); CreateNewFriendChain(fileName, inputLevel); friendType++; } @@ -455,7 +444,7 @@ void FairFileSource::PrintFriendList() fileElements = chain->GetListOfFiles(); TIter next1(fileElements); chEl = 0; - while ((chEl=static_cast(next1()))) { + while ((chEl = static_cast(next1()))) { LOG(info) << " - " << chEl->GetTitle(); } } @@ -463,7 +452,7 @@ void FairFileSource::PrintFriendList() void FairFileSource::CheckFriendChains() { - std::multimap>::iterator it1; + std::multimap>::iterator it1; std::multimap map1; // Get the structure from the input chain @@ -502,7 +491,7 @@ void FairFileSource::CheckFriendChains() } counter++; } - if (errorFlag>0) { + if (errorFlag > 0) { break; } } @@ -514,7 +503,7 @@ void FairFileSource::CheckFriendChains() LOG(error) << "The input chain and the friend chain " << inputLevel.Data() << " have a different structure:"; if (errorFlag == 1) { LOG(error) << "The input chain has the following runids and event numbers:"; - for (UInt_t i=0; i; if (list) { - TObjString* Obj=0; - for (Int_t i =0; i< list->GetEntries(); i++) { - Obj=dynamic_cast(list->At(i)); + TObjString* Obj = 0; + for (Int_t i = 0; i < list->GetEntries(); i++) { + Obj = dynamic_cast(list->At(i)); fCheckInputBranches[chainName]->push_back(Obj->GetString().Data()); FairRootManager::Instance()->AddBranchToList(Obj->GetString().Data()); } } - TChain* chain = new TChain(inputLevel,folderName); + TChain* chain = new TChain(inputLevel, folderName); fFriendTypeList[inputLevel] = chain; f->Close(); @@ -604,14 +595,14 @@ Bool_t FairFileSource::CompareBranchList(TFile* fileHandle, TString inputLevel) // the list. If in the end no branch is left in the list everything is // fine. set::iterator iter1; - TList* list= dynamic_cast(fileHandle->Get("BranchList")); + TList* list = dynamic_cast(fileHandle->Get("BranchList")); if (list) { TObjString* Obj = 0; - for (Int_t i = 0; i< list->GetEntries(); i++) { + for (Int_t i = 0; i < list->GetEntries(); i++) { Obj = dynamic_cast(list->At(i)); - iter1=branches.find(Obj->GetString().Data()); + iter1 = branches.find(Obj->GetString().Data()); if (iter1 != branches.end()) { - branches.erase (iter1); + branches.erase(iter1); } else { // Not found is an error because branch structure is // different. It is impossible to add to tree with a @@ -636,12 +627,12 @@ Bool_t FairFileSource::CompareBranchList(TFile* fileHandle, TString inputLevel) Bool_t FairFileSource::ActivateObject(TObject** obj, const char* BrName) { if (fInTree) { - fInTree->SetBranchStatus(BrName,1); - fInTree->SetBranchAddress(BrName,obj); + fInTree->SetBranchStatus(BrName, 1); + fInTree->SetBranchAddress(BrName, obj); } if (fInChain) { - fInChain->SetBranchStatus(BrName,1); - fInChain->SetBranchAddress(BrName,obj); + fInChain->SetBranchStatus(BrName, 1); + fInChain->SetBranchAddress(BrName, obj); } return kTRUE; @@ -650,7 +641,8 @@ Bool_t FairFileSource::ActivateObject(TObject** obj, const char* BrName) namespace { template -bool ActivateObjectAnyImpl(S* source, void **obj, const std::type_info& info, const char* brname) { +bool ActivateObjectAnyImpl(S* source, void** obj, const std::type_info& info, const char* brname) +{ // we check if the types match at all auto br = source->GetBranch(brname); if (!br) { @@ -669,7 +661,8 @@ bool ActivateObjectAnyImpl(S* source, void **obj, const std::type_info& info, co // check consistency of types if (info.hash_code() != storedtype->hash_code()) { - LOG(info) << "Trying to read from branch " << brname << " with wrong type " << info.name() << " (expected: " << storedtype->name() << ")\n"; + LOG(info) << "Trying to read from branch " << brname << " with wrong type " << info.name() + << " (expected: " << storedtype->name() << ")\n"; return false; } source->SetBranchStatus(brname, 1); @@ -678,7 +671,7 @@ bool ActivateObjectAnyImpl(S* source, void **obj, const std::type_info& info, co return true; } -} +} // namespace Bool_t FairFileSource::ActivateObjectAny(void** obj, const std::type_info& info, const char* BrName) { @@ -723,10 +716,10 @@ void FairFileSource::SetEventMeanTime(Double_t mean) form+=")"; fTimeProb= new TF1("TimeProb.", form.Data(), 0., mean*10); */ - fTimeProb = new TF1("TimeProb","(1/[0])*exp(-x/[0])", 0., mean*10); - fTimeProb->SetParameter(0,mean); + fTimeProb = new TF1("TimeProb", "(1/[0])*exp(-x/[0])", 0., mean * 10); + fTimeProb->SetParameter(0, mean); fTimeProb->GetRandom(); - fEventTimeInMCHeader=kFALSE; + fEventTimeInMCHeader = kFALSE; } void FairFileSource::SetEventTimeInterval(Double_t min, Double_t max) @@ -746,11 +739,10 @@ void FairFileSource::SetBeamTime(Double_t beamTime, Double_t gapTime) void FairFileSource::SetEventTime() { // Check if the time for the current entry is already set - if (fTimeforEntryNo==fCurrentEntryNo) return; - LOG(debug) << "Set event time for Entry = " - << fTimeforEntryNo << " , where the current entry is " - << fCurrentEntryNo << " and eventTime is " - << fEventTime; + if (fTimeforEntryNo == fCurrentEntryNo) + return; + LOG(debug) << "Set event time for Entry = " << fTimeforEntryNo << " , where the current entry is " + << fCurrentEntryNo << " and eventTime is " << fEventTime; if (fBeamTime < 0) { fEventTime += GetDeltaEventTime(); } else { @@ -759,67 +751,66 @@ void FairFileSource::SetEventTime() } while (fmod(fEventTime, fBeamTime + fGapTime) > fBeamTime); } LOG(debug) << "New time = " << fEventTime; - fTimeforEntryNo=fCurrentEntryNo; + fTimeforEntryNo = fCurrentEntryNo; } Double_t FairFileSource::GetDeltaEventTime() { - Double_t deltaTime = 0; - if (fTimeProb != 0) { - deltaTime = fTimeProb->GetRandom(); - LOG(debug) << "Time set via sampling method : " << deltaTime; - } else { - deltaTime = gRandom->Uniform(fEventTimeMin, fEventTimeMax); - LOG(debug) << "Time set via Uniform Random : " - << deltaTime; - } - return deltaTime; + Double_t deltaTime = 0; + if (fTimeProb != 0) { + deltaTime = fTimeProb->GetRandom(); + LOG(debug) << "Time set via sampling method : " << deltaTime; + } else { + deltaTime = gRandom->Uniform(fEventTimeMin, fEventTimeMax); + LOG(debug) << "Time set via Uniform Random : " << deltaTime; + } + return deltaTime; } Double_t FairFileSource::GetEventTime() { - LOG(debug) << "-- Get Event Time --"; - if (!fEvtHeaderIsNew && fEvtHeader!=0) { - Double_t EvtTime=fEvtHeader->GetEventTime(); - if (!(EvtTime<0)) { - return EvtTime; - } - } - - if (fEventTimeInMCHeader && !fMCHeader) { - LOG(debug) << "No MCEventHeader, time is set to 0"; - return 0; - } else if (fEventTimeInMCHeader && fMCHeader) { - fEventTime=fMCHeader->GetT(); - LOG(debug) << "Get event time from MCEventHeader : " - << fEventTime << " ns"; - return fEventTime; - } else { - - if (fTimeforEntryNo!=fCurrentEntryNo) { - SetEventTime(); - } - LOG(debug) << "Calculate event time from user input : " - << fEventTime << " ns"; - return fEventTime; - } + LOG(debug) << "-- Get Event Time --"; + if (!fEvtHeaderIsNew && fEvtHeader != 0) { + Double_t EvtTime = fEvtHeader->GetEventTime(); + if (!(EvtTime < 0)) { + return EvtTime; + } + } + + if (fEventTimeInMCHeader && !fMCHeader) { + LOG(debug) << "No MCEventHeader, time is set to 0"; + return 0; + } else if (fEventTimeInMCHeader && fMCHeader) { + fEventTime = fMCHeader->GetT(); + LOG(debug) << "Get event time from MCEventHeader : " << fEventTime << " ns"; + return fEventTime; + } else { + + if (fTimeforEntryNo != fCurrentEntryNo) { + SetEventTime(); + } + LOG(debug) << "Calculate event time from user input : " << fEventTime << " ns"; + return fEventTime; + } } void FairFileSource::ReadBranchEvent(const char* BrName) { - /**fill the object with content if the other branches in this tree entry were already read**/ - if (fEvtHeader == 0) { return; } //No event header, Reading will start later - if (fInTree) { - fInTree->FindBranch(BrName)->GetEntry(fEvtHeader->GetMCEntryNumber()); - fEventTime = GetEventTime(); - return; - } - if (fInChain) { - fInChain->FindBranch(BrName)->GetEntry(fEvtHeader->GetMCEntryNumber()); - fEventTime = GetEventTime(); + /**fill the object with content if the other branches in this tree entry were already read**/ + if (fEvtHeader == 0) { + return; + } // No event header, Reading will start later + if (fInTree) { + fInTree->FindBranch(BrName)->GetEntry(fEvtHeader->GetMCEntryNumber()); + fEventTime = GetEventTime(); + return; + } + if (fInChain) { + fInChain->FindBranch(BrName)->GetEntry(fEvtHeader->GetMCEntryNumber()); + fEventTime = GetEventTime(); + return; + } return; - } - return; } void FairFileSource::ReadBranchEvent(const char* BrName, Int_t Entry) { @@ -839,17 +830,17 @@ void FairFileSource::ReadBranchEvent(const char* BrName, Int_t Entry) void FairFileSource::FillEventHeader(FairEventHeader* feh) { - feh->SetEventTime(fEventTime); - if (fEvtHeader) { - feh->SetRunId(fEvtHeader->GetRunId()); - feh->SetMCEntryNumber(fEvtHeader->GetMCEntryNumber()); - } - if (fMCHeader) { - feh->SetRunId(fMCHeader->GetRunID()); - feh->SetMCEntryNumber(fMCHeader->GetEventID()); - } - feh->SetInputFileId(0); - return; + feh->SetEventTime(fEventTime); + if (fEvtHeader) { + feh->SetRunId(fEvtHeader->GetRunId()); + feh->SetMCEntryNumber(fEvtHeader->GetMCEntryNumber()); + } + if (fMCHeader) { + feh->SetRunId(fMCHeader->GetRunID()); + feh->SetMCEntryNumber(fMCHeader->GetEventID()); + } + feh->SetInputFileId(0); + return; } -ClassImp(FairFileSource) +ClassImp(FairFileSource); diff --git a/base/source/FairFileSource.h b/base/source/FairFileSource.h index 51f04ccfe7..3cba58fd92 100644 --- a/base/source/FairFileSource.h +++ b/base/source/FairFileSource.h @@ -18,13 +18,11 @@ #include "FairSource.h" - -#include -#include #include -#include #include - +#include +#include +#include #include #include @@ -38,16 +36,16 @@ class TTree; class FairFileSource : public FairSource { public: - FairFileSource(TFile *f, const char* Title="InputRootFile", UInt_t identifier=0); - FairFileSource(const TString* RootFileName, const char* Title="InputRootFile", UInt_t identifier=0); - FairFileSource(const TString RootFileName, const char* Title="InputRootFile", UInt_t identifier=0); + FairFileSource(TFile* f, const char* Title = "InputRootFile", UInt_t identifier = 0); + FairFileSource(const TString* RootFileName, const char* Title = "InputRootFile", UInt_t identifier = 0); + FairFileSource(const TString RootFileName, const char* Title = "InputRootFile", UInt_t identifier = 0); // FairFileSource(const FairFileSource& file); virtual ~FairFileSource(); - Bool_t Init(); - Int_t ReadEvent(UInt_t i=0); - void Close(); - void Reset(); + Bool_t Init(); + Int_t ReadEvent(UInt_t i = 0); + void Close(); + void Reset(); virtual Source_Type GetSourceType() { return kFILE; } @@ -58,141 +56,147 @@ class FairFileSource : public FairSource virtual Bool_t ReInitUnpackers() { return kTRUE; } /**Check the maximum event number we can run to*/ - virtual Int_t CheckMaxEventNo(Int_t EvtEnd=0); + virtual Int_t CheckMaxEventNo(Int_t EvtEnd = 0); /**Read the tree entry on one branch**/ - virtual void ReadBranchEvent(const char* BrName); + virtual void ReadBranchEvent(const char* BrName); /**Read specific tree entry on one branch**/ - virtual void ReadBranchEvent(const char* BrName, Int_t Entry); + virtual void ReadBranchEvent(const char* BrName, Int_t Entry); virtual void FillEventHeader(FairEventHeader* feh); - const TFile* GetRootFile(){return fRootFile;} + const TFile* GetRootFile() { return fRootFile; } /** Add a friend file (input) by name)*/ - void AddFriend(TString FileName); + void AddFriend(TString FileName); /**Add ROOT file to input, the file will be chained to already added files*/ - void AddFile(TString FileName); - void AddFriendsToChain(); - void PrintFriendList(); - Bool_t CompareBranchList(TFile* fileHandle, TString inputLevel); - void CheckFriendChains(); - void CreateNewFriendChain(TString inputFile, TString inputLevel); - TTree* GetInTree() {return fInChain->GetTree();} - TChain* GetInChain() {return fInChain;} - TFile* GetInFile() {return fRootFile;} - void CloseInFile() { if(fRootFile) { fRootFile->Close(); }} + void AddFile(TString FileName); + void AddFriendsToChain(); + void PrintFriendList(); + Bool_t CompareBranchList(TFile* fileHandle, TString inputLevel); + void CheckFriendChains(); + void CreateNewFriendChain(TString inputFile, TString inputLevel); + TTree* GetInTree() { return fInChain->GetTree(); } + TChain* GetInChain() { return fInChain; } + TFile* GetInFile() { return fRootFile; } + void CloseInFile() + { + if (fRootFile) { + fRootFile->Close(); + } + } /**Set the input tree when running on PROOF worker*/ - void SetInTree (TTree* tempTree); - TObjArray* GetListOfFolders(){return fListFolder;} - TFolder* GetBranchDescriptionFolder(){return fCbmroot;} - UInt_t GetEntries(){return fNoOfEntries; } + void SetInTree(TTree* tempTree); + TObjArray* GetListOfFolders() { return fListFolder; } + TFolder* GetBranchDescriptionFolder() { return fCbmroot; } + UInt_t GetEntries() { return fNoOfEntries; } // TList* GetBranchNameList() {return fBranchNameList;} - void SetInputFile(TString name); + void SetInputFile(TString name); - /** Set the repetition time of the beam when it can interact (beamTime) and when no interaction happen (gapTime). The total repetition time is beamTime + gapTime */ - void SetBeamTime(Double_t beamTime, Double_t gapTime); + /** Set the repetition time of the beam when it can interact (beamTime) and when no interaction happen (gapTime). + * The total repetition time is beamTime + gapTime */ + void SetBeamTime(Double_t beamTime, Double_t gapTime); /** Set the min and max limit for event time in ns */ - void SetEventTimeInterval(Double_t min, Double_t max); + void SetEventTimeInterval(Double_t min, Double_t max); /** Set the mean time for the event in ns */ - void SetEventMeanTime(Double_t mean); - void SetEventTime(); - Double_t GetDeltaEventTime(); - void SetFileHeader(FairFileHeader* f) {fFileHeader =f;} - Double_t GetEventTime(); + void SetEventMeanTime(Double_t mean); + void SetEventTime(); + Double_t GetDeltaEventTime(); + void SetFileHeader(FairFileHeader* f) { fFileHeader = f; } + Double_t GetEventTime(); // virtual Bool_t SetObject(TObject* obj, const char* ObjType); // virtual void SetObjectName(const char* ObjName, const char* ObjType); - virtual Bool_t ActivateObject(TObject** obj, const char* BrName); - virtual Bool_t ActivateObjectAny(void **, const std::type_info &, const char*); + virtual Bool_t ActivateObject(TObject** obj, const char* BrName); + virtual Bool_t ActivateObjectAny(void**, const std::type_info&, const char*); /**Set the status of the EvtHeader *@param Status: True: The header was creatged in this session and has to be filled FALSE: We use an existing header from previous data level */ - void SetEvtHeaderNew(Bool_t Status) {fEvtHeaderIsNew = Status;} - Bool_t IsEvtHeaderNew() {return fEvtHeaderIsNew;} + void SetEvtHeaderNew(Bool_t Status) { fEvtHeaderIsNew = Status; } + Bool_t IsEvtHeaderNew() { return fEvtHeaderIsNew; } /** Allow to disable the testing the file layout when adding files to a chain. */ - void SetCheckFileLayout(Bool_t enable) {fCheckFileLayout = enable;} + void SetCheckFileLayout(Bool_t enable) { fCheckFileLayout = enable; } private: /** Title of input source, could be input, background or signal*/ - TString fInputTitle; + TString fInputTitle; /**ROOT file*/ - TFile* fRootFile; + TFile* fRootFile; /** Current Entry number */ - Int_t fCurrentEntryNr; //! + Int_t fCurrentEntryNr; //! /** List of all files added with AddFriend */ - std::list fFriendFileList; //! - std::list fInputChainList;//! - std::map fFriendTypeList;//! - std::map* > fCheckInputBranches; //! - std::list fInputLevel; //! - std::map > fRunIdInfoAll; //! + std::list fFriendFileList; //! + std::list fInputChainList; //! + std::map fFriendTypeList; //! + std::map*> fCheckInputBranches; //! + std::list fInputLevel; //! + std::map> fRunIdInfoAll; //! /**Input Chain */ - TChain* fInChain; + TChain* fInChain; /**Input Tree */ - TTree* fInTree; + TTree* fInTree; /** list of folders from all input (and friends) files*/ - TObjArray *fListFolder; //! + TObjArray* fListFolder; //! /** RuntimeDb*/ - FairRuntimeDb* fRtdb; + FairRuntimeDb* fRtdb; /**folder structure of output*/ - TFolder* fCbmout; + TFolder* fCbmout; /**folder structure of input*/ - TFolder* fCbmroot; + TFolder* fCbmroot; /***/ - UInt_t fSourceIdentifier; + UInt_t fSourceIdentifier; /**No of Entries in this source*/ - UInt_t fNoOfEntries; + UInt_t fNoOfEntries; /**Initialization flag, true if initialized*/ - Bool_t IsInitialized; + Bool_t IsInitialized; FairFileSource(const FairFileSource&); FairFileSource operator=(const FairFileSource&); /** MC Event header */ - FairMCEventHeader* fMCHeader; //! + FairMCEventHeader* fMCHeader; //! /**Event Header*/ - FairEventHeader* fEvtHeader; //! + FairEventHeader* fEvtHeader; //! /**File Header*/ - FairFileHeader* fFileHeader; //! + FairFileHeader* fFileHeader; //! /** This is true if the event time used, came from simulation*/ - Bool_t fEventTimeInMCHeader; //! + Bool_t fEventTimeInMCHeader; //! /**This flag is true if the event header was created in this session - * otherwise it is false which means the header was created in a previous data - * level and used here (e.g. in the digi) - */ - Bool_t fEvtHeaderIsNew; //! + * otherwise it is false which means the header was created in a previous data + * level and used here (e.g. in the digi) + */ + Bool_t fEvtHeaderIsNew; //! /** for internal use, to return the same event time for the same entry*/ - UInt_t fCurrentEntryNo; //! + UInt_t fCurrentEntryNo; //! /** for internal use, to return the same event time for the same entry*/ - UInt_t fTimeforEntryNo; //! + UInt_t fTimeforEntryNo; //! /** min time for one event (ns) */ - Double_t fEventTimeMin; //! + Double_t fEventTimeMin; //! /** max time for one Event (ns) */ - Double_t fEventTimeMax; //! + Double_t fEventTimeMax; //! /** Time of event since th start (ns) */ - Double_t fEventTime; //! + Double_t fEventTime; //! /** Time of particles in beam (ns) */ - Double_t fBeamTime; //! + Double_t fBeamTime; //! /** Time without particles in beam (gap) (ns) */ - Double_t fGapTime; //! + Double_t fGapTime; //! /** EventMean time used (P(t)=1/fEventMeanTime*Exp(-t/fEventMeanTime) */ - Double_t fEventMeanTime; //! + Double_t fEventMeanTime; //! /** used to generate random numbers for event time; */ - TF1* fTimeProb; //! - /** True if the file layout should be checked when adding files to a chain. - * Default value is true. - */ - Bool_t fCheckFileLayout; //! + TF1* fTimeProb; //! + /** True if the file layout should be checked when adding files to a chain. + * Default value is true. + */ + Bool_t fCheckFileLayout; //! ClassDef(FairFileSource, 3) }; diff --git a/base/source/FairLmdSource.cxx b/base/source/FairLmdSource.cxx index 6f3ee4383a..9355f18525 100644 --- a/base/source/FairLmdSource.cxx +++ b/base/source/FairLmdSource.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ----------------------------------------------------------------------------- @@ -12,6 +12,7 @@ // ----------------------------------------------------------------------------- #include "FairLmdSource.h" + #include "FairLogger.h" #include @@ -23,234 +24,220 @@ #include FairLmdSource::FairLmdSource() - : FairMbsSource(), - fCurrentFile(0), - fNEvent(0), - fCurrentEvent(0), - fFileNames(new TList()), - fxInputChannel(nullptr), - fxEvent(nullptr), - fxBuffer(nullptr), - fxEventData(nullptr), - fxSubEvent(nullptr), - fxInfoHeader(nullptr) -{ -} + : FairMbsSource() + , fCurrentFile(0) + , fNEvent(0) + , fCurrentEvent(0) + , fFileNames(new TList()) + , fxInputChannel(nullptr) + , fxEvent(nullptr) + , fxBuffer(nullptr) + , fxEventData(nullptr) + , fxSubEvent(nullptr) + , fxInfoHeader(nullptr) +{} FairLmdSource::FairLmdSource(const FairLmdSource& source) - : FairMbsSource(source), - fCurrentFile(source.GetCurrentFile()), - fNEvent(0), - fCurrentEvent(0), - fFileNames(new TList()), - fxInputChannel(nullptr), - fxEvent(nullptr), - fxBuffer(nullptr), - fxEventData(nullptr), - fxSubEvent(nullptr), - fxInfoHeader(nullptr) -{ -} + : FairMbsSource(source) + , fCurrentFile(source.GetCurrentFile()) + , fNEvent(0) + , fCurrentEvent(0) + , fFileNames(new TList()) + , fxInputChannel(nullptr) + , fxEvent(nullptr) + , fxBuffer(nullptr) + , fxEventData(nullptr) + , fxSubEvent(nullptr) + , fxInfoHeader(nullptr) +{} FairLmdSource::~FairLmdSource() { - fFileNames->Delete(); - delete fFileNames; + fFileNames->Delete(); + delete fFileNames; } void FairLmdSource::AddFile(TString fileName) { - FileStat_t buf; - if(1 == gSystem->GetPathInfo(fileName.Data(), buf)) - { - LOG(warn) << "FairLmdSource: not found: " << fileName; - return; - } - - TObjString* str = new TObjString(fileName); - fFileNames->Add(str); + FileStat_t buf; + if (1 == gSystem->GetPathInfo(fileName.Data(), buf)) { + LOG(warn) << "FairLmdSource: not found: " << fileName; + return; + } + + TObjString* str = new TObjString(fileName); + fFileNames->Add(str); } void FairLmdSource::AddPath(TString dir, TString wildCard) { - FileStat_t buf; - if(1 == gSystem->GetPathInfo(dir.Data(), buf)) - { - LOG(warn) << "FairLmdSource: not found: " << dir; - return; - } - - TRegexp *re = new TRegexp(wildCard.Data(), kTRUE); - TSystemDirectory *sdir = new TSystemDirectory("dir", dir.Data()); - TString dname(dir); - if(! dname.EndsWith("/")) - { - dname += "/"; - } - TList *list = sdir->GetListOfFiles(); - - TIterator *iter = list->MakeIterator(); - TSystemFile *file; - TString name; - while(nullptr != (file = static_cast(iter->Next()))) - { - name = file->GetName(); - if(name.Contains(*re)) - { - name = dname + name; - AddFile(name); + FileStat_t buf; + if (1 == gSystem->GetPathInfo(dir.Data(), buf)) { + LOG(warn) << "FairLmdSource: not found: " << dir; + return; + } + + TRegexp* re = new TRegexp(wildCard.Data(), kTRUE); + TSystemDirectory* sdir = new TSystemDirectory("dir", dir.Data()); + TString dname(dir); + if (!dname.EndsWith("/")) { + dname += "/"; + } + TList* list = sdir->GetListOfFiles(); + + TIterator* iter = list->MakeIterator(); + TSystemFile* file; + TString name; + while (nullptr != (file = static_cast(iter->Next()))) { + name = file->GetName(); + if (name.Contains(*re)) { + name = dname + name; + AddFile(name); + } } - } - list->Delete(); + list->Delete(); } Bool_t FairLmdSource::Init() { - if(fFileNames->GetSize() == 0) { - return kFALSE; - } + if (fFileNames->GetSize() == 0) { + return kFALSE; + } - TString name = (static_cast(fFileNames->At(fCurrentFile)))->GetString(); - if(! OpenNextFile(name)) { - return kFALSE; - } + TString name = (static_cast(fFileNames->At(fCurrentFile)))->GetString(); + if (!OpenNextFile(name)) { + return kFALSE; + } - fCurrentFile += 1; + fCurrentFile += 1; - // Init Counters - fNEvent=fCurrentEvent=0; + // Init Counters + fNEvent = fCurrentEvent = 0; - return kTRUE; + return kTRUE; } Bool_t FairLmdSource::OpenNextFile(TString fileName) { - Int_t inputMode = GETEVT__FILE; - fxInputChannel = new s_evt_channel; - void* headptr = &fxInfoHeader; - INTS4 status; + Int_t inputMode = GETEVT__FILE; + fxInputChannel = new s_evt_channel; + void* headptr = &fxInfoHeader; + INTS4 status; - LOG(info) << "File " << fileName << " will be opened."; + LOG(info) << "File " << fileName << " will be opened."; - status = f_evt_get_open(inputMode, - const_cast(fileName.Data()), - fxInputChannel, - static_cast(headptr), - 1, - 1); + status = f_evt_get_open( + inputMode, const_cast(fileName.Data()), fxInputChannel, static_cast(headptr), 1, 1); - if(status) { - LOG(error) << "File " << fileName << " opening failed."; - return kFALSE; - } + if (status) { + LOG(error) << "File " << fileName << " opening failed."; + return kFALSE; + } - LOG(info) << "File " << fileName << " opened."; + LOG(info) << "File " << fileName << " opened."; - // Decode File Header - //Bool_t result = Unpack((Int_t*)fxInfoHeader, sizeof(s_filhe), -4, -4, -4, -4, -4); - Unpack(reinterpret_cast(fxInfoHeader), sizeof(s_filhe), -4, -4, -4, -4, -4); + // Decode File Header + // Bool_t result = Unpack((Int_t*)fxInfoHeader, sizeof(s_filhe), -4, -4, -4, -4, -4); + Unpack(reinterpret_cast(fxInfoHeader), sizeof(s_filhe), -4, -4, -4, -4, -4); - return kTRUE; + return kTRUE; } Int_t FairLmdSource::ReadEvent(UInt_t) { - void* evtptr = &fxEvent; - void* buffptr = &fxBuffer; + void* evtptr = &fxEvent; + void* buffptr = &fxBuffer; - Int_t status = f_evt_get_event(fxInputChannel, static_cast(evtptr),static_cast(buffptr)); - //Int_t fuEventCounter = fxEvent->l_count; - //Int_t fCurrentMbsEventNo = fuEventCounter; + Int_t status = f_evt_get_event(fxInputChannel, static_cast(evtptr), static_cast(buffptr)); + // Int_t fuEventCounter = fxEvent->l_count; + // Int_t fCurrentMbsEventNo = fuEventCounter; - if(GETEVT__SUCCESS != status) { + if (GETEVT__SUCCESS != status) { - LOG(info) << "FairMbsStreamSource::ReadEvent()"; + LOG(info) << "FairMbsStreamSource::ReadEvent()"; - CHARS* sErrorString = nullptr; - f_evt_error(status, sErrorString , 0); + CHARS* sErrorString = nullptr; + f_evt_error(status, sErrorString, 0); - if(fCurrentFile >= fFileNames->GetSize()) { - return 1; - } + if (fCurrentFile >= fFileNames->GetSize()) { + return 1; + } - if(GETEVT__NOMORE == status) { - Close(); - } + if (GETEVT__NOMORE == status) { + Close(); + } - TString name = (static_cast(fFileNames->At(fCurrentFile)))->GetString(); - if(! OpenNextFile(name)) { - return 1; - } else { - fCurrentFile += 1; - return ReadEvent(); - } - } - - //Store Start Times - if (fCurrentEvent==0 ) - Unpack(reinterpret_cast(fxBuffer), sizeof(s_bufhe), -4, -4, -4, -4, -4); - - - // Decode event header - Bool_t result = kFALSE; - /*Bool_t result = */Unpack(reinterpret_cast(fxEvent), sizeof(s_ve10_1), -2, -2, -2, -2, -2); - - Int_t nrSubEvts = f_evt_get_subevent(fxEvent, 0, nullptr, nullptr, nullptr); - Int_t sebuflength; - Short_t setype; - Short_t sesubtype; - Short_t seprocid; - Short_t sesubcrate; - Short_t secontrol; - - LOG(debug2)<< "FairLmdSource::ReadEvent => Found " << nrSubEvts << " Sub-event "; - //if (fCurrentEvent%10000==0) - //cout << " -I- LMD_ANA: evt# " << fCurrentEvent << " n_subevt# " << nrSubEvts << " evt processed# " << fNEvent << " : " << fxEvent->l_count << endl; - - -// Int_t* SubEventDataPtr = new Int_t; - for(Int_t i = 1; i <= nrSubEvts; i++) { - void* SubEvtptr = &fxSubEvent; - void* EvtDataptr = &fxEventData; - Int_t nrlongwords; - status = f_evt_get_subevent(fxEvent, i, static_cast(SubEvtptr), static_cast(EvtDataptr), &nrlongwords); - if(status) { - return 1; + TString name = (static_cast(fFileNames->At(fCurrentFile)))->GetString(); + if (!OpenNextFile(name)) { + return 1; + } else { + fCurrentFile += 1; + return ReadEvent(); + } } - sebuflength = nrlongwords; - setype = fxSubEvent->i_type; - sesubtype = fxSubEvent->i_subtype; - seprocid = fxSubEvent->i_procid; - sesubcrate = fxSubEvent->h_subcrate; - secontrol = fxSubEvent->h_control; - - //cout << setype << " " << sesubtype << " " << seprocid << " " << sesubcrate << " " << secontrol << endl; - - if(Unpack(fxEventData, sebuflength, - setype, sesubtype, - seprocid, sesubcrate, secontrol)) { - result = kTRUE; + + // Store Start Times + if (fCurrentEvent == 0) + Unpack(reinterpret_cast(fxBuffer), sizeof(s_bufhe), -4, -4, -4, -4, -4); + + // Decode event header + Bool_t result = kFALSE; + /*Bool_t result = */ Unpack(reinterpret_cast(fxEvent), sizeof(s_ve10_1), -2, -2, -2, -2, -2); + + Int_t nrSubEvts = f_evt_get_subevent(fxEvent, 0, nullptr, nullptr, nullptr); + Int_t sebuflength; + Short_t setype; + Short_t sesubtype; + Short_t seprocid; + Short_t sesubcrate; + Short_t secontrol; + + LOG(debug2) << "FairLmdSource::ReadEvent => Found " << nrSubEvts << " Sub-event "; + // if (fCurrentEvent%10000==0) + // cout << " -I- LMD_ANA: evt# " << fCurrentEvent << " n_subevt# " << nrSubEvts << " evt processed# " << fNEvent + // << " : " << fxEvent->l_count << endl; + + // Int_t* SubEventDataPtr = new Int_t; + for (Int_t i = 1; i <= nrSubEvts; i++) { + void* SubEvtptr = &fxSubEvent; + void* EvtDataptr = &fxEventData; + Int_t nrlongwords; + status = f_evt_get_subevent( + fxEvent, i, static_cast(SubEvtptr), static_cast(EvtDataptr), &nrlongwords); + if (status) { + return 1; + } + sebuflength = nrlongwords; + setype = fxSubEvent->i_type; + sesubtype = fxSubEvent->i_subtype; + seprocid = fxSubEvent->i_procid; + sesubcrate = fxSubEvent->h_subcrate; + secontrol = fxSubEvent->h_control; + + // cout << setype << " " << sesubtype << " " << seprocid << " " << sesubcrate << " " << secontrol << endl; + + if (Unpack(fxEventData, sebuflength, setype, sesubtype, seprocid, sesubcrate, secontrol)) { + result = kTRUE; + } } - } - // Increment evt counters. - fNEvent++; - fCurrentEvent++; + // Increment evt counters. + fNEvent++; + fCurrentEvent++; - if(! result) - { - return 2; - } + if (!result) { + return 2; + } - return 0; + return 0; } void FairLmdSource::Close() { - f_evt_get_close(fxInputChannel); - Unpack(reinterpret_cast(fxBuffer), sizeof(s_bufhe), -4, -4, -4, -4, -4); - fCurrentEvent=0; + f_evt_get_close(fxInputChannel); + Unpack(reinterpret_cast(fxBuffer), sizeof(s_bufhe), -4, -4, -4, -4, -4); + fCurrentEvent = 0; } -ClassImp(FairLmdSource) +ClassImp(FairLmdSource); diff --git a/base/source/FairLmdSource.h b/base/source/FairLmdSource.h index 3abef4c84b..61b85c971e 100644 --- a/base/source/FairLmdSource.h +++ b/base/source/FairLmdSource.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ----------------------------------------------------------------------------- @@ -17,15 +17,15 @@ extern "C" { #include "f_evt.h" -#include "s_filhe_swap.h" #include "s_bufhe_swap.h" +#include "s_filhe_swap.h" } -#include -#include - #include "FairMbsSource.h" +#include +#include + class TList; class FairLmdSource : public FairMbsSource @@ -41,7 +41,7 @@ class FairLmdSource : public FairMbsSource inline const TList* GetFileNames() const { return fFileNames; } virtual Bool_t Init(); - virtual Int_t ReadEvent(UInt_t=0); + virtual Int_t ReadEvent(UInt_t = 0); virtual void Close(); protected: diff --git a/base/source/FairMbsSource.cxx b/base/source/FairMbsSource.cxx index 066effc884..be8b4bbd02 100644 --- a/base/source/FairMbsSource.cxx +++ b/base/source/FairMbsSource.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ----------------------------------------------------------------------------- @@ -14,44 +14,44 @@ // ----------------------------------------------------------------------------- #include "FairMbsSource.h" + #include "FairLogger.h" -FairMbsSource::FairMbsSource() : FairOnlineSource() {} +FairMbsSource::FairMbsSource() + : FairOnlineSource() +{} FairMbsSource::FairMbsSource(const FairMbsSource &source) : FairOnlineSource(source) {} -FairMbsSource::~FairMbsSource() -{} +FairMbsSource::~FairMbsSource() {} -Bool_t FairMbsSource::Unpack(Int_t *data, Int_t size, Short_t type, - Short_t subType, Short_t procId, Short_t subCrate, +Bool_t FairMbsSource::Unpack(Int_t *data, + Int_t size, + Short_t type, + Short_t subType, + Short_t procId, + Short_t subCrate, Short_t control) { LOG(debug2) << "FairMbsSource::Unpack => Found Sub-event with flags: " - << " Type " << type << " SubType " << subType - << " ProcId " << procId << " SubCrate " << subCrate + << " Type " << type << " SubType " << subType << " ProcId " << procId << " SubCrate " << subCrate << " Control " << control; FairUnpack *unpack; Bool_t seen = kFALSE; for (Int_t i = 0; i < fUnpackers->GetEntriesFast(); i++) { - unpack = static_cast(fUnpackers->At(i)); + unpack = static_cast(fUnpackers->At(i)); - if (unpack->GetSubCrate() < 0) { // All sub-crates - if (type != unpack->GetType() - || subType != unpack->GetSubType() - || procId != unpack->GetProcId() + if (unpack->GetSubCrate() < 0) { // All sub-crates + if (type != unpack->GetType() || subType != unpack->GetSubType() || procId != unpack->GetProcId() || control != unpack->GetControl()) { continue; } - } else { // specified sub-crate - if (type != unpack->GetType() - || subType != unpack->GetSubType() - || procId != unpack->GetProcId() - || subCrate != unpack->GetSubCrate() - || control != unpack->GetControl()) { + } else { // specified sub-crate + if (type != unpack->GetType() || subType != unpack->GetSubType() || procId != unpack->GetProcId() + || subCrate != unpack->GetSubCrate() || control != unpack->GetControl()) { continue; } } @@ -66,4 +66,4 @@ Bool_t FairMbsSource::Unpack(Int_t *data, Int_t size, Short_t type, return seen; } -ClassImp(FairMbsSource) +ClassImp(FairMbsSource); diff --git a/base/source/FairMbsSource.h b/base/source/FairMbsSource.h index 94b841f25b..c94b6194a4 100644 --- a/base/source/FairMbsSource.h +++ b/base/source/FairMbsSource.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ----------------------------------------------------------------------------- @@ -17,6 +17,7 @@ #define FAIRMBSSOURCE_H #include "FairOnlineSource.h" + #include class FairMbsSource : public FairOnlineSource @@ -27,13 +28,17 @@ class FairMbsSource : public FairOnlineSource virtual ~FairMbsSource(); virtual Bool_t Init() = 0; - virtual Int_t ReadEvent(UInt_t=0) = 0; + virtual Int_t ReadEvent(UInt_t = 0) = 0; virtual void Close() = 0; protected: - Bool_t Unpack(Int_t* data, Int_t size, - Short_t type, Short_t subType, - Short_t procId, Short_t subCrate, Short_t control); + Bool_t Unpack(Int_t* data, + Int_t size, + Short_t type, + Short_t subType, + Short_t procId, + Short_t subCrate, + Short_t control); ClassDef(FairMbsSource, 0) }; diff --git a/base/source/FairMbsStreamSource.cxx b/base/source/FairMbsStreamSource.cxx index ae61831558..a53911e3b3 100644 --- a/base/source/FairMbsStreamSource.cxx +++ b/base/source/FairMbsStreamSource.cxx @@ -13,133 +13,124 @@ #include "FairLogger.h" FairMbsStreamSource::FairMbsStreamSource(TString tServerName) - : FairMbsSource(), - fServerName(tServerName), - fxInputChannel(nullptr), - fxEvent(nullptr), - fxBuffer(nullptr), - fxEventData(nullptr), - fxSubEvent(nullptr) -{ -} + : FairMbsSource() + , fServerName(tServerName) + , fxInputChannel(nullptr) + , fxEvent(nullptr) + , fxBuffer(nullptr) + , fxEventData(nullptr) + , fxSubEvent(nullptr) +{} FairMbsStreamSource::FairMbsStreamSource(const FairMbsStreamSource& source) - : FairMbsSource(source), - fServerName(source.GetServerName()), - fxInputChannel(nullptr), - fxEvent(nullptr), - fxBuffer(nullptr), - fxEventData(nullptr), - fxSubEvent(nullptr) -{ -} + : FairMbsSource(source) + , fServerName(source.GetServerName()) + , fxInputChannel(nullptr) + , fxEvent(nullptr) + , fxBuffer(nullptr) + , fxEventData(nullptr) + , fxSubEvent(nullptr) +{} -FairMbsStreamSource::~FairMbsStreamSource() -{ -} +FairMbsStreamSource::~FairMbsStreamSource() {} Bool_t FairMbsStreamSource::Init() { - if(! ConnectToServer()) { - return kFALSE; - } + if (!ConnectToServer()) { + return kFALSE; + } - return kTRUE; + return kTRUE; } Bool_t FairMbsStreamSource::ConnectToServer() { - Int_t inputMode = GETEVT__STREAM; - fxInputChannel = new s_evt_channel; - s_filhe fxInfoHeader; - void* headptr = &fxInfoHeader; - INTS4 status; + Int_t inputMode = GETEVT__STREAM; + fxInputChannel = new s_evt_channel; + s_filhe fxInfoHeader; + void* headptr = &fxInfoHeader; + INTS4 status; - LOG(info) << "FairMbsStreamSource::ConnectToServer()"; - LOG(info) << Form("- open connection to MBS stream server %s...", fServerName.Data()); + LOG(info) << "FairMbsStreamSource::ConnectToServer()"; + LOG(info) << Form("- open connection to MBS stream server %s...", fServerName.Data()); - status = f_evt_get_open(inputMode, - const_cast(fServerName.Data()), - fxInputChannel, - static_cast(headptr), - 1, - 1); + status = f_evt_get_open( + inputMode, const_cast(fServerName.Data()), fxInputChannel, static_cast(headptr), 1, 1); - CHARS* sErrorString = nullptr; - f_evt_error(status, sErrorString , 0); + CHARS* sErrorString = nullptr; + f_evt_error(status, sErrorString, 0); - if(GETEVT__SUCCESS != status) { - return kFALSE; - } + if (GETEVT__SUCCESS != status) { + return kFALSE; + } - LOG(info) << Form("- connection to MBS stream server %s established.", fServerName.Data()); + LOG(info) << Form("- connection to MBS stream server %s established.", fServerName.Data()); - return kTRUE; + return kTRUE; } Int_t FairMbsStreamSource::ReadEvent(UInt_t) { - void* evtptr = &fxEvent; - void* buffptr = &fxBuffer; + void* evtptr = &fxEvent; + void* buffptr = &fxBuffer; - LOG(debug2)<< "FairLmdSource::ReadEvent => New event "; + LOG(debug2) << "FairLmdSource::ReadEvent => New event "; - Int_t status = f_evt_get_event(fxInputChannel, static_cast(evtptr),static_cast(buffptr)); + Int_t status = f_evt_get_event(fxInputChannel, static_cast(evtptr), static_cast(buffptr)); - LOG(debug2)<< "FairLmdSource::ReadEvent => f_evt_get_event status: " << status; + LOG(debug2) << "FairLmdSource::ReadEvent => f_evt_get_event status: " << status; - if(GETEVT__SUCCESS != status) { - LOG(info) << "FairMbsStreamSource::ReadEvent()"; + if (GETEVT__SUCCESS != status) { + LOG(info) << "FairMbsStreamSource::ReadEvent()"; - CHARS* sErrorString = nullptr; - f_evt_error(status, sErrorString , 0); + CHARS* sErrorString = nullptr; + f_evt_error(status, sErrorString, 0); - return 1; - } + return 1; + } - Int_t nrSubEvts = f_evt_get_subevent(fxEvent, 0, nullptr, nullptr, nullptr); + Int_t nrSubEvts = f_evt_get_subevent(fxEvent, 0, nullptr, nullptr, nullptr); - Int_t sebuflength; - Short_t setype; - Short_t sesubtype; - Short_t seprocid; - Short_t sesubcrate; - Short_t secontrol; + Int_t sebuflength; + Short_t setype; + Short_t sesubtype; + Short_t seprocid; + Short_t sesubcrate; + Short_t secontrol; - LOG(debug2)<< "FairLmdSource::ReadEvent => Found " << nrSubEvts << " Sub-event "; + LOG(debug2) << "FairLmdSource::ReadEvent => Found " << nrSubEvts << " Sub-event "; - for(Int_t i = 1; i <= nrSubEvts; i++) { - void* SubEvtptr = &fxSubEvent; - void* EvtDataptr = &fxEventData; - Int_t nrlongwords; + for (Int_t i = 1; i <= nrSubEvts; i++) { + void* SubEvtptr = &fxSubEvent; + void* EvtDataptr = &fxEventData; + Int_t nrlongwords; - status = f_evt_get_subevent(fxEvent, i, static_cast(SubEvtptr), static_cast(EvtDataptr), &nrlongwords); + status = f_evt_get_subevent( + fxEvent, i, static_cast(SubEvtptr), static_cast(EvtDataptr), &nrlongwords); - sebuflength = nrlongwords; - setype = fxSubEvent->i_type; - sesubtype = fxSubEvent->i_subtype; - seprocid = fxSubEvent->i_procid; - sesubcrate = fxSubEvent->h_subcrate; - secontrol = fxSubEvent->h_control; + sebuflength = nrlongwords; + setype = fxSubEvent->i_type; + sesubtype = fxSubEvent->i_subtype; + seprocid = fxSubEvent->i_procid; + sesubcrate = fxSubEvent->h_subcrate; + secontrol = fxSubEvent->h_control; - if(! Unpack(fxEventData, sebuflength, - setype, sesubtype, - seprocid, sesubcrate, secontrol)) { - return 2; + if (!Unpack(fxEventData, sebuflength, setype, sesubtype, seprocid, sesubcrate, secontrol)) { + return 2; + } } - } - return 0; + return 0; } void FairMbsStreamSource::Close() { - Int_t status = f_evt_get_close(fxInputChannel); + Int_t status = f_evt_get_close(fxInputChannel); - LOG(info) << "FairMbsStreamSource::Close()"; + LOG(info) << "FairMbsStreamSource::Close()"; - CHARS* sErrorString = nullptr; - f_evt_error(status, sErrorString , 0); + CHARS* sErrorString = nullptr; + f_evt_error(status, sErrorString, 0); } -ClassImp(FairMbsStreamSource) +ClassImp(FairMbsStreamSource); diff --git a/base/source/FairMbsStreamSource.h b/base/source/FairMbsStreamSource.h index cbb310fb50..a46b57f43a 100644 --- a/base/source/FairMbsStreamSource.h +++ b/base/source/FairMbsStreamSource.h @@ -14,15 +14,15 @@ extern "C" { #include "f_evt.h" -#include "s_filhe_swap.h" #include "s_bufhe_swap.h" +#include "s_filhe_swap.h" } -#include -#include - #include "FairMbsSource.h" +#include +#include + class FairMbsStreamSource : public FairMbsSource { public: @@ -31,10 +31,10 @@ class FairMbsStreamSource : public FairMbsSource virtual ~FairMbsStreamSource(); virtual Bool_t Init(); - virtual Int_t ReadEvent(UInt_t=0); + virtual Int_t ReadEvent(UInt_t = 0); virtual void Close(); - const char* GetServerName() const {return fServerName.Data();}; + const char* GetServerName() const { return fServerName.Data(); }; private: Bool_t ConnectToServer(); diff --git a/base/source/FairMixedSource.cxx b/base/source/FairMixedSource.cxx index aa2a4f2f07..e53ca8ea21 100644 --- a/base/source/FairMixedSource.cxx +++ b/base/source/FairMixedSource.cxx @@ -13,72 +13,72 @@ // Created by Mohammad Al-Turany on 08/02/14. // // +#include "FairMixedSource.h" + #include "FairEventHeader.h" #include "FairLogger.h" #include "FairMCEventHeader.h" -#include "FairMixedSource.h" #include "FairRootManager.h" -#include "FairRuntimeDb.h" // for FairRuntimeDb +#include "FairRuntimeDb.h" // for FairRuntimeDb #include #include #include -#include #include -#include // for TRandom, gRandom +#include #include +#include // for TRandom, gRandom #include - -#include // floor, fmod +#include // floor, fmod #include #include using std::map; using std::set; -FairMixedSource::FairMixedSource(TFile *f, const char* Title, UInt_t) - :FairSource(), - fRootManager(0), - fInputTitle(Title), - fRootFile(f), - fFriendFileList(), - fInputChainList(), - fFriendTypeList(), - fCheckInputBranches(), - fInputLevel(), - fRunIdInfoAll(), - fListFolder(new TObjArray(16)), - fRtdb(FairRuntimeDb::instance()), - fCbmout(0), - fCbmroot(0), - fSourceIdentifier(0), - fNoOfEntries(-1), - IsInitialized(kFALSE), - fMCHeader(0), - fEvtHeader(0), - fOutHeader(0), - fFileHeader(0), - fEventTimeInMCHeader(kTRUE), - fEvtHeaderIsNew(kFALSE), - fCurrentEntryNo(0), - fTimeforEntryNo(0), - fNoOfBGEntries(0), - fCurrentEntry(), - fEventTimeMin(0.), - fEventTimeMax(0.), - fEventTime(0.), - fBeamTime(-1.), - fGapTime(-1.), - fEventMeanTime(0.), - fTimeProb(0), - fSignalBGN(), - fSBRatiobyN(kFALSE), - fSBRatiobyT(kFALSE), - fActualSignalIdentifier(0), - fNoOfSignals(0), - fSignalChainList(nullptr), - fBackgroundChain(nullptr), - fSignalTypeList() +FairMixedSource::FairMixedSource(TFile* f, const char* Title, UInt_t) + : FairSource() + , fRootManager(0) + , fInputTitle(Title) + , fRootFile(f) + , fFriendFileList() + , fInputChainList() + , fFriendTypeList() + , fCheckInputBranches() + , fInputLevel() + , fRunIdInfoAll() + , fListFolder(new TObjArray(16)) + , fRtdb(FairRuntimeDb::instance()) + , fCbmout(0) + , fCbmroot(0) + , fSourceIdentifier(0) + , fNoOfEntries(-1) + , IsInitialized(kFALSE) + , fMCHeader(0) + , fEvtHeader(0) + , fOutHeader(0) + , fFileHeader(0) + , fEventTimeInMCHeader(kTRUE) + , fEvtHeaderIsNew(kFALSE) + , fCurrentEntryNo(0) + , fTimeforEntryNo(0) + , fNoOfBGEntries(0) + , fCurrentEntry() + , fEventTimeMin(0.) + , fEventTimeMax(0.) + , fEventTime(0.) + , fBeamTime(-1.) + , fGapTime(-1.) + , fEventMeanTime(0.) + , fTimeProb(0) + , fSignalBGN() + , fSBRatiobyN(kFALSE) + , fSBRatiobyT(kFALSE) + , fActualSignalIdentifier(0) + , fNoOfSignals(0) + , fSignalChainList(nullptr) + , fBackgroundChain(nullptr) + , fSignalTypeList() { if (fRootFile->IsZombie()) { LOG(fatal) << "Error opening the Input file"; @@ -89,107 +89,107 @@ FairMixedSource::FairMixedSource(TFile *f, const char* Title, UInt_t) } FairMixedSource::FairMixedSource(const TString* RootFileName, const char* Title, UInt_t) - :FairSource(), - fRootManager(0), - fInputTitle(Title), - fRootFile(0), - fFriendFileList(), - fInputChainList(), - fFriendTypeList(), - fCheckInputBranches(), - fInputLevel(), - fRunIdInfoAll(), - fListFolder(new TObjArray(16)), - fRtdb(FairRuntimeDb::instance()), - fCbmout(0), - fCbmroot(0), - fSourceIdentifier(0), - fNoOfEntries(-1), - IsInitialized(kFALSE), - fMCHeader(0), - fEvtHeader(0), - fOutHeader(0), - fFileHeader(0), - fEventTimeInMCHeader(kTRUE), - fEvtHeaderIsNew(kFALSE), - fCurrentEntryNo(0), - fTimeforEntryNo(0), - fNoOfBGEntries(0), - fCurrentEntry(), - fEventTimeMin(0.), - fEventTimeMax(0.), - fEventTime(0.), - fBeamTime(-1.), - fGapTime(-1.), - fEventMeanTime(0.), - fTimeProb(0), - fSignalBGN(), - fSBRatiobyN(kFALSE), - fSBRatiobyT(kFALSE), - fActualSignalIdentifier(0), - fNoOfSignals(0), - fSignalChainList(nullptr), - fBackgroundChain(nullptr), - fSignalTypeList() + : FairSource() + , fRootManager(0) + , fInputTitle(Title) + , fRootFile(0) + , fFriendFileList() + , fInputChainList() + , fFriendTypeList() + , fCheckInputBranches() + , fInputLevel() + , fRunIdInfoAll() + , fListFolder(new TObjArray(16)) + , fRtdb(FairRuntimeDb::instance()) + , fCbmout(0) + , fCbmroot(0) + , fSourceIdentifier(0) + , fNoOfEntries(-1) + , IsInitialized(kFALSE) + , fMCHeader(0) + , fEvtHeader(0) + , fOutHeader(0) + , fFileHeader(0) + , fEventTimeInMCHeader(kTRUE) + , fEvtHeaderIsNew(kFALSE) + , fCurrentEntryNo(0) + , fTimeforEntryNo(0) + , fNoOfBGEntries(0) + , fCurrentEntry() + , fEventTimeMin(0.) + , fEventTimeMax(0.) + , fEventTime(0.) + , fBeamTime(-1.) + , fGapTime(-1.) + , fEventMeanTime(0.) + , fTimeProb(0) + , fSignalBGN() + , fSBRatiobyN(kFALSE) + , fSBRatiobyT(kFALSE) + , fActualSignalIdentifier(0) + , fNoOfSignals(0) + , fSignalChainList(nullptr) + , fBackgroundChain(nullptr) + , fSignalTypeList() { - fRootFile = TFile::Open(RootFileName->Data()); - if (fRootFile->IsZombie()) { - LOG(fatal) << "Error opening the Input file"; - } - fRootManager = FairRootManager::Instance(); - LOG(info) << "FairMixedSource created------------"; + fRootFile = TFile::Open(RootFileName->Data()); + if (fRootFile->IsZombie()) { + LOG(fatal) << "Error opening the Input file"; + } + fRootManager = FairRootManager::Instance(); + LOG(info) << "FairMixedSource created------------"; } FairMixedSource::FairMixedSource(const TString RootFileName, const Int_t signalId, const char* Title, UInt_t) - :FairSource(), - fRootManager(0), - fInputTitle(Title), - fRootFile(0), - fFriendFileList(), - fInputChainList(), - fFriendTypeList(), - fCheckInputBranches(), - fInputLevel(), - fRunIdInfoAll(), - fListFolder(new TObjArray(16)), - fRtdb(FairRuntimeDb::instance()), - fCbmout(0), - fCbmroot(0), - fSourceIdentifier(0), - fNoOfEntries(-1), - IsInitialized(kFALSE), - fMCHeader(0), - fEvtHeader(0), - fOutHeader(0), - fFileHeader(0), - fEventTimeInMCHeader(kTRUE), - fEvtHeaderIsNew(kFALSE), - fCurrentEntryNo(0), - fTimeforEntryNo(0), - fNoOfBGEntries(0), - fCurrentEntry(), - fEventTimeMin(0.), - fEventTimeMax(0.), - fEventTime(0.), - fBeamTime(-1.), - fGapTime(-1.), - fEventMeanTime(0.), - fTimeProb(0), - fSignalBGN(), - fSBRatiobyN(kFALSE), - fSBRatiobyT(kFALSE), - fActualSignalIdentifier(0), - fNoOfSignals(0), - fSignalChainList(nullptr), - fBackgroundChain(nullptr), - fSignalTypeList() + : FairSource() + , fRootManager(0) + , fInputTitle(Title) + , fRootFile(0) + , fFriendFileList() + , fInputChainList() + , fFriendTypeList() + , fCheckInputBranches() + , fInputLevel() + , fRunIdInfoAll() + , fListFolder(new TObjArray(16)) + , fRtdb(FairRuntimeDb::instance()) + , fCbmout(0) + , fCbmroot(0) + , fSourceIdentifier(0) + , fNoOfEntries(-1) + , IsInitialized(kFALSE) + , fMCHeader(0) + , fEvtHeader(0) + , fOutHeader(0) + , fFileHeader(0) + , fEventTimeInMCHeader(kTRUE) + , fEvtHeaderIsNew(kFALSE) + , fCurrentEntryNo(0) + , fTimeforEntryNo(0) + , fNoOfBGEntries(0) + , fCurrentEntry() + , fEventTimeMin(0.) + , fEventTimeMax(0.) + , fEventTime(0.) + , fBeamTime(-1.) + , fGapTime(-1.) + , fEventMeanTime(0.) + , fTimeProb(0) + , fSignalBGN() + , fSBRatiobyN(kFALSE) + , fSBRatiobyT(kFALSE) + , fActualSignalIdentifier(0) + , fNoOfSignals(0) + , fSignalChainList(nullptr) + , fBackgroundChain(nullptr) + , fSignalTypeList() { fRootFile = TFile::Open(RootFileName.Data()); if (signalId == 0) { SetBackgroundFile(RootFileName); } else { - SetSignalFile(RootFileName,signalId); + SetSignalFile(RootFileName, signalId); } fRootManager = FairRootManager::Instance(); // fBackgroundFile = TFile::Open(name); @@ -200,16 +200,15 @@ FairMixedSource::FairMixedSource(const TString RootFileName, const Int_t signalI // } } -FairMixedSource::~FairMixedSource() -{ -} +FairMixedSource::~FairMixedSource() {} Bool_t FairMixedSource::Init() { fOutHeader = new FairEventHeader(); - LOG(info) << "fSBRatiobyN = " << (fSBRatiobyN?"true":"false") << " / fSBRatiobyT = " << (fSBRatiobyT?"true":"false"); + LOG(info) << "fSBRatiobyN = " << (fSBRatiobyN ? "true" : "false") + << " / fSBRatiobyT = " << (fSBRatiobyT ? "true" : "false"); // LOG(info) << "*********** CHAIN HAS " << fBackgroundChain->GetEntries() << " entries"; - if (IsInitialized){ + if (IsInitialized) { LOG(info) << "FairMixedSource already initialized"; return kTRUE; } @@ -223,11 +222,11 @@ Bool_t FairMixedSource::Init() // Get the folder structure from file which describes the input tree. // There are two different names possible, so check both. - fCbmroot = dynamic_cast (fRootFile->Get(FairRootManager::GetFolderName())); + fCbmroot = dynamic_cast(fRootFile->Get(FairRootManager::GetFolderName())); if (!fCbmroot) { - fCbmroot = dynamic_cast (fRootFile->Get("cbmroot")); + fCbmroot = dynamic_cast(fRootFile->Get("cbmroot")); if (!fCbmroot) { - fCbmroot = dynamic_cast (fRootFile->Get("cbmout")); + fCbmroot = dynamic_cast(fRootFile->Get("cbmout")); if (!fCbmroot) { fCbmroot = gROOT->GetRootFolder()->AddFolder(FairRootManager::GetFolderName(), "Main Folder"); } else { @@ -248,19 +247,20 @@ Bool_t FairMixedSource::Init() // with a different branch structure but the same tree name. ROOT // probably only checks if the name of the tree is the same. - TList* list= dynamic_cast (fRootFile->Get("BranchList")); - if (list==0) LOG(fatal) << "No Branch list in input file"; + TList* list = dynamic_cast(fRootFile->Get("BranchList")); + if (list == 0) + LOG(fatal) << "No Branch list in input file"; TString chainName = fInputTitle; TString ObjName; fInputLevel.push_back(chainName); fCheckInputBranches[chainName] = new std::list; if (list) { - TObjString* Obj=0; + TObjString* Obj = 0; LOG(info) << "Enteries in the list " << list->GetEntries(); - for (Int_t i =0; i< list->GetEntries(); i++) { - Obj=dynamic_cast (list->At(i)); - if (Obj!=0){ - ObjName=Obj->GetString(); + for (Int_t i = 0; i < list->GetEntries(); i++) { + Obj = dynamic_cast(list->At(i)); + if (Obj != 0) { + ObjName = Obj->GetString(); LOG(info) << "Branch name " << ObjName.Data(); fCheckInputBranches[chainName]->push_back(ObjName.Data()); @@ -289,48 +289,49 @@ Bool_t FairMixedSource::Init() // is needed to bring the friend trees in the correct order TFile* inputFile = TFile::Open(fileName); if (inputFile->IsZombie()) { - LOG(fatal) << "Error opening the file " << fileName.Data() << " which should be added to the input chain or as friend chain"; + LOG(fatal) << "Error opening the file " << fileName.Data() + << " which should be added to the input chain or as friend chain"; } // Check if the branchlist is the same as for the first input file. Bool_t isOk = CompareBranchList(inputFile, chainName); if (!isOk) { - LOG(fatal) << "Branch structure of the input file " << fRootFile->GetName() << " and the file to be added " << fileName.Data(); - return kFALSE; + LOG(fatal) << "Branch structure of the input file " << fRootFile->GetName() << " and the file to be added " + << fileName.Data(); + return kFALSE; } // Add the runid information for all files in the chain. - //GetRunIdInfo(inputFile->GetName(), chainName); + // GetRunIdInfo(inputFile->GetName(), chainName); // Add the file to the input chain fBackgroundChain->Add(fileName); // Close the temporarly file and restore the gFile pointer. inputFile->Close(); gFile = temp; - } fNoOfEntries = fBackgroundChain->GetEntries(); - FairRootManager::Instance()->SetInChain(fBackgroundChain,0); + FairRootManager::Instance()->SetInChain(fBackgroundChain, 0); - for (Int_t i=0; iGetEntriesFast(); i++) { + for (Int_t i = 0; i < fListFolder->GetEntriesFast(); i++) { TFolder* fold = static_cast(fListFolder->At(i)); fEvtHeader = static_cast(fold->FindObjectAny("EventHeader.")); - fMCHeader = static_cast(fold->FindObjectAny("MCEventHeader.")); + fMCHeader = static_cast(fold->FindObjectAny("MCEventHeader.")); if (fEvtHeader) { - ActivateObject(reinterpret_cast(&fEvtHeader),"EventHeader."); + ActivateObject(reinterpret_cast(&fEvtHeader), "EventHeader."); } - if (fMCHeader ) { - ActivateObject(reinterpret_cast(&fMCHeader),"MCEventHeader."); + if (fMCHeader) { + ActivateObject(reinterpret_cast(&fMCHeader), "MCEventHeader."); } } FairRootManager::Instance()->SetListOfFolders(fListFolder); fBackgroundChain->GetEntry(0); if (fEvtHeader) { - fOutHeader->SetRunId (fEvtHeader->GetRunId()); + fOutHeader->SetRunId(fEvtHeader->GetRunId()); } if (fMCHeader) { - fOutHeader->SetRunId (fMCHeader->GetRunID()); + fOutHeader->SetRunId(fMCHeader->GetRunID()); } LOG(info) << "Entries in this Source " << fNoOfEntries << " ------------"; @@ -339,349 +340,342 @@ Bool_t FairMixedSource::Init() Int_t FairMixedSource::ReadEvent(UInt_t i) { - SetEventTime(); + SetEventTime(); + + Double_t SBratio = gRandom->Uniform(0, 1); + Bool_t GetASignal = kFALSE; + + if (fSBRatiobyN || fSBRatiobyT) { + Double_t ratio = 0; + if (fCurrentEntryNo == 0) { + for (const auto& mi : fSignalBGN) { + ratio += mi.second; + fSignalBGN[mi.first] = ratio; + LOG(debug) << "--------------Set signal no. " << mi.first << " weight " << ratio << "."; + } + } + ratio = 0; + for (const auto& mi : fSignalBGN) { + ratio = mi.second; + LOG(debug) << "---Check signal no. " << mi.first << " SBratio " << SBratio << " : ratio " << ratio; + if (SBratio <= ratio) { + TChain* chain = fSignalTypeList[mi.first]; + UInt_t entry = fCurrentEntry[mi.first]; + chain->GetEntry(entry); + fOutHeader->SetMCEntryNumber(entry); + fOutHeader->SetInputFileId(mi.first); + fOutHeader->SetEventTime(GetEventTime()); + GetASignal = kTRUE; + fCurrentEntry[mi.first] = entry + 1; + LOG(debug) << "---Get entry No. " << entry << " from signal chain number --- " << mi.first << " --- "; + break; + } + } + if (!GetASignal) { + UInt_t entry = fCurrentEntry[0]; + fBackgroundChain->GetEntry(entry); + fOutHeader->SetMCEntryNumber(entry); + fOutHeader->SetInputFileId(0); // Background files has always 0 as Id + fOutHeader->SetEventTime(GetEventTime()); + fCurrentEntry[0] = entry + 1; + LOG(debug) << "---Get entry from background chain --- "; + } + } - Double_t SBratio=gRandom->Uniform(0,1); - Bool_t GetASignal=kFALSE; + fCurrentEntryNo = i; + fOutHeader->SetEventTime(GetEventTime()); + LOG(debug) << "--Event number --- " << fCurrentEntryNo << " with time ----" << GetEventTime(); - if (fSBRatiobyN || fSBRatiobyT) { - Double_t ratio=0; - if (fCurrentEntryNo==0) { - for (const auto& mi : fSignalBGN) { - ratio+=mi.second; - fSignalBGN[mi.first]=ratio; - LOG(debug) << "--------------Set signal no. " << mi.first << " weight " << ratio << "."; - } - } - ratio=0; - for (const auto& mi : fSignalBGN) { - ratio=mi.second; - LOG(debug) << "---Check signal no. " << mi.first << " SBratio " << SBratio << " : ratio " << ratio; - if (SBratio <=ratio) { - TChain* chain = fSignalTypeList[mi.first]; - UInt_t entry = fCurrentEntry[mi.first]; - chain->GetEntry(entry); - fOutHeader->SetMCEntryNumber(entry); - fOutHeader->SetInputFileId(mi.first); - fOutHeader->SetEventTime(GetEventTime()); - GetASignal=kTRUE; - fCurrentEntry[mi.first]=entry+1; - LOG(debug) << "---Get entry No. " << entry << " from signal chain number --- " << mi.first << " --- "; - break; - } - } - if (!GetASignal) { - UInt_t entry = fCurrentEntry[0]; - fBackgroundChain->GetEntry(entry); - fOutHeader->SetMCEntryNumber(entry); - fOutHeader->SetInputFileId(0); //Background files has always 0 as Id - fOutHeader->SetEventTime(GetEventTime()); - fCurrentEntry[0]=entry+1; - LOG(debug) << "---Get entry from background chain --- "; - } - } - - fCurrentEntryNo=i; - fOutHeader->SetEventTime(GetEventTime()); - LOG(debug) << "--Event number --- " << fCurrentEntryNo << " with time ----" << GetEventTime(); - - return 0; + return 0; } -void FairMixedSource::Close() -{ -} +void FairMixedSource::Close() {} -void FairMixedSource::Reset() -{ -} +void FairMixedSource::Reset() {} void FairMixedSource::FillEventHeader(FairEventHeader* feh) { - feh->SetEventTime (fOutHeader->GetEventTime()); - feh->SetMCEntryNumber(fOutHeader->GetMCEntryNumber()); - feh->SetInputFileId (fOutHeader->GetInputFileId()); - feh->SetRunId (fOutHeader->GetRunId()); - LOG(debug) << "FairMixedSource::FillEventHeader() Event " << fCurrentEntryNo << " at " << feh->GetEventTime() << " -> Run id = " << fOutHeader->GetRunId() << " event#" << feh->GetMCEntryNumber() << " from file#" << fOutHeader->GetInputFileId(); - return; + feh->SetEventTime(fOutHeader->GetEventTime()); + feh->SetMCEntryNumber(fOutHeader->GetMCEntryNumber()); + feh->SetInputFileId(fOutHeader->GetInputFileId()); + feh->SetRunId(fOutHeader->GetRunId()); + LOG(debug) << "FairMixedSource::FillEventHeader() Event " << fCurrentEntryNo << " at " << feh->GetEventTime() + << " -> Run id = " << fOutHeader->GetRunId() << " event#" << feh->GetMCEntryNumber() << " from file#" + << fOutHeader->GetInputFileId(); + return; } Bool_t FairMixedSource::CompareBranchList(TFile* fileHandle, TString inputLevel) { - // fill a set with the original branch structure - // This allows to use functions find and erase - std::set branches; - for (auto li : (*fCheckInputBranches[inputLevel])) { - branches.insert(li); - } - - // To do so we have to loop over the branches in the file and to compare - // the branches in the file with the information stored in - // fCheckInputBranches["InputChain"]. If both lists are equal everything - // is okay - - // Get The list of branches from the input file one by one and compare - // it to the reference list of branches which is defined for this tree. - // If a branch with the same name is found, this branch is removed from - // the list. If in the end no branch is left in the list everything is - // fine. - set::iterator iter1; - TList* list= dynamic_cast (fileHandle->Get("BranchList")); - if (list) { - TObjString* Obj=0; - for (Int_t i =0; i< list->GetEntries(); i++) { - Obj=dynamic_cast (list->At(i)); - iter1=branches.find(Obj->GetString().Data()); - if (iter1 != branches.end()) { - branches.erase (iter1); - } else { - // Not found is an error because branch structure is - // different. It is impossible to add to tree with a - // different branch structure + // fill a set with the original branch structure + // This allows to use functions find and erase + std::set branches; + for (auto li : (*fCheckInputBranches[inputLevel])) { + branches.insert(li); + } + + // To do so we have to loop over the branches in the file and to compare + // the branches in the file with the information stored in + // fCheckInputBranches["InputChain"]. If both lists are equal everything + // is okay + + // Get The list of branches from the input file one by one and compare + // it to the reference list of branches which is defined for this tree. + // If a branch with the same name is found, this branch is removed from + // the list. If in the end no branch is left in the list everything is + // fine. + set::iterator iter1; + TList* list = dynamic_cast(fileHandle->Get("BranchList")); + if (list) { + TObjString* Obj = 0; + for (Int_t i = 0; i < list->GetEntries(); i++) { + Obj = dynamic_cast(list->At(i)); + iter1 = branches.find(Obj->GetString().Data()); + if (iter1 != branches.end()) { + branches.erase(iter1); + } else { + // Not found is an error because branch structure is + // different. It is impossible to add to tree with a + // different branch structure + return kFALSE; + } + } + } + // If the size of branches is !=0 after removing all branches also in the + // reference list, this is also a sign that both branch list are not the + // same + if (branches.size() != 0) { return kFALSE; - } } - } - // If the size of branches is !=0 after removing all branches also in the - // reference list, this is also a sign that both branch list are not the - // same - if (branches.size() != 0) { - return kFALSE; - } - return kTRUE; + return kTRUE; } void FairMixedSource::SetSignalFile(TString name, UInt_t identifier) { - TFile* SignalInFile = TFile::Open(name.Data()); - if (SignalInFile->IsZombie()) { - LOG(fatal) << "Error opening the Signal file"; - } else { - /** Set a signal file of certain type (identifier) if already exist add the file to the chain*/ - if (fSignalTypeList[identifier]==0) { - TChain* chain = new TChain(FairRootManager::GetTreeName(), Form("/%s", FairRootManager::GetFolderName())); - fSignalTypeList[identifier]=chain; - FairRootManager::Instance()->SetInChain(chain,identifier); - fCurrentEntry[identifier]= 0; - fNoOfSignals++; - fActualSignalIdentifier= identifier; - chain->AddFile(name.Data()); + TFile* SignalInFile = TFile::Open(name.Data()); + if (SignalInFile->IsZombie()) { + LOG(fatal) << "Error opening the Signal file"; } else { - TChain* CurrentChain=fSignalTypeList[identifier]; - CurrentChain->AddFile(name.Data()); -// TObjArray* fileElements=CurrentChain->GetListOfFiles(); + /** Set a signal file of certain type (identifier) if already exist add the file to the chain*/ + if (fSignalTypeList[identifier] == 0) { + TChain* chain = new TChain(FairRootManager::GetTreeName(), Form("/%s", FairRootManager::GetFolderName())); + fSignalTypeList[identifier] = chain; + FairRootManager::Instance()->SetInChain(chain, identifier); + fCurrentEntry[identifier] = 0; + fNoOfSignals++; + fActualSignalIdentifier = identifier; + chain->AddFile(name.Data()); + } else { + TChain* CurrentChain = fSignalTypeList[identifier]; + CurrentChain->AddFile(name.Data()); + // TObjArray* fileElements=CurrentChain->GetListOfFiles(); + } } - - } } -void FairMixedSource::AddSignalFile(TString name, UInt_t identifier) -{ - SetSignalFile(name, identifier); -} +void FairMixedSource::AddSignalFile(TString name, UInt_t identifier) { SetSignalFile(name, identifier); } TChain* FairMixedSource::GetSignalChainNo(UInt_t i) { - if (i<IsZombie()) { - LOG(fatal) << "Error opening the Background file " << name.Data(); - } + fCurrentEntry[0] = 0; + if (name.IsNull()) { + LOG(info) << "No background file defined."; + } + fRootFile = TFile::Open(name); + if (fRootFile->IsZombie()) { + LOG(fatal) << "Error opening the Background file " << name.Data(); + } } - void FairMixedSource::AddBackgroundFile(TString name) { - if (name.IsNull()) { - LOG(info) << "No background file defined."; - } - TFile* BGFile = TFile::Open(name); - if (BGFile->IsZombie()) { - LOG(fatal) << "Error opening the Background file " << name.Data(); - } else { - if (fBackgroundChain!=0) { - fBackgroundChain->AddFile(name.Data()); -// TObjArray* fileElements=fBackgroundChain->GetListOfFiles(); + if (name.IsNull()) { + LOG(info) << "No background file defined."; + } + TFile* BGFile = TFile::Open(name); + if (BGFile->IsZombie()) { + LOG(fatal) << "Error opening the Background file " << name.Data(); } else { - LOG(fatal) << "Use SetBackGroundFile first, then add files to background"; + if (fBackgroundChain != 0) { + fBackgroundChain->AddFile(name.Data()); + // TObjArray* fileElements=fBackgroundChain->GetListOfFiles(); + } else { + LOG(fatal) << "Use SetBackGroundFile first, then add files to background"; + } } - } } Bool_t FairMixedSource::OpenBackgroundChain() { - // Get the folder structure from file which describes the input tree. - // There are two different names possible, so check both. - fCbmroot = dynamic_cast (fRootFile->Get(FairRootManager::GetFolderName())); - if (!fCbmroot) { - fCbmroot = dynamic_cast (fRootFile->Get("cbmroot")); + // Get the folder structure from file which describes the input tree. + // There are two different names possible, so check both. + fCbmroot = dynamic_cast(fRootFile->Get(FairRootManager::GetFolderName())); if (!fCbmroot) { - fCbmroot = dynamic_cast (fRootFile->Get("cbmout")); - if (!fCbmroot) { - fCbmroot = gROOT->GetRootFolder()->AddFolder(FairRootManager::GetFolderName(), "Main Folder"); - } else { - fCbmroot->SetName(FairRootManager::GetFolderName()); - } - } - } - - // Get The list of branches from the input file and add it to the - // actual list of existing branches. - // Add this list of branches also to the map of input trees, which - // stores the information which branches belong to which input tree. - // There is at least one primary input tree, but there can be many - // additional friend trees. - // This information is needed to add new files to the correct friend - // tree. With this information it is also possible to check if the - // input files which are added to the input chain all have the same - // branch structure. Without this check it is possible to add trees - // with a different branch structure but the same tree name. ROOT - // probably only checks if the name of the tree is the same. - - TList* list= dynamic_cast (fRootFile->Get("BranchList")); - TString chainName = "BGInChain"; - fInputLevel.push_back(chainName); - fCheckInputBranches[chainName] = new std::list; - if (list) { - TObjString* Obj=0; - for (Int_t i =0; i< list->GetEntries(); i++) { - Obj=dynamic_cast (list->At(i)); - fCheckInputBranches[chainName]->push_back(Obj->GetString().Data()); - FairRootManager::Instance()->AddBranchToList(Obj->GetString().Data()); - } - } - - gROOT->GetListOfBrowsables()->Add(fCbmroot); - fListFolder->Add(fCbmroot); - return kTRUE; + fCbmroot = dynamic_cast(fRootFile->Get("cbmroot")); + if (!fCbmroot) { + fCbmroot = dynamic_cast(fRootFile->Get("cbmout")); + if (!fCbmroot) { + fCbmroot = gROOT->GetRootFolder()->AddFolder(FairRootManager::GetFolderName(), "Main Folder"); + } else { + fCbmroot->SetName(FairRootManager::GetFolderName()); + } + } + } + + // Get The list of branches from the input file and add it to the + // actual list of existing branches. + // Add this list of branches also to the map of input trees, which + // stores the information which branches belong to which input tree. + // There is at least one primary input tree, but there can be many + // additional friend trees. + // This information is needed to add new files to the correct friend + // tree. With this information it is also possible to check if the + // input files which are added to the input chain all have the same + // branch structure. Without this check it is possible to add trees + // with a different branch structure but the same tree name. ROOT + // probably only checks if the name of the tree is the same. + + TList* list = dynamic_cast(fRootFile->Get("BranchList")); + TString chainName = "BGInChain"; + fInputLevel.push_back(chainName); + fCheckInputBranches[chainName] = new std::list; + if (list) { + TObjString* Obj = 0; + for (Int_t i = 0; i < list->GetEntries(); i++) { + Obj = dynamic_cast(list->At(i)); + fCheckInputBranches[chainName]->push_back(Obj->GetString().Data()); + FairRootManager::Instance()->AddBranchToList(Obj->GetString().Data()); + } + } + gROOT->GetListOfBrowsables()->Add(fCbmroot); + fListFolder->Add(fCbmroot); + return kTRUE; } Bool_t FairMixedSource::OpenSignalChain() { - for (const auto& mi : fSignalTypeList) { - TChain* currentChain=mi.second; - // cout << "Signal chain is : " << currentChain->GetName()<< endl; - // currentChain->Dump(); - TFile* ChainFirstFile = currentChain->GetFile(); - //cout << "First file in signal chain is : " << ChainFirstFile << endl; - // Check if the branchlist is the same as for the first input file. - Bool_t isOk = CompareBranchList(ChainFirstFile,"BGInChain"); - if (!isOk) { - LOG(fatal) << "Branch structure of the signal chain is different than the back ground one"; - } - } - return kTRUE; + for (const auto& mi : fSignalTypeList) { + TChain* currentChain = mi.second; + // cout << "Signal chain is : " << currentChain->GetName()<< endl; + // currentChain->Dump(); + TFile* ChainFirstFile = currentChain->GetFile(); + // cout << "First file in signal chain is : " << ChainFirstFile << endl; + // Check if the branchlist is the same as for the first input file. + Bool_t isOk = CompareBranchList(ChainFirstFile, "BGInChain"); + if (!isOk) { + LOG(fatal) << "Branch structure of the signal chain is different than the back ground one"; + } + } + return kTRUE; } -Bool_t FairMixedSource::ActivateObject(TObject** obj, const char* BrName) { - fBackgroundChain->SetBranchStatus(BrName,1); - fBackgroundChain->SetBranchAddress(BrName,obj); - - Int_t no=0; - for (const auto& mi : fSignalTypeList) { - TChain* currentChain = mi.second; - LOG(debug2) << "Set the Branch address for signal file number " << no++ << " and branch " << BrName; - currentChain->SetBranchStatus(BrName,1); - currentChain->SetBranchAddress(BrName,obj); - } +Bool_t FairMixedSource::ActivateObject(TObject** obj, const char* BrName) +{ + fBackgroundChain->SetBranchStatus(BrName, 1); + fBackgroundChain->SetBranchAddress(BrName, obj); + + Int_t no = 0; + for (const auto& mi : fSignalTypeList) { + TChain* currentChain = mi.second; + LOG(debug2) << "Set the Branch address for signal file number " << no++ << " and branch " << BrName; + currentChain->SetBranchStatus(BrName, 1); + currentChain->SetBranchAddress(BrName, obj); + } - return kTRUE; + return kTRUE; } -void FairMixedSource::ReadBKEvent(UInt_t i) +void FairMixedSource::ReadBKEvent(UInt_t i) { - if (0==i) { - Int_t totEnt = fBackgroundChain->GetEntries(); - LOG(info) << "The number of entries in background chain is " << totEnt; - } - fBackgroundChain->GetEntry(i); + if (0 == i) { + Int_t totEnt = fBackgroundChain->GetEntries(); + LOG(info) << "The number of entries in background chain is " << totEnt; + } + fBackgroundChain->GetEntry(i); } -void FairMixedSource::BGWindowWidthNo(UInt_t background, UInt_t Signalid) +void FairMixedSource::BGWindowWidthNo(UInt_t background, UInt_t Signalid) { - fSBRatiobyN=kTRUE; - if (fSBRatiobyT) { - LOG(fatal) << "Signal rate already set by TIME!!"; - } - Double_t value=1.0/background; - if (background!=0) { - fSignalBGN[Signalid]=value; - } else { - LOG(fatal) << "Background cannot be Zero when setting the signal rate!!"; - } + fSBRatiobyN = kTRUE; + if (fSBRatiobyT) { + LOG(fatal) << "Signal rate already set by TIME!!"; + } + Double_t value = 1.0 / background; + if (background != 0) { + fSignalBGN[Signalid] = value; + } else { + LOG(fatal) << "Background cannot be Zero when setting the signal rate!!"; + } } -void FairMixedSource::BGWindowWidthTime(Double_t background, UInt_t Signalid) +void FairMixedSource::BGWindowWidthTime(Double_t background, UInt_t Signalid) { - fSBRatiobyT=kTRUE; - if (fSBRatiobyN) { - LOG(fatal) << "Signal rate already set by NUMBER!!"; - } - if (fEventTimeInMCHeader) { - LOG(fatal) << "You have to Set the Event mean time before using SetSignalRateTime!"; - } - if (fEventMeanTime==0) { - LOG(fatal) << "Event mean time cannot be zero when using signal rate with time "; - } - /**convert to number of event by dividing by the mean time */ - Double_t value=fEventMeanTime/background; - if (background!=0) { - fSignalBGN[Signalid]=value; - } else { - LOG(fatal) << "Background cannot be Zero when setting the signal rate!!"; - } - + fSBRatiobyT = kTRUE; + if (fSBRatiobyN) { + LOG(fatal) << "Signal rate already set by NUMBER!!"; + } + if (fEventTimeInMCHeader) { + LOG(fatal) << "You have to Set the Event mean time before using SetSignalRateTime!"; + } + if (fEventMeanTime == 0) { + LOG(fatal) << "Event mean time cannot be zero when using signal rate with time "; + } + /**convert to number of event by dividing by the mean time */ + Double_t value = fEventMeanTime / background; + if (background != 0) { + fSignalBGN[Signalid] = value; + } else { + LOG(fatal) << "Background cannot be Zero when setting the signal rate!!"; + } } -Int_t FairMixedSource::CheckMaxEventNo(Int_t EvtEnd) +Int_t FairMixedSource::CheckMaxEventNo(Int_t EvtEnd) { - Int_t MaxEventNo=0; - if (EvtEnd!=0) { - MaxEventNo=EvtEnd; - } - Int_t localMax=0; - Int_t MaxBG=fBackgroundChain->GetEntries(); - Int_t MaxS=0; - Double_t ratio=0.; - for (const auto& mi : fSignalBGN) { - TChain* chain = fSignalTypeList[mi.first]; - MaxS=chain->GetEntries(); - LOG(info) << "Signal chain No " << mi.first << " has : " << MaxS << " entries "; - ratio=mi.second; - if (floor(MaxS/ratio) > MaxBG) { - localMax=MaxBG+static_cast(floor(MaxBG*ratio)); - LOG(warn) << "No of Event in Background chain is not enough for all signals in chain " << mi.first; - } else { - localMax=static_cast(floor(MaxS/ratio)); - LOG(warn) << "No of Event in signal chain " << mi.first << " is not enough, the maximum event number will be reduced to : " << localMax; + Int_t MaxEventNo = 0; + if (EvtEnd != 0) { + MaxEventNo = EvtEnd; } - if (MaxEventNo==0 || MaxEventNo > localMax) { - MaxEventNo=localMax; + Int_t localMax = 0; + Int_t MaxBG = fBackgroundChain->GetEntries(); + Int_t MaxS = 0; + Double_t ratio = 0.; + for (const auto& mi : fSignalBGN) { + TChain* chain = fSignalTypeList[mi.first]; + MaxS = chain->GetEntries(); + LOG(info) << "Signal chain No " << mi.first << " has : " << MaxS << " entries "; + ratio = mi.second; + if (floor(MaxS / ratio) > MaxBG) { + localMax = MaxBG + static_cast(floor(MaxBG * ratio)); + LOG(warn) << "No of Event in Background chain is not enough for all signals in chain " << mi.first; + } else { + localMax = static_cast(floor(MaxS / ratio)); + LOG(warn) << "No of Event in signal chain " << mi.first + << " is not enough, the maximum event number will be reduced to : " << localMax; + } + if (MaxEventNo == 0 || MaxEventNo > localMax) { + MaxEventNo = localMax; + } } - } - LOG(info) << "Maximum No of Event will be set to : " << MaxEventNo; - return MaxEventNo; + LOG(info) << "Maximum No of Event will be set to : " << MaxEventNo; + return MaxEventNo; } -void FairMixedSource::SetEventMeanTime(Double_t mean) +void FairMixedSource::SetEventMeanTime(Double_t mean) { - fEventMeanTime =mean; -/* + fEventMeanTime = mean; + /* TString form="(1/"; form+= mean; form+=")*exp(-x/"; @@ -689,92 +683,91 @@ void FairMixedSource::SetEventMeanTime(Double_t mean) form+=")"; fTimeProb= new TF1("TimeProb", form.Data(), 0., mean*10); */ - fTimeProb = new TF1("TimeProb","(1/[0])*exp(-x/[0])", 0., mean*10); - fTimeProb->SetParameter(0,mean); - fTimeProb->GetRandom(); - fEventTimeInMCHeader=kFALSE; + fTimeProb = new TF1("TimeProb", "(1/[0])*exp(-x/[0])", 0., mean * 10); + fTimeProb->SetParameter(0, mean); + fTimeProb->GetRandom(); + fEventTimeInMCHeader = kFALSE; } void FairMixedSource::SetEventTimeInterval(Double_t min, Double_t max) { - fEventTimeMin=min; - fEventTimeMax=max; - fEventMeanTime=(fEventTimeMin+fEventTimeMax)/2; - fEventTimeInMCHeader=kFALSE; + fEventTimeMin = min; + fEventTimeMax = max; + fEventMeanTime = (fEventTimeMin + fEventTimeMax) / 2; + fEventTimeInMCHeader = kFALSE; } void FairMixedSource::SetBeamTime(Double_t beamTime, Double_t gapTime) { - fBeamTime = beamTime; - fGapTime = gapTime; + fBeamTime = beamTime; + fGapTime = gapTime; } void FairMixedSource::SetEventTime() { - LOG(debug) << "Set event time for Entry = " - << fTimeforEntryNo << " , where the current entry is " - << fCurrentEntryNo << " and eventTime is " - << fEventTime; - if (fBeamTime < 0){ - fEventTime += GetDeltaEventTime(); - } else { - do { - fEventTime += GetDeltaEventTime(); - } while(fmod(fEventTime, fBeamTime + fGapTime) > fBeamTime); - } - LOG(debug) << "New time = " << fEventTime; - fTimeforEntryNo=fCurrentEntryNo; + LOG(debug) << "Set event time for Entry = " << fTimeforEntryNo << " , where the current entry is " + << fCurrentEntryNo << " and eventTime is " << fEventTime; + if (fBeamTime < 0) { + fEventTime += GetDeltaEventTime(); + } else { + do { + fEventTime += GetDeltaEventTime(); + } while (fmod(fEventTime, fBeamTime + fGapTime) > fBeamTime); + } + LOG(debug) << "New time = " << fEventTime; + fTimeforEntryNo = fCurrentEntryNo; } Double_t FairMixedSource::GetDeltaEventTime() { - Double_t deltaTime = 0; - if (fTimeProb != 0) { - deltaTime = fTimeProb->GetRandom(); - LOG(debug) << "Time set via sampling method : " << deltaTime; - } else { - deltaTime = gRandom->Uniform(fEventTimeMin, fEventTimeMax); - LOG(debug) << "Time set via Uniform Random : " - << deltaTime; - } - return deltaTime; + Double_t deltaTime = 0; + if (fTimeProb != 0) { + deltaTime = fTimeProb->GetRandom(); + LOG(debug) << "Time set via sampling method : " << deltaTime; + } else { + deltaTime = gRandom->Uniform(fEventTimeMin, fEventTimeMax); + LOG(debug) << "Time set via Uniform Random : " << deltaTime; + } + return deltaTime; } Double_t FairMixedSource::GetEventTime() { - LOG(debug) << "-- Get Event Time --"; - if (!fEvtHeaderIsNew && fEvtHeader!=0) { - Double_t EvtTime=fEvtHeader->GetEventTime(); - if (!(EvtTime<0)) { - return EvtTime; + LOG(debug) << "-- Get Event Time --"; + if (!fEvtHeaderIsNew && fEvtHeader != 0) { + Double_t EvtTime = fEvtHeader->GetEventTime(); + if (!(EvtTime < 0)) { + return EvtTime; + } } - } - if (fEventTimeInMCHeader && !fMCHeader) { - LOG(debug) << "No MCEventHeader, time is set to 0"; - return 0; - } else if (fEventTimeInMCHeader && fMCHeader) { - fEventTime=fMCHeader->GetT(); - LOG(debug) << "Get event time from MCEventHeader : " - << fEventTime << " ns"; - return fEventTime; - } else { - - if (fTimeforEntryNo!=fCurrentEntryNo) { - SetEventTime(); - } - LOG(debug) << "Calculate event time from user input : " - << fEventTime << " ns"; - return fEventTime; - } + if (fEventTimeInMCHeader && !fMCHeader) { + LOG(debug) << "No MCEventHeader, time is set to 0"; + return 0; + } else if (fEventTimeInMCHeader && fMCHeader) { + fEventTime = fMCHeader->GetT(); + LOG(debug) << "Get event time from MCEventHeader : " << fEventTime << " ns"; + return fEventTime; + } else { + + if (fTimeforEntryNo != fCurrentEntryNo) { + SetEventTime(); + } + LOG(debug) << "Calculate event time from user input : " << fEventTime << " ns"; + return fEventTime; + } } void FairMixedSource::ReadBranchEvent(const char* BrName) { /**fill the object with content if the other branches in this tree entry were already read**/ - if (fEvtHeader == 0) { return; } //No event header, Reading will start later + if (fEvtHeader == 0) { + return; + } // No event header, Reading will start later TChain* chain = fSignalTypeList[fEvtHeader->GetInputFileId()]; - if (!chain) { return; } + if (!chain) { + return; + } chain->FindBranch(BrName)->GetEntry(fEvtHeader->GetMCEntryNumber()); return; } @@ -782,11 +775,15 @@ void FairMixedSource::ReadBranchEvent(const char* BrName) void FairMixedSource::ReadBranchEvent(const char* BrName, Int_t Entry) { /**fill the object with content if the other branches in this tree entry were already read**/ - if (fEvtHeader == 0) { return; } //No event header, Reading will start later + if (fEvtHeader == 0) { + return; + } // No event header, Reading will start later TChain* chain = fSignalTypeList[fEvtHeader->GetInputFileId()]; - if (!chain) { return; } + if (!chain) { + return; + } chain->FindBranch(BrName)->GetEntry(Entry); return; } -ClassImp(FairMixedSource) +ClassImp(FairMixedSource); diff --git a/base/source/FairMixedSource.h b/base/source/FairMixedSource.h index ed64dedba5..17a1a9ca62 100644 --- a/base/source/FairMixedSource.h +++ b/base/source/FairMixedSource.h @@ -18,11 +18,10 @@ #include "FairSource.h" +#include #include -#include #include -#include - +#include #include #include @@ -39,16 +38,19 @@ class FairRootManager; class FairMixedSource : public FairSource { public: - FairMixedSource(TFile *f, const char* Title="InputRootFile", UInt_t identifier=0); - FairMixedSource(const TString* RootFileName, const char* Title="InputRootFile", UInt_t identifier=0); - FairMixedSource(const TString RootFileName, const Int_t signalId, const char* Title="InputRootFile", UInt_t identifier=0); + FairMixedSource(TFile* f, const char* Title = "InputRootFile", UInt_t identifier = 0); + FairMixedSource(const TString* RootFileName, const char* Title = "InputRootFile", UInt_t identifier = 0); + FairMixedSource(const TString RootFileName, + const Int_t signalId, + const char* Title = "InputRootFile", + UInt_t identifier = 0); // FairMixedSource(const FairMixedSource& file); virtual ~FairMixedSource(); - Bool_t Init(); - Int_t ReadEvent(UInt_t i=0); - void Close(); - void Reset(); + Bool_t Init(); + Int_t ReadEvent(UInt_t i = 0); + void Close(); + void Reset(); virtual Source_Type GetSourceType() { return kFILE; } @@ -59,172 +61,173 @@ class FairMixedSource : public FairSource virtual Bool_t ReInitUnpackers() { return kTRUE; } /**Check the maximum event number we can run to*/ - virtual Int_t CheckMaxEventNo(Int_t EvtEnd=0); + virtual Int_t CheckMaxEventNo(Int_t EvtEnd = 0); /**Read the tree entry on one branch**/ - void ReadBranchEvent(const char* BrName); + void ReadBranchEvent(const char* BrName); /** Read specific tree entry on one branch**/ - void ReadBranchEvent(const char* BrName, Int_t Entry); + void ReadBranchEvent(const char* BrName, Int_t Entry); - void FillEventHeader(FairEventHeader* feh); + void FillEventHeader(FairEventHeader* feh); - const TFile* GetRootFile(){return fRootFile;} + const TFile* GetRootFile() { return fRootFile; } /** Add a friend file (input) by name)*/ - virtual Bool_t ActivateObject(TObject** obj, const char* BrName); + virtual Bool_t ActivateObject(TObject** obj, const char* BrName); - void ReadBKEvent(UInt_t i=0); + void ReadBKEvent(UInt_t i = 0); /**Set the input signal file *@param name : signal file name *@param identifier : Unsigned integer which identify the signal file */ - void SetSignalFile(TString name, UInt_t identifier ); + void SetSignalFile(TString name, UInt_t identifier); /**Set the input background file by name*/ - void SetBackgroundFile(TString name); + void SetBackgroundFile(TString name); /**Add signal file to input *@param name : signal file name *@param identifier : Unsigned integer which identify the signal file to which this signal should be added */ - void AddSignalFile(TString name, UInt_t identifier ); - void AddBackgroundFile(TString name); + void AddSignalFile(TString name, UInt_t identifier); + void AddBackgroundFile(TString name); - TChain* GetBGChain() { return fBackgroundChain;} - TChain* GetSignalChainNo(UInt_t i); + TChain* GetBGChain() { return fBackgroundChain; } + TChain* GetSignalChainNo(UInt_t i); - Bool_t OpenBackgroundChain(); - Bool_t OpenSignalChain(); + Bool_t OpenBackgroundChain(); + Bool_t OpenSignalChain(); /**Set the signal to background ratio in event units - *@param background : Number of background Events for one signal - *@param Signalid : Signal file Id, used when adding (setting) the signal file - */ + *@param background : Number of background Events for one signal + *@param Signalid : Signal file Id, used when adding (setting) the signal file + */ void BGWindowWidthNo(UInt_t background, UInt_t Signalid); /**Set the signal to background rate in time units - *@param background : Time of background Events before one signal - *@param Signalid : Signal file Id, used when adding (setting) the signal file - */ + *@param background : Time of background Events before one signal + *@param Signalid : Signal file Id, used when adding (setting) the signal file + */ void BGWindowWidthTime(Double_t background, UInt_t Signalid); /** Set the min and max limit for event time in ns */ - void SetEventTimeInterval(Double_t min, Double_t max); + void SetEventTimeInterval(Double_t min, Double_t max); /** Set the mean time for the event in ns */ - void SetEventMeanTime(Double_t mean); - /** Set the repetition time of the beam when it can interact (beamTime) and when no interaction happen (gapTime). The total repetition time is beamTime + gapTime */ - void SetBeamTime(Double_t beamTime, Double_t gapTime); - void SetEventTime(); - Double_t GetDeltaEventTime(); - void SetFileHeader(FairFileHeader* f) {fFileHeader =f;} - Double_t GetEventTime(); + void SetEventMeanTime(Double_t mean); + /** Set the repetition time of the beam when it can interact (beamTime) and when no interaction happen (gapTime). + * The total repetition time is beamTime + gapTime */ + void SetBeamTime(Double_t beamTime, Double_t gapTime); + void SetEventTime(); + Double_t GetDeltaEventTime(); + void SetFileHeader(FairFileHeader* f) { fFileHeader = f; } + Double_t GetEventTime(); /**Add ROOT file to input, the file will be chained to already added files*/ - Bool_t CompareBranchList(TFile* fileHandle, TString inputLevel); + Bool_t CompareBranchList(TFile* fileHandle, TString inputLevel); /**Set the input tree when running on PROOF worker*/ - TObjArray* GetListOfFolders(){return fListFolder;} - TFolder* GetBranchDescriptionFolder(){return fCbmroot;} - UInt_t GetEntries(){return fNoOfEntries; } + TObjArray* GetListOfFolders() { return fListFolder; } + TFolder* GetBranchDescriptionFolder() { return fCbmroot; } + UInt_t GetEntries() { return fNoOfEntries; } /**Set the status of the EvtHeader *@param Status: True: The header was creatged in this session and has to be filled FALSE: We use an existing header from previous data level */ - void SetEvtHeaderNew(Bool_t Status) {fEvtHeaderIsNew = Status;} - Bool_t IsEvtHeaderNew() {return fEvtHeaderIsNew;} + void SetEvtHeaderNew(Bool_t Status) { fEvtHeaderIsNew = Status; } + Bool_t IsEvtHeaderNew() { return fEvtHeaderIsNew; } private: /**IO manager */ - FairRootManager* fRootManager; + FairRootManager* fRootManager; /** Title of input source, could be input, background or signal*/ - TString fInputTitle; + TString fInputTitle; /**ROOT file*/ - TFile* fRootFile; + TFile* fRootFile; /** List of all files added with AddFriend */ - std::list fFriendFileList; //! - std::list fInputChainList;//! - std::map fFriendTypeList;//! - std::map* > fCheckInputBranches; //! - std::list fInputLevel; //! - std::map > fRunIdInfoAll; //! + std::list fFriendFileList; //! + std::list fInputChainList; //! + std::map fFriendTypeList; //! + std::map*> fCheckInputBranches; //! + std::list fInputLevel; //! + std::map> fRunIdInfoAll; //! /** list of folders from all input (and friends) files*/ - TObjArray *fListFolder; //! + TObjArray* fListFolder; //! /** RuntimeDb*/ - FairRuntimeDb* fRtdb; + FairRuntimeDb* fRtdb; /**folder structure of output*/ - TFolder* fCbmout; + TFolder* fCbmout; /**folder structure of input*/ - TFolder* fCbmroot; + TFolder* fCbmroot; /***/ - UInt_t fSourceIdentifier; + UInt_t fSourceIdentifier; /**No of Entries in this source*/ - UInt_t fNoOfEntries; + UInt_t fNoOfEntries; /**Initialization flag, true if initialized*/ - Bool_t IsInitialized; + Bool_t IsInitialized; /** MC Event header */ - FairMCEventHeader* fMCHeader; //! + FairMCEventHeader* fMCHeader; //! /**Event Header*/ - FairEventHeader* fEvtHeader; //! + FairEventHeader* fEvtHeader; //! /**Output Event Header*/ - FairEventHeader* fOutHeader; //! + FairEventHeader* fOutHeader; //! /**File Header*/ - FairFileHeader* fFileHeader; //! + FairFileHeader* fFileHeader; //! /** This is true if the event time used, came from simulation*/ - Bool_t fEventTimeInMCHeader; //! + Bool_t fEventTimeInMCHeader; //! /**This flag is true if the event header was created in this session - * otherwise it is false which means the header was created in a previous data - * level and used here (e.g. in the digi) - */ - Bool_t fEvtHeaderIsNew; //! + * otherwise it is false which means the header was created in a previous data + * level and used here (e.g. in the digi) + */ + Bool_t fEvtHeaderIsNew; //! /** for internal use, to return the same event time for the same entry*/ - UInt_t fCurrentEntryNo; //! + UInt_t fCurrentEntryNo; //! /** for internal use, to return the same event time for the same entry*/ - UInt_t fTimeforEntryNo; //! + UInt_t fTimeforEntryNo; //! /* /\**No of entries in BG Chain*\/ */ - UInt_t fNoOfBGEntries; //! + UInt_t fNoOfBGEntries; //! /* /\**Hold the current entry for each input chain*\/ */ - std::map fCurrentEntry; //! + std::map fCurrentEntry; //! /** min time for one event (ns) */ - Double_t fEventTimeMin; //! + Double_t fEventTimeMin; //! /** max time for one Event (ns) */ - Double_t fEventTimeMax; //! + Double_t fEventTimeMax; //! /** Time of event since th start (ns) */ - Double_t fEventTime; //! + Double_t fEventTime; //! /** Time of particles in beam (ns) */ - Double_t fBeamTime; //! + Double_t fBeamTime; //! /** Time without particles in beam (gap) (ns) */ - Double_t fGapTime; //! + Double_t fGapTime; //! /** EventMean time used (P(t)=1/fEventMeanTime*Exp(-t/fEventMeanTime) */ - Double_t fEventMeanTime; //! + Double_t fEventMeanTime; //! /** used to generate random numbers for event time; */ - TF1* fTimeProb; //! + TF1* fTimeProb; //! /**holds the SB ratio by number*/ - std::map fSignalBGN;//! + std::map fSignalBGN; //! /* /\**True for background window in entry units*\/ */ - Bool_t fSBRatiobyN; //! + Bool_t fSBRatiobyN; //! /* /\**True for background window in time units (ns) *\/ */ - Bool_t fSBRatiobyT; //! + Bool_t fSBRatiobyT; //! /**Actual identifier of the added signals, this is used to identify how many signals are added*/ - UInt_t fActualSignalIdentifier; //! + UInt_t fActualSignalIdentifier; //! /** Total number of signals added (Types and not files!)*/ - UInt_t fNoOfSignals; //! + UInt_t fNoOfSignals; //! /** list of chains which has to be created for the different signals*/ - std::list* fSignalChainList; //! + std::list* fSignalChainList; //! /**Chain containing the background*/ - TChain* fBackgroundChain; //! - std::map fSignalTypeList;//! + TChain* fBackgroundChain; //! + std::map fSignalTypeList; //! FairMixedSource(const FairMixedSource&); FairMixedSource& operator=(const FairMixedSource&); -public: + public: ClassDef(FairMixedSource, 0) }; diff --git a/base/source/FairOnlineSource.cxx b/base/source/FairOnlineSource.cxx index 04a45aae12..a9a3b4948e 100644 --- a/base/source/FairOnlineSource.cxx +++ b/base/source/FairOnlineSource.cxx @@ -14,46 +14,57 @@ // ----------------------------------------------------------------------------- #include "FairOnlineSource.h" + #include "FairLogger.h" -FairOnlineSource::FairOnlineSource() : FairSource(), fUnpackers(new TObjArray()) {} +FairOnlineSource::FairOnlineSource() + : FairSource() + , fUnpackers(new TObjArray()) +{} FairOnlineSource::FairOnlineSource(const FairOnlineSource &source) - : FairSource(source), fUnpackers(new TObjArray(*(source.GetUnpackers()))) {} + : FairSource(source) + , fUnpackers(new TObjArray(*(source.GetUnpackers()))) +{} -FairOnlineSource::~FairOnlineSource() { - fUnpackers->Delete(); - delete fUnpackers; +FairOnlineSource::~FairOnlineSource() +{ + fUnpackers->Delete(); + delete fUnpackers; } -Bool_t FairOnlineSource::InitUnpackers() { - for (Int_t i = 0; i < fUnpackers->GetEntriesFast(); i++) { - if (!((FairUnpack *)fUnpackers->At(i))->Init()) { - return kFALSE; +Bool_t FairOnlineSource::InitUnpackers() +{ + for (Int_t i = 0; i < fUnpackers->GetEntriesFast(); i++) { + if (!((FairUnpack *)fUnpackers->At(i))->Init()) { + return kFALSE; + } } - } - return kTRUE; + return kTRUE; } -Bool_t FairOnlineSource::ReInitUnpackers() { - for (Int_t i = 0; i < fUnpackers->GetEntriesFast(); i++) { - if (!((FairUnpack *)fUnpackers->At(i))->ReInit()) { - return kFALSE; +Bool_t FairOnlineSource::ReInitUnpackers() +{ + for (Int_t i = 0; i < fUnpackers->GetEntriesFast(); i++) { + if (!((FairUnpack *)fUnpackers->At(i))->ReInit()) { + return kFALSE; + } } - } - return kTRUE; + return kTRUE; } -void FairOnlineSource::SetParUnpackers() { +void FairOnlineSource::SetParUnpackers() +{ for (Int_t i = 0; i < fUnpackers->GetEntriesFast(); i++) { ((FairUnpack *)fUnpackers->At(i))->SetParContainers(); } } -void FairOnlineSource::Reset() { - for (Int_t i = 0; i < fUnpackers->GetEntriesFast(); i++) { - ((FairUnpack *)fUnpackers->At(i))->Reset(); - } +void FairOnlineSource::Reset() +{ + for (Int_t i = 0; i < fUnpackers->GetEntriesFast(); i++) { + ((FairUnpack *)fUnpackers->At(i))->Reset(); + } } -ClassImp(FairOnlineSource) +ClassImp(FairOnlineSource); diff --git a/base/source/FairOnlineSource.h b/base/source/FairOnlineSource.h index f5955cce73..2e56f0d8d9 100644 --- a/base/source/FairOnlineSource.h +++ b/base/source/FairOnlineSource.h @@ -17,11 +17,11 @@ #define FAIRONLINESOURCE_H #include "FairSource.h" -#include -#include - #include "FairUnpack.h" +#include +#include + class FairOnlineSource : public FairSource { public: @@ -33,7 +33,7 @@ class FairOnlineSource : public FairSource inline const TObjArray* GetUnpackers() const { return fUnpackers; } virtual Bool_t Init() = 0; - virtual Int_t ReadEvent(UInt_t=0) = 0; + virtual Int_t ReadEvent(UInt_t = 0) = 0; virtual void Close() = 0; virtual void SetParUnpackers(); diff --git a/base/source/FairRemoteSource.cxx b/base/source/FairRemoteSource.cxx index 22b509c197..1bb5625b55 100644 --- a/base/source/FairRemoteSource.cxx +++ b/base/source/FairRemoteSource.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ----------------------------------------------------------------------------- @@ -12,80 +12,76 @@ // ----------------------------------------------------------------------------- #include "FairRemoteSource.h" -#include // usleep - -#include "ptrevmbsdef.h" // MBS data definitions +#include "MRevBuffer.h" +#include "ptrevmbsdef.h" // MBS data definitions #include - -#include "MRevBuffer.h" +#include // usleep FairRemoteSource::FairRemoteSource(char* node) - : FairMbsSource(), - fNode(node), - fSocket(nullptr), - fBuffer(new MRevBuffer(1)), - fREvent(nullptr) -{ -} + : FairMbsSource() + , fNode(node) + , fSocket(nullptr) + , fBuffer(new MRevBuffer(1)) + , fREvent(nullptr) +{} FairRemoteSource::FairRemoteSource(const FairRemoteSource& source) - : FairMbsSource(source), - fNode(const_cast(source.GetNode())), - fSocket(nullptr), - fBuffer(new MRevBuffer(1)), - fREvent(nullptr) -{ -} + : FairMbsSource(source) + , fNode(const_cast(source.GetNode())) + , fSocket(nullptr) + , fBuffer(new MRevBuffer(1)) + , fREvent(nullptr) +{} -FairRemoteSource::~FairRemoteSource() -{ - delete fBuffer; -} +FairRemoteSource::~FairRemoteSource() { delete fBuffer; } Bool_t FairRemoteSource::Init() { - fBuffer->RevStatus(0); - fSocket = fBuffer->RevOpen(fNode, 6003, 0); - fBuffer->RevStatus(0); - if(! fSocket) { - return kFALSE; - } - return kTRUE; + fBuffer->RevStatus(0); + fSocket = fBuffer->RevOpen(fNode, 6003, 0); + fBuffer->RevStatus(0); + if (!fSocket) { + return kFALSE; + } + return kTRUE; } Int_t FairRemoteSource::ReadEvent(UInt_t) { - usleep(10000); - fREvent = fBuffer->RevGet(fSocket, 0, 0); - fBuffer->RevStatus(0); - if(! fREvent) { - return 1; - } + usleep(10000); + fREvent = fBuffer->RevGet(fSocket, 0, 0); + fBuffer->RevStatus(0); + if (!fREvent) { + return 1; + } - // Decode event header - Bool_t result = Unpack(fREvent->GetData(), sizeof(sMbsEv101), -2, -2, -2, -2, -2); + // Decode event header + Bool_t result = Unpack(fREvent->GetData(), sizeof(sMbsEv101), -2, -2, -2, -2, -2); - for(Int_t i = 0; i < fREvent->nSubEvt; i++) { - if(Unpack(fREvent->pSubEvt[i], fREvent->subEvtSize[i], - fREvent->subEvtType[i], fREvent->subEvtSubType[i], - fREvent->subEvtProcId[i], fREvent->subEvtSubCrate[i], - fREvent->subEvtControl[i])) { - result = kTRUE; + for (Int_t i = 0; i < fREvent->nSubEvt; i++) { + if (Unpack(fREvent->pSubEvt[i], + fREvent->subEvtSize[i], + fREvent->subEvtType[i], + fREvent->subEvtSubType[i], + fREvent->subEvtProcId[i], + fREvent->subEvtSubCrate[i], + fREvent->subEvtControl[i])) { + result = kTRUE; + } } - } - if(! result) { - return 2; - } + if (!result) { + return 2; + } - return 0; + return 0; } void FairRemoteSource::Close() { - fBuffer->RevClose(fSocket); - fBuffer->RevStatus(0); + fBuffer->RevClose(fSocket); + fBuffer->RevStatus(0); } -ClassImp(FairRemoteSource) +ClassImp(FairRemoteSource); diff --git a/base/source/FairRemoteSource.h b/base/source/FairRemoteSource.h index 2934d0d3f6..3cbd587c5a 100644 --- a/base/source/FairRemoteSource.h +++ b/base/source/FairRemoteSource.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ----------------------------------------------------------------------------- @@ -29,7 +29,7 @@ class FairRemoteSource : public FairMbsSource virtual ~FairRemoteSource(); virtual Bool_t Init(); - virtual Int_t ReadEvent(UInt_t=0); + virtual Int_t ReadEvent(UInt_t = 0); virtual void Close(); inline const char* GetNode() const { return fNode; } diff --git a/base/source/FairSource.cxx b/base/source/FairSource.cxx index a5687efa5c..bbcf93eab3 100644 --- a/base/source/FairSource.cxx +++ b/base/source/FairSource.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ----------------------------------------------------------------------------- @@ -13,29 +13,26 @@ // ----------------------------------------------------------------------------- #include "FairSource.h" + #include "FairEventHeader.h" FairSource::FairSource() - : TObject() - , fRunId(0) -{ -} + : TObject() + , fRunId(0) +{} FairSource::FairSource(const FairSource& source) - : TObject(source) - , fRunId(source.fRunId) -{ -} + : TObject(source) + , fRunId(source.fRunId) +{} -FairSource::~FairSource() -{ -} +FairSource::~FairSource() {} void FairSource::FillEventHeader(FairEventHeader* eh) { - if (eh) { - eh->SetRunId(fRunId); - } + if (eh) { + eh->SetRunId(fRunId); + } } -ClassImp(FairSource) +ClassImp(FairSource); diff --git a/base/source/FairSource.h b/base/source/FairSource.h index 3036bd0ba4..571b3ce523 100644 --- a/base/source/FairSource.h +++ b/base/source/FairSource.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ----------------------------------------------------------------------------- @@ -15,12 +15,16 @@ #ifndef FAIRSOURCE_H #define FAIRSOURCE_H -#include #include +#include class FairEventHeader; -enum Source_Type {kONLINE, kFILE}; +enum Source_Type +{ + kONLINE, + kFILE +}; class FairSource : public TObject { @@ -30,13 +34,13 @@ class FairSource : public TObject virtual ~FairSource(); virtual Bool_t Init() = 0; - virtual Int_t ReadEvent(UInt_t=0) = 0; + virtual Int_t ReadEvent(UInt_t = 0) = 0; virtual void Close() = 0; virtual void Reset() = 0; - virtual Bool_t ActivateObject(TObject**, const char*) { return kFALSE; } - virtual Bool_t ActivateObjectAny(void **, const std::type_info &, const char*) { return kFALSE; } + virtual Bool_t ActivateObject(TObject**, const char*) { return kFALSE; } + virtual Bool_t ActivateObjectAny(void**, const std::type_info&, const char*) { return kFALSE; } virtual Source_Type GetSourceType() = 0; @@ -47,14 +51,14 @@ class FairSource : public TObject virtual Bool_t ReInitUnpackers() = 0; /**Check the maximum event number we can run to*/ - virtual Int_t CheckMaxEventNo(Int_t=0) {return -1;} + virtual Int_t CheckMaxEventNo(Int_t = 0) { return -1; } /**Read the tree entry on one branch**/ - virtual void ReadBranchEvent(const char*) {return;} - virtual void ReadBranchEvent(const char*, Int_t) {return;} + virtual void ReadBranchEvent(const char*) { return; } + virtual void ReadBranchEvent(const char*, Int_t) { return; } virtual void FillEventHeader(FairEventHeader* feh); void SetRunId(Int_t runId) { fRunId = runId; } - Int_t GetRunId() const { return fRunId; } + Int_t GetRunId() const { return fRunId; } protected: Int_t fRunId; diff --git a/base/source/FairUnpack.cxx b/base/source/FairUnpack.cxx index 010cc7a346..b21c9f759b 100644 --- a/base/source/FairUnpack.cxx +++ b/base/source/FairUnpack.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ----------------------------------------------------------------------------- @@ -14,17 +14,14 @@ #include "FairUnpack.h" FairUnpack::FairUnpack(Short_t type, Short_t subType, Short_t procId, Short_t subCrate, Short_t control) - : TObject(), - fType(type), - fSubType(subType), - fProcId(procId), - fSubCrate(subCrate), - fControl(control) -{ -} + : TObject() + , fType(type) + , fSubType(subType) + , fProcId(procId) + , fSubCrate(subCrate) + , fControl(control) +{} -FairUnpack::~FairUnpack() -{ -} +FairUnpack::~FairUnpack() {} -ClassImp(FairUnpack) +ClassImp(FairUnpack); diff --git a/base/source/FairUnpack.h b/base/source/FairUnpack.h index 048441fe80..a87d36a1dd 100644 --- a/base/source/FairUnpack.h +++ b/base/source/FairUnpack.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ----------------------------------------------------------------------------- @@ -14,7 +14,7 @@ #ifndef FAIRUNPACK_H #define FAIRUNPACK_H -#include // for Int_t, Bool_t, etc +#include // for Int_t, Bool_t, etc #include class FairUnpack : public TObject @@ -26,8 +26,8 @@ class FairUnpack : public TObject virtual Bool_t Init() = 0; virtual Bool_t ReInit() { return kTRUE; } virtual Bool_t DoUnpack(Int_t* data, Int_t size) = 0; - virtual void Reset() = 0; - virtual void SetParContainers() { }; + virtual void Reset() = 0; + virtual void SetParContainers(){}; inline Short_t GetType() const { return fType; } inline Short_t GetSubType() const { return fSubType; } diff --git a/base/source/MRevBuffer.cxx b/base/source/MRevBuffer.cxx index 42940cf093..4b5428575c 100644 --- a/base/source/MRevBuffer.cxx +++ b/base/source/MRevBuffer.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ ////////////////////////////////////////////////////////////////////// @@ -24,26 +24,25 @@ // 19.11.2001, H.G.: increase data buffer dynamically ////////////////////////////////////////////////////////////////////// -#include "MRevBuffer.h" // class definition +#include "MRevBuffer.h" // class definition -#include // for TSocket, etc - -#include // IWYU pragma: keep -#include // IWYU pragma: keep -#include // IWYU pragma: keep -#include // IWYU pragma: keep +#include // for TSocket, etc +#include // IWYU pragma: keep +#include // IWYU pragma: keep +#include // IWYU pragma: keep +#include // IWYU pragma: keep #ifdef Linux -#include // IWYU pragma: keep -#include // IWYU pragma: keep -#else // AIX -#include // IWYU pragma: keep -#include // IWYU pragma: keep -#include // IWYU pragma: keep +#include // IWYU pragma: keep +#include // IWYU pragma: keep +#else // AIX +#include // IWYU pragma: keep +#include // IWYU pragma: keep +#include // IWYU pragma: keep #endif -#include "ptrevcomm.h" // communication structure -#include "ptrevmbsdef.h" // MBS data definitions +#include "ptrevcomm.h" // communication structure +#include "ptrevmbsdef.h" // MBS data definitions // IWYU pragma: no_include // IWYU pragma: no_include @@ -51,55 +50,56 @@ #include "FairLogger.h" -ClassImp(MRevBuffer) -ClassImp(REvent) +ClassImp(MRevBuffer); +ClassImp(REvent); extern "C" { - long swaplw( int*, int, int); // swap data - void exitCli(int); // handle CTL C - int rclose(int*, int); // close connection to server + long swaplw(int*, int, int); // swap data + void exitCli(int); // handle CTL C + int rclose(int*, int); // close connection to server } #ifdef Linux -struct timeval { - long tv_sec; - long tv_usec; +struct timeval +{ + long tv_sec; + long tv_usec; }; #endif -int iTimeOut; // needed in exitCli to handle CTL C -int imySig = 0; // needed in exitCli to handle CTL C -int iOutMode = 0; // needed in exitCli to handle CTL C +int iTimeOut; // needed in exitCli to handle CTL C +int imySig = 0; // needed in exitCli to handle CTL C +int iOutMode = 0; // needed in exitCli to handle CTL C MRevBuffer::MRevBuffer(Int_t iMode) - : TObject(), - pTSocket(nullptr), - iSocket(0), - iBufNo1(0), - iBufNo2(0), - iDebug(iMode), - iSwap(0), - iStatus(1), - iBufSizeAlloc(512000), - iBufSize(0), - iBufNo(0), - iFragBegin(0), - iFragConc(0), - iFragBeginIgn(0), - iFragEndIgn(0), - iHeadPar(0), - iEvtMax(0), - iEvtNo(0), - iEvtRel(0), - iEvtBuf(0), - iEvtPar(0), - piBuf(new int [iBufSizeAlloc/sizeof(int)+1]), - piNextEvt(nullptr), - pEvt(new REvent()) + : TObject() + , pTSocket(nullptr) + , iSocket(0) + , iBufNo1(0) + , iBufNo2(0) + , iDebug(iMode) + , iSwap(0) + , iStatus(1) + , iBufSizeAlloc(512000) + , iBufSize(0) + , iBufNo(0) + , iFragBegin(0) + , iFragConc(0) + , iFragBeginIgn(0) + , iFragEndIgn(0) + , iHeadPar(0) + , iEvtMax(0) + , iEvtNo(0) + , iEvtRel(0) + , iEvtBuf(0) + , iEvtPar(0) + , piBuf(new int[iBufSizeAlloc / sizeof(int) + 1]) + , piNextEvt(nullptr) + , pEvt(new REvent()) { -// iStatus = 1; // server not yet connected - /* + // iStatus = 1; // server not yet connected + /* iSwap = 0; iSocket = 0; iEvtRel = 0; @@ -107,616 +107,613 @@ MRevBuffer::MRevBuffer(Int_t iMode) iBufSize = 0; */ - signal(SIGINT, exitCli); // from now catch CTL C - -// iDebug = iMode; - iOutMode = iMode; - if (iDebug == 1) { - LOG(debug) << "-I- client runs in debug mode (1)"; - } else if (iDebug == 2) - LOG(debug) << "-I- client shows buffer numbers and select/receive (mode 2)"; - else if (iDebug == 3) { - LOG(debug) << "-I- client shows buffer numbers (mode 3)"; - } else if (iDebug == 5) { - LOG(debug) << "-I- client shows event parameters (mode 5)"; - } - - if (iDebug == 1) { - LOG(debug) << " check ENDIAN, "; + signal(SIGINT, exitCli); // from now catch CTL C + + // iDebug = iMode; + iOutMode = iMode; + if (iDebug == 1) { + LOG(debug) << "-I- client runs in debug mode (1)"; + } else if (iDebug == 2) + LOG(debug) << "-I- client shows buffer numbers and select/receive (mode 2)"; + else if (iDebug == 3) { + LOG(debug) << "-I- client shows buffer numbers (mode 3)"; + } else if (iDebug == 5) { + LOG(debug) << "-I- client shows event parameters (mode 5)"; + } + + if (iDebug == 1) { + LOG(debug) << " check ENDIAN, "; #ifdef _AIX - LOG(debug) << " should be BIG_ENDIAN: "; + LOG(debug) << " should be BIG_ENDIAN: "; #endif #ifdef Linux - LOG(debug) << " should be LITTLE_ENDIAN: "; + LOG(debug) << " should be LITTLE_ENDIAN: "; #endif #ifdef BIG__ENDIAN - LOG(debug) << " BIG_ENDIAN"; + LOG(debug) << " BIG_ENDIAN"; #else - LOG(debug) << " LITTLE_ENDIAN"; + LOG(debug) << " LITTLE_ENDIAN"; #endif - } + } - // iBufSizeAlloc = 16384; - // piBuf = new int [iBufSizeAlloc/sizeof(int)+1]; // 16k buffer + len - if (iDebug == 1) - LOG(debug) << "-D- buffer allocated (" << iBufSizeAlloc+sizeof(int) - << " byte)"; + // iBufSizeAlloc = 16384; + // piBuf = new int [iBufSizeAlloc/sizeof(int)+1]; // 16k buffer + len + if (iDebug == 1) + LOG(debug) << "-D- buffer allocated (" << iBufSizeAlloc + sizeof(int) << " byte)"; - // REvent* pev = new REvent(); // create event (once) - // pEvt = pev; // keep pointer in class MRevBuffer + // REvent* pev = new REvent(); // create event (once) + // pEvt = pev; // keep pointer in class MRevBuffer - // LOG(info) << " MRevBuffer() executed"; + // LOG(info) << " MRevBuffer() executed"; -} // constructor +} // constructor MRevBuffer::~MRevBuffer() { - // LOG(info) << " ~MRevBuffer() ..."; - delete [] piBuf; - piNextEvt = 0; - pEvt->~REvent(); - // LOG(info) << " ~MRevBuffer() executed"; + // LOG(info) << " ~MRevBuffer() ..."; + delete[] piBuf; + piNextEvt = 0; + pEvt->~REvent(); + // LOG(info) << " ~MRevBuffer() executed"; -} // destructor +} // destructor -TSocket* MRevBuffer::RevOpen ( char* pNode, Int_t iPort, Int_t iEvent) +TSocket* MRevBuffer::RevOpen(char* pNode, Int_t iPort, Int_t iEvent) { - if (iEvent < 0) { - LOG(info) << "-E- number of requested events (" << iEvent - << ") invalid"; - return(0); - } - if (iEvent == 0) { - iEvent = 2000000000; // nearly unlimited - LOG(info) << "-I- unlimited no. of MBS events requested - break with 'CTL C'"; - } - - if (iPort == 6001) { - LOG(info) << "-E- old event server (port no. 6001) running on DAQ frontend not yet supported"; - LOG(info) << " use stream server (port no. 6002) and remote event server (port no. 6003)"; - return(0); - } - if (iPort == 0) { iPort = 6003; } // default MBS remote event server - - iEvtMax = iEvent; - iEvtNo = 0; - iBufNo = 0; - iBufNo1 = 0; - iBufNo2 = 0; - iFragConc = 0; - iFragBegin = 0; - iFragBeginIgn = 0; - iFragEndIgn = 0; - - if (!iSocket) { - iEvtNo = -1; // initialization (info buffer) required - LOG(info) << "-I- open connection to server " << pNode - << ":" << iPort; - - pTSocket = new TSocket(pNode, iPort); - if ( !pTSocket->IsValid() ) { - LOG(info) << "-E- open connection to server " << pNode - << " failed"; - return(0); + if (iEvent < 0) { + LOG(info) << "-E- number of requested events (" << iEvent << ") invalid"; + return (0); + } + if (iEvent == 0) { + iEvent = 2000000000; // nearly unlimited + LOG(info) << "-I- unlimited no. of MBS events requested - break with 'CTL C'"; } - LOG(info) << " connection to server " << pNode - << ":" << iPort << " okay"; - iSocket = pTSocket->GetDescriptor(); - imySig = iSocket; - if (iDebug == 1) { - LOG(debug) << " socket " << iSocket; + if (iPort == 6001) { + LOG(info) << "-E- old event server (port no. 6001) running on DAQ frontend not yet supported"; + LOG(info) << " use stream server (port no. 6002) and remote event server (port no. 6003)"; + return (0); } + if (iPort == 0) { + iPort = 6003; + } // default MBS remote event server + + iEvtMax = iEvent; + iEvtNo = 0; + iBufNo = 0; + iBufNo1 = 0; + iBufNo2 = 0; + iFragConc = 0; + iFragBegin = 0; + iFragBeginIgn = 0; + iFragEndIgn = 0; + + if (!iSocket) { + iEvtNo = -1; // initialization (info buffer) required + LOG(info) << "-I- open connection to server " << pNode << ":" << iPort; + + pTSocket = new TSocket(pNode, iPort); + if (!pTSocket->IsValid()) { + LOG(info) << "-E- open connection to server " << pNode << " failed"; + return (0); + } + LOG(info) << " connection to server " << pNode << ":" << iPort << " okay"; - } else if (iDebug == 1) { - LOG(debug) << "-D- socket " << iSocket; - } + iSocket = pTSocket->GetDescriptor(); + imySig = iSocket; + if (iDebug == 1) { + LOG(debug) << " socket " << iSocket; + } - iStatus = 2; // server connected - return(pTSocket); + } else if (iDebug == 1) { + LOG(debug) << "-D- socket " << iSocket; + } -} // RevOpen + iStatus = 2; // server connected + return (pTSocket); + +} // RevOpen Int_t* MRevBuffer::RevGetI(TSocket* pSocket, Int_t iFlush) { - Int_t* piEvent; - REvent* pEvent; + Int_t* piEvent; + REvent* pEvent; - pEvent = RevGet(pSocket, iFlush, 0); - if (pEvent) { piEvent = piNextEvt; } - else { piEvent = 0; } - return piEvent; + pEvent = RevGet(pSocket, iFlush, 0); + if (pEvent) { + piEvent = piNextEvt; + } else { + piEvent = 0; + } + return piEvent; -} // RevGetI +} // RevGetI REvent* MRevBuffer::RevGet(TSocket* pSocket, Int_t iFlush, Int_t) { - Int_t iint = sizeof(int); - Int_t ii; - Int_t ilen, iselen, iselen1, ielen, inew = 0; - - Short_t* pshort; - - Char_t cMsg[128] = ""; - Char_t* pcBuf; - Int_t iSize, iRC; - - Int_t iError = 0; - Int_t iRetry; - Int_t iRetryMax = 1000; - Int_t iRetryFirst; - Int_t iRetryRecv = 0; // count retries of recv call - Int_t iRetryRecvLim = 1; // max. no. of succeeding retries - - Int_t* piComm; - srevComm sComm; - Int_t iCommSize = sizeof(sComm); // size comm. buffer (byte) - - Int_t* piInfo; - //srevInfo sInfo = {.iSize=0, .iMode=1, .iHeadPar=0 , .iTimeOut=0 }; - /** To support C++98 we have to put the initializers in the right order without the names*/ - srevInfo sInfo = {0, 1, 0 ,0 }; - Int_t iInfoSize = sizeof(sInfo); // size info buffer (byte) - -// Int_t iHeadPar = 12; // no. of params in MBS buffer header - iHeadPar = 12; // no. of params in MBS buffer header - Int_t iBufNoServ; // buffer no. sent from server - short* psNextEvt; - Int_t iHead[2]; - - sMbsEv101 sEvtHead, *pEvtHead; // header event 10.1 - pEvtHead = &sEvtHead; - sMbsSev101 sSEvtHead, *pSEvtHead; // header event 10.1 - pSEvtHead = &sSEvtHead; - sMbsBufFrag sFrag, *pFrag; // fragmented event flags - pFrag = &sFrag; - - if (iEvtNo >= iEvtMax) { goto gEndGet; } - - piComm = &(sComm.iSize); // communication buffer - sComm.iSize = htonl(iCommSize-iint); // size of data following - sComm.iMode = htonl(1); // required: get events - sComm.iIdent = 1; // required: tell endian type - sComm.iBufRequ = htonl(1); // send one buffer - - // initialize communication with server - if (iEvtNo == -1) { // initialize communication with server - if (iDebug == 1) - LOG(debug) << "-D- commbuf (data size " << ntohl(sComm.iSize) - << " byte): mode(1) " << ntohl(sComm.iMode) - << ", request " << ntohl(sComm.iBufRequ) - << " event buffer(s)"; - - // request event buffer from server - ilen = pSocket->SendRaw(piComm, iCommSize, kDefault); - if (ilen < 0) { - LOG(info) << "-E- sending request for events to server, rc = " - << ilen; - iError = 1; - goto gEndGet; - } - - if (iDebug == 1) - LOG(debug) << " communication buffer sent (request info buffer) "; - - // receive info buffer from server - piInfo = &(sInfo.iSize); - ilen = pSocket->RecvRaw(piInfo, iInfoSize, kDefault); - if (ilen < 0) { - LOG(info) << "-E- receiving info buffer from server, rc = " - << ilen; - iError = 1; - goto gEndGet; - } - - iHeadPar = ntohl(sInfo.iHeadPar); - iTimeOut = ntohl(sInfo.iTimeOut); - if (iDebug == 1) { - LOG(debug) << "-D- info buffer received:"; - LOG(debug) << " size data " << ntohl(sInfo.iSize) - << ", mode (1) " << ntohl(sInfo.iMode) - << ", header parms " << iHeadPar - << ", timeout " << iTimeOut; + Int_t iint = sizeof(int); + Int_t ii; + Int_t ilen, iselen, iselen1, ielen, inew = 0; + + Short_t* pshort; + + Char_t cMsg[128] = ""; + Char_t* pcBuf; + Int_t iSize, iRC; + + Int_t iError = 0; + Int_t iRetry; + Int_t iRetryMax = 1000; + Int_t iRetryFirst; + Int_t iRetryRecv = 0; // count retries of recv call + Int_t iRetryRecvLim = 1; // max. no. of succeeding retries + + Int_t* piComm; + srevComm sComm; + Int_t iCommSize = sizeof(sComm); // size comm. buffer (byte) + + Int_t* piInfo; + // srevInfo sInfo = {.iSize=0, .iMode=1, .iHeadPar=0 , .iTimeOut=0 }; + /** To support C++98 we have to put the initializers in the right order without the names*/ + srevInfo sInfo = {0, 1, 0, 0}; + Int_t iInfoSize = sizeof(sInfo); // size info buffer (byte) + + // Int_t iHeadPar = 12; // no. of params in MBS buffer header + iHeadPar = 12; // no. of params in MBS buffer header + Int_t iBufNoServ; // buffer no. sent from server + short* psNextEvt; + Int_t iHead[2]; + + sMbsEv101 sEvtHead, *pEvtHead; // header event 10.1 + pEvtHead = &sEvtHead; + sMbsSev101 sSEvtHead, *pSEvtHead; // header event 10.1 + pSEvtHead = &sSEvtHead; + sMbsBufFrag sFrag, *pFrag; // fragmented event flags + pFrag = &sFrag; + + if (iEvtNo >= iEvtMax) { + goto gEndGet; } - if ( (ntohl(sInfo.iMode) != 1) || - ( static_cast(ntohl(sInfo.iSize)) != iInfoSize-iint) ) { - LOG(info) << "-E- invalid info buffer received: "; - LOG(info) << " size data ( " << iInfoSize-iint - << ") " << ntohl(sInfo.iSize) - << ", mode (1) " << ntohl(sInfo.iMode) - << ", header parms " << iHeadPar - << ", timeout " << iTimeOut; - iError = 1; - goto gEndGet; - } + piComm = &(sComm.iSize); // communication buffer + sComm.iSize = htonl(iCommSize - iint); // size of data following + sComm.iMode = htonl(1); // required: get events + sComm.iIdent = 1; // required: tell endian type + sComm.iBufRequ = htonl(1); // send one buffer - iEvtNo = 0; // initilization done - inew = 1; // request new buffer + // initialize communication with server + if (iEvtNo == -1) { // initialize communication with server + if (iDebug == 1) + LOG(debug) << "-D- commbuf (data size " << ntohl(sComm.iSize) << " byte): mode(1) " << ntohl(sComm.iMode) + << ", request " << ntohl(sComm.iBufRequ) << " event buffer(s)"; - } // (iEvtNo == -1) - else { - if (iFlush) { - inew = 1; // request new buffer - if (iDebug == 1) { - LOG(debug) << "-D- skip current buffer"; - } - } else { - if (iEvtNo >= 0) { - // refresh some buffer infos not stored in class data - pFrag = reinterpret_cast(&piBuf[3]); + // request event buffer from server + ilen = pSocket->SendRaw(piComm, iCommSize, kDefault); + if (ilen < 0) { + LOG(info) << "-E- sending request for events to server, rc = " << ilen; + iError = 1; + goto gEndGet; + } - // check if new buffer needed - ii = 0; // count buffer header - if (pFrag->cBuf_fragBegin) { ii++; } - if (pFrag->cBuf_fragEnd) { ii++; } - - if (iEvtRel+ii >= iEvtBuf) { - if (iDebug == 1) { - LOG(debug) << "-D- request new buffer"; - } - inew = 1; - if (iDebug == -1) { - piNextEvt += iEvtPar; // skip previous event - LOG(debug) << "-D- next 40 2byte-words of buffer:"; - psNextEvt = reinterpret_cast(piNextEvt); - for (Int_t iii=0; iii<40; iii++) { - LOG(debug) << " " << iii+1 << ": " << psNextEvt[iii]; - } - } - } else { inew = 0; } + if (iDebug == 1) + LOG(debug) << " communication buffer sent (request info buffer) "; - } // (iEvtNo > 0) - } // (!iFlush) - } // (iEvtNo != -1) + // receive info buffer from server + piInfo = &(sInfo.iSize); + ilen = pSocket->RecvRaw(piInfo, iInfoSize, kDefault); + if (ilen < 0) { + LOG(info) << "-E- receiving info buffer from server, rc = " << ilen; + iError = 1; + goto gEndGet; + } - // request new buffer - if (inew) { - iEvtRel = 0; - iRetry = 0; - iRetryFirst = 1; - if (imySig == -1) { - sComm.iBufRequ = htonl(0); // signal finish to server - } + iHeadPar = ntohl(sInfo.iHeadPar); + iTimeOut = ntohl(sInfo.iTimeOut); + if (iDebug == 1) { + LOG(debug) << "-D- info buffer received:"; + LOG(debug) << " size data " << ntohl(sInfo.iSize) << ", mode (1) " << ntohl(sInfo.iMode) + << ", header parms " << iHeadPar << ", timeout " << iTimeOut; + } - // request next buffer or finish - ilen = pSocket->SendRaw(piComm, iCommSize, kDefault); - if (ilen < 0) { - LOG(info) << "-E- sending request for buffer " << iBufNo+1 - << " to server, rc = " << ilen; - iError = 1; - goto gEndGet; - } + if ((ntohl(sInfo.iMode) != 1) || (static_cast(ntohl(sInfo.iSize)) != iInfoSize - iint)) { + LOG(info) << "-E- invalid info buffer received: "; + LOG(info) << " size data ( " << iInfoSize - iint << ") " << ntohl(sInfo.iSize) << ", mode (1) " + << ntohl(sInfo.iMode) << ", header parms " << iHeadPar << ", timeout " << iTimeOut; + iError = 1; + goto gEndGet; + } - if (imySig == -1) { goto gEndGet; } + iEvtNo = 0; // initilization done + inew = 1; // request new buffer - if (iDebug == 1) - LOG(debug) << "-D- communication buffer sent (request next buffer) "; - -gRetryLen: - // get size of data following - piBuf[0] = -1; // enables receive check - iSize = iint; - pcBuf = reinterpret_cast(piBuf); - while(iSize > 0) { - if ( (imySig == -1) && (iDebug) ) { - LOG(debug) << " CTL C detected (before recv len)"; - } -gNextRecvL: - iRC = recv(iSocket, pcBuf, iSize, 0); - if (iRC < 0) { + } // (iEvtNo == -1) + else { + if (iFlush) { + inew = 1; // request new buffer + if (iDebug == 1) { + LOG(debug) << "-D- skip current buffer"; + } + } else { + if (iEvtNo >= 0) { + // refresh some buffer infos not stored in class data + pFrag = reinterpret_cast(&piBuf[3]); + + // check if new buffer needed + ii = 0; // count buffer header + if (pFrag->cBuf_fragBegin) { + ii++; + } + if (pFrag->cBuf_fragEnd) { + ii++; + } + + if (iEvtRel + ii >= iEvtBuf) { + if (iDebug == 1) { + LOG(debug) << "-D- request new buffer"; + } + inew = 1; + if (iDebug == -1) { + piNextEvt += iEvtPar; // skip previous event + LOG(debug) << "-D- next 40 2byte-words of buffer:"; + psNextEvt = reinterpret_cast(piNextEvt); + for (Int_t iii = 0; iii < 40; iii++) { + LOG(debug) << " " << iii + 1 << ": " << psNextEvt[iii]; + } + } + } else { + inew = 0; + } + + } // (iEvtNo > 0) + } // (!iFlush) + } // (iEvtNo != -1) + + // request new buffer + if (inew) { + iEvtRel = 0; + iRetry = 0; + iRetryFirst = 1; if (imySig == -1) { - if (iDebug) { - sprintf(cMsg, - "\n-E- receiving data length from server"); - perror(cMsg); - LOG(debug) << " CTL C detected (during recv len)" -; - } - goto gNextRecvL; - } else { // a real problem - sprintf(cMsg, "\n-E- receiving data length from server"); - perror(cMsg); - if (iDebug) { LOG(debug) << " retry"; } - - iRetryRecv++; // count no. of retries to limit them - if (iRetryRecv > iRetryRecvLim) { // avoid infinite loop + sComm.iBufRequ = htonl(0); // signal finish to server + } + + // request next buffer or finish + ilen = pSocket->SendRaw(piComm, iCommSize, kDefault); + if (ilen < 0) { + LOG(info) << "-E- sending request for buffer " << iBufNo + 1 << " to server, rc = " << ilen; iError = 1; goto gEndGet; - } else { goto gNextRecvL; } } - } - if ( iRC == 0 ) { - if ( (iDebug == 2) || (iDebug == 3) ) { - LOG(debug) << "\n"; + + if (imySig == -1) { + goto gEndGet; } - LOG(info) << "-E- receiving data length: connection closed by server" -; - iError = 1; - goto gEndGet; - } - iRetryRecv = 0; - iSize -= iRC; - pcBuf += iRC; + if (iDebug == 1) + LOG(debug) << "-D- communication buffer sent (request next buffer) "; + + gRetryLen: + // get size of data following + piBuf[0] = -1; // enables receive check + iSize = iint; + pcBuf = reinterpret_cast(piBuf); + while (iSize > 0) { + if ((imySig == -1) && (iDebug)) { + LOG(debug) << " CTL C detected (before recv len)"; + } + gNextRecvL: + iRC = recv(iSocket, pcBuf, iSize, 0); + if (iRC < 0) { + if (imySig == -1) { + if (iDebug) { + sprintf(cMsg, "\n-E- receiving data length from server"); + perror(cMsg); + LOG(debug) << " CTL C detected (during recv len)"; + } + goto gNextRecvL; + } else { // a real problem + sprintf(cMsg, "\n-E- receiving data length from server"); + perror(cMsg); + if (iDebug) { + LOG(debug) << " retry"; + } + + iRetryRecv++; // count no. of retries to limit them + if (iRetryRecv > iRetryRecvLim) { // avoid infinite loop + iError = 1; + goto gEndGet; + } else { + goto gNextRecvL; + } + } + } + if (iRC == 0) { + if ((iDebug == 2) || (iDebug == 3)) { + LOG(debug) << "\n"; + } + LOG(info) << "-E- receiving data length: connection closed by server"; + iError = 1; + goto gEndGet; + } - } /* while(iSize > 0) */ + iRetryRecv = 0; + iSize -= iRC; + pcBuf += iRC; - if (iDebug == 2) { - printf("Rl:"); - fflush(stdout); - } + } /* while(iSize > 0) */ - if ( (imySig == -1) && (iDebug) ) { - LOG(debug) << " CTL C detected (after recv len)"; - } + if (iDebug == 2) { + printf("Rl:"); + fflush(stdout); + } - iBufSize = ntohl(piBuf[0]); - if (iDebug == 1) { - LOG(debug) << " data size received: " << iBufSize; - } + if ((imySig == -1) && (iDebug)) { + LOG(debug) << " CTL C detected (after recv len)"; + } - if (iBufSize <= 0) { - if (iBufSize == 0) { - if (iDebug) { - LOG(debug) << "\n"; + iBufSize = ntohl(piBuf[0]); + if (iDebug == 1) { + LOG(debug) << " data size received: " << iBufSize; } - LOG(info) << "-W- server closed connection"; - LOG(info) << " " << iEvtNo << " of " << iEvtMax - << " events received"; - iError = 1; - goto gEndGet; - } - - if (iBufSize == -1) { - if (iRetryFirst) { - LOG(info) << "\n" << "-E- no data length received: "; - iRetryFirst = 0; - } - iRetry++; - if (iRetry > iRetryMax) { - LOG(info) << iRetryMax << "times"; - iError = 1; - goto gEndGet; - } - goto gRetryLen; - } else { - LOG(info) << "\n" << "-E- invalid data length received: " - << iBufSize; - iError = 1; - } - - goto gEndGet; - } - if (iRetry) { - LOG(info) << iRetry << "times"; - } - // increase data buffer, if necessary - if (iBufSize+iint > iBufSizeAlloc) { - delete [] piBuf; - iBufSizeAlloc = iBufSize+iint; - // new total buffer size (including length field) - piBuf = new int [iBufSizeAlloc/iint]; - piBuf[0] = iBufSize; - // keep sent buffer size (without length field) - if (iDebug == 1) - LOG(debug) << "-I- total buffer increased to " - << iBufSizeAlloc << " byte"; - } + if (iBufSize <= 0) { + if (iBufSize == 0) { + if (iDebug) { + LOG(debug) << "\n"; + } + LOG(info) << "-W- server closed connection"; + LOG(info) << " " << iEvtNo << " of " << iEvtMax << " events received"; + iError = 1; + goto gEndGet; + } + + if (iBufSize == -1) { + if (iRetryFirst) { + LOG(info) << "\n" + << "-E- no data length received: "; + iRetryFirst = 0; + } + iRetry++; + if (iRetry > iRetryMax) { + LOG(info) << iRetryMax << "times"; + iError = 1; + goto gEndGet; + } + goto gRetryLen; + } else { + LOG(info) << "\n" + << "-E- invalid data length received: " << iBufSize; + iError = 1; + } - // get event buffer without length field - piBuf[1] = -1; // enables receive check - iSize = iBufSize; - pcBuf = reinterpret_cast(&(piBuf[1])); - while(iSize > 0) { - if ( (imySig == -1) && (iDebug) ) { - LOG(debug) << " CTL C detected (before recv data)"; - } -gNextRecvD: - iRC = recv(iSocket, pcBuf, iSize, 0); - if (iRC < 0) { - if (imySig == -1) { - if (iDebug) { - sprintf(cMsg, "\n-E- receiving data from server"); - perror(cMsg); - LOG(debug) << " CTL C detected (during recv data)"; - } - goto gNextRecvD; - } else { // a real problem - sprintf(cMsg, "\n-E- receiving data from server"); - perror(cMsg); - - iRetryRecv++; // count no. of retries to limit them - if (iRetryRecv > iRetryRecvLim) { // avoid infinite loop - iError = 1; goto gEndGet; - } else { goto gNextRecvD; } } - } - if ( iRC == 0 ) { - if ( (iDebug == 2) || (iDebug == 3) ) { - LOG(debug) << "\n"; + if (iRetry) { + LOG(info) << iRetry << "times"; } - LOG(info) << "-E- receiving data: connection closed by server" -; - iError = 1; - goto gEndGet; - } - - iRetryRecv = 0; - iSize -= iRC; - pcBuf += iRC; - - } /* while(iSize > 0) */ - - if (iDebug == 2) { - printf("Rd:"); - fflush(stdout); - } - - if (imySig == -1) { - if (iDebug) { - LOG(debug) << " CTL C detected (after recv data)"; - } - goto gEndGet; - } - // test for dummy buffer (no DAQ events available) - if ( iBufSize == (sizeof(sptrevDummy)-sizeof(int)) ) { - iBufNoServ = ntohl(piBuf[1]); - iEvtBuf = ntohl(piBuf[2]); - if (iEvtBuf == 0) { - if (iDebug == 1) - printf(" dummy buffer no. %d, %d events\n", - iBufNoServ, iEvtBuf); - if (iDebug == 3) { LOG(info) << "\n"; } - LOG(debug) << "*** connection to remote event server okay, but currently no DAQ events (" - << iBufNoServ << ")"; - iStatus = 3; - goto gRetryLen; - } else { - LOG(info) << "-E- invalid event number in dummy buffer no. " - << iBufNoServ << ": " - << iEvtBuf << " (expected: 0)"; - iError = 1; - goto gEndGet; - } - } - - if (!iSwap) { - if (piBuf[9] != 1) { iSwap = 1; } - } + // increase data buffer, if necessary + if (iBufSize + iint > iBufSizeAlloc) { + delete[] piBuf; + iBufSizeAlloc = iBufSize + iint; + // new total buffer size (including length field) + piBuf = new int[iBufSizeAlloc / iint]; + piBuf[0] = iBufSize; + // keep sent buffer size (without length field) + if (iDebug == 1) + LOG(debug) << "-I- total buffer increased to " << iBufSizeAlloc << " byte"; + } -// Long_t lRC; + // get event buffer without length field + piBuf[1] = -1; // enables receive check + iSize = iBufSize; + pcBuf = reinterpret_cast(&(piBuf[1])); + while (iSize > 0) { + if ((imySig == -1) && (iDebug)) { + LOG(debug) << " CTL C detected (before recv data)"; + } + gNextRecvD: + iRC = recv(iSocket, pcBuf, iSize, 0); + if (iRC < 0) { + if (imySig == -1) { + if (iDebug) { + sprintf(cMsg, "\n-E- receiving data from server"); + perror(cMsg); + LOG(debug) << " CTL C detected (during recv data)"; + } + goto gNextRecvD; + } else { // a real problem + sprintf(cMsg, "\n-E- receiving data from server"); + perror(cMsg); + + iRetryRecv++; // count no. of retries to limit them + if (iRetryRecv > iRetryRecvLim) { // avoid infinite loop + iError = 1; + goto gEndGet; + } else { + goto gNextRecvD; + } + } + } + if (iRC == 0) { + if ((iDebug == 2) || (iDebug == 3)) { + LOG(debug) << "\n"; + } + LOG(info) << "-E- receiving data: connection closed by server"; + iError = 1; + goto gEndGet; + } - /* swap MBS buffer */ - if (iSwap) { -// lRC = swaplw( &piBuf[1], iBufSize/iint, 0); - swaplw( &piBuf[1], iBufSize/iint, 0); - if ( (iBufNo == 0) && (iDebug) ) { - LOG(debug) << " Event data swapped"; - } - } + iRetryRecv = 0; + iSize -= iRC; + pcBuf += iRC; - iBufNo++; - iBufNoServ = piBuf[4]; - iEvtBuf = piBuf[5]; // no. of events in current buffer - - if (iEvtNo == 0) { - iBufNo = 1; // restart counting - iBufNo1 = iBufNoServ; // keep first buffer no. - iFragBegin = 0; - iFragBeginIgn = 0; - iFragEndIgn = 0; - iFragConc = 0; - } - iBufNo2 = iBufNoServ; // keep last buffer no. + } /* while(iSize > 0) */ - if (iDebug >= 2) { - printf("%d:", iBufNoServ); - fflush(stdout); - } + if (iDebug == 2) { + printf("Rd:"); + fflush(stdout); + } - pFrag = reinterpret_cast(&piBuf[3]); - if (iDebug == 1) { - LOG(debug) << "\n" << "buffer " << iBufNo - << " (" << iBufNoServ << "): " - << " size " - << iBufSize << " byte"; - if (pFrag->cBuf_fragBegin) { - LOG(debug) << " last event fragment"; - } - if (pFrag->cBuf_fragEnd) { - LOG(debug) << " first event fragment"; - } - LOG(debug) << " buffer contains " << iEvtBuf << " elements" -; - } + if (imySig == -1) { + if (iDebug) { + LOG(debug) << " CTL C detected (after recv data)"; + } + goto gEndGet; + } - if (pFrag->cBuf_fragEnd) { - iFragEndIgn++; - if ( (iEvtNo > 0) && (iFragBegin) ) { - iFragConc++; - } - } + // test for dummy buffer (no DAQ events available) + if (iBufSize == (sizeof(sptrevDummy) - sizeof(int))) { + iBufNoServ = ntohl(piBuf[1]); + iEvtBuf = ntohl(piBuf[2]); + if (iEvtBuf == 0) { + if (iDebug == 1) + printf(" dummy buffer no. %d, %d events\n", iBufNoServ, iEvtBuf); + if (iDebug == 3) { + LOG(info) << "\n"; + } + LOG(debug) << "*** connection to remote event server okay, but currently no DAQ events (" << iBufNoServ + << ")"; + iStatus = 3; + goto gRetryLen; + } else { + LOG(info) << "-E- invalid event number in dummy buffer no. " << iBufNoServ << ": " << iEvtBuf + << " (expected: 0)"; + iError = 1; + goto gEndGet; + } + } - if (pFrag->cBuf_fragBegin) { - iFragBegin = 1; // keep info for next buffer - iFragBeginIgn++; - } + if (!iSwap) { + if (piBuf[9] != 1) { + iSwap = 1; + } + } - if (iDebug == -1) { - LOG(debug) << "-D- first 50 2byte-words of buffer:"; - psNextEvt = reinterpret_cast(&piBuf[1]); - for (Int_t iii=0; iii<50; iii++) { - LOG(debug) << " " << iii+1 << ": " << psNextEvt[iii]; - } - } + // Long_t lRC; - iEvtRel = 1; // first event in buffer - piNextEvt = piBuf + iHeadPar+1; // ptr first element in buffer - iEvtPar = piNextEvt[0]/2 + 2; // no. of parameters new event + /* swap MBS buffer */ + if (iSwap) { + // lRC = swaplw( &piBuf[1], iBufSize/iint, 0); + swaplw(&piBuf[1], iBufSize / iint, 0); + if ((iBufNo == 0) && (iDebug)) { + LOG(debug) << " Event data swapped"; + } + } - if (pFrag->cBuf_fragEnd) { - piNextEvt += iEvtPar; // skip fragment end - iEvtPar = piNextEvt[0]/2 + 2; // no. of parameters new event - } + iBufNo++; + iBufNoServ = piBuf[4]; + iEvtBuf = piBuf[5]; // no. of events in current buffer + + if (iEvtNo == 0) { + iBufNo = 1; // restart counting + iBufNo1 = iBufNoServ; // keep first buffer no. + iFragBegin = 0; + iFragBeginIgn = 0; + iFragEndIgn = 0; + iFragConc = 0; + } + iBufNo2 = iBufNoServ; // keep last buffer no. - } // new buffer - else { - iEvtRel++; // event no. in buffer - piNextEvt += iEvtPar; // skip previous event - iEvtPar = piNextEvt[0]/2 + 2; // no. of parameters new event + if (iDebug >= 2) { + printf("%d:", iBufNoServ); + fflush(stdout); + } - // also if starting with current buffer: keep first buffer no. - if (iEvtNo == 0) { - iBufNo = 1; // restart counting - iBufNoServ = piBuf[4]; - iBufNo1 = iBufNoServ; + pFrag = reinterpret_cast(&piBuf[3]); + if (iDebug == 1) { + LOG(debug) << "\n" + << "buffer " << iBufNo << " (" << iBufNoServ << "): " + << " size " << iBufSize << " byte"; + if (pFrag->cBuf_fragBegin) { + LOG(debug) << " last event fragment"; + } + if (pFrag->cBuf_fragEnd) { + LOG(debug) << " first event fragment"; + } + LOG(debug) << " buffer contains " << iEvtBuf << " elements"; + } - iFragBegin = 0; - iFragBeginIgn = 0; - iFragEndIgn = 0; - iFragConc = 0; - pFrag = reinterpret_cast(&piBuf[3]); - if (pFrag->cBuf_fragBegin) { - iFragBegin = 1; // keep info for next buffer - iFragBeginIgn++; - } - if (pFrag->cBuf_fragEnd) { iFragEndIgn++; } + if (pFrag->cBuf_fragEnd) { + iFragEndIgn++; + if ((iEvtNo > 0) && (iFragBegin)) { + iFragConc++; + } + } - } // (iEvtNo == 0) - } // continue with current buffer + if (pFrag->cBuf_fragBegin) { + iFragBegin = 1; // keep info for next buffer + iFragBeginIgn++; + } - iEvtNo++; // total event no. - psNextEvt = reinterpret_cast(piNextEvt); - pEvtHead = reinterpret_cast(piNextEvt); - ielen = pEvtHead->iMbsEv101_dlen; - pSEvtHead = reinterpret_cast(&piNextEvt[4]); - pshort = reinterpret_cast(pSEvtHead); + if (iDebug == -1) { + LOG(debug) << "-D- first 50 2byte-words of buffer:"; + psNextEvt = reinterpret_cast(&piBuf[1]); + for (Int_t iii = 0; iii < 50; iii++) { + LOG(debug) << " " << iii + 1 << ": " << psNextEvt[iii]; + } + } + iEvtRel = 1; // first event in buffer + piNextEvt = piBuf + iHeadPar + 1; // ptr first element in buffer + iEvtPar = piNextEvt[0] / 2 + 2; // no. of parameters new event + if (pFrag->cBuf_fragEnd) { + piNextEvt += iEvtPar; // skip fragment end + iEvtPar = piNextEvt[0] / 2 + 2; // no. of parameters new event + } - pEvt->nSubEvt = 0; + } // new buffer + else { + iEvtRel++; // event no. in buffer + piNextEvt += iEvtPar; // skip previous event + iEvtPar = piNextEvt[0] / 2 + 2; // no. of parameters new event + + // also if starting with current buffer: keep first buffer no. + if (iEvtNo == 0) { + iBufNo = 1; // restart counting + iBufNoServ = piBuf[4]; + iBufNo1 = iBufNoServ; + + iFragBegin = 0; + iFragBeginIgn = 0; + iFragEndIgn = 0; + iFragConc = 0; + pFrag = reinterpret_cast(&piBuf[3]); + if (pFrag->cBuf_fragBegin) { + iFragBegin = 1; // keep info for next buffer + iFragBeginIgn++; + } + if (pFrag->cBuf_fragEnd) { + iFragEndIgn++; + } + } // (iEvtNo == 0) + } // continue with current buffer + iEvtNo++; // total event no. + psNextEvt = reinterpret_cast(piNextEvt); + pEvtHead = reinterpret_cast(piNextEvt); + ielen = pEvtHead->iMbsEv101_dlen; + pSEvtHead = reinterpret_cast(&piNextEvt[4]); + pshort = reinterpret_cast(pSEvtHead); - if ( (iDebug == 1) || (iDebug == 5) ) { - iselen1 = pSEvtHead->iMbsSev101_dlen; + pEvt->nSubEvt = 0; + if ((iDebug == 1) || (iDebug == 5)) { + iselen1 = pSEvtHead->iMbsSev101_dlen; - pEvt->nSubEvt += 1; - pEvt->subEvtSize[0] = pSEvtHead->iMbsSev101_dlen/2 - 1; - pEvt->subEvtType[0] = pSEvtHead->sMbsSev101_type; - pEvt->subEvtSubType[0] = pSEvtHead->sMbsSev101_subtype; - pEvt->subEvtProcId[0] = pSEvtHead->sMbsSev101_procid; - pEvt->subEvtSubCrate[0] = pSEvtHead->cMbsSev101_subcrate; - pEvt->subEvtControl[0] = pSEvtHead->cMbsSev101_control; - pEvt->pSubEvt[0] = reinterpret_cast(&pshort[6]); + pEvt->nSubEvt += 1; + pEvt->subEvtSize[0] = pSEvtHead->iMbsSev101_dlen / 2 - 1; + pEvt->subEvtType[0] = pSEvtHead->sMbsSev101_type; + pEvt->subEvtSubType[0] = pSEvtHead->sMbsSev101_subtype; + pEvt->subEvtProcId[0] = pSEvtHead->sMbsSev101_procid; + pEvt->subEvtSubCrate[0] = pSEvtHead->cMbsSev101_subcrate; + pEvt->subEvtControl[0] = pSEvtHead->cMbsSev101_control; + pEvt->pSubEvt[0] = reinterpret_cast(&pshort[6]); -/* + /* std::stringstream ss ss << " evt " << iEvtNo << " (" << piNextEvt[3] << "), len " << pEvtHead->iMbsEv101_dlen @@ -726,229 +723,223 @@ REvent* MRevBuffer::RevGet(TSocket* pSocket, Int_t iFlush, Int_t) ss << ", SE1 len " << iselen1 << " procid " << pSEvtHead->sMbsSev101_procid; */ - ielen -= (iselen1 + 8); - - ii = 1; - iselen = iselen1; - while (ielen > 0) { - ii++; -// if (ii > 3) break; - pshort += iselen + 4; - pSEvtHead = reinterpret_cast(pshort); - iselen = pSEvtHead->iMbsSev101_dlen; -// ss << ", SE" << ii << " " << iselen -// << " " << pSEvtHead->sMbsSev101_procid; - ielen -= (iselen + 4); - + ielen -= (iselen1 + 8); + + ii = 1; + iselen = iselen1; + while (ielen > 0) { + ii++; + // if (ii > 3) break; + pshort += iselen + 4; + pSEvtHead = reinterpret_cast(pshort); + iselen = pSEvtHead->iMbsSev101_dlen; + // ss << ", SE" << ii << " " << iselen + // << " " << pSEvtHead->sMbsSev101_procid; + ielen -= (iselen + 4); + + pEvt->nSubEvt += 1; + pEvt->subEvtSize[ii - 1] = pSEvtHead->iMbsSev101_dlen / 2 - 1; + pEvt->subEvtType[ii - 1] = pSEvtHead->sMbsSev101_type; + pEvt->subEvtSubType[ii - 1] = pSEvtHead->sMbsSev101_subtype; + pEvt->subEvtProcId[ii - 1] = pSEvtHead->sMbsSev101_procid; + pEvt->subEvtSubCrate[ii - 1] = pSEvtHead->cMbsSev101_subcrate; + pEvt->subEvtControl[ii - 1] = pSEvtHead->cMbsSev101_control; + pEvt->pSubEvt[ii - 1] = reinterpret_cast(&pshort[6]); + } + // LOG(debug) << ss.str(); + } + // fill event header + iHead[0] = piNextEvt[0]; // event length + iHead[1] = piNextEvt[3]; // event number + pEvt->ReFillHead(iHead); - pEvt->nSubEvt += 1; - pEvt->subEvtSize[ii-1] = pSEvtHead->iMbsSev101_dlen/2 - 1; - pEvt->subEvtType[ii-1] = pSEvtHead->sMbsSev101_type; - pEvt->subEvtSubType[ii-1] = pSEvtHead->sMbsSev101_subtype; - pEvt->subEvtProcId[ii-1] = pSEvtHead->sMbsSev101_procid; - pEvt->subEvtSubCrate[ii-1] = pSEvtHead->cMbsSev101_subcrate; - pEvt->subEvtControl[ii-1] = pSEvtHead->cMbsSev101_control; - pEvt->pSubEvt[ii-1] = reinterpret_cast(&pshort[6]); + // fill event data + pEvt->ReFillData(piNextEvt); + if (imySig == -1) { + LOG(info) << "\n" + << "-D- CTL C specified"; + if (iDebug) { + LOG(debug) << " (at end RevGet)"; + } else { + LOG(info) << "\n"; + } + goto gEndGet; + } + if (iEvtNo == iEvtMax) { + LOG(info) << "\n" + << "-I- all required events (" << iEvtMax << ") received: " << iBufNo << " buffers (" << iBufNo1 + << " - " << iBufNo2 << ")"; + LOG(info) << " fragments found: " << iFragBeginIgn << " begin, " << iFragEndIgn << " end"; + if (iFragConc) + LOG(info) << " " << iFragConc << " events not concatenated from fragments"; } -// LOG(debug) << ss.str(); - } - - // fill event header - iHead[0] = piNextEvt[0]; // event length - iHead[1] = piNextEvt[3]; // event number - pEvt->ReFillHead(iHead); - - // fill event data - pEvt->ReFillData(piNextEvt); - - if (imySig == -1) { - LOG(info) << "\n" << "-D- CTL C specified"; - if (iDebug) { LOG(debug) << " (at end RevGet)"; } - else { LOG(info) << "\n"; } - goto gEndGet; - } - - if (iEvtNo == iEvtMax) { - LOG(info) << "\n" << "-I- all required events (" - << iEvtMax << ") received: " << iBufNo << " buffers (" - << iBufNo1 << " - " << iBufNo2 << ")"; - LOG(info) << " fragments found: " << iFragBeginIgn << " begin, " - << iFragEndIgn << " end"; - if (iFragConc) - LOG(info) << " " << iFragConc - << " events not concatenated from fragments"; - } - - iStatus = 0; // last event request successfull - return(pEvt); + + iStatus = 0; // last event request successfull + return (pEvt); gEndGet: - if ( (iError) || (imySig == -1) ) { - if (iDebug) { - LOG(debug) << " RevGet: closing connection to server"; - } - iRC = rclose(&iSocket, 2); - if ( (iDebug) && (iRC == 0) ) { - LOG(debug) << " - done"; + if ((iError) || (imySig == -1)) { + if (iDebug) { + LOG(debug) << " RevGet: closing connection to server"; + } + iRC = rclose(&iSocket, 2); + if ((iDebug) && (iRC == 0)) { + LOG(debug) << " - done"; + } + + if (imySig == -1) { + iStatus = 5; + } // user break (CTL C) + else { + iStatus = 6; + } // failure + imySig = 0; // notify CTL C handler + } else if (iDebug == 1) { + LOG(debug) << " RevGet: keeping connection to server"; } - if (imySig == -1) { iStatus = 5; } // user break (CTL C) - else { iStatus = 6; } // failure - imySig = 0; // notify CTL C handler - } else if (iDebug == 1) { - LOG(debug) << " RevGet: keeping connection to server"; - } + return 0; - return 0 ; +} // RevGet -} // RevGet +Int_t MRevBuffer::RevBufsize() { return iBufSize; } // RevBufsize -Int_t MRevBuffer::RevBufsize() +void MRevBuffer::RevBufWait(Int_t iWait) { - return iBufSize; -} // RevBufsize + if (iWait > 0) { + sleep(iWait); + } +} // RevBufWait -void MRevBuffer::RevBufWait( Int_t iWait ) +Int_t MRevBuffer::RevStatus(Int_t iOut) { - if (iWait > 0) { sleep(iWait); } -} // RevBufWait + if (iOut) + switch (iStatus) { + case 0: + LOG(info) << "-I- *** Last request for events was successfull"; + break; + case 1: + LOG(info) << "-I- *** Remote event server not yet connected"; + break; + case 2: + LOG(info) << "-I- *** Remote event server connected, but still no request for events"; + break; + case 3: + LOG(info) << "-I- *** Connection to remote event server okay, but currently no DAQ events"; + break; + case 4: + LOG(info) << "-I- *** Connection to remote event server closed"; + break; + case 5: + LOG(info) << "-I- *** Connection to remote event server closed after user break (CTL C)"; + break; + case 6: + LOG(info) << "-I- *** Connection to remote event server closed after failure"; + break; + default: + LOG(info) << "-E- Invalid status remote event server found: " << iStatus; + } + return iStatus; + +} // RevStatus -Int_t MRevBuffer::RevStatus( Int_t iOut ) +void MRevBuffer::RevClose(TSocket* pSocket) { - if (iOut) switch(iStatus) { - case 0: - LOG(info) << "-I- *** Last request for events was successfull"; - break; - case 1: - LOG(info) << "-I- *** Remote event server not yet connected"; - break; - case 2: - LOG(info) << "-I- *** Remote event server connected, but still no request for events"; - break; - case 3: - LOG(info) << "-I- *** Connection to remote event server okay, but currently no DAQ events"; - break; - case 4: - LOG(info) << "-I- *** Connection to remote event server closed"; - break; - case 5: - LOG(info) << "-I- *** Connection to remote event server closed after user break (CTL C)"; - break; - case 6: - LOG(info) << "-I- *** Connection to remote event server closed after failure"; - break; - default: - LOG(info) << "-E- Invalid status remote event server found: " << iStatus; + int iRC; + Int_t* piComm; + srevComm sComm; + Int_t iCommSize = sizeof(sComm); // size comm. buffer (byte) + + if (imySig < 0) { + return; + } // CTL Y: connection closed elsewhere + if (iSocket == 0) { + return; } - return iStatus; -} // RevStatus + // tell server that no more events needed + piComm = &(sComm.iSize); // communication buffer + sComm.iSize = htonl(iCommSize - sizeof(int)); // size of data following + sComm.iMode = htonl(1); // required: get events + sComm.iIdent = 1; // required: tell endian type + sComm.iBufRequ = htonl(0); // no more event buffers -void MRevBuffer::RevClose( TSocket* pSocket ) -{ - int iRC; - Int_t* piComm; - srevComm sComm; - Int_t iCommSize = sizeof(sComm); // size comm. buffer (byte) - - if (imySig < 0) { return; } // CTL Y: connection closed elsewhere - if (iSocket == 0) { return; } - - // tell server that no more events needed - piComm = &(sComm.iSize); // communication buffer - sComm.iSize = htonl(iCommSize-sizeof(int));// size of data following - sComm.iMode = htonl(1); // required: get events - sComm.iIdent = 1; // required: tell endian type - sComm.iBufRequ = htonl(0); // no more event buffers - - if (iDebug == 1) - LOG(debug) << "-D- send close request (data size " - << ntohl(sComm.iSize) << " byte): " - << ntohl(sComm.iMode) << ", " - << ntohl(sComm.iBufRequ); - - iRC = pSocket->SendRaw(piComm, iCommSize, kDefault); - if (iRC < 0) - LOG(info) << "-E- sending close request to server, rc = " << iRC; - else if (iDebug == 1) { - LOG(debug) << " close request sent"; - } - - if (iDebug) { - LOG(debug) << " RevClose: closing connection to server"; - } - iRC = rclose(&iSocket, 2); - if ( (iDebug) && (iRC == 0) ) { - LOG(debug) << " - done"; - } - - iStatus = 4; // connection to server closed - imySig = 0; // notify CTL C handler - LOG(info) << "-I- connection to server closed"; - -} // RevClose + if (iDebug == 1) + LOG(debug) << "-D- send close request (data size " << ntohl(sComm.iSize) << " byte): " << ntohl(sComm.iMode) + << ", " << ntohl(sComm.iBufRequ); + + iRC = pSocket->SendRaw(piComm, iCommSize, kDefault); + if (iRC < 0) + LOG(info) << "-E- sending close request to server, rc = " << iRC; + else if (iDebug == 1) { + LOG(debug) << " close request sent"; + } + + if (iDebug) { + LOG(debug) << " RevClose: closing connection to server"; + } + iRC = rclose(&iSocket, 2); + if ((iDebug) && (iRC == 0)) { + LOG(debug) << " - done"; + } + + iStatus = 4; // connection to server closed + imySig = 0; // notify CTL C handler + LOG(info) << "-I- connection to server closed"; + +} // RevClose ///////////////////////////////////////////////////////////////////// REvent::REvent() - : TObject(), - iSize(0), - iNumb(0), - piData(nullptr), - nSubEvt(0), - subEvtSize(), - subEvtType(), - subEvtSubType(), - pSubEvt() + : TObject() + , iSize(0) + , iNumb(0) + , piData(nullptr) + , nSubEvt(0) + , subEvtSize() + , subEvtType() + , subEvtSubType() + , pSubEvt() { - // LOG(info) << " REvent() ..."; -// iNumb = 0; -// piData = 0; + // LOG(info) << " REvent() ..."; + // iNumb = 0; + // piData = 0; } REvent::~REvent() { - // LOG(info) << " ~REvent() ..."; + // LOG(info) << " ~REvent() ..."; } void REvent::ReFillHead(Int_t* pHead) { - iSize = pHead[0]; // event size without header in 2-byte-words - iNumb = pHead[1]; + iSize = pHead[0]; // event size without header in 2-byte-words + iNumb = pHead[1]; } -void REvent::ReFillData(Int_t* pdata) -{ - piData = pdata; -} +void REvent::ReFillData(Int_t* pdata) { piData = pdata; } -Int_t REvent::ReGetNumb() -{ - return iNumb; -} +Int_t REvent::ReGetNumb() { return iNumb; } -Int_t REvent::ReGetSize() -{ - return iSize; -} +Int_t REvent::ReGetSize() { return iSize; } Int_t REvent::ReGetData(Int_t iChan) { - Int_t iValue; - Int_t* pint; - - //if ( (iChan < 1) || (iChan > iSize/( (signed) sizeof(int))) ) - if ( (iChan < 1) || (iChan > (iSize+4)/( static_cast(sizeof(short)))) ) { - LOG(info) << "-E- event parameter number " << iChan - << " out of range (" << (iSize+4)/( static_cast(sizeof(short))) - << " long words)"; - return(-1); - } - pint = piData; - iValue = pint[iChan-1]; - //LOG(info) << " param " << iChan << ": " << iValue; - return iValue; + Int_t iValue; + Int_t* pint; + + // if ( (iChan < 1) || (iChan > iSize/( (signed) sizeof(int))) ) + if ((iChan < 1) || (iChan > (iSize + 4) / (static_cast(sizeof(short))))) { + LOG(info) << "-E- event parameter number " << iChan << " out of range (" + << (iSize + 4) / (static_cast(sizeof(short))) << " long words)"; + return (-1); + } + pint = piData; + iValue = pint[iChan - 1]; + // LOG(info) << " param " << iChan << ": " << iValue; + return iValue; } diff --git a/base/source/MRevBuffer.h b/base/source/MRevBuffer.h index 57b08c45c8..3bc458ef67 100644 --- a/base/source/MRevBuffer.h +++ b/base/source/MRevBuffer.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ ////////////////////////////////////////////////////////////////////// @@ -24,31 +24,31 @@ #ifndef MRevBuffer_H #define MRevBuffer_H -#include // for TObject -#include // for Int_t, ClassDef, etc +#include // for Int_t, ClassDef, etc +#include // for TObject class TSocket; class REvent : public TObject { private: - Int_t iSize; // event size (byte) - Int_t iNumb; // event number - Int_t* piData; // event parameter + Int_t iSize; // event size (byte) + Int_t iNumb; // event number + Int_t* piData; // event parameter REvent(const REvent&); REvent& operator=(const REvent&); public: - REvent(); // constructor - ~REvent(); // destructor + REvent(); // constructor + ~REvent(); // destructor void ReFillHead(Int_t* pHead); // unpack and fill event header void ReFillData(Int_t* pData); // unpack and fill event data - Int_t ReGetNumb(); // get event number - Int_t ReGetSize(); // get event size - Int_t ReGetData(Int_t ichan); // get event parameter ichan + Int_t ReGetNumb(); // get event number + Int_t ReGetSize(); // get event size + Int_t ReGetData(Int_t ichan); // get event parameter ichan Int_t* GetData() { return piData; } Int_t nSubEvt; @@ -60,44 +60,44 @@ class REvent : public TObject Short_t subEvtControl[100]; Int_t* pSubEvt[100]; - ClassDef(REvent, 0) // prototype for event + ClassDef(REvent, 0) // prototype for event }; class MRevBuffer : public TObject { private: - TSocket* pTSocket; // ptr socket of channel to event server - Int_t iSocket; // socket id of channel to event server - Int_t iBufNo1; // first buffer no. received (test) - Int_t iBufNo2; // last buffer no. received (test) - Int_t iDebug; // verbosity level (test) - Int_t iSwap; // > 0: swap event data - Int_t iStatus; // current status of server - - Int_t iBufSizeAlloc; // allocated buffer size - Int_t iBufSize; // size current buffer - Int_t iBufNo; // current buffer no. - Int_t iFragBegin; // > 0: last buffer ended with fragment - Int_t iFragConc; // no. of concatenated fragments - Int_t iFragBeginIgn; // no. of ignored fragment begins - Int_t iFragEndIgn; // no. of ignored fragment ends - - Int_t iHeadPar; // no. of (4 byte) parms buffer header - Int_t iEvtMax; // no. of events requested - Int_t iEvtNo; // last event no. handled - Int_t iEvtRel; // rel. event no. in buffer - Int_t iEvtBuf; // no. of events in current buffer - Int_t iEvtPar; // no. of parameters in event (incl. len) - Int_t* piBuf; // ptr event buffer - Int_t* piNextEvt; // ptr first element next event - REvent* pEvt; // ptr event class + TSocket* pTSocket; // ptr socket of channel to event server + Int_t iSocket; // socket id of channel to event server + Int_t iBufNo1; // first buffer no. received (test) + Int_t iBufNo2; // last buffer no. received (test) + Int_t iDebug; // verbosity level (test) + Int_t iSwap; // > 0: swap event data + Int_t iStatus; // current status of server + + Int_t iBufSizeAlloc; // allocated buffer size + Int_t iBufSize; // size current buffer + Int_t iBufNo; // current buffer no. + Int_t iFragBegin; // > 0: last buffer ended with fragment + Int_t iFragConc; // no. of concatenated fragments + Int_t iFragBeginIgn; // no. of ignored fragment begins + Int_t iFragEndIgn; // no. of ignored fragment ends + + Int_t iHeadPar; // no. of (4 byte) parms buffer header + Int_t iEvtMax; // no. of events requested + Int_t iEvtNo; // last event no. handled + Int_t iEvtRel; // rel. event no. in buffer + Int_t iEvtBuf; // no. of events in current buffer + Int_t iEvtPar; // no. of parameters in event (incl. len) + Int_t* piBuf; // ptr event buffer + Int_t* piNextEvt; // ptr first element next event + REvent* pEvt; // ptr event class MRevBuffer(const MRevBuffer&); MRevBuffer& operator=(const MRevBuffer&); public: - MRevBuffer(Int_t iMode); // constructor - ~MRevBuffer(); // destructor + MRevBuffer(Int_t iMode); // constructor + ~MRevBuffer(); // destructor TSocket* RevOpen(char* pNode, Int_t iPort, Int_t iEvent); // input: node name and port number server, req. no. of events @@ -130,9 +130,9 @@ class MRevBuffer : public TObject Int_t RevBufsize(); // get size of current buffer (byte) - void RevClose(TSocket* pSocket); // input Socket ptr + void RevClose(TSocket* pSocket); // input Socket ptr - ClassDef(MRevBuffer, 0) // prototype for remote event buffer + ClassDef(MRevBuffer, 0) // prototype for remote event buffer }; -#endif // !MRevBuffer_H +#endif // !MRevBuffer_H diff --git a/base/source/exitCli.c b/base/source/exitCli.c index 3330193657..5f397d4d37 100644 --- a/base/source/exitCli.c +++ b/base/source/exitCli.c @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /******************************************************************** @@ -20,38 +20,38 @@ * 10. 6.1999, H.G.: call sleep only if required ******************************************************************** */ -#include // for printf -#include // for sleep +#include // for printf +#include // for sleep extern int imySig; extern int iTimeOut; extern int iOutMode; -void exitCli() /* handles Ctl C */ +void exitCli() /* handles Ctl C */ { - // int iRC; - int iSleep; /* sleep time here */ - int iSocket; - // int iMode = 2; - // char cMsg[128] = ""; + // int iRC; + int iSleep; /* sleep time here */ + int iSocket; + // int iMode = 2; + // char cMsg[128] = ""; - iSocket = imySig; - imySig = -1; - iSleep = iTimeOut; + iSocket = imySig; + imySig = -1; + iSleep = iTimeOut; - printf("\n-I- user specified CTL C: "); + printf("\n-I- user specified CTL C: "); - if (iSocket > 0) { - if (iOutMode) { - printf("close connection (socket %d), hold client for %d s\n", iSocket, iSleep); - } else { - printf("close connection\n"); - } + if (iSocket > 0) { + if (iOutMode) { + printf("close connection (socket %d), hold client for %d s\n", iSocket, iSleep); + } else { + printf("close connection\n"); + } - if (iSleep) { - sleep(iSleep); - } - } else { - printf("\n"); - } + if (iSleep) { + sleep(iSleep); + } + } else { + printf("\n"); + } } /* exitCli */ diff --git a/base/source/ptrevcomm.h b/base/source/ptrevcomm.h index 4c9fbc8a37..0c4abce852 100644 --- a/base/source/ptrevcomm.h +++ b/base/source/ptrevcomm.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /********************************************************************* @@ -24,25 +24,28 @@ */ /* client requests events from server */ -typedef struct { - int iSize; /* size of comm. buffer without this element (bytes) */ - int iMode; /* must be 1: client requests data */ - int iIdent;/* =1: NOT IN NET REPR. to identify client endian type */ - int iBufRequ; /* number of buffers requested */ +typedef struct +{ + int iSize; /* size of comm. buffer without this element (bytes) */ + int iMode; /* must be 1: client requests data */ + int iIdent; /* =1: NOT IN NET REPR. to identify client endian type */ + int iBufRequ; /* number of buffers requested */ } srevComm; /* server sends info to client */ -typedef struct { - int iSize; /* size of info buffer without this element (bytes) */ - int iMode; /* must be 1: server sends info */ - /* else: client tries swap */ - int iHeadPar; /* no. of header parms in buffer */ - int iTimeOut; /* wait time client after CTL C */ +typedef struct +{ + int iSize; /* size of info buffer without this element (bytes) */ + int iMode; /* must be 1: server sends info */ + /* else: client tries swap */ + int iHeadPar; /* no. of header parms in buffer */ + int iTimeOut; /* wait time client after CTL C */ } srevInfo; /* server sends dummy buffer to client, if no DAQ events available */ -typedef struct { - int iSize; /* size of data following */ - int iBufNo; /* current buffer number */ - int iEvtNo; /* no. of events in buffer (= 0) */ +typedef struct +{ + int iSize; /* size of data following */ + int iBufNo; /* current buffer number */ + int iEvtNo; /* no. of events in buffer (= 0) */ } sptrevDummy; diff --git a/base/source/ptrevmbsdef.h b/base/source/ptrevmbsdef.h index 99fbcf8b1f..0655110ffd 100644 --- a/base/source/ptrevmbsdef.h +++ b/base/source/ptrevmbsdef.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /********************************************************************* @@ -26,80 +26,84 @@ #define LITTLE__ENDIAN 1 #endif -#define COMMSIZE 404 /* max size comm. buffer (old and new clients) */ -#define INFOALL 512 +#define COMMSIZE 404 /* max size comm. buffer (old and new clients) */ +#define INFOALL 512 /* max size info buffers (old and new clients) and header (old) */ -#define HEADOLD 344 /* header size (old clients) */ +#define HEADOLD 344 /* header size (old clients) */ /************************* buffer header *****************************/ -typedef struct { /* MBS buffer header */ - long lBuf_dlen; /* buffer length without header (2byte words) */ +typedef struct +{ /* MBS buffer header */ + long lBuf_dlen; /* buffer length without header (2byte words) */ #ifdef BIG__ENDIAN - short sBuf_subtype; /* buffer subtype */ - short sBuf_type; /* buffer type */ - short sBuf_frag; /* fragment bytes */ - short sBuf_ulen; /* used data length (2byte words) */ + short sBuf_subtype; /* buffer subtype */ + short sBuf_type; /* buffer type */ + short sBuf_frag; /* fragment bytes */ + short sBuf_ulen; /* used data length (2byte words) */ #else - short sBuf_type; /* buffer type */ - short sBuf_subtype; /* buffer subtype */ - short sBuf_ulen; /* used data length (2byte words) */ - short sBuf_frag; /* fragment bytes */ + short sBuf_type; /* buffer type */ + short sBuf_subtype; /* buffer subtype */ + short sBuf_ulen; /* used data length (2byte words) */ + short sBuf_frag; /* fragment bytes */ #endif - long lBuf_bufno; /* current buffer number */ - long lBuf_ele; /* number of elements in buffer */ - long lBuf_rem[7]; /* unused remainder of buffer header */ + long lBuf_bufno; /* current buffer number */ + long lBuf_ele; /* number of elements in buffer */ + long lBuf_rem[7]; /* unused remainder of buffer header */ } sMbsBufHead; /* */ -typedef struct { /* fragment word of buffer header */ +typedef struct +{ /* fragment word of buffer header */ #ifdef BIG__ENDIAN - unsigned char cBuf_fragBegin; /* fragment begin flag */ - unsigned char cBuf_fragEnd; /* fragment end flag */ - short sBuf_ulen; /* used Data length in words (2 byte) */ + unsigned char cBuf_fragBegin; /* fragment begin flag */ + unsigned char cBuf_fragEnd; /* fragment end flag */ + short sBuf_ulen; /* used Data length in words (2 byte) */ #else - short sBuf_ulen; /* used Data length in words (2 byte) */ - unsigned char cBuf_fragEnd; /* fragment end flag */ - unsigned char cBuf_fragBegin; /* fragment begin flag */ + short sBuf_ulen; /* used Data length in words (2 byte) */ + unsigned char cBuf_fragEnd; /* fragment end flag */ + unsigned char cBuf_fragBegin; /* fragment begin flag */ #endif } sMbsBufFrag; /************************ event header *******************************/ -typedef struct { /* event header */ - int iMbsEv101_dlen; /* Data length in words */ +typedef struct +{ /* event header */ + int iMbsEv101_dlen; /* Data length in words */ #ifdef BIG__ENDIAN - short sMbsEv101_subtype; - short sMbsEv101_type; - short sMbsEv101_trigger; /* Trigger number */ - short sMbsEv101_dummy; /* Not used yet */ + short sMbsEv101_subtype; + short sMbsEv101_type; + short sMbsEv101_trigger; /* Trigger number */ + short sMbsEv101_dummy; /* Not used yet */ #else - short sMbsEv101_type; - short sMbsEv101_subtype; - short sMbsEv101_dummy; /* Not used yet */ - short sMbsEv101_trigger; /* Trigger number */ + short sMbsEv101_type; + short sMbsEv101_subtype; + short sMbsEv101_dummy; /* Not used yet */ + short sMbsEv101_trigger; /* Trigger number */ #endif - int iMbsEv101_count; /* Current event number */ + int iMbsEv101_count; /* Current event number */ } sMbsEv101; /************************* subevent header ***************************/ -typedef struct { /* subevent header 10.1 */ +typedef struct +{ /* subevent header 10.1 */ #ifdef BIG__ENDIAN - int iMbsSev101_dlen; /* Data length in words */ - short sMbsSev101_subtype; - short sMbsSev101_type; - unsigned char cMbsSev101_control; - unsigned char cMbsSev101_subcrate; /* Camac subcrate */ - short sMbsSev101_procid; /* processor id. */ + int iMbsSev101_dlen; /* Data length in words */ + short sMbsSev101_subtype; + short sMbsSev101_type; + unsigned char cMbsSev101_control; + unsigned char cMbsSev101_subcrate; /* Camac subcrate */ + short sMbsSev101_procid; /* processor id. */ #else - int iMbsSev101_dlen; /* Data length in words */ - short sMbsSev101_type; - short sMbsSev101_subtype; - short sMbsSev101_procid; /* processor id. */ - unsigned char cMbsSev101_subcrate; /* Camac subcrate */ - unsigned char cMbsSev101_control; + int iMbsSev101_dlen; /* Data length in words */ + short sMbsSev101_type; + short sMbsSev101_subtype; + short sMbsSev101_procid; /* processor id. */ + unsigned char cMbsSev101_subcrate; /* Camac subcrate */ + unsigned char cMbsSev101_control; #endif } sMbsSev101; diff --git a/base/source/rclose.c b/base/source/rclose.c index 7b48a70061..29d3cf9313 100644 --- a/base/source/rclose.c +++ b/base/source/rclose.c @@ -18,76 +18,68 @@ ******************************************************************** */ // IWYU pragma: no_include -#include // for printf, perror -#include // for close -#include // for shutdown +#include // for printf, perror +#include // for shutdown +#include // for close int rclose(int *piSocket, int iMode) { - int iSocket; - int iRC; -// int iDebug = 0; - int iError = 0; - int iClose = 1; - char cModule[32] = "rclose"; - char cMsg[128] = ""; + int iSocket; + int iRC; + // int iDebug = 0; + int iError = 0; + int iClose = 1; + char cModule[32] = "rclose"; + char cMsg[128] = ""; - if (iMode < 0) - { - iMode = -iMode; - iClose = 0; /* no shutdown, only close */ - } - if ( (iMode < 0) || (iMode > 3) ) - { - if (iClose == 0) iMode = -iMode; - printf("-E- %s: invalid shutdown mode: %d\n", cModule, iMode); - iError = 2; - } + if (iMode < 0) { + iMode = -iMode; + iClose = 0; /* no shutdown, only close */ + } + if ((iMode < 0) || (iMode > 3)) { + if (iClose == 0) + iMode = -iMode; + printf("-E- %s: invalid shutdown mode: %d\n", cModule, iMode); + iError = 2; + } - iSocket = *piSocket; - if (iSocket > 0) - { - if (iMode < 3) - { - iRC = shutdown(iSocket, iMode); - if (iRC) - { - sprintf(cMsg, "-E- %s: shutdown(%d) rc = %d", - cModule, iMode, iRC); - perror(cMsg); - iError = -1; - } -/* + iSocket = *piSocket; + if (iSocket > 0) { + if (iMode < 3) { + iRC = shutdown(iSocket, iMode); + if (iRC) { + sprintf(cMsg, "-E- %s: shutdown(%d) rc = %d", cModule, iMode, iRC); + perror(cMsg); + iError = -1; + } + /* else if (iDebug) printf(" %s: shutdown(%d) successfull\n", cModule, iMode); */ - } + } - if (iClose) - { - iRC = close(iSocket); - if (iRC) - { - sprintf(cMsg, "-E- %s: close rc = %d", cModule, iRC); - perror(cMsg); - iError = -2; - } -/* + if (iClose) { + iRC = close(iSocket); + if (iRC) { + sprintf(cMsg, "-E- %s: close rc = %d", cModule, iRC); + perror(cMsg); + iError = -2; + } + /* else if (iDebug) printf(" %s: connection closed\n", cModule); */ - } /* (iClose) */ + } /* (iClose) */ - } /* (iSocket > 0) */ - else - { - printf("-E- %s: invalid socket: %d\n", cModule, iSocket); - iError = 1; - } + } /* (iSocket > 0) */ + else { + printf("-E- %s: invalid socket: %d\n", cModule, iSocket); + iError = 1; + } - *piSocket = 0; - return(iError); + *piSocket = 0; + return (iError); } /* rclose */ diff --git a/base/source/swaplw.c b/base/source/swaplw.c index f54fb1b739..7a028c41d6 100644 --- a/base/source/swaplw.c +++ b/base/source/swaplw.c @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /******************************************************************** @@ -17,51 +17,39 @@ ****************************+*************************************** */ -long swaplw(pp_source, l_len, pp_dest) -long *pp_source, *pp_dest; -long l_len; +long swaplw(pp_source, l_len, pp_dest) long *pp_source, *pp_dest; +long l_len; { - char unsigned *p_source, *p_dest, *p_s, *p_d; -// char c_modnam[] = "f_swaplw"; - long unsigned lu_save; + char unsigned *p_source, *p_dest, *p_s, *p_d; + // char c_modnam[] = "f_swaplw"; + long unsigned lu_save; - /* +++ action +++ */ - p_source = (unsigned char *) pp_source; - p_dest = (unsigned char *) pp_dest; + /* +++ action +++ */ + p_source = (unsigned char *)pp_source; + p_dest = (unsigned char *)pp_dest; - if(p_dest) - { - /* source != destination */ - for (p_s = (unsigned char *) p_source, - p_d = (unsigned char *) p_dest; - p_s < p_source + (l_len * 4); - p_s += 4) - { - p_s += 4; /* increment source */ - *(p_d++) = *(--p_s); - *(p_d++) = *(--p_s); - *(p_d++) = *(--p_s); - *(p_d++) = *(--p_s); - } - } - else - { - /* source == destination */ - for (p_d = (unsigned char *) p_source, - p_s = (unsigned char *) &lu_save; - p_d < p_source + (l_len * 4); - ) - { - lu_save = *( (long *) p_d); - p_s += 4; /* increment source */ - *(p_d++) = *(--p_s); - *(p_d++) = *(--p_s); - *(p_d++) = *(--p_s); - *(p_d++) = *(--p_s); - } + if (p_dest) { + /* source != destination */ + for (p_s = (unsigned char *)p_source, p_d = (unsigned char *)p_dest; p_s < p_source + (l_len * 4); p_s += 4) { + p_s += 4; /* increment source */ + *(p_d++) = *(--p_s); + *(p_d++) = *(--p_s); + *(p_d++) = *(--p_s); + *(p_d++) = *(--p_s); + } + } else { + /* source == destination */ + for (p_d = (unsigned char *)p_source, p_s = (unsigned char *)&lu_save; p_d < p_source + (l_len * 4);) { + lu_save = *((long *)p_d); + p_s += 4; /* increment source */ + *(p_d++) = *(--p_s); + *(p_d++) = *(--p_s); + *(p_d++) = *(--p_s); + *(p_d++) = *(--p_s); + } } - return(1); + return (1); } /* swaplw */ diff --git a/base/steer/FairAnaSelector.cxx b/base/steer/FairAnaSelector.cxx index 41fea3c55f..8494449e3e 100644 --- a/base/steer/FairAnaSelector.cxx +++ b/base/steer/FairAnaSelector.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -13,278 +13,275 @@ #include "FairAnaSelector.h" -#include "FairFileSource.h" // for FairFileSource -#include "FairLogger.h" // for FairLogger, MESSAGE_ORIGIN -#include "FairParAsciiFileIo.h" // for FairParAsciiFileIo -#include "FairParRootFileIo.h" // for FairParRootFileIo -#include "FairRootFileSink.h" // for FairRootFileSink -#include "FairRootManager.h" // for FairRootManager -#include "FairRunAnaProof.h" // for FairRunAnaProof -#include "FairRuntimeDb.h" // for FairRuntimeDb -#include "FairTask.h" // for FairTask - -#include // for TFile -#include // for TList -#include // for TNamed -#include // for TObject -#include // for TProofOutputFile -#include // for TProofServ -#include // for TSystem, gSystem +#include "FairFileSource.h" // for FairFileSource +#include "FairLogger.h" // for FairLogger, MESSAGE_ORIGIN +#include "FairParAsciiFileIo.h" // for FairParAsciiFileIo +#include "FairParRootFileIo.h" // for FairParRootFileIo +#include "FairRootFileSink.h" // for FairRootFileSink +#include "FairRootManager.h" // for FairRootManager +#include "FairRunAnaProof.h" // for FairRunAnaProof +#include "FairRuntimeDb.h" // for FairRuntimeDb +#include "FairTask.h" // for FairTask + +#include // for TFile +#include // for TList +#include // for TNamed +#include // for TObject +#include // for TProofOutputFile +#include // for TProofServ +#include // for TSystem, gSystem void FairAnaSelector::Init(TTree* tree) { - // The Init() function is called when the selector needs to initialize - // a new tree or chain. Typically here the branch addresses and branch - // pointers of the tree will be set. - // It is normally not necessary to make changes to the generated - // code, but the routine can be extended by the user if needed. - // Init() will be called many times when running on PROOF - // (once per file to be processed). - if (!tree) { - LOG(warn) << "FairAnaSelector::Init(): There is no tree."; - return; - } else { - LOG(info) << "FairAnaSelector::Init(): Got tree : \"" << tree << "\""; - LOG(info) << "FairAnaSelector::Init(): Tree name : \"" << tree->GetName() << "\""; - LOG(info) << "FairAnaSelector::Init(): Tree title : \"" << tree->GetTitle() << "\""; - LOG(info) << "FairAnaSelector::Init(): Tree filename: \"" << tree->GetCurrentFile()->GetName() << "\""; - } - - if ( fRunAna ) { - LOG(info) << "FairAnaSelector::Init(): Already have fRunAna."; - - LOG(info) << "FairAnaSelector::Init(): SetInTree(" << tree << ")"; - fProofSource->SetInTree(tree); - LOG(info) << "FairAnaSelector::Init(): SetInTree done"; - - LOG(info) << "FairAnaSelector::Init(): Containers static? " << (fRunAna->GetContainerStatic()?"YES":"NO"); - - if ( !fRunAna->GetContainerStatic() ) { - fRunAna->InitContainers(); - } - FairRootManager::Instance()->UpdateBranches(); - } else { - LOG(info) << "FairAnaSelector::Init(): Have to create fRunAna."; - - TString vmcPath = gSystem->Getenv("VMCWORKDIR"); - - TNamed* contStat = static_cast( fInput->FindObject("FAIRRUNANA_fContainerStatic") ); - TNamed* outStat = static_cast( fInput->FindObject("FAIRRUNANA_fProofOutputStatus") ); - TNamed* outFile = static_cast( fInput->FindObject("FAIRRUNANA_fOutputFileName") ); - TNamed* outDir = static_cast( fInput->FindObject("FAIRRUNANA_fOutputDirectory") ); - TNamed* par1Name = static_cast( fInput->FindObject("FAIRRUNANA_fParInput1FName") ); - TNamed* par2Name = static_cast( fInput->FindObject("FAIRRUNANA_fParInput2FName") ); - TString containerS = contStat->GetTitle(); - TString outputStat = outStat->GetTitle(); - TString par1Str = par1Name->GetTitle(); - TString par2Str = par2Name->GetTitle(); - TString outFileName = outFile->GetTitle(); - TString outDirName = outDir->GetTitle(); - - LOG(info) << "FairAnaSelector::Init(): out status : \"" << outputStat.Data() << "\""; - LOG(info) << "FairAnaSelector::Init(): par1 file : \"" << par1Str.Data() << "\""; - LOG(info) << "FairAnaSelector::Init(): par2 file : \"" << par2Str.Data() << "\""; - - LOG(info) << "FairAnaSelector::Init(): OutputFile option \"" << outputStat.Data() << "\" RECOGNIZED"; - - if ( outputStat.Contains("copy") ) { - TString outputFileName = outFile->GetTitle(); - if ( outputFileName[0] != '/' ) { - outputFileName = Form("%s/%s",outDir->GetTitle(),outFile->GetTitle()); - } - outputFileName.Remove(outputFileName.Length()-5); - outputFileName = Form("%s_worker_%s.root",outputFileName.Data(),gProofServ->GetOrdinal()); - // outputFileName = outputFileName(outputFileName.Last('/')+1,outputFileName.Length()); - LOG(info) << "the file name = \"" << outputFileName.Data() << "\""; - fFile = TFile::Open(outputFileName.Data(),"RECREATE"); - } - else if ( outputStat.Contains("merge") ) { - TString outputFileName = outFile->GetTitle(); - if ( outputFileName[0] != '/' ) { - outputFileName = Form("%s/%s",outDir->GetTitle(),outFile->GetTitle()); - } - // outputFileName = outputFileName(outputFileName.Last('/')+1,outputFileName.Length()); - fProofFile = new TProofOutputFile(outputFileName.Data()); - if (!(fFile = fProofFile->OpenFile("RECREATE"))) { - Warning("SlaveBegin", "problems opening file: %s/%s", fProofFile->GetDir(), fProofFile->GetFileName()); - } - } - - fRunAna = new FairRunAnaProof("RunOnProofWorker"); - - LOG(info) << "FairAnaSelector::Init(): SetInTree(" << tree << ")"; - fProofSource = new FairFileSource(tree->GetCurrentFile()); - fRunAna->SetSource(fProofSource); - LOG(info) << "FairAnaSelector::Init(): SetInTree done"; - - fRunAna->SetSink(new FairRootFileSink(fFile)); - if ( containerS == "kTRUE" ) { - fRunAna->SetContainerStatic(kTRUE); + // The Init() function is called when the selector needs to initialize + // a new tree or chain. Typically here the branch addresses and branch + // pointers of the tree will be set. + // It is normally not necessary to make changes to the generated + // code, but the routine can be extended by the user if needed. + // Init() will be called many times when running on PROOF + // (once per file to be processed). + if (!tree) { + LOG(warn) << "FairAnaSelector::Init(): There is no tree."; + return; } else { - fRunAna->SetContainerStatic(kFALSE); - } - - // ----- Parameter database -------------------------------------------- - FairRuntimeDb* rtdb = fRunAna->GetRuntimeDb(); - - if ( par1Str.Contains(".root") ) { - FairParRootFileIo* parInput1 = new FairParRootFileIo(); - parInput1->open(par1Str.Data()); - rtdb->setFirstInput (parInput1); - } - if ( par1Str.Contains(".par") ) { - FairParAsciiFileIo* parInput1 = new FairParAsciiFileIo(); - parInput1->open(par1Str.Data(),"in"); - rtdb->setFirstInput (parInput1); + LOG(info) << "FairAnaSelector::Init(): Got tree : \"" << tree << "\""; + LOG(info) << "FairAnaSelector::Init(): Tree name : \"" << tree->GetName() << "\""; + LOG(info) << "FairAnaSelector::Init(): Tree title : \"" << tree->GetTitle() << "\""; + LOG(info) << "FairAnaSelector::Init(): Tree filename: \"" << tree->GetCurrentFile()->GetName() << "\""; } - if ( par2Str.Contains(".root") ) { - FairParRootFileIo* parInput2 = new FairParRootFileIo(); - parInput2->open(par2Str.Data()); - rtdb->setSecondInput(parInput2); - } - if ( par2Str.Contains(".par") ) { - FairParAsciiFileIo* parInput2 = new FairParAsciiFileIo(); - parInput2->open(par2Str.Data(),"in"); - rtdb->setSecondInput(parInput2); - } + if (fRunAna) { + LOG(info) << "FairAnaSelector::Init(): Already have fRunAna."; - // ------------------------------------------------------------------------ + LOG(info) << "FairAnaSelector::Init(): SetInTree(" << tree << ")"; + fProofSource->SetInTree(tree); + LOG(info) << "FairAnaSelector::Init(): SetInTree done"; - FairTask* fairTaskList = dynamic_cast(fInput->FindObject("FairTaskList")); + LOG(info) << "FairAnaSelector::Init(): Containers static? " << (fRunAna->GetContainerStatic() ? "YES" : "NO"); - if ( fairTaskList != 0 ) { - LOG(info) << "FairAnaSelector::Init(): FairTask = \"" << fairTaskList << "\""; - fRunAna->SetTask(fairTaskList); + if (!fRunAna->GetContainerStatic()) { + fRunAna->InitContainers(); + } + FairRootManager::Instance()->UpdateBranches(); + } else { + LOG(info) << "FairAnaSelector::Init(): Have to create fRunAna."; + + TString vmcPath = gSystem->Getenv("VMCWORKDIR"); + + TNamed* contStat = static_cast(fInput->FindObject("FAIRRUNANA_fContainerStatic")); + TNamed* outStat = static_cast(fInput->FindObject("FAIRRUNANA_fProofOutputStatus")); + TNamed* outFile = static_cast(fInput->FindObject("FAIRRUNANA_fOutputFileName")); + TNamed* outDir = static_cast(fInput->FindObject("FAIRRUNANA_fOutputDirectory")); + TNamed* par1Name = static_cast(fInput->FindObject("FAIRRUNANA_fParInput1FName")); + TNamed* par2Name = static_cast(fInput->FindObject("FAIRRUNANA_fParInput2FName")); + TString containerS = contStat->GetTitle(); + TString outputStat = outStat->GetTitle(); + TString par1Str = par1Name->GetTitle(); + TString par2Str = par2Name->GetTitle(); + TString outFileName = outFile->GetTitle(); + TString outDirName = outDir->GetTitle(); + + LOG(info) << "FairAnaSelector::Init(): out status : \"" << outputStat.Data() << "\""; + LOG(info) << "FairAnaSelector::Init(): par1 file : \"" << par1Str.Data() << "\""; + LOG(info) << "FairAnaSelector::Init(): par2 file : \"" << par2Str.Data() << "\""; + + LOG(info) << "FairAnaSelector::Init(): OutputFile option \"" << outputStat.Data() << "\" RECOGNIZED"; + + if (outputStat.Contains("copy")) { + TString outputFileName = outFile->GetTitle(); + if (outputFileName[0] != '/') { + outputFileName = Form("%s/%s", outDir->GetTitle(), outFile->GetTitle()); + } + outputFileName.Remove(outputFileName.Length() - 5); + outputFileName = Form("%s_worker_%s.root", outputFileName.Data(), gProofServ->GetOrdinal()); + // outputFileName = outputFileName(outputFileName.Last('/')+1,outputFileName.Length()); + LOG(info) << "the file name = \"" << outputFileName.Data() << "\""; + fFile = TFile::Open(outputFileName.Data(), "RECREATE"); + } else if (outputStat.Contains("merge")) { + TString outputFileName = outFile->GetTitle(); + if (outputFileName[0] != '/') { + outputFileName = Form("%s/%s", outDir->GetTitle(), outFile->GetTitle()); + } + // outputFileName = outputFileName(outputFileName.Last('/')+1,outputFileName.Length()); + fProofFile = new TProofOutputFile(outputFileName.Data()); + if (!(fFile = fProofFile->OpenFile("RECREATE"))) { + Warning("SlaveBegin", "problems opening file: %s/%s", fProofFile->GetDir(), fProofFile->GetFileName()); + } + } + + fRunAna = new FairRunAnaProof("RunOnProofWorker"); + + LOG(info) << "FairAnaSelector::Init(): SetInTree(" << tree << ")"; + fProofSource = new FairFileSource(tree->GetCurrentFile()); + fRunAna->SetSource(fProofSource); + LOG(info) << "FairAnaSelector::Init(): SetInTree done"; + + fRunAna->SetSink(new FairRootFileSink(fFile)); + if (containerS == "kTRUE") { + fRunAna->SetContainerStatic(kTRUE); + } else { + fRunAna->SetContainerStatic(kFALSE); + } + + // ----- Parameter database -------------------------------------------- + FairRuntimeDb* rtdb = fRunAna->GetRuntimeDb(); + + if (par1Str.Contains(".root")) { + FairParRootFileIo* parInput1 = new FairParRootFileIo(); + parInput1->open(par1Str.Data()); + rtdb->setFirstInput(parInput1); + } + if (par1Str.Contains(".par")) { + FairParAsciiFileIo* parInput1 = new FairParAsciiFileIo(); + parInput1->open(par1Str.Data(), "in"); + rtdb->setFirstInput(parInput1); + } + + if (par2Str.Contains(".root")) { + FairParRootFileIo* parInput2 = new FairParRootFileIo(); + parInput2->open(par2Str.Data()); + rtdb->setSecondInput(parInput2); + } + if (par2Str.Contains(".par")) { + FairParAsciiFileIo* parInput2 = new FairParAsciiFileIo(); + parInput2->open(par2Str.Data(), "in"); + rtdb->setSecondInput(parInput2); + } + + // ------------------------------------------------------------------------ + + FairTask* fairTaskList = dynamic_cast(fInput->FindObject("FairTaskList")); + + if (fairTaskList != 0) { + LOG(info) << "FairAnaSelector::Init(): FairTask = \"" << fairTaskList << "\""; + fRunAna->SetTask(fairTaskList); + } + + LOG(info) << "FairAnaSelector::Init(): vvvvv fRunAna->Init() vvvvv"; + fRunAna->Init(); + LOG(info) << "FairAnaSelector::Init(): ^^^^^ fRunAna->Init() ^^^^^"; } - - LOG(info) << "FairAnaSelector::Init(): vvvvv fRunAna->Init() vvvvv"; - fRunAna->Init(); - LOG(info) << "FairAnaSelector::Init(): ^^^^^ fRunAna->Init() ^^^^^"; - } - } Bool_t FairAnaSelector::Notify() { - // The Notify() function is called when a new file is opened. This - // can be either for a new TTree in a TChain or when when a new TTree - // is started when using PROOF. It is normally not necessary to make changes - // to the generated code, but the routine can be extended by the - // user if needed. The return value is currently not used. - LOG(info) << "FairAnaSelector::Notify()"; - - return kTRUE; + // The Notify() function is called when a new file is opened. This + // can be either for a new TTree in a TChain or when when a new TTree + // is started when using PROOF. It is normally not necessary to make changes + // to the generated code, but the routine can be extended by the + // user if needed. The return value is currently not used. + LOG(info) << "FairAnaSelector::Notify()"; + + return kTRUE; } void FairAnaSelector::Begin(TTree* /*tree*/) { - // The Begin() function is called at the start of the query. - // When running with PROOF Begin() is only called on the client. - // The tree argument is deprecated (on PROOF 0 is passed). - LOG(info) << "FairAnaSelector::Begin()"; - - fCurrentDirectory = gSystem->pwd(); - TNamed* outFile = static_cast( fInput->FindObject("FAIRRUNANA_fOutputFileName") ); - TNamed* outDir = static_cast( fInput->FindObject("FAIRRUNANA_fOutputDirectory") ); - - TString outputFileName = outFile->GetTitle(); - if ( outputFileName[0] != '/' ) { - outputFileName = Form("%s/%s",outDir->GetTitle(),outFile->GetTitle()); - } - TString outputDir = outputFileName(0,outputFileName.Last('/')+1); - fCurrentDirectory = gSystem->pwd(); - gSystem->cd(outputDir.Data()); - + // The Begin() function is called at the start of the query. + // When running with PROOF Begin() is only called on the client. + // The tree argument is deprecated (on PROOF 0 is passed). + LOG(info) << "FairAnaSelector::Begin()"; + + fCurrentDirectory = gSystem->pwd(); + TNamed* outFile = static_cast(fInput->FindObject("FAIRRUNANA_fOutputFileName")); + TNamed* outDir = static_cast(fInput->FindObject("FAIRRUNANA_fOutputDirectory")); + + TString outputFileName = outFile->GetTitle(); + if (outputFileName[0] != '/') { + outputFileName = Form("%s/%s", outDir->GetTitle(), outFile->GetTitle()); + } + TString outputDir = outputFileName(0, outputFileName.Last('/') + 1); + fCurrentDirectory = gSystem->pwd(); + gSystem->cd(outputDir.Data()); } void FairAnaSelector::SlaveBegin(TTree* tree) { - // The SlaveBegin() function is called after the Begin() function. - // When running with PROOF SlaveBegin() is called on each slave server. - // The tree argument is deprecated (on PROOF 0 is passed). - LOG(info) << "FairAnaSelector::SlaveBegin(): Tree address : \"" << tree << "\""; + // The SlaveBegin() function is called after the Begin() function. + // When running with PROOF SlaveBegin() is called on each slave server. + // The tree argument is deprecated (on PROOF 0 is passed). + LOG(info) << "FairAnaSelector::SlaveBegin(): Tree address : \"" << tree << "\""; - // useless, because have no tree anyways in slavebegin, init will be anyways called whenever a new tree comes - // Init(tree); + // useless, because have no tree anyways in slavebegin, init will be anyways called whenever a new tree comes + // Init(tree); - LOG(info) << "FairAnaSelector::SlaveBegin(): finishing"; + LOG(info) << "FairAnaSelector::SlaveBegin(): finishing"; } Bool_t FairAnaSelector::Process(Long64_t entry) { - // The Process() function is called for each entry in the tree (or possibly - // keyed object in the case of PROOF) to be processed. The entry argument - // specifies which entry in the currently loaded tree is to be processed. - // It can be passed to either FairAnaSelector::GetEntry() or TBranch::GetEntry() - // to read either all or the required parts of the data. When processing - // keyed objects with PROOF, the object is already loaded and is available - // via the fObject pointer. - // - // This function should contain the "body" of the analysis. It can contain - // simple or elaborate selection criteria, run algorithms on the data - // of the event and typically fill histograms. - // - // The processing can be stopped by calling Abort(). - // - // Use fStatus to set the return value of TTree::Process(). - // - // The return value is currently not used. - // LOG(info) << "FairAnaSelector::Process(): Proceeding to analyze event " << entry << "."; - - fRunAna->RunOneEvent(entry); - - // LOG(info) << "FairAnaSelector::Process(): Event " << entry << " analyzed."; - return kTRUE; + // The Process() function is called for each entry in the tree (or possibly + // keyed object in the case of PROOF) to be processed. The entry argument + // specifies which entry in the currently loaded tree is to be processed. + // It can be passed to either FairAnaSelector::GetEntry() or TBranch::GetEntry() + // to read either all or the required parts of the data. When processing + // keyed objects with PROOF, the object is already loaded and is available + // via the fObject pointer. + // + // This function should contain the "body" of the analysis. It can contain + // simple or elaborate selection criteria, run algorithms on the data + // of the event and typically fill histograms. + // + // The processing can be stopped by calling Abort(). + // + // Use fStatus to set the return value of TTree::Process(). + // + // The return value is currently not used. + // LOG(info) << "FairAnaSelector::Process(): Proceeding to analyze event " << entry << "."; + + fRunAna->RunOneEvent(entry); + + // LOG(info) << "FairAnaSelector::Process(): Event " << entry << " analyzed."; + return kTRUE; } void FairAnaSelector::SlaveTerminate() { - // The SlaveTerminate() function is called after all entries or objects - // have been processed. When running with PROOF SlaveTerminate() is called - // on each slave server. - if ( !fRunAna ) { - return; - } - - if ( !fProofFile ) { - LOG(info) << "FairAnaSelector::SlaveTerminate(): Calling fRunAna->TerminateRun()"; - fRunAna->TerminateRun(); - } - - LOG(info) << "FairAnaSelector::SlaveTerminate(): fProofFile = \"" << fProofFile << "\""; - if ( fProofFile ) - LOG(info) << "FairAnaSelector::SlaveTerminate(): fProofFile = \"" << fProofFile->GetName() << "\""; - LOG(info) << "FairAnaSelector::SlaveTerminate(): fFile = \"" << fFile << "\""; - if ( fFile ) - LOG(info) << "FairAnaSelector::SlaveTerminate(): fFile = \"" << fFile->GetName() << "\""; - - LOG(info) << "FairAnaSelector::SlaveTerminate(): WorkingDirectory = \"" << gSystem->WorkingDirectory() << "\""; - - if ( fProofFile ) { - // fOutput->ls(); - // fOutput->Print(); - // fProofFile->Print(); - - LOG(info) << "FairAnaSelector::SlaveTerminate(): fOutput->Add(fProofFile);"; - fOutput->Add(fProofFile); - - // fProofFile->Print(); - - LOG(info) << "FairAnaSelector::SlaveTerminate(): fFile->Close();"; - fRunAna->TerminateRun(); - - // fFile->Close(); - } - LOG(info) << "FairAnaSelector::SlaveTerminate(): Finishing..."; + // The SlaveTerminate() function is called after all entries or objects + // have been processed. When running with PROOF SlaveTerminate() is called + // on each slave server. + if (!fRunAna) { + return; + } + + if (!fProofFile) { + LOG(info) << "FairAnaSelector::SlaveTerminate(): Calling fRunAna->TerminateRun()"; + fRunAna->TerminateRun(); + } + + LOG(info) << "FairAnaSelector::SlaveTerminate(): fProofFile = \"" << fProofFile << "\""; + if (fProofFile) + LOG(info) << "FairAnaSelector::SlaveTerminate(): fProofFile = \"" << fProofFile->GetName() << "\""; + LOG(info) << "FairAnaSelector::SlaveTerminate(): fFile = \"" << fFile << "\""; + if (fFile) + LOG(info) << "FairAnaSelector::SlaveTerminate(): fFile = \"" << fFile->GetName() << "\""; + + LOG(info) << "FairAnaSelector::SlaveTerminate(): WorkingDirectory = \"" << gSystem->WorkingDirectory() << "\""; + + if (fProofFile) { + // fOutput->ls(); + // fOutput->Print(); + // fProofFile->Print(); + + LOG(info) << "FairAnaSelector::SlaveTerminate(): fOutput->Add(fProofFile);"; + fOutput->Add(fProofFile); + + // fProofFile->Print(); + + LOG(info) << "FairAnaSelector::SlaveTerminate(): fFile->Close();"; + fRunAna->TerminateRun(); + + // fFile->Close(); + } + LOG(info) << "FairAnaSelector::SlaveTerminate(): Finishing..."; } void FairAnaSelector::Terminate() { - // The Terminate() function is the last function to be called during - // a query. It always runs on the client, it can be used to present - // the results graphically or save the results to file. - LOG(info) << "FairAnaSelector::Terminate(): fOutput->ls()"; - gSystem->cd(fCurrentDirectory.Data()); - LOG(info) << "FairAnaSelector::Terminate(): -------------"; + // The Terminate() function is the last function to be called during + // a query. It always runs on the client, it can be used to present + // the results graphically or save the results to file. + LOG(info) << "FairAnaSelector::Terminate(): fOutput->ls()"; + gSystem->cd(fCurrentDirectory.Data()); + LOG(info) << "FairAnaSelector::Terminate(): -------------"; } diff --git a/base/steer/FairAnaSelector.h b/base/steer/FairAnaSelector.h index 92c4693b45..c57479939b 100644 --- a/base/steer/FairAnaSelector.h +++ b/base/steer/FairAnaSelector.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -14,13 +14,13 @@ #ifndef FAIRANASELECTOR_H #define FAIRANASELECTOR_H -#include "FairLogger.h" // for FairLogger, MESSAGE_ORIGIN +#include "FairLogger.h" // for FairLogger, MESSAGE_ORIGIN -#include // for TSelector -#include // for Int_t, Bool_t, etc -#include // for TSelectorList -#include // for TString -#include // for TTree +#include // for Int_t, Bool_t, etc +#include // for TSelector +#include // for TSelectorList +#include // for TString +#include // for TTree class FairFileSource; class FairRunAnaProof; @@ -33,43 +33,39 @@ class TProofOutputFile; class FairAnaSelector : public TSelector { public: - TProofOutputFile* fProofFile; - TFile* fFile; - TTree* fChain; //!pointer to the analyzed TTree or TChain - FairRunAnaProof* fRunAna; + TProofOutputFile* fProofFile; + TFile* fFile; + TTree* fChain; //! pointer to the analyzed TTree or TChain + FairRunAnaProof* fRunAna; - FairAnaSelector(TTree* /*tree*/ =0) : fProofFile(0), fFile(0), fChain(0), fRunAna(nullptr), fProofSource(0), fCurrentDirectory("") { } + FairAnaSelector(TTree* /*tree*/ = 0) + : fProofFile(0) + , fFile(0) + , fChain(0) + , fRunAna(nullptr) + , fProofSource(0) + , fCurrentDirectory("") + {} - virtual ~FairAnaSelector() { } - virtual Int_t Version() const { - return 1; + virtual ~FairAnaSelector() {} + virtual Int_t Version() const { return 1; } + virtual void Begin(TTree* tree); + virtual void SlaveBegin(TTree* tree); + virtual void Init(TTree* tree); + virtual Bool_t Notify(); + virtual Bool_t Process(Long64_t entry); + virtual Int_t GetEntry(Long64_t entry, Int_t getall = 0) + { + return fChain ? fChain->GetTree()->GetEntry(entry, getall) : 0; } - virtual void Begin(TTree* tree); - virtual void SlaveBegin(TTree* tree); - virtual void Init(TTree* tree); - virtual Bool_t Notify(); - virtual Bool_t Process(Long64_t entry); - virtual Int_t GetEntry(Long64_t entry, Int_t getall = 0) { - return fChain ? fChain->GetTree()->GetEntry(entry, getall) : 0; - } - virtual void SetOption(const char* option) { - fOption = option; - } - virtual void SetObject(TObject* obj) { - fObject = obj; - } - virtual void SetInputList(TList* input) { - fInput = input; - } - virtual TList* GetOutputList() const { - return fOutput; - } - virtual void SlaveTerminate(); - virtual void Terminate(); + virtual void SetOption(const char* option) { fOption = option; } + virtual void SetObject(TObject* obj) { fObject = obj; } + virtual void SetInputList(TList* input) { fInput = input; } + virtual TList* GetOutputList() const { return fOutput; } + virtual void SlaveTerminate(); + virtual void Terminate(); - void SetFairRunAnaProof(FairRunAnaProof* runAna) { - fRunAna = runAna; - } + void SetFairRunAnaProof(FairRunAnaProof* runAna) { fRunAna = runAna; } private: FairAnaSelector(const FairAnaSelector&); @@ -79,7 +75,7 @@ class FairAnaSelector : public TSelector TString fCurrentDirectory; - ClassDef(FairAnaSelector,0); + ClassDef(FairAnaSelector, 0); }; -#endif //FAIRANASELECTOR_H +#endif // FAIRANASELECTOR_H diff --git a/base/steer/FairLinkManager.cxx b/base/steer/FairLinkManager.cxx index 4b53da74ee..17c940340f 100644 --- a/base/steer/FairLinkManager.cxx +++ b/base/steer/FairLinkManager.cxx @@ -12,63 +12,63 @@ TMCThreadLocal FairLinkManager* FairLinkManager::fgInstance = 0; FairLinkManager* FairLinkManager::Instance() { -// Returns singleton instance. -// --- - return fgInstance; + // Returns singleton instance. + // --- + return fgInstance; } FairLinkManager::FairLinkManager() - : TObject(), - fIgnoreTypes(), - fIgnoreSetting(kTRUE), - fLogger(0) + : TObject() + , fIgnoreTypes() + , fIgnoreSetting(kTRUE) + , fLogger(0) { - if (fgInstance) { - Fatal("FairLinkManager", "Singleton instance already exists."); - return; - } -// std::cout << "-I- FairLinkManager::FairLinkManager created!" << std::endl; - fgInstance = this; + if (fgInstance) { + Fatal("FairLinkManager", "Singleton instance already exists."); + return; + } + // std::cout << "-I- FairLinkManager::FairLinkManager created!" << std::endl; + fgInstance = this; - // Logger only on master - TO DO - if ( FairRun::Instance()->GetIsMaster() ) { - fLogger = FairLogger::GetLogger(); - } + // Logger only on master - TO DO + if (FairRun::Instance()->GetIsMaster()) { + fLogger = FairLogger::GetLogger(); + } } FairLinkManager::~FairLinkManager() { - LOG(debug) << "Enter Destructor of FairLinkManager"; - fgInstance = 0; - LOG(debug) << "Leave Destructor of FairLinkManager"; + LOG(debug) << "Enter Destructor of FairLinkManager"; + fgInstance = 0; + LOG(debug) << "Leave Destructor of FairLinkManager"; } void FairLinkManager::AddIgnoreType(Int_t type) { - if (fIgnoreSetting == kFALSE) { - LOG(debug) << "AddIgnoreType ignored because of IncludeType setting"; - return; - } - LOG(debug) << "AddIgnoreType"; - fIgnoreTypes.insert(type); + if (fIgnoreSetting == kFALSE) { + LOG(debug) << "AddIgnoreType ignored because of IncludeType setting"; + return; + } + LOG(debug) << "AddIgnoreType"; + fIgnoreTypes.insert(type); } void FairLinkManager::AddIncludeType(Int_t type) { - LOG(debug) << "AddIgnoreType"; - if (fIgnoreSetting == kTRUE) { - fIgnoreSetting=kFALSE; - fIgnoreTypes.clear(); - } - fIgnoreTypes.insert(type); + LOG(debug) << "AddIgnoreType"; + if (fIgnoreSetting == kTRUE) { + fIgnoreSetting = kFALSE; + fIgnoreTypes.clear(); + } + fIgnoreTypes.insert(type); } Bool_t FairLinkManager::IsIgnoreType(Int_t type) const { - if (fIgnoreSetting) - return fIgnoreTypes.count(type); - else - return !fIgnoreTypes.count(type); + if (fIgnoreSetting) + return fIgnoreTypes.count(type); + else + return !fIgnoreTypes.count(type); } -ClassImp(FairLinkManager) +ClassImp(FairLinkManager); diff --git a/base/steer/FairLinkManager.h b/base/steer/FairLinkManager.h index f97eea1e8d..538b6afc08 100644 --- a/base/steer/FairLinkManager.h +++ b/base/steer/FairLinkManager.h @@ -1,11 +1,10 @@ #ifndef FAIR_LINK_MANAGER_H #define FAIR_LINK_MANAGER_H -#include // for TObject -#include // for multi-threading -#include // for Bool_t, Int_t, UInt_t, etc - -#include // for set of branch types to ignore +#include // for Bool_t, Int_t, UInt_t, etc +#include // for multi-threading +#include // for TObject +#include // for set of branch types to ignore class FairLogger; @@ -17,15 +16,16 @@ class FairLinkManager : public TObject /**dtor*/ virtual ~FairLinkManager(); - /** static access method */ static FairLinkManager* Instance(); - virtual void AddIgnoreType(Int_t type); ///< Adds a BranchId (Type) to which links are not included in the link list. Either ignore types or include types can be given. + virtual void AddIgnoreType(Int_t type); ///< Adds a BranchId (Type) to which links are not included in the link + ///< list. Either ignore types or include types can be given. virtual Bool_t IsIgnoreType(Int_t type) const; - virtual void AddIncludeType(Int_t type); ///< Adds a BranchId (Type) to which links are included in the link list. Either ignore types or include types can be given (XOR). + virtual void AddIncludeType(Int_t type); ///< Adds a BranchId (Type) to which links are included in the link list. + ///< Either ignore types or include types can be given (XOR). - std::set GetIgnoreTypes() const {return fIgnoreTypes;} + std::set GetIgnoreTypes() const { return fIgnoreTypes; } private: /**private methods*/ @@ -34,15 +34,15 @@ class FairLinkManager : public TObject /** Set the branch address for a given branch name and return a TObject pointer, the user have to cast this pointer to the right type.*/ - std::set fIgnoreTypes; //! + std::set fIgnoreTypes; //! Bool_t fIgnoreSetting; /**Singleton instance*/ static TMCThreadLocal FairLinkManager* fgInstance; - FairLogger* fLogger; //! + FairLogger* fLogger; //! - ClassDef(FairLinkManager,1) // Root IO manager + ClassDef(FairLinkManager, 1) // Root IO manager }; -#endif //FAIR_ROOT_MANAGER_H +#endif // FAIR_ROOT_MANAGER_H diff --git a/base/steer/FairRadGridManager.cxx b/base/steer/FairRadGridManager.cxx index 9426db6cfd..6856bebf3c 100644 --- a/base/steer/FairRadGridManager.cxx +++ b/base/steer/FairRadGridManager.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -12,158 +12,151 @@ // ------------------------------------------------------------------------- #include "FairRadGridManager.h" -#include "FairRootManager.h" + #include "FairMesh.h" +#include "FairRootManager.h" #include #include -ClassImp(FairRadGridManager) +ClassImp(FairRadGridManager); FairRadGridManager* FairRadGridManager::fgInstance = nullptr; -Double_t FairRadGridManager::fLtmp = 0.0 ; +Double_t FairRadGridManager::fLtmp = 0.0; FairRadGridManager* FairRadGridManager::Instance() { - /**singelton instance*/ - return fgInstance; + /**singelton instance*/ + return fgInstance; } FairRadGridManager::FairRadGridManager() - : fPointCollection(nullptr), - fTrackID(0), - fVolumeID(0), - fPosIn(TLorentzVector(0,0,0,0)), - fPosOut(TLorentzVector(0,0,0,0)), - fMomIn(TLorentzVector(0,0,0,0)), - fMomOut(TLorentzVector(0,0,0,0)), - fTime(0), - fLength(0), - fELoss(0), - fA(0), - fZmat(0), - fDensity(0), - fRadl(0), - fAbsl(0), - fEstimator(0), - fMeshList(nullptr), - fOutputFileName("radGridManager.root") + : fPointCollection(nullptr) + , fTrackID(0) + , fVolumeID(0) + , fPosIn(TLorentzVector(0, 0, 0, 0)) + , fPosOut(TLorentzVector(0, 0, 0, 0)) + , fMomIn(TLorentzVector(0, 0, 0, 0)) + , fMomOut(TLorentzVector(0, 0, 0, 0)) + , fTime(0) + , fLength(0) + , fELoss(0) + , fA(0) + , fZmat(0) + , fDensity(0) + , fRadl(0) + , fAbsl(0) + , fEstimator(0) + , fMeshList(nullptr) + , fOutputFileName("radGridManager.root") { - /** radiation length default ctor */ - if(nullptr == fgInstance) { - fgInstance = this; - } - fLtmp=0; + /** radiation length default ctor */ + if (nullptr == fgInstance) { + fgInstance = this; + } + fLtmp = 0; } FairRadGridManager::~FairRadGridManager() { - /** radiation length default dtor */ - fgInstance = nullptr; + /** radiation length default dtor */ + fgInstance = nullptr; } void FairRadGridManager::Init() { -// fMeshList = new TObjArray(); + // fMeshList = new TObjArray(); } void FairRadGridManager::Reset() { - // No free of memory ? - // fMesh->Reset(); + // No free of memory ? + // fMesh->Reset(); } void FairRadGridManager::FillMeshList() { - /**Add a point to the collection*/ - TParticle* part = TVirtualMC::GetMC()->GetStack()->GetCurrentTrack(); - fTrackID = TVirtualMC::GetMC()->GetStack()->GetCurrentTrackNumber(); - TVirtualMC::GetMC()->TrackPosition(fPosIn); - TVirtualMC::GetMC()->TrackMomentum(fMomIn); - fELoss = 0.; -// Int_t MatId= TVirtualMC::GetMC()->CurrentMaterial(fA, fZmat, fDensity, fRadl, fAbsl); - - /** Sum energy loss for all steps in the mesh*/ - for (Int_t i=0; iGetEntriesFast(); i++ ) { - FairMesh* aMesh = static_cast(fMeshList->At(i)); - Double_t fBinVolume = aMesh->GetBinVolume(); - Double_t fDiag = aMesh->GetDiag(); - - // Geometry bound test - if ( IsTrackInside(fPosIn,aMesh) ) { - fELoss = TVirtualMC::GetMC()->Edep(); - //cout << "-I- track (" << fTrackID << ") is inside " << endl; - //cout << " E deposited is " << fELoss << endl; - TVirtualMC::GetMC()->TrackPosition(fPosOut); - TVirtualMC::GetMC()->TrackMomentum(fMomOut); - - // Now cumulate fEloss (Gev/cm3) - // and normalize it to the mesh volume - - // 1 estimator Edep - fELoss = fELoss/fBinVolume; - // 2 estimator TrackLengh - fLength = TVirtualMC::GetMC()->TrackStep(); - // fill TID - - aMesh->fillTID(fPosOut.X(),fPosOut.Y(),fELoss); - // fill total Fluence - if ( fLength < 5*fDiag ) { - - fLength = fLength/fBinVolume; - aMesh->fillFluence(fPosOut.X(),fPosOut.Y(),fLength); - - // fill SEU - if ( part->P() > 0.02 ) { - aMesh->fillSEU(fPosOut.X(),fPosOut.Y(),fLength); + /**Add a point to the collection*/ + TParticle* part = TVirtualMC::GetMC()->GetStack()->GetCurrentTrack(); + fTrackID = TVirtualMC::GetMC()->GetStack()->GetCurrentTrackNumber(); + TVirtualMC::GetMC()->TrackPosition(fPosIn); + TVirtualMC::GetMC()->TrackMomentum(fMomIn); + fELoss = 0.; + // Int_t MatId= TVirtualMC::GetMC()->CurrentMaterial(fA, fZmat, fDensity, fRadl, fAbsl); + + /** Sum energy loss for all steps in the mesh*/ + for (Int_t i = 0; i < fMeshList->GetEntriesFast(); i++) { + FairMesh* aMesh = static_cast(fMeshList->At(i)); + Double_t fBinVolume = aMesh->GetBinVolume(); + Double_t fDiag = aMesh->GetDiag(); + + // Geometry bound test + if (IsTrackInside(fPosIn, aMesh)) { + fELoss = TVirtualMC::GetMC()->Edep(); + // cout << "-I- track (" << fTrackID << ") is inside " << endl; + // cout << " E deposited is " << fELoss << endl; + TVirtualMC::GetMC()->TrackPosition(fPosOut); + TVirtualMC::GetMC()->TrackMomentum(fMomOut); + + // Now cumulate fEloss (Gev/cm3) + // and normalize it to the mesh volume + + // 1 estimator Edep + fELoss = fELoss / fBinVolume; + // 2 estimator TrackLengh + fLength = TVirtualMC::GetMC()->TrackStep(); + // fill TID + + aMesh->fillTID(fPosOut.X(), fPosOut.Y(), fELoss); + // fill total Fluence + if (fLength < 5 * fDiag) { + + fLength = fLength / fBinVolume; + aMesh->fillFluence(fPosOut.X(), fPosOut.Y(), fLength); + + // fill SEU + if (part->P() > 0.02) { + aMesh->fillSEU(fPosOut.X(), fPosOut.Y(), fLength); + } + } } - } - } - - } } -Bool_t FairRadGridManager::IsTrackEntering(TLorentzVector&, - TLorentzVector&) +Bool_t FairRadGridManager::IsTrackEntering(TLorentzVector&, TLorentzVector&) { - // assume for the moment vertical scoring planes - // cout << " is entering diagnosis " << endl; - // cout << " Z pos " << pos.Z() << endl; - // cout << " Zmin " << fZmin << endl; - // cout << " diff " << pos.Z()-fZmin << endl; + // assume for the moment vertical scoring planes + // cout << " is entering diagnosis " << endl; + // cout << " Z pos " << pos.Z() << endl; + // cout << " Zmin " << fZmin << endl; + // cout << " diff " << pos.Z()-fZmin << endl; + + // if ( (( TMath::Abs(pos.Z() - fZmin) ) < 1.0e-06 ) + // && + // ( mom.Z() > 0 ) + // ) return kTRUE; + // else + // return kFALSE; - - // if ( (( TMath::Abs(pos.Z() - fZmin) ) < 1.0e-06 ) - // && - // ( mom.Z() > 0 ) - // ) return kTRUE; - // else - // return kFALSE; - - return kFALSE; + return kFALSE; } -Bool_t FairRadGridManager::IsTrackInside(TLorentzVector& pos , FairMesh* aMesh) +Bool_t FairRadGridManager::IsTrackInside(TLorentzVector& pos, FairMesh* aMesh) { - // check if inside volume - if ( (pos.X() >= aMesh->GetXmin()) && (pos.X() <= aMesh->GetXmax()) - && - (pos.Y() >= aMesh->GetYmin()) && (pos.Y() <= aMesh->GetYmax()) - && - (pos.Z() >= aMesh->GetZmin()) && (pos.Z() <= aMesh->GetZmax()) - ) { - /* cout << " inside Xpos: " << pos.X() << " Xmin: " << aMesh->GetXmin() + // check if inside volume + if ((pos.X() >= aMesh->GetXmin()) && (pos.X() <= aMesh->GetXmax()) && (pos.Y() >= aMesh->GetYmin()) + && (pos.Y() <= aMesh->GetYmax()) && (pos.Z() >= aMesh->GetZmin()) && (pos.Z() <= aMesh->GetZmax())) { + /* cout << " inside Xpos: " << pos.X() << " Xmin: " << aMesh->GetXmin() << " Xmax: " << aMesh->GetXmax() << endl; cout << " inside Ypos: " << pos.Y() << " Ymin: " << aMesh->GetYmin() << " Ymax: " << aMesh->GetYmax() << endl; cout << " inside Zpos: " << pos.Z() << " Zmin: " << aMesh->GetZmin() << " Zmax: " << aMesh->GetZmax() << endl; */ - return kTRUE; - } else { - return kFALSE; - } + return kTRUE; + } else { + return kFALSE; + } } diff --git a/base/steer/FairRadGridManager.h b/base/steer/FairRadGridManager.h index e4a9b1effe..885e8c6616 100644 --- a/base/steer/FairRadGridManager.h +++ b/base/steer/FairRadGridManager.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -13,12 +13,11 @@ #ifndef FAIRRADGRIDMANAGER_H #define FAIRRADGRIDMANAGER_H 1 -#include // for Float_t, Double_t, Int_t, etc -#include // for TLorentzVector -#include // for TObjArray -#include // for TString - -#include // for basic_ostream::operator<<, etc +#include // for Float_t, Double_t, Int_t, etc +#include // for TLorentzVector +#include // for TObjArray +#include // for TString +#include // for basic_ostream::operator<<, etc class FairMesh; class TClonesArray; @@ -44,7 +43,7 @@ class FairRadGridManager /** * Class definition. */ - ClassDef(FairRadGridManager,1); + ClassDef(FairRadGridManager, 1); private: FairRadGridManager(const FairRadGridManager&); @@ -55,35 +54,35 @@ class FairRadGridManager /** * collection of point */ - TClonesArray* fPointCollection; + TClonesArray* fPointCollection; /**track index */ - Int_t fTrackID; //! + Int_t fTrackID; //! /**volume id */ - Int_t fVolumeID; //! + Int_t fVolumeID; //! /** entry position in global frame*/ - TLorentzVector fPosIn; //! + TLorentzVector fPosIn; //! /** exit position in global frame*/ - TLorentzVector fPosOut; //! + TLorentzVector fPosOut; //! /** momentum in*/ - TLorentzVector fMomIn; //! + TLorentzVector fMomIn; //! /** momentum out*/ - TLorentzVector fMomOut; //! + TLorentzVector fMomOut; //! /**track time */ - Double_t fTime; //! + Double_t fTime; //! /**track length */ - Double_t fLength; //! + Double_t fLength; //! /** energy loss */ - Double_t fELoss; //! + Double_t fELoss; //! /** mass umber*/ - Float_t fA; + Float_t fA; /** atomic number*/ - Float_t fZmat; + Float_t fZmat; /** density */ - Float_t fDensity; + Float_t fDensity; /**radition length */ - Float_t fRadl; + Float_t fRadl; /**absorption length */ - Float_t fAbsl; + Float_t fAbsl; /**estimator*/ Int_t fEstimator; /** the mesh */ @@ -95,20 +94,21 @@ class FairRadGridManager public: TObjArray* GetMeshList() { return fMeshList; } - void AddMeshList ( TObjArray* list ) { - std::cout << " grid manag " << list->GetEntriesFast() << std::endl; - fMeshList = list; + void AddMeshList(TObjArray* list) + { + std::cout << " grid manag " << list->GetEntriesFast() << std::endl; + fMeshList = list; } - Bool_t IsTrackInside(TLorentzVector& vec, FairMesh* aMesh); - Bool_t IsTrackEntering(TLorentzVector& vec1,TLorentzVector& vec2); + Bool_t IsTrackInside(TLorentzVector& vec, FairMesh* aMesh); + Bool_t IsTrackEntering(TLorentzVector& vec1, TLorentzVector& vec2); /** fill the 2D mesh */ void FillMeshList(); /**initialize the manager*/ - void Init(); + void Init(); /**reset*/ - void Reset(); + void Reset(); /**set output file name*/ - void SetOutputFileName(TString tempString) { fOutputFileName = tempString; } + void SetOutputFileName(TString tempString) { fOutputFileName = tempString; } TString GetOutputFileName() { return fOutputFileName; } /** * This function is used to access the methods of the class. diff --git a/base/steer/FairRadLenManager.cxx b/base/steer/FairRadLenManager.cxx index d162380a7d..31a4d8e03e 100644 --- a/base/steer/FairRadLenManager.cxx +++ b/base/steer/FairRadLenManager.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -12,106 +12,108 @@ #include "FairRadLenManager.h" -#include "FairRadLenPoint.h" // for FairRadLenPoint -#include "FairRootManager.h" // for FairRootManager +#include "FairRadLenPoint.h" // for FairRadLenPoint +#include "FairRootManager.h" // for FairRootManager -#include // for TClonesArray -#include // for TVector3 -#include // for TVirtualMC -#include // for TVirtualMCStack +#include // for TClonesArray +#include // for TVector3 +#include // for TVirtualMC +#include // for TVirtualMCStack using namespace std; -ClassImp(FairRadLenManager) +ClassImp(FairRadLenManager); FairRadLenManager* FairRadLenManager::fgInstance = nullptr; FairRadLenManager* FairRadLenManager::Instance() { - /**singelton instance*/ - return fgInstance; + /**singelton instance*/ + return fgInstance; } FairRadLenManager::FairRadLenManager() - : fPointCollection(new TClonesArray("FairRadLenPoint")), - fTrackID(0), - fVolumeID(0), - fPosIn(TLorentzVector(0,0,0,0)), - fPosOut(TLorentzVector(0,0,0,0)), - fMomIn(TLorentzVector(0,0,0,0)), - fMomOut(TLorentzVector(0,0,0,0)), - fTime(0), - fLength(0), - fELoss(0), - fA(0), - fZmat(0), - fDensity(0), - fRadl(0), - fAbsl(0) + : fPointCollection(new TClonesArray("FairRadLenPoint")) + , fTrackID(0) + , fVolumeID(0) + , fPosIn(TLorentzVector(0, 0, 0, 0)) + , fPosOut(TLorentzVector(0, 0, 0, 0)) + , fMomIn(TLorentzVector(0, 0, 0, 0)) + , fMomOut(TLorentzVector(0, 0, 0, 0)) + , fTime(0) + , fLength(0) + , fELoss(0) + , fA(0) + , fZmat(0) + , fDensity(0) + , fRadl(0) + , fAbsl(0) { - /** radiation length default ctor */ - if (nullptr == fgInstance) { - fgInstance = this; - // fPointCollection=new TClonesArray("FairRadLenPoint"); - } + /** radiation length default ctor */ + if (nullptr == fgInstance) { + fgInstance = this; + // fPointCollection=new TClonesArray("FairRadLenPoint"); + } } FairRadLenManager::~FairRadLenManager() { - /** radiation length default dtor */ - fgInstance = nullptr; - fPointCollection->Delete(); - delete fPointCollection; + /** radiation length default dtor */ + fgInstance = nullptr; + fPointCollection->Delete(); + delete fPointCollection; } void FairRadLenManager::Init() { - /**create the branch for output */ - FairRootManager::Instance()->Register("RadLen","RadLenPoint", fPointCollection, kTRUE); + /**create the branch for output */ + FairRootManager::Instance()->Register("RadLen", "RadLenPoint", fPointCollection, kTRUE); } void FairRadLenManager::Reset() { - /**We have to free the momeory, Clear() is faster but not enough! */ - fPointCollection->Delete(); + /**We have to free the momeory, Clear() is faster but not enough! */ + fPointCollection->Delete(); } void FairRadLenManager::AddPoint(Int_t& ModuleId) { - /**Add a point to the collection*/ - if ( TVirtualMC::GetMC()->IsTrackEntering() ) { - fELoss = 0.; - Int_t copyNo; - fVolumeID = TVirtualMC::GetMC()->CurrentVolID(copyNo); - fTime = TVirtualMC::GetMC()->TrackTime() * 1.0e09; - fLength = TVirtualMC::GetMC()->TrackLength(); - TVirtualMC::GetMC()->TrackPosition(fPosIn); - TVirtualMC::GetMC()->TrackMomentum(fMomIn); - // Int_t MatId= TVirtualMC::GetMC()->CurrentMaterial(fA, fZmat, fDensity, fRadl, fAbsl); - TVirtualMC::GetMC()->CurrentMaterial(fA, fZmat, fDensity, fRadl, fAbsl); - } - /** Sum energy loss for all steps in the active volume */ - fELoss += TVirtualMC::GetMC()->Edep(); - /** Create a point at exit of the volume */ - if ( TVirtualMC::GetMC()->IsTrackExiting() || - TVirtualMC::GetMC()->IsTrackStop() || - TVirtualMC::GetMC()->IsTrackDisappeared() ) { -// FairRadLenPoint* p=0; - fTrackID = TVirtualMC::GetMC()->GetStack()->GetCurrentTrackNumber(); - TVirtualMC::GetMC()->TrackPosition(fPosOut); - TVirtualMC::GetMC()->TrackMomentum(fMomOut); - TClonesArray& clref = *fPointCollection; - Int_t tsize = clref.GetEntriesFast(); -// p=new(clref[tsize]) FairRadLenPoint(fTrackID, ModuleId, - new(clref[tsize]) FairRadLenPoint(fTrackID, ModuleId, - TVector3(fPosIn.X(),fPosIn.Y(),fPosIn.Z()), - TVector3(fMomIn.X(),fMomIn.Y(),fMomIn.Z()), - fTime, fLength, fELoss, - TVector3(fPosOut.X(),fPosOut.Y(),fPosOut.Z()), - TVector3(fMomOut.X(),fMomOut.Y(),fMomOut.Z()), - fA, fZmat, fDensity, fRadl); - } - + /**Add a point to the collection*/ + if (TVirtualMC::GetMC()->IsTrackEntering()) { + fELoss = 0.; + Int_t copyNo; + fVolumeID = TVirtualMC::GetMC()->CurrentVolID(copyNo); + fTime = TVirtualMC::GetMC()->TrackTime() * 1.0e09; + fLength = TVirtualMC::GetMC()->TrackLength(); + TVirtualMC::GetMC()->TrackPosition(fPosIn); + TVirtualMC::GetMC()->TrackMomentum(fMomIn); + // Int_t MatId= TVirtualMC::GetMC()->CurrentMaterial(fA, fZmat, fDensity, fRadl, fAbsl); + TVirtualMC::GetMC()->CurrentMaterial(fA, fZmat, fDensity, fRadl, fAbsl); + } + /** Sum energy loss for all steps in the active volume */ + fELoss += TVirtualMC::GetMC()->Edep(); + /** Create a point at exit of the volume */ + if (TVirtualMC::GetMC()->IsTrackExiting() || TVirtualMC::GetMC()->IsTrackStop() + || TVirtualMC::GetMC()->IsTrackDisappeared()) { + // FairRadLenPoint* p=0; + fTrackID = TVirtualMC::GetMC()->GetStack()->GetCurrentTrackNumber(); + TVirtualMC::GetMC()->TrackPosition(fPosOut); + TVirtualMC::GetMC()->TrackMomentum(fMomOut); + TClonesArray& clref = *fPointCollection; + Int_t tsize = clref.GetEntriesFast(); + // p=new(clref[tsize]) FairRadLenPoint(fTrackID, ModuleId, + new (clref[tsize]) FairRadLenPoint(fTrackID, + ModuleId, + TVector3(fPosIn.X(), fPosIn.Y(), fPosIn.Z()), + TVector3(fMomIn.X(), fMomIn.Y(), fMomIn.Z()), + fTime, + fLength, + fELoss, + TVector3(fPosOut.X(), fPosOut.Y(), fPosOut.Z()), + TVector3(fMomOut.X(), fMomOut.Y(), fMomOut.Z()), + fA, + fZmat, + fDensity, + fRadl); + } } - - diff --git a/base/steer/FairRadLenManager.h b/base/steer/FairRadLenManager.h index f142d78828..13573a2fca 100644 --- a/base/steer/FairRadLenManager.h +++ b/base/steer/FairRadLenManager.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -12,8 +12,8 @@ #ifndef FAIRRADLENMANAGER_H #define FAIRRADLENMANAGER_H 1 -#include // for Float_t, Double_t, Int_t, etc -#include // for TLorentzVector +#include // for Float_t, Double_t, Int_t, etc +#include // for TLorentzVector class TClonesArray; @@ -39,7 +39,7 @@ class FairRadLenManager /** * Class definition. */ - ClassDef(FairRadLenManager,1); + ClassDef(FairRadLenManager, 1); private: FairRadLenManager(const FairRadLenManager&); @@ -50,43 +50,43 @@ class FairRadLenManager /** * collection of point */ - TClonesArray* fPointCollection; + TClonesArray* fPointCollection; /**track index */ - Int_t fTrackID; //! + Int_t fTrackID; //! /**volume id */ - Int_t fVolumeID; //! + Int_t fVolumeID; //! /** entry position in global frame*/ - TLorentzVector fPosIn; //! + TLorentzVector fPosIn; //! /** exit position in global frame*/ - TLorentzVector fPosOut; //! + TLorentzVector fPosOut; //! /** momentum in*/ - TLorentzVector fMomIn; //! + TLorentzVector fMomIn; //! /** momentum out*/ - TLorentzVector fMomOut; //! + TLorentzVector fMomOut; //! /**track time */ - Double_t fTime; //! + Double_t fTime; //! /**track length */ - Double_t fLength; //! + Double_t fLength; //! /** energy loss */ - Double_t fELoss; //! + Double_t fELoss; //! /** mass umber*/ - Float_t fA; + Float_t fA; /** atomic number*/ - Float_t fZmat; + Float_t fZmat; /** density */ - Float_t fDensity; + Float_t fDensity; /**radition length */ - Float_t fRadl; + Float_t fRadl; /**absorption length */ - Float_t fAbsl; + Float_t fAbsl; public: /**Add point to collection*/ - void AddPoint(Int_t& ModuleId); + void AddPoint(Int_t& ModuleId); /**initialize the manager*/ - void Init(); + void Init(); /**reset*/ - void Reset(); + void Reset(); /** * This function is used to access the methods of the class. * @return Pointer to the singleton FairRadLenManager object, created diff --git a/base/steer/FairRadMapManager.cxx b/base/steer/FairRadMapManager.cxx index 2f96fb5968..4109e9fabc 100644 --- a/base/steer/FairRadMapManager.cxx +++ b/base/steer/FairRadMapManager.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -11,195 +11,200 @@ #include "FairRadMapManager.h" -#include "FairRadMapPoint.h" // for FairRadMapPoint -#include "FairRootManager.h" // for FairRootManager - -#include // for TClonesArray -#include // for TGeoManager, gGeoManager -#include // for TGeoVolume -#include // for TMap -#include // for TObjArray -#include // for TObject -#include // for TVector3 -#include // for TVectorD -#include // for TVectorT -#include // for TVirtualMC -#include // for TVirtualMCStack - -#include // for operator<<, basic_ostream, etc +#include "FairRadMapPoint.h" // for FairRadMapPoint +#include "FairRootManager.h" // for FairRootManager + +#include // for TClonesArray +#include // for TGeoManager, gGeoManager +#include // for TGeoVolume +#include // for TMap +#include // for TObjArray +#include // for TObject +#include // for TVector3 +#include // for TVectorD +#include // for TVectorT +#include // for TVirtualMC +#include // for TVirtualMCStack +#include // for operator<<, basic_ostream, etc using namespace std; -ClassImp(FairRadMapManager) +ClassImp(FairRadMapManager); FairRadMapManager* FairRadMapManager::fgInstance = nullptr; FairRadMapManager* FairRadMapManager::Instance() { - /**singelton instance*/ - return fgInstance; + /**singelton instance*/ + return fgInstance; } FairRadMapManager::FairRadMapManager() - : fPointCollection(new TClonesArray("FairRadMapPoint")), - fTrackID(0), - fVolumeID(0), - fPdg(0), - fPosIn(TLorentzVector(0,0,0,0)), - fPosOut(TLorentzVector(0,0,0,0)), - fMomIn(TLorentzVector(0,0,0,0)), - fMomOut(TLorentzVector(0,0,0,0)), - fTime(0), - fLength(0), - fStep(0), - fELoss(0), - fDose(0), - fDoseSL(0), - fA(0), - fZmat(0), - fRadl(0), - fDensity(0), - fAbsl(0), - fActVol(0), - fActMass(0), - fMassMap(nullptr) + : fPointCollection(new TClonesArray("FairRadMapPoint")) + , fTrackID(0) + , fVolumeID(0) + , fPdg(0) + , fPosIn(TLorentzVector(0, 0, 0, 0)) + , fPosOut(TLorentzVector(0, 0, 0, 0)) + , fMomIn(TLorentzVector(0, 0, 0, 0)) + , fMomOut(TLorentzVector(0, 0, 0, 0)) + , fTime(0) + , fLength(0) + , fStep(0) + , fELoss(0) + , fDose(0) + , fDoseSL(0) + , fA(0) + , fZmat(0) + , fRadl(0) + , fDensity(0) + , fAbsl(0) + , fActVol(0) + , fActMass(0) + , fMassMap(nullptr) { - /** radiation length default ctor */ - if(nullptr == fgInstance) { - fgInstance = this; - // fPointCollection=new TClonesArray("FairRadMapPoint"); - } - + /** radiation length default ctor */ + if (nullptr == fgInstance) { + fgInstance = this; + // fPointCollection=new TClonesArray("FairRadMapPoint"); + } } FairRadMapManager::~FairRadMapManager() { - /** radiation length default dtor */ - fgInstance = nullptr; - fPointCollection->Delete(); - delete fPointCollection; - delete fMassMap; + /** radiation length default dtor */ + fgInstance = nullptr; + fPointCollection->Delete(); + delete fPointCollection; + delete fMassMap; } void FairRadMapManager::Init() { - /**create the branch for output */ - FairRootManager::Instance()->Register("RadMap","RadMapPoint", fPointCollection, kTRUE); - cout << "RadMapMan initialized" << endl; - - // compute once the masses of the volumes in this simulation and store them in a TMap object + /**create the branch for output */ + FairRootManager::Instance()->Register("RadMap", "RadMapPoint", fPointCollection, kTRUE); + cout << "RadMapMan initialized" << endl; - Int_t volumeiterator=0,lastvolume=0; - Double_t vmass; - TObjArray* volumelist; - TGeoVolume* myvolume; - const char* volumename; - fMassMap = new TMap(lastvolume+1,0); + // compute once the masses of the volumes in this simulation and store them in a TMap object - volumelist = gGeoManager->GetListOfVolumes(); + Int_t volumeiterator = 0, lastvolume = 0; + Double_t vmass; + TObjArray* volumelist; + TGeoVolume* myvolume; + const char* volumename; + fMassMap = new TMap(lastvolume + 1, 0); - lastvolume = volumelist->GetLast(); + volumelist = gGeoManager->GetListOfVolumes(); - volumeiterator=0; + lastvolume = volumelist->GetLast(); - cout << "RadMapMan: calculating the masses for " << lastvolume << " volumes in this simulation" << endl; + volumeiterator = 0; - while ( volumeiterator<=lastvolume ) { - volumename = volumelist->At(volumeiterator)->GetName(); - myvolume = gGeoManager->GetVolume(volumename); - vmass = myvolume->WeightA(); // calculate weight analytically - TVectorD* vomass= new TVectorD(1,1,vmass,"END"); // 1-dim vector + cout << "RadMapMan: calculating the masses for " << lastvolume << " volumes in this simulation" << endl; - fMassMap->Add(myvolume,vomass); + while (volumeiterator <= lastvolume) { + volumename = volumelist->At(volumeiterator)->GetName(); + myvolume = gGeoManager->GetVolume(volumename); + vmass = myvolume->WeightA(); // calculate weight analytically + TVectorD* vomass = new TVectorD(1, 1, vmass, "END"); // 1-dim vector - cout << myvolume->GetName() << " has " << vmass << " kg" << endl; + fMassMap->Add(myvolume, vomass); - volumeiterator++; - } + cout << myvolume->GetName() << " has " << vmass << " kg" << endl; + volumeiterator++; + } } void FairRadMapManager::Reset() { - /**We have to free the momeory, Clear() is faster but not enough! */ - fPointCollection->Delete(); - cout << " FairRadMapManager::Reset() ------------------------------------------------\n" << endl; + /**We have to free the momeory, Clear() is faster but not enough! */ + fPointCollection->Delete(); + cout << " FairRadMapManager::Reset() ------------------------------------------------\n" << endl; } void FairRadMapManager::AddPoint(Int_t&) { - /**Add a point to the collection*/ - if ( TVirtualMC::GetMC()->IsTrackEntering() ) { - fELoss = 0.; - fStep = 0.; - fDose = 0.; - fDoseSL = 0.; - fPdg = 0; - fActVol = 0.; - fActMass = 0.; - Int_t copyNo; - fVolumeID = TVirtualMC::GetMC()->CurrentVolID(copyNo); - fTime = TVirtualMC::GetMC()->TrackTime() * 1.0e09; - fLength = TVirtualMC::GetMC()->TrackLength(); - TVirtualMC::GetMC()->TrackPosition(fPosIn); - TVirtualMC::GetMC()->TrackMomentum(fMomIn); - // Int_t MatId= TVirtualMC::GetMC()->CurrentMaterial(fA, fZmat, fDensity, fRadl, fAbsl); - TVirtualMC::GetMC()->CurrentMaterial(fA, fZmat, fDensity, fRadl, fAbsl); - - // if (!gGeoManager) { GetGeoManager(); } - // TGeoVolume* actVolume = gGeoManager->GetCurrentVolume(); - TGeoVolume* actVolume = gGeoManager->GetVolume(fVolumeID); - - TVectorD* ActMass = static_cast(fMassMap->GetValue(actVolume)); - - fActMass = ActMass->Min(); // read from TVectorD - - // cout << actVolume->GetName() << " has " << fActMass << " kg" << endl; - - } - /** Sum energy loss for all steps in the active volume */ - fELoss += TVirtualMC::GetMC()->Edep(); - fStep += TVirtualMC::GetMC()->TrackStep(); - - fPdg = TVirtualMC::GetMC()->TrackPid(); - - // calculate the energy dose - // exclude fragments with PDG code >= 10000 - - if (fPdg<10000 && fStep>0 && fActMass>0 ) { - // fDose = fELoss*1.602e-10/(fDensity*actvol*0.001); // per mass/kg - fDose = fELoss*1.602e-10/(fActMass); // per mass/kg - } else { - fDose = -.00001; - } - - // exclude very high, probably wrong, energy doses - if ( fDose>0.02 ) { - fDose = -.00001; - } - - /** Create a point at exit of the volume */ - if ( TVirtualMC::GetMC()->IsTrackExiting() || - TVirtualMC::GetMC()->IsTrackStop() || - TVirtualMC::GetMC()->IsTrackDisappeared() ) { - -// FairRadMapPoint* p=0; - fTrackID = TVirtualMC::GetMC()->GetStack()->GetCurrentTrackNumber(); - Int_t copyNo; - Int_t fVolID = TVirtualMC::GetMC()->CurrentVolID(copyNo); // CAVEAT: fVolID is NOT an unique identifier!! - TVirtualMC::GetMC()->TrackPosition(fPosOut); - TVirtualMC::GetMC()->TrackMomentum(fMomOut); - - TClonesArray& clref = *fPointCollection; - Int_t tsize = clref.GetEntriesFast(); - -// p=new(clref[tsize]) FairRadMapPoint(fTrackID, fVolID, - new(clref[tsize]) FairRadMapPoint(fTrackID, fVolID, - TVector3(fPosIn.X(),fPosIn.Y(),fPosIn.Z()), - TVector3(fMomIn.X(),fMomIn.Y(),fMomIn.Z()), - fTime, fLength, fELoss, - TVector3(fPosOut.X(),fPosOut.Y(),fPosOut.Z()), - TVector3(fMomOut.X(),fMomOut.Y(),fMomOut.Z()), - fA, fZmat, fDensity, fActMass, fStep, fDose, fDoseSL, fPdg); - } + /**Add a point to the collection*/ + if (TVirtualMC::GetMC()->IsTrackEntering()) { + fELoss = 0.; + fStep = 0.; + fDose = 0.; + fDoseSL = 0.; + fPdg = 0; + fActVol = 0.; + fActMass = 0.; + Int_t copyNo; + fVolumeID = TVirtualMC::GetMC()->CurrentVolID(copyNo); + fTime = TVirtualMC::GetMC()->TrackTime() * 1.0e09; + fLength = TVirtualMC::GetMC()->TrackLength(); + TVirtualMC::GetMC()->TrackPosition(fPosIn); + TVirtualMC::GetMC()->TrackMomentum(fMomIn); + // Int_t MatId= TVirtualMC::GetMC()->CurrentMaterial(fA, fZmat, fDensity, fRadl, fAbsl); + TVirtualMC::GetMC()->CurrentMaterial(fA, fZmat, fDensity, fRadl, fAbsl); + + // if (!gGeoManager) { GetGeoManager(); } + // TGeoVolume* actVolume = gGeoManager->GetCurrentVolume(); + TGeoVolume* actVolume = gGeoManager->GetVolume(fVolumeID); + + TVectorD* ActMass = static_cast(fMassMap->GetValue(actVolume)); + + fActMass = ActMass->Min(); // read from TVectorD + + // cout << actVolume->GetName() << " has " << fActMass << " kg" << endl; + } + /** Sum energy loss for all steps in the active volume */ + fELoss += TVirtualMC::GetMC()->Edep(); + fStep += TVirtualMC::GetMC()->TrackStep(); + + fPdg = TVirtualMC::GetMC()->TrackPid(); + + // calculate the energy dose + // exclude fragments with PDG code >= 10000 + + if (fPdg < 10000 && fStep > 0 && fActMass > 0) { + // fDose = fELoss*1.602e-10/(fDensity*actvol*0.001); // per mass/kg + fDose = fELoss * 1.602e-10 / (fActMass); // per mass/kg + } else { + fDose = -.00001; + } + + // exclude very high, probably wrong, energy doses + if (fDose > 0.02) { + fDose = -.00001; + } + + /** Create a point at exit of the volume */ + if (TVirtualMC::GetMC()->IsTrackExiting() || TVirtualMC::GetMC()->IsTrackStop() + || TVirtualMC::GetMC()->IsTrackDisappeared()) { + + // FairRadMapPoint* p=0; + fTrackID = TVirtualMC::GetMC()->GetStack()->GetCurrentTrackNumber(); + Int_t copyNo; + Int_t fVolID = TVirtualMC::GetMC()->CurrentVolID(copyNo); // CAVEAT: fVolID is NOT an unique identifier!! + TVirtualMC::GetMC()->TrackPosition(fPosOut); + TVirtualMC::GetMC()->TrackMomentum(fMomOut); + + TClonesArray& clref = *fPointCollection; + Int_t tsize = clref.GetEntriesFast(); + + // p=new(clref[tsize]) FairRadMapPoint(fTrackID, fVolID, + new (clref[tsize]) FairRadMapPoint(fTrackID, + fVolID, + TVector3(fPosIn.X(), fPosIn.Y(), fPosIn.Z()), + TVector3(fMomIn.X(), fMomIn.Y(), fMomIn.Z()), + fTime, + fLength, + fELoss, + TVector3(fPosOut.X(), fPosOut.Y(), fPosOut.Z()), + TVector3(fMomOut.X(), fMomOut.Y(), fMomOut.Z()), + fA, + fZmat, + fDensity, + fActMass, + fStep, + fDose, + fDoseSL, + fPdg); + } } diff --git a/base/steer/FairRadMapManager.h b/base/steer/FairRadMapManager.h index deba000520..766af76ff8 100644 --- a/base/steer/FairRadMapManager.h +++ b/base/steer/FairRadMapManager.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -11,8 +11,8 @@ #ifndef FAIRRADMAPMANAGER_H #define FAIRRADMAPMANAGER_H 1 -#include // for Double_t, Float_t, Int_t, etc -#include // for TLorentzVector +#include // for Double_t, Float_t, Int_t, etc +#include // for TLorentzVector class TClonesArray; class TMap; @@ -39,7 +39,7 @@ class FairRadMapManager /** * Class definition. */ - ClassDef(FairRadMapManager,1); + ClassDef(FairRadMapManager, 1); private: FairRadMapManager(const FairRadMapManager&); @@ -50,55 +50,55 @@ class FairRadMapManager /** * collection of point */ - TClonesArray* fPointCollection; + TClonesArray* fPointCollection; /**track index */ - Int_t fTrackID; //! + Int_t fTrackID; //! /**volume id */ - Int_t fVolumeID; //! + Int_t fVolumeID; //! /** pid */ - Int_t fPdg; //! + Int_t fPdg; //! /** entry position in global frame*/ - TLorentzVector fPosIn; //! + TLorentzVector fPosIn; //! /** exit position in global frame*/ - TLorentzVector fPosOut; //! + TLorentzVector fPosOut; //! /** momentum in*/ - TLorentzVector fMomIn; //! + TLorentzVector fMomIn; //! /** momentum out*/ - TLorentzVector fMomOut; //! + TLorentzVector fMomOut; //! /**track time */ - Double_t fTime; //! + Double_t fTime; //! /**track length */ - Double_t fLength; //! + Double_t fLength; //! /**track setp */ - Double_t fStep; + Double_t fStep; /** energy loss */ - Double_t fELoss; //! + Double_t fELoss; //! /**dose */ - Double_t fDose; - Double_t fDoseSL; + Double_t fDose; + Double_t fDoseSL; /** mass umber*/ - Float_t fA; + Float_t fA; /** atomic number*/ - Float_t fZmat; + Float_t fZmat; /** radiation length*/ - Float_t fRadl; + Float_t fRadl; /** density */ - Float_t fDensity; + Float_t fDensity; /**absorption length */ - Float_t fAbsl; + Float_t fAbsl; //**volume, mass */ - Double_t fActVol; - Double_t fActMass; + Double_t fActVol; + Double_t fActMass; TMap* fMassMap; public: /**Add point to collection*/ - void AddPoint(Int_t& ModuleId); + void AddPoint(Int_t& ModuleId); /**initialize the manager*/ - void Init(); + void Init(); /**reset*/ - void Reset(); + void Reset(); /** * This function is used to access the methods of the class. * @return Pointer to the singleton FairRadMapManager object, created diff --git a/base/steer/FairRingSorter.cxx b/base/steer/FairRingSorter.cxx index 93f7269c45..a9926db45f 100644 --- a/base/steer/FairRingSorter.cxx +++ b/base/steer/FairRingSorter.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -12,101 +12,102 @@ // ------------------------------------------------------------------------- #include "FairRingSorter.h" -#include "FairTimeStamp.h" // for FairTimeStamp -FairTimeStamp* FairRingSorter::CreateElement(FairTimeStamp* data) -{ - return static_cast(data->Clone()); -} +#include "FairTimeStamp.h" // for FairTimeStamp + +FairTimeStamp* FairRingSorter::CreateElement(FairTimeStamp* data) { return static_cast(data->Clone()); } void FairRingSorter::AddElement(FairTimeStamp* digi, double timestamp) { - FairTimeStamp* newElement = CreateElement(digi); - if (timestamp < fLowerBoundPointer.second) { - std::cout << "-E- Timestamp " << timestamp << " below lower bound " << fLowerBoundPointer.second << std::endl; - newElement->Print(); - return; - } - int index = CalcIndex(timestamp); - - if (timestamp >= fLowerBoundPointer.second + (2 * GetBufferSize())) { - if (fVerbose > 0) { - std::cout << "-I- FairRingSorterT::AddElement : Timestamp " - << timestamp << " larger than 2 * bufferspace: " << fLowerBoundPointer.second + GetBufferSize() << " writing out " << index + 1 << std::endl; + FairTimeStamp* newElement = CreateElement(digi); + if (timestamp < fLowerBoundPointer.second) { + std::cout << "-E- Timestamp " << timestamp << " below lower bound " << fLowerBoundPointer.second << std::endl; + newElement->Print(); + return; } - WriteOutAll(); - SetLowerBound(timestamp); - } else if (timestamp >= fLowerBoundPointer.second + GetBufferSize()) { - if (fVerbose > 0) { - std::cout << "-I- FairRingSorterT::AddElement :Timestamp " - << timestamp << " larger than bufferspace: " - << fLowerBoundPointer.second + GetBufferSize() << " writing out " << index+1 << std::endl; + int index = CalcIndex(timestamp); + + if (timestamp >= fLowerBoundPointer.second + (2 * GetBufferSize())) { + if (fVerbose > 0) { + std::cout << "-I- FairRingSorterT::AddElement : Timestamp " << timestamp + << " larger than 2 * bufferspace: " << fLowerBoundPointer.second + GetBufferSize() + << " writing out " << index + 1 << std::endl; + } + WriteOutAll(); + SetLowerBound(timestamp); + } else if (timestamp >= fLowerBoundPointer.second + GetBufferSize()) { + if (fVerbose > 0) { + std::cout << "-I- FairRingSorterT::AddElement :Timestamp " << timestamp + << " larger than bufferspace: " << fLowerBoundPointer.second + GetBufferSize() << " writing out " + << index + 1 << std::endl; + } + WriteOutElements(index + 1); + SetLowerBound(timestamp); } - WriteOutElements(index+1); - SetLowerBound(timestamp); - } - fRingBuffer[index].insert(std::pair (timestamp, newElement)); + fRingBuffer[index].insert(std::pair(timestamp, newElement)); } void FairRingSorter::SetLowerBound(double timestampOfHitToWrite) { - int index = CalcIndex(timestampOfHitToWrite + fCellWidth); + int index = CalcIndex(timestampOfHitToWrite + fCellWidth); - int cellValue = static_cast(timestampOfHitToWrite / fCellWidth); + int cellValue = static_cast(timestampOfHitToWrite / fCellWidth); - fLowerBoundPointer.second = ((cellValue + 1) * fCellWidth) - GetBufferSize(); - fLowerBoundPointer.first = index; - if (fVerbose > 0) { std::cout << "-I- FairRingSorter::SetLowerBound " << index << " / " << fLowerBoundPointer.second << std::endl; } + fLowerBoundPointer.second = ((cellValue + 1) * fCellWidth) - GetBufferSize(); + fLowerBoundPointer.first = index; + if (fVerbose > 0) { + std::cout << "-I- FairRingSorter::SetLowerBound " << index << " / " << fLowerBoundPointer.second << std::endl; + } } void FairRingSorter::WriteOutElements(int index) { - if (fLowerBoundPointer.first >= index) { - for (unsigned int i = fLowerBoundPointer.first; i < fRingBuffer.size(); i++) { - WriteOutElement(i); - } - for (int i = 0; i < index; i++) { - WriteOutElement(i); + if (fLowerBoundPointer.first >= index) { + for (unsigned int i = fLowerBoundPointer.first; i < fRingBuffer.size(); i++) { + WriteOutElement(i); + } + for (int i = 0; i < index; i++) { + WriteOutElement(i); + } + } else { + for (int i = fLowerBoundPointer.first; i < index; i++) { + WriteOutElement(i); + } } - } else { - for (int i = fLowerBoundPointer.first; i < index; i++) { - WriteOutElement(i); - } - } - if (fVerbose > 1) { - std::cout << "-I- FairRingSorter::WriteOutElements: Size of Output-Array: " << fOutputData.size() << std::endl; - for (unsigned int i = 0; i < fOutputData.size(); i++) { - fOutputData[i]->Print(); - std::cout << " | "; + if (fVerbose > 1) { + std::cout << "-I- FairRingSorter::WriteOutElements: Size of Output-Array: " << fOutputData.size() << std::endl; + for (unsigned int i = 0; i < fOutputData.size(); i++) { + fOutputData[i]->Print(); + std::cout << " | "; + } + std::cout << std::endl; } - std::cout << std::endl; - } } void FairRingSorter::WriteOutElement(int index) { - std::multimap* myDataField = &fRingBuffer.at(index); - std::multimap::iterator it; - if (!myDataField->empty()) { - if (fVerbose > 1) { - std::cout << "-I- FairRingSorter:WriteOutElement "; - myDataField->begin()->second->Print(); - std::cout << std::endl; - } - for (auto& mmi : *myDataField) { - fOutputData.push_back(mmi.second); + std::multimap* myDataField = &fRingBuffer.at(index); + std::multimap::iterator it; + if (!myDataField->empty()) { + if (fVerbose > 1) { + std::cout << "-I- FairRingSorter:WriteOutElement "; + myDataField->begin()->second->Print(); + std::cout << std::endl; + } + for (auto& mmi : *myDataField) { + fOutputData.push_back(mmi.second); + } + myDataField->clear(); } - myDataField->clear(); - } } int FairRingSorter::CalcIndex(double val) { - unsigned int index = static_cast(val / fCellWidth); - while (index >= fRingBuffer.size()) { - index -= fRingBuffer.size(); - } - return index; + unsigned int index = static_cast(val / fCellWidth); + while (index >= fRingBuffer.size()) { + index -= fRingBuffer.size(); + } + return index; } ClassImp(FairRingSorter); diff --git a/base/steer/FairRingSorter.h b/base/steer/FairRingSorter.h index 1351a8e714..703f610220 100644 --- a/base/steer/FairRingSorter.h +++ b/base/steer/FairRingSorter.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* @@ -15,13 +15,12 @@ #ifndef FairRingSorter_H_ #define FairRingSorter_H_ -#include // for TObject -#include // for FairRingSorter::Class, etc - -#include // for operator<<, ostream, etc -#include // for multimap -#include // for pair -#include // for vector +#include // for FairRingSorter::Class, etc +#include // for TObject +#include // for operator<<, ostream, etc +#include // for multimap +#include // for pair +#include // for vector class FairTimeStamp; @@ -29,43 +28,49 @@ class FairRingSorter : public TObject { public: FairRingSorter(int size = 100, double width = 10) - : TObject(), fRingBuffer(size), fOutputData(), fLowerBoundPointer(0,0), - fCellWidth(width), fVerbose(0) { - } + : TObject() + , fRingBuffer(size) + , fOutputData() + , fLowerBoundPointer(0, 0) + , fCellWidth(width) + , fVerbose(0) + {} - virtual ~FairRingSorter() {}; + virtual ~FairRingSorter(){}; virtual FairTimeStamp* CreateElement(FairTimeStamp* data); virtual void AddElement(FairTimeStamp* digi, double timestamp); - virtual void WriteOutElements(int index); ///< writes out the entries from LowerBoundPointer up to index - virtual void WriteOutElement(int index); ///< writes out the entry at the index and clears it + virtual void WriteOutElements(int index); ///< writes out the entries from LowerBoundPointer up to index + virtual void WriteOutElement(int index); ///< writes out the entry at the index and clears it virtual void WriteOutAll() { WriteOutElements(fLowerBoundPointer.first); } virtual double GetBufferSize() { return fCellWidth * fRingBuffer.size(); } virtual std::vector GetOutputData() { return fOutputData; } - virtual void DeleteOutputData() {fOutputData.clear(); } + virtual void DeleteOutputData() { fOutputData.clear(); } virtual void SetLowerBound(double timestampOfHitToWrite); - virtual void print(std::ostream& out = std::cout) { - out << "RingSorter: Size " << fRingBuffer.size() << " CellWidth: " << fCellWidth << "\n"; - out << "LowerBoundPointer at index: " << fLowerBoundPointer.first << " Time: " << fLowerBoundPointer.second << "\n"; - out << "| "; - for (unsigned int i = 0; i < fRingBuffer.size(); i++) { - out << fRingBuffer[i].size() << " |"; - } - out << std::endl; + virtual void print(std::ostream& out = std::cout) + { + out << "RingSorter: Size " << fRingBuffer.size() << " CellWidth: " << fCellWidth << "\n"; + out << "LowerBoundPointer at index: " << fLowerBoundPointer.first << " Time: " << fLowerBoundPointer.second + << "\n"; + out << "| "; + for (unsigned int i = 0; i < fRingBuffer.size(); i++) { + out << fRingBuffer[i].size() << " |"; + } + out << std::endl; } private: int CalcIndex(double val); - std::vector > fRingBuffer; + std::vector> fRingBuffer; std::vector fOutputData; std::pair fLowerBoundPointer; double fCellWidth; int fVerbose; - ClassDef(FairRingSorter,1) + ClassDef(FairRingSorter, 1) }; #endif /* FairRingSorter_H_ */ diff --git a/base/steer/FairRingSorterTask.cxx b/base/steer/FairRingSorterTask.cxx index 7f17b812d5..5e77b7ead8 100644 --- a/base/steer/FairRingSorterTask.cxx +++ b/base/steer/FairRingSorterTask.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -11,114 +11,114 @@ #include "FairRingSorterTask.h" -#include "FairLink.h" // for FairLink -#include "FairRootManager.h" // for FairRootManager -#include "FairTimeStamp.h" // for FairTimeStamp +#include "FairLink.h" // for FairLink +#include "FairRootManager.h" // for FairRootManager +#include "FairTimeStamp.h" // for FairTimeStamp -#include // for TClass -#include // for TClonesArray +#include // for TClass +#include // for TClonesArray +#include // for operator<<, cout, ostream, etc +#include // for vector -#include // for operator<<, cout, ostream, etc -#include // for vector - -InitStatus FairRingSorterTask::ReInit() -{ - return kSUCCESS; -} +InitStatus FairRingSorterTask::ReInit() { return kSUCCESS; } FairRingSorter* FairRingSorterTask::InitSorter(Int_t numberOfCells, Double_t widthOfCells) const { - return new FairRingSorter(numberOfCells, widthOfCells); + return new FairRingSorter(numberOfCells, widthOfCells); } InitStatus FairRingSorterTask::Init() { - FairRootManager* ioman = FairRootManager::Instance(); - if ( ! ioman ) { - std::cout << "-E- FairRingSorterTaskT::Init: " - << "RootManager not instantiated!" << std::endl; - return kFATAL; - } + FairRootManager* ioman = FairRootManager::Instance(); + if (!ioman) { + std::cout << "-E- FairRingSorterTaskT::Init: " + << "RootManager not instantiated!" << std::endl; + return kFATAL; + } - fSorter = InitSorter(fNumberOfCells, fWidthOfCells); + fSorter = InitSorter(fNumberOfCells, fWidthOfCells); - // Create and register output array - fInputArray = FairRootManager::Instance()->GetTClonesArray(fInputBranch); + // Create and register output array + fInputArray = FairRootManager::Instance()->GetTClonesArray(fInputBranch); - if(fVerbose>1) { Info("Init","Registering this branch: %s/%s",fFolder.Data(),fOutputBranch.Data()); } - fOutputArray = ioman->Register(fOutputBranch, fInputArray->GetClass()->GetName(), fFolder, fPersistance); + if (fVerbose > 1) { + Info("Init", "Registering this branch: %s/%s", fFolder.Data(), fOutputBranch.Data()); + } + fOutputArray = ioman->Register(fOutputBranch, fInputArray->GetClass()->GetName(), fFolder, fPersistance); - return kSUCCESS; + return kSUCCESS; } void FairRingSorterTask::Exec(Option_t*) { - fInputArray = FairRootManager::Instance()->GetTClonesArray(fInputBranch); - if (fVerbose > 1) { - std::cout << "-I- FairRingSorterTask: Size PixelArray: " << fInputArray->GetEntriesFast() << std::endl; - } - for (int i = 0; i < fInputArray->GetEntriesFast(); i++) { - FairTimeStamp* myData = static_cast(fInputArray->At(i)); - myData->SetEntryNr(FairLink(0, fEntryNr, fInputBranch, i)); + fInputArray = FairRootManager::Instance()->GetTClonesArray(fInputBranch); if (fVerbose > 1) { - std::cout << "Sorter filled with: "; - myData->Print(); - std::cout<< std::endl; + std::cout << "-I- FairRingSorterTask: Size PixelArray: " << fInputArray->GetEntriesFast() << std::endl; + } + for (int i = 0; i < fInputArray->GetEntriesFast(); i++) { + FairTimeStamp* myData = static_cast(fInputArray->At(i)); + myData->SetEntryNr(FairLink(0, fEntryNr, fInputBranch, i)); + if (fVerbose > 1) { + std::cout << "Sorter filled with: "; + myData->Print(); + std::cout << std::endl; + } + fSorter->AddElement(myData, myData->GetTimeStamp()); } - fSorter->AddElement(myData, myData->GetTimeStamp()); - } - if (fVerbose > 2) { fSorter->Print(); } - - std::vector sortedData = fSorter->GetOutputData(); - - fOutputArray = FairRootManager::Instance()->GetEmptyTClonesArray(fOutputBranch); - for (unsigned int i = 0; i < sortedData.size(); i++) { - AddNewDataToTClonesArray(sortedData[i]); - } - fSorter->DeleteOutputData(); - fEntryNr++; + if (fVerbose > 2) { + fSorter->Print(); + } + + std::vector sortedData = fSorter->GetOutputData(); + + fOutputArray = FairRootManager::Instance()->GetEmptyTClonesArray(fOutputBranch); + for (unsigned int i = 0; i < sortedData.size(); i++) { + AddNewDataToTClonesArray(sortedData[i]); + } + fSorter->DeleteOutputData(); + fEntryNr++; } void FairRingSorterTask::AddNewDataToTClonesArray(FairTimeStamp* data) { - FairRootManager* ioman = FairRootManager::Instance(); - TClonesArray* myArray = ioman->GetTClonesArray(fOutputBranch); - (*myArray)[myArray->GetEntries()] = data; + FairRootManager* ioman = FairRootManager::Instance(); + TClonesArray* myArray = ioman->GetTClonesArray(fOutputBranch); + (*myArray)[myArray->GetEntries()] = data; } -void FairRingSorterTask::FinishEvent() -{ - fOutputArray->Delete(); -} +void FairRingSorterTask::FinishEvent() { fOutputArray->Delete(); } void FairRingSorterTask::FinishTask() { - fInputArray = FairRootManager::Instance()->GetTClonesArray(fInputBranch); - if (fVerbose > 2) { std::cout << "-I- FairRingSorterTaskT::FinishTask Size InputArray: " << fInputArray->GetEntriesFast() << std::endl; } - for (int i = 0; i < fInputArray->GetEntriesFast(); i++) { - FairTimeStamp* myDigi = static_cast( fInputArray->At(i)); - fSorter->AddElement(myDigi, (static_cast(myDigi))->GetTimeStamp()); - } - fSorter->Print(); - fSorter->WriteOutAll(); - std::vector sortedData = fSorter->GetOutputData(); - - FairRootManager* ioman = FairRootManager::Instance(); - fOutputArray = ioman->GetEmptyTClonesArray(fOutputBranch); - for (unsigned int i = 0; i < sortedData.size(); i++) { + fInputArray = FairRootManager::Instance()->GetTClonesArray(fInputBranch); if (fVerbose > 2) { - std::cout << i << " FinishTask : "; - sortedData[i]->Print(); - std::cout << std::endl; + std::cout << "-I- FairRingSorterTaskT::FinishTask Size InputArray: " << fInputArray->GetEntriesFast() + << std::endl; + } + for (int i = 0; i < fInputArray->GetEntriesFast(); i++) { + FairTimeStamp* myDigi = static_cast(fInputArray->At(i)); + fSorter->AddElement(myDigi, (static_cast(myDigi))->GetTimeStamp()); } - - AddNewDataToTClonesArray(sortedData[i]); - } - fSorter->DeleteOutputData(); - if (fVerbose > 1) { fSorter->Print(); - } - ioman->SetLastFill(); + fSorter->WriteOutAll(); + std::vector sortedData = fSorter->GetOutputData(); + + FairRootManager* ioman = FairRootManager::Instance(); + fOutputArray = ioman->GetEmptyTClonesArray(fOutputBranch); + for (unsigned int i = 0; i < sortedData.size(); i++) { + if (fVerbose > 2) { + std::cout << i << " FinishTask : "; + sortedData[i]->Print(); + std::cout << std::endl; + } + + AddNewDataToTClonesArray(sortedData[i]); + } + fSorter->DeleteOutputData(); + if (fVerbose > 1) { + fSorter->Print(); + } + ioman->SetLastFill(); } ClassImp(FairRingSorterTask); diff --git a/base/steer/FairRingSorterTask.h b/base/steer/FairRingSorterTask.h index 64658a7261..e6c5042517 100644 --- a/base/steer/FairRingSorterTask.h +++ b/base/steer/FairRingSorterTask.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ @@ -13,12 +13,11 @@ #ifndef FairRingSorterTask_H #define FairRingSorterTask_H -#include "FairTask.h" // for FairTask, InitStatus +#include "FairRingSorter.h" // for FairRingSorter +#include "FairTask.h" // for FairTask, InitStatus -#include "FairRingSorter.h" // for FairRingSorter - -#include // for Bool_t, Int_t, kTRUE, etc -#include // for TString +#include // for Bool_t, Int_t, kTRUE, etc +#include // for TString class FairTimeStamp; class TClonesArray; @@ -27,59 +26,64 @@ class FairRingSorterTask : public FairTask { public: /** Default constructor **/ - FairRingSorterTask(): - FairTask("SorterTask"), - fSorter(0), - fPersistance(kTRUE), - fDigiPixelMCInfo(kFALSE), - fNumberOfCells(1000), - fWidthOfCells(10), - fInputBranch(), - fInputArray(0), - fOutputBranch(), - fFolder(), - fOutputArray(0), - fEntryNr(0) { - SetVerbose(0); + FairRingSorterTask() + : FairTask("SorterTask") + , fSorter(0) + , fPersistance(kTRUE) + , fDigiPixelMCInfo(kFALSE) + , fNumberOfCells(1000) + , fWidthOfCells(10) + , fInputBranch() + , fInputArray(0) + , fOutputBranch() + , fFolder() + , fOutputArray(0) + , fEntryNr(0) + { + SetVerbose(0); } /** Named constructor **/ - FairRingSorterTask(const char* name): - FairTask(name), - fSorter(0), - fPersistance(kTRUE), - fDigiPixelMCInfo(kFALSE), - fNumberOfCells(1000), - fWidthOfCells(10), - fInputBranch(), - fInputArray(0), - fOutputBranch(), - fFolder(), - fOutputArray(0), - fEntryNr(0) { - SetVerbose(0); + FairRingSorterTask(const char* name) + : FairTask(name) + , fSorter(0) + , fPersistance(kTRUE) + , fDigiPixelMCInfo(kFALSE) + , fNumberOfCells(1000) + , fWidthOfCells(10) + , fInputBranch() + , fInputArray(0) + , fOutputBranch() + , fFolder() + , fOutputArray(0) + , fEntryNr(0) + { + SetVerbose(0); } - FairRingSorterTask(Int_t numberOfCells, Double_t widthOfCells, TString inputBranch, TString outputBranch, TString folderName): - FairTask("Sorter"), - fSorter(0), - fPersistance(kTRUE), - fDigiPixelMCInfo(kFALSE), - fNumberOfCells(numberOfCells), - fWidthOfCells(widthOfCells), - fInputBranch(inputBranch), - fInputArray(0), - fOutputBranch(outputBranch), - fFolder(folderName), - fOutputArray(0), - fEntryNr(0) { - SetVerbose(0); + FairRingSorterTask(Int_t numberOfCells, + Double_t widthOfCells, + TString inputBranch, + TString outputBranch, + TString folderName) + : FairTask("Sorter") + , fSorter(0) + , fPersistance(kTRUE) + , fDigiPixelMCInfo(kFALSE) + , fNumberOfCells(numberOfCells) + , fWidthOfCells(widthOfCells) + , fInputBranch(inputBranch) + , fInputArray(0) + , fOutputBranch(outputBranch) + , fFolder(folderName) + , fOutputArray(0) + , fEntryNr(0) + { + SetVerbose(0); } /** Destructor **/ - virtual ~FairRingSorterTask() { - delete fSorter; - } + virtual ~FairRingSorterTask() { delete fSorter; } /** Virtual method Init **/ virtual InitStatus Init(); @@ -90,10 +94,10 @@ class FairRingSorterTask : public FairTask virtual void FinishEvent(); virtual void FinishTask(); - virtual void SetParContainers() {}; + virtual void SetParContainers(){}; - void SetPersistance(Bool_t p = kTRUE) {fPersistance=p;}; - Bool_t GetPersistance() {return fPersistance;}; + void SetPersistance(Bool_t p = kTRUE) { fPersistance = p; }; + Bool_t GetPersistance() { return fPersistance; }; virtual void AddNewDataToTClonesArray(FairTimeStamp* data); virtual FairRingSorter* InitSorter(Int_t numberOfCells, Double_t widthOfCells) const; @@ -105,7 +109,7 @@ class FairRingSorterTask : public FairTask /** switch to turn on/off storing additional MC Info of Digis*/ Bool_t fDigiPixelMCInfo; Int_t fNumberOfCells; - Double_t fWidthOfCells; // in ns + Double_t fWidthOfCells; // in ns /** Input array of PndSdsPixelDigis **/ TString fInputBranch; TClonesArray* fInputArray; @@ -117,7 +121,7 @@ class FairRingSorterTask : public FairTask FairRingSorterTask(const FairRingSorterTask&); FairRingSorterTask& operator=(const FairRingSorterTask&); - ClassDef(FairRingSorterTask,2); + ClassDef(FairRingSorterTask, 2); }; #endif diff --git a/base/steer/FairRootManager.cxx b/base/steer/FairRootManager.cxx index 2fe9c8baf3..4cbfbf235d 100644 --- a/base/steer/FairRootManager.cxx +++ b/base/steer/FairRootManager.cxx @@ -15,1067 +15,1052 @@ // Class that takes care of Root IO. #include "FairRootManager.h" -#include "FairEventHeader.h" // for FairEventHeader -#include "FairFileHeader.h" // for FairFileHeader -#include "FairLink.h" // for FairLink -#include "FairLogger.h" // for FairLogger, MESSAGE_ORIGIN -#include "FairMonitor.h" // for FairMonitor -#include "FairRun.h" // for FairRun -#include "FairTSBufferFunctional.h" // for FairTSBufferFunctional, etc -#include "FairWriteoutBuffer.h" // for FairWriteoutBuffer -#include "FairLinkManager.h" // for FairLinkManager -#include "FairRootFileSink.h" // to enable GetOutFile() - -#include // for TBranch -#include // for TClonesArray -#include // for TCollection, TIter -#include // for TFolder -#include // for TGeoManager, gGeoManager -#include // for TIterator -#include // for TList -#include // for TNamed -#include // for TObjArray -#include // for TObjString -#include // for TTree -#include // for TRefArray -#include // for TFile +#include "FairEventHeader.h" // for FairEventHeader +#include "FairFileHeader.h" // for FairFileHeader +#include "FairLink.h" // for FairLink +#include "FairLinkManager.h" // for FairLinkManager +#include "FairLogger.h" // for FairLogger, MESSAGE_ORIGIN +#include "FairMonitor.h" // for FairMonitor +#include "FairRootFileSink.h" // to enable GetOutFile() +#include "FairRun.h" // for FairRun +#include "FairTSBufferFunctional.h" // for FairTSBufferFunctional, etc +#include "FairWriteoutBuffer.h" // for FairWriteoutBuffer + +#include // for TBranch +#include // for TClonesArray +#include // for TCollection, TIter +#include // for TFile +#include // for TFolder +#include // for TGeoManager, gGeoManager +#include // for TIterator +#include // for TList #include - -#include // for exit -#include // for strcmp -#include // for find -#include // for operator<<, basic_ostream, etc -#include // for _List_iterator, list, etc -#include // for map, _Rb_tree_iterator, etc -#include // for set, set<>::iterator -#include // for pair -#include // for vector +#include // for TNamed +#include // for TObjArray +#include // for TObjString +#include // for TRefArray +#include // for TTree +#include // for find #include #include +#include // for strcmp +#include // for operator<<, basic_ostream, etc +#include // for _List_iterator, list, etc +#include // for map, _Rb_tree_iterator, etc +#include // for set, set<>::iterator +#include // for exit +#include // for pair +#include // for vector -using std::map; using std::list; +using std::map; using std::pair; using std::set; namespace { - // Define mutexes per operation which modify shared data - TMCMutex createMutex = TMCMUTEX_INITIALIZER; - TMCMutex deleteMutex = TMCMUTEX_INITIALIZER; -} +// Define mutexes per operation which modify shared data +TMCMutex createMutex = TMCMUTEX_INITIALIZER; +TMCMutex deleteMutex = TMCMUTEX_INITIALIZER; +} // namespace Int_t FairRootManager::fgCounter = 0; FairRootManager* FairRootManager::Instance() { -// Returns singleton instance. -// --- + // Returns singleton instance. + // --- static thread_local FairRootManager instance; return &instance; } FairRootManager::FairRootManager() - : TObject(), - fOldEntryNr(-1), - fOutFolder(0), - fRootFolder(0), - fCurrentTime(0), - fObj2(new TObject*[1000]), - fNObj(-1), - fMap(), - fBranchSeqId(0), - fBranchNameList(new TList()), - fMCTrackBranchId(-1), - fTimeBasedBranchNameList(new TList()), - fActiveContainer(), - fTSBufferMap(), - fWriteoutBufferMap(), - fInputBranchMap(), - fTimeStamps(kFALSE), - fBranchPerMap(kFALSE), - fBrPerMap(), - fBrPerMapIter(), - fCurrentEntryNo(0), - fTimeforEntryNo(0), - fFillLastData(kFALSE), - fEntryNr(0), - fListFolder(0), - fSource(0), - fSourceChain(new TChain(GetTreeName(), Form("/%s", GetFolderName()))), - fSignalChainList(), - fEventHeader(new FairEventHeader()), - fSink(nullptr), - fUseFairLinks(kFALSE), - fFinishRun(kFALSE), - fListOfBranchesFromInput(0), - fListOfBranchesFromInputIter(0), - fListOfNonTimebasedBranches(new TRefArray()), - fListOfNonTimebasedBranchesIter(0), - fId(0) + : TObject() + , fOldEntryNr(-1) + , fOutFolder(0) + , fRootFolder(0) + , fCurrentTime(0) + , fObj2(new TObject*[1000]) + , fNObj(-1) + , fMap() + , fBranchSeqId(0) + , fBranchNameList(new TList()) + , fMCTrackBranchId(-1) + , fTimeBasedBranchNameList(new TList()) + , fActiveContainer() + , fTSBufferMap() + , fWriteoutBufferMap() + , fInputBranchMap() + , fTimeStamps(kFALSE) + , fBranchPerMap(kFALSE) + , fBrPerMap() + , fBrPerMapIter() + , fCurrentEntryNo(0) + , fTimeforEntryNo(0) + , fFillLastData(kFALSE) + , fEntryNr(0) + , fListFolder(0) + , fSource(0) + , fSourceChain(new TChain(GetTreeName(), Form("/%s", GetFolderName()))) + , fSignalChainList() + , fEventHeader(new FairEventHeader()) + , fSink(nullptr) + , fUseFairLinks(kFALSE) + , fFinishRun(kFALSE) + , fListOfBranchesFromInput(0) + , fListOfBranchesFromInputIter(0) + , fListOfNonTimebasedBranches(new TRefArray()) + , fListOfNonTimebasedBranchesIter(0) + , fId(0) { - LOG(debug) << "FairRootManager::FairRootManager: going to lock " << this; + LOG(debug) << "FairRootManager::FairRootManager: going to lock " << this; - TMCAutoLock lk(&createMutex); + TMCAutoLock lk(&createMutex); - // Set Id - fId = fgCounter; + // Set Id + fId = fgCounter; - // Increment counter - ++fgCounter; + // Increment counter + ++fgCounter; - lk.unlock(); + lk.unlock(); - LOG(debug) << "Released lock and done FairRootManager::FairRootManager in " << fId << " " << this; + LOG(debug) << "Released lock and done FairRootManager::FairRootManager in " << fId << " " << this; } FairRootManager::~FairRootManager() { -// - LOG(debug) << "Enter Destructor of FairRootManager"; + // + LOG(debug) << "Enter Destructor of FairRootManager"; - delete[] fObj2; - fBranchNameList->Delete(); - delete fBranchNameList; - LOG(debug) << "Leave Destructor of FairRootManager"; - delete fEventHeader; - delete fSourceChain; - if ( fSink ) - delete fSink; - if ( fSource ) - delete fSource; + delete[] fObj2; + fBranchNameList->Delete(); + delete fBranchNameList; + LOG(debug) << "Leave Destructor of FairRootManager"; + delete fEventHeader; + delete fSourceChain; + if (fSink) + delete fSink; + if (fSource) + delete fSource; - // Global cleanup - TMCAutoLock lk(&deleteMutex); + // Global cleanup + TMCAutoLock lk(&deleteMutex); - LOG(debug) << "FairRootManager::~FairRootManager: going to lock " - << fId << " " << this; + LOG(debug) << "FairRootManager::~FairRootManager: going to lock " << fId << " " << this; - --fgCounter; + --fgCounter; - // - lk.unlock(); + // + lk.unlock(); - LOG(debug) << "Released lock and done FairRootManager::~FairRootManager in " - << fId << " " << this; + LOG(debug) << "Released lock and done FairRootManager::~FairRootManager in " << fId << " " << this; } -Bool_t FairRootManager::InitSource() { - - LOG(debug) << "Call the initialiazer for the FairSource in FairRootManager "; - if ( fSource ) { - Bool_t sourceInitBool = fSource->Init(); - fListOfBranchesFromInput=fSourceChain->GetListOfBranches(); - TObject *obj; - if(fListOfBranchesFromInput){ - fListOfBranchesFromInputIter=fListOfBranchesFromInput->MakeIterator(); - while((obj=fListOfBranchesFromInputIter->Next())) { - if((fTimeBasedBranchNameList->FindObject(obj->GetName()))==0) - fListOfNonTimebasedBranches->Add(obj); - } - } - LOG(debug) << "Source is intialized and the list of branches is created in FairRootManager "; - fListOfNonTimebasedBranchesIter=fListOfNonTimebasedBranches->MakeIterator(); - return sourceInitBool; - } - return kFALSE; +Bool_t FairRootManager::InitSource() +{ + + LOG(debug) << "Call the initialiazer for the FairSource in FairRootManager "; + if (fSource) { + Bool_t sourceInitBool = fSource->Init(); + fListOfBranchesFromInput = fSourceChain->GetListOfBranches(); + TObject* obj; + if (fListOfBranchesFromInput) { + fListOfBranchesFromInputIter = fListOfBranchesFromInput->MakeIterator(); + while ((obj = fListOfBranchesFromInputIter->Next())) { + if ((fTimeBasedBranchNameList->FindObject(obj->GetName())) == 0) + fListOfNonTimebasedBranches->Add(obj); + } + } + LOG(debug) << "Source is intialized and the list of branches is created in FairRootManager "; + fListOfNonTimebasedBranchesIter = fListOfNonTimebasedBranches->MakeIterator(); + return sourceInitBool; + } + return kFALSE; } -Bool_t FairRootManager::InitSink() { - if ( fSink ) { - fSink->InitSink(); - } - return kTRUE; +Bool_t FairRootManager::InitSink() +{ + if (fSink) { + fSink->InitSink(); + } + return kTRUE; } template -void FairRootManager::RegisterImpl(const char* name, const char *folderName, T* obj, Bool_t toFile) +void FairRootManager::RegisterImpl(const char* name, const char* folderName, T* obj, Bool_t toFile) { -/// a common implementation for Register - FairMonitor::GetMonitor()->RecordRegister(name,folderName,toFile); - - // Security check. If the the name is equal the folder name there are problems with reading - // back the data. Instead of the object inside the folder the RootManger will return a pointer - // to the folder. To avoid such problems we check here if both strings are equal and stop the - // execution with some error message if this is the case. - if (strcmp (name, folderName) == 0 ) { - LOG(fatal) << "The names for the object name " - << name << " and the folder name " - << folderName <<" are equal. This isn't allowed. So we stop the execution at this point. Pleae change either the name or the folder name."; - } - - if(toFile) { /**Write the Object to the Tree*/ - obj->SetName(name); - if ( fSink ) - { - fSink->RegisterImpl(name,folderName,obj); - } - else - { - LOG(fatal) << "The sink does not exist to store persistent branches."; - } - } - AddMemoryBranch(name, obj); - AddBranchToList(name); - - if (toFile == kFALSE) { - FairLinkManager::Instance()->AddIgnoreType(GetBranchId(name)); - } + /// a common implementation for Register + FairMonitor::GetMonitor()->RecordRegister(name, folderName, toFile); + + // Security check. If the the name is equal the folder name there are problems with reading + // back the data. Instead of the object inside the folder the RootManger will return a pointer + // to the folder. To avoid such problems we check here if both strings are equal and stop the + // execution with some error message if this is the case. + if (strcmp(name, folderName) == 0) { + LOG(fatal) << "The names for the object name " << name << " and the folder name " << folderName + << " are equal. This isn't allowed. So we stop the execution at this point. Pleae change either the " + "name or the folder name."; + } + + if (toFile) { /**Write the Object to the Tree*/ + obj->SetName(name); + if (fSink) { + fSink->RegisterImpl(name, folderName, obj); + } else { + LOG(fatal) << "The sink does not exist to store persistent branches."; + } + } + AddMemoryBranch(name, obj); + AddBranchToList(name); + + if (toFile == kFALSE) { + FairLinkManager::Instance()->AddIgnoreType(GetBranchId(name)); + } } -void FairRootManager::Register(const char* name, const char* folderName , TNamed* obj, Bool_t toFile) +void FairRootManager::Register(const char* name, const char* folderName, TNamed* obj, Bool_t toFile) { - RegisterImpl(name, folderName, obj, toFile); + RegisterImpl(name, folderName, obj, toFile); } -Int_t FairRootManager::AddBranchToList(const char* name) +Int_t FairRootManager::AddBranchToList(const char* name) { - if(fBranchNameList->FindObject(name)==0) { - fBranchNameList->AddLast(new TObjString(name)); - // check if we are setting the MCTrack Branch - if(strcmp(name, "MCTrack") == 0) { - fMCTrackBranchId = fBranchSeqId; - } - fBranchSeqId++; - } - return fBranchSeqId; + if (fBranchNameList->FindObject(name) == 0) { + fBranchNameList->AddLast(new TObjString(name)); + // check if we are setting the MCTrack Branch + if (strcmp(name, "MCTrack") == 0) { + fMCTrackBranchId = fBranchSeqId; + } + fBranchSeqId++; + } + return fBranchSeqId; } -void FairRootManager::Register(const char* name,const char* foldername ,TCollection* obj, Bool_t toFile) +void FairRootManager::Register(const char* name, const char* foldername, TCollection* obj, Bool_t toFile) { - RegisterImpl(name, foldername, obj, toFile); + RegisterImpl(name, foldername, obj, toFile); } void FairRootManager::RegisterInputObject(const char* name, TObject* obj) { - AddMemoryBranch(name, obj); - AddBranchToList(name); + AddMemoryBranch(name, obj); + AddBranchToList(name); } TClonesArray* FairRootManager::Register(TString branchName, TString className, TString folderName, Bool_t toFile) { - FairMonitor::GetMonitor()->RecordRegister(branchName,folderName,toFile); + FairMonitor::GetMonitor()->RecordRegister(branchName, folderName, toFile); - TClonesArray* outputArray; - if (fActiveContainer.find(branchName) == fActiveContainer.end()) { - fActiveContainer[branchName] = new TClonesArray(className); - outputArray = fActiveContainer[branchName]; - Register(branchName, folderName, outputArray, toFile); - } + TClonesArray* outputArray; + if (fActiveContainer.find(branchName) == fActiveContainer.end()) { + fActiveContainer[branchName] = new TClonesArray(className); + outputArray = fActiveContainer[branchName]; + Register(branchName, folderName, outputArray, toFile); + } - return fActiveContainer[branchName]; + return fActiveContainer[branchName]; } TClonesArray* FairRootManager::GetEmptyTClonesArray(TString branchName) { - if (fActiveContainer.find(branchName) != fActiveContainer.end()) {//if a TClonesArray is registered in the active container - if (fActiveContainer[branchName] == 0) { //the address of the TClonesArray is still valid - std::cout << "-E- FairRootManager::GetEmptyTClonesArray: Container deleted outside FairRootManager!" << std::endl; + if (fActiveContainer.find(branchName) + != fActiveContainer.end()) { // if a TClonesArray is registered in the active container + if (fActiveContainer[branchName] == 0) { // the address of the TClonesArray is still valid + std::cout << "-E- FairRootManager::GetEmptyTClonesArray: Container deleted outside FairRootManager!" + << std::endl; + } else { + fActiveContainer[branchName]->Delete(); + } + return fActiveContainer[branchName]; // return the container } else { - fActiveContainer[branchName]->Delete(); + std::cout << "-E- Branch: " << branchName << " not registered!" + << std::endl; // error if the branch is not registered } - return fActiveContainer[branchName]; // return the container - } else { - std::cout << "-E- Branch: " << branchName << " not registered!" << std::endl; // error if the branch is not registered - } - return 0; + return 0; } TClonesArray* FairRootManager::GetTClonesArray(TString branchName) { - if (fActiveContainer.find(branchName) != fActiveContainer.end()) { - return fActiveContainer[branchName]; // return the container - } else { - LOG(info) << "Branch: " << branchName.Data() - << " not registered!" ; - } - // error if the branch is not registered - return 0; + if (fActiveContainer.find(branchName) != fActiveContainer.end()) { + return fActiveContainer[branchName]; // return the container + } else { + LOG(info) << "Branch: " << branchName.Data() << " not registered!"; + } + // error if the branch is not registered + return 0; } TString FairRootManager::GetBranchName(Int_t id) { - /**Return the branch name from the id*/ - if(id < fBranchSeqId) { - TObjString* ObjStr= static_cast(fBranchNameList->At(id)); - return ObjStr->GetString(); - } else { - TString NotFound("Branch not found"); - return NotFound; - } + /**Return the branch name from the id*/ + if (id < fBranchSeqId) { + TObjString* ObjStr = static_cast(fBranchNameList->At(id)); + return ObjStr->GetString(); + } else { + TString NotFound("Branch not found"); + return NotFound; + } } -Int_t FairRootManager::GetBranchId(TString const &BrName) +Int_t FairRootManager::GetBranchId(TString const& BrName) { - /**Return the branch id from the name*/ - TObjString* ObjStr; - Int_t Id=-1; - for(Int_t t=0; tGetEntries(); t++) { - ObjStr= static_cast(fBranchNameList->TList::At(t)); - if(BrName==ObjStr->GetString()) { - Id=t; - break; - } - } - return Id; + /**Return the branch id from the name*/ + TObjString* ObjStr; + Int_t Id = -1; + for (Int_t t = 0; t < fBranchNameList->GetEntries(); t++) { + ObjStr = static_cast(fBranchNameList->TList::At(t)); + if (BrName == ObjStr->GetString()) { + Id = t; + break; + } + } + return Id; } void FairRootManager::InitTSBuffer(TString branchName, BinaryFunctor* function) { - fTSBufferMap[branchName] = new FairTSBufferFunctional(branchName, GetInTree(), function); + fTSBufferMap[branchName] = new FairTSBufferFunctional(branchName, GetInTree(), function); } -TClonesArray* FairRootManager::GetData(TString branchName, BinaryFunctor* function, Double_t parameter) +TClonesArray* FairRootManager::GetData(TString branchName, BinaryFunctor* function, Double_t parameter) { - if (fTSBufferMap[branchName] == 0) { - fTSBufferMap[branchName] = new FairTSBufferFunctional(branchName, GetInTree(), function); - } - fTSBufferMap[branchName]->SetStopFunction(function); - return fTSBufferMap[branchName]->GetData(parameter); + if (fTSBufferMap[branchName] == 0) { + fTSBufferMap[branchName] = new FairTSBufferFunctional(branchName, GetInTree(), function); + } + fTSBufferMap[branchName]->SetStopFunction(function); + return fTSBufferMap[branchName]->GetData(parameter); } -TClonesArray* FairRootManager::GetData(TString branchName, BinaryFunctor* startFunction, Double_t startParameter, BinaryFunctor* stopFunction, Double_t stopParameter) +TClonesArray* FairRootManager::GetData(TString branchName, + BinaryFunctor* startFunction, + Double_t startParameter, + BinaryFunctor* stopFunction, + Double_t stopParameter) { - if (fTSBufferMap[branchName] == 0) { - fTSBufferMap[branchName] = new FairTSBufferFunctional(branchName, GetInTree(), stopFunction, startFunction); - } - fTSBufferMap[branchName]->SetStopFunction(stopFunction); - fTSBufferMap[branchName]->SetStartFunction(startFunction); - return fTSBufferMap[branchName]->GetData(startParameter, stopParameter); + if (fTSBufferMap[branchName] == 0) { + fTSBufferMap[branchName] = new FairTSBufferFunctional(branchName, GetInTree(), stopFunction, startFunction); + } + fTSBufferMap[branchName]->SetStopFunction(stopFunction); + fTSBufferMap[branchName]->SetStartFunction(startFunction); + return fTSBufferMap[branchName]->GetData(startParameter, stopParameter); } void FairRootManager::TerminateTSBuffer(TString branchName) { - if (fTSBufferMap.count(branchName) > 0){ - fTSBufferMap[branchName]->Terminate(); - } + if (fTSBufferMap.count(branchName) > 0) { + fTSBufferMap[branchName]->Terminate(); + } } void FairRootManager::TerminateAllTSBuffer() { - for (auto& mi : fTSBufferMap) - { - mi.second->Terminate(); - } + for (auto& mi : fTSBufferMap) { + mi.second->Terminate(); + } } Bool_t FairRootManager::AllDataProcessed() { - for (auto& mi : fTSBufferMap) { - if (mi.second->AllDataProcessed() == kFALSE && mi.second->TimeOut() == kFALSE) { - return kFALSE; + for (auto& mi : fTSBufferMap) { + if (mi.second->AllDataProcessed() == kFALSE && mi.second->TimeOut() == kFALSE) { + return kFALSE; + } } - } - return kTRUE; + return kTRUE; } void FairRootManager::Fill() { - if ( fSink ) fSink->Fill(); + if (fSink) + fSink->Fill(); } void FairRootManager::LastFill() { // FairMonitor::GetMonitor()->StoreHistograms(); MOVED TO FairRootFileSink - if (fFillLastData) { - if ( fSink ) fSink->Fill(); - } + if (fFillLastData) { + if (fSink) + fSink->Fill(); + } } Int_t FairRootManager::Write(const char*, Int_t, Int_t) { - /** Writes the tree in the file.*/ + /** Writes the tree in the file.*/ - LOG(debug) << "FairRootManager::Write " << this; + LOG(debug) << "FairRootManager::Write " << this; - if ( fSink ) return (fSink->Write()); + if (fSink) + return (fSink->Write()); - return 0; + return 0; } -void FairRootManager:: WriteGeometry() +void FairRootManager::WriteGeometry() { - /** Writes the geometry in the current output file.*/ - if ( fSink ) fSink->WriteGeometry(); + /** Writes the geometry in the current output file.*/ + if (fSink) + fSink->WriteGeometry(); } void FairRootManager::CreateGeometryFile(const char* geofile) { - /** Writes the geometry in a separate file. - * This is only to have a file which can be read without the - * framework. The geomanager used by the framework is still - * stored in the parameter file or database - */ - TFile* oldfile=gFile; - TFile* file=TFile::Open(geofile,"RECREATE"); - file->cd(); - gGeoManager->Write(); - file->Close(); - file->Delete(); - gFile=oldfile; + /** Writes the geometry in a separate file. + * This is only to have a file which can be read without the + * framework. The geomanager used by the framework is still + * stored in the parameter file or database + */ + TFile* oldfile = gFile; + TFile* file = TFile::Open(geofile, "RECREATE"); + file->cd(); + gGeoManager->Write(); + file->Close(); + file->Delete(); + gFile = oldfile; } -void FairRootManager:: WriteFolder() +void FairRootManager::WriteFolder() { - if ( fSink ) { - fSink->WriteFolder(); - fSink->WriteObject(fBranchNameList, "BranchList", TObject::kSingleKey); - fSink->WriteObject(fTimeBasedBranchNameList, "TimeBasedBranchList", TObject::kSingleKey); - } + if (fSink) { + fSink->WriteFolder(); + fSink->WriteObject(fBranchNameList, "BranchList", TObject::kSingleKey); + fSink->WriteObject(fTimeBasedBranchNameList, "TimeBasedBranchList", TObject::kSingleKey); + } } -Int_t FairRootManager::ReadEvent(Int_t i) +Int_t FairRootManager::ReadEvent(Int_t i) { - if ( !fSource ) return 0; + if (!fSource) + return 0; - fSource->Reset(); + fSource->Reset(); - SetEntryNr(i); + SetEntryNr(i); - if ( !fSource ) { - LOG(fatal) << "No Source available"; - return -1; - } + if (!fSource) { + LOG(fatal) << "No Source available"; + return -1; + } - fCurrentEntryNo=i; + fCurrentEntryNo = i; - Int_t readEventResult = fSource->ReadEvent(i); + Int_t readEventResult = fSource->ReadEvent(i); - fSource->FillEventHeader(fEventHeader); - fCurrentTime = fEventHeader->GetEventTime(); + fSource->FillEventHeader(fEventHeader); + fCurrentTime = fEventHeader->GetEventTime(); - LOG(debug) << "--Event number --- " - << fCurrentEntryNo << " with time ---- " - << fCurrentTime; + LOG(debug) << "--Event number --- " << fCurrentEntryNo << " with time ---- " << fCurrentTime; - return readEventResult; + return readEventResult; } void FairRootManager::ReadBranchEvent(const char* BrName, Int_t entry) { - if ( !fSource) return; - fSource->Reset(); - SetEntryNr(entry); + if (!fSource) + return; + fSource->Reset(); + SetEntryNr(entry); - fSource->ReadBranchEvent(BrName, entry); - fSource->FillEventHeader(fEventHeader); - fCurrentTime = fEventHeader->GetEventTime(); + fSource->ReadBranchEvent(BrName, entry); + fSource->FillEventHeader(fEventHeader); + fCurrentTime = fEventHeader->GetEventTime(); } Int_t FairRootManager::GetRunId() { - if ( fSource ) { - fSource->FillEventHeader(fEventHeader); - return fEventHeader->GetRunId(); - } - return -1; + if (fSource) { + fSource->FillEventHeader(fEventHeader); + return fEventHeader->GetRunId(); + } + return -1; } void FairRootManager::ReadBranchEvent(const char* BrName) { - if ( fSource ) { - fSource->ReadBranchEvent(BrName); - fSource->FillEventHeader(fEventHeader); - fCurrentTime = fEventHeader->GetEventTime(); - } + if (fSource) { + fSource->ReadBranchEvent(BrName); + fSource->FillEventHeader(fEventHeader); + fCurrentTime = fEventHeader->GetEventTime(); + } } Int_t FairRootManager::ReadNonTimeBasedEventFromBranches(Int_t Entry) { - if ( fSource ){ - TObject *Obj; - fListOfNonTimebasedBranchesIter->Reset(); - while ( (Obj=fListOfNonTimebasedBranchesIter->Next())) { - fSource->ReadBranchEvent(Obj->GetName(),Entry); - fSource->FillEventHeader(fEventHeader); - fCurrentTime = fEventHeader->GetEventTime(); + if (fSource) { + TObject* Obj; + fListOfNonTimebasedBranchesIter->Reset(); + while ((Obj = fListOfNonTimebasedBranchesIter->Next())) { + fSource->ReadBranchEvent(Obj->GetName(), Entry); + fSource->FillEventHeader(fEventHeader); + fCurrentTime = fEventHeader->GetEventTime(); + } + } else { + return 0; } - } else{ - return 0; - } - return 1; + return 1; } Bool_t FairRootManager::ReadNextEvent(Double_t) { - Bool_t readentry=kFALSE; - ///TODO - return readentry; + Bool_t readentry = kFALSE; + /// TODO + return readentry; } TObject* FairRootManager::GetObject(const char* BrName) { - fReqBrNames.emplace_back(BrName); - /**Get Data object by name*/ - TObject* Obj =nullptr; - LOG(debug2) << " Try to find if the object " - << BrName << " is already activated by another task or call"; - /**Try to find the object in the folder structure, object already activated by other task or call*/ - if(fOutFolder) { - Obj = fOutFolder->FindObjectAny(BrName); - if (Obj) { - LOG(debug2) <<"Object " - << BrName << " was already activated by another task"; - } - } - /**if the object does not exist then it could be a memory branch */ - if(!Obj) { - LOG(debug2) << "Try to find if the object " - << BrName << " is a memory branch"; - Obj=GetMemoryBranch(BrName); - if (Obj) { - LOG(debug2) << "Object " - << BrName << " is a memory branch"; - } - } - /**if the object does not exist then look in the input tree */ - if(fRootFolder && !Obj) { - /** there is an input tree and the object was not in memory */ - LOG(debug2) << "Object " - << BrName << " is not a memory branch and not yet activated, try the Input Tree (Chain)"; - Obj=fRootFolder->FindObjectAny(BrName); - Obj=ActivateBranch(BrName); - } - if(!Obj) { - Obj=ActivateBranch(BrName); - } - if ( Obj!=nullptr ) - FairMonitor::GetMonitor()->RecordGetting(BrName); - return Obj; + fReqBrNames.emplace_back(BrName); + /**Get Data object by name*/ + TObject* Obj = nullptr; + LOG(debug2) << " Try to find if the object " << BrName << " is already activated by another task or call"; + /**Try to find the object in the folder structure, object already activated by other task or call*/ + if (fOutFolder) { + Obj = fOutFolder->FindObjectAny(BrName); + if (Obj) { + LOG(debug2) << "Object " << BrName << " was already activated by another task"; + } + } + /**if the object does not exist then it could be a memory branch */ + if (!Obj) { + LOG(debug2) << "Try to find if the object " << BrName << " is a memory branch"; + Obj = GetMemoryBranch(BrName); + if (Obj) { + LOG(debug2) << "Object " << BrName << " is a memory branch"; + } + } + /**if the object does not exist then look in the input tree */ + if (fRootFolder && !Obj) { + /** there is an input tree and the object was not in memory */ + LOG(debug2) << "Object " << BrName + << " is not a memory branch and not yet activated, try the Input Tree (Chain)"; + Obj = fRootFolder->FindObjectAny(BrName); + Obj = ActivateBranch(BrName); + } + if (!Obj) { + Obj = ActivateBranch(BrName); + } + if (Obj != nullptr) + FairMonitor::GetMonitor()->RecordGetting(BrName); + return Obj; } TObject* FairRootManager::GetCloneOfLinkData(const FairLink link) { - TObject* result = 0; + TObject* result = 0; -// std::cout << "GetCloneOfLinkData: Link " << link << std::endl; - Int_t fileId = link.GetFile(); - Int_t entryNr = link.GetEntry(); - Int_t type = link.GetType(); - Int_t index = link.GetIndex(); + // std::cout << "GetCloneOfLinkData: Link " << link << std::endl; + Int_t fileId = link.GetFile(); + Int_t entryNr = link.GetEntry(); + Int_t type = link.GetType(); + Int_t index = link.GetIndex(); - Int_t oldEntryNr = GetEntryNr(); + Int_t oldEntryNr = GetEntryNr(); -// std::cout << "OldEntryNr: " << GetEntryNr(); + // std::cout << "OldEntryNr: " << GetEntryNr(); -// std::cout << "GetLinkData: " << link << std::endl; + // std::cout << "GetLinkData: " << link << std::endl; - TTree* dataTree; //get the correct Tree - if (fileId < 0) { - dataTree = GetInTree(); - } else if (fileId == 0) { - dataTree = GetInChain(); - } else { - dataTree = GetSignalChainNo(fileId); - } + TTree* dataTree; // get the correct Tree + if (fileId < 0) { + dataTree = GetInTree(); + } else if (fileId == 0) { + dataTree = GetInChain(); + } else { + dataTree = GetSignalChainNo(fileId); + } - if (dataTree == 0) { - dataTree = GetInTree(); - } + if (dataTree == 0) { + dataTree = GetInTree(); + } - if (type < 0) { - return 0; - } + if (type < 0) { + return 0; + } + + TBranch* dataBranch = 0; - TBranch* dataBranch = 0; + // std::cout << "DataType: " << GetBranchName(type) << std::endl; -// std::cout << "DataType: " << GetBranchName(type) << std::endl; + if (fileId < 0 && fInputBranchMap[type] != 0) { + dataBranch = fInputBranchMap[type]; + } else if (fileId < 0) { + fInputBranchMap[type] = dataTree->GetBranch(GetBranchName(type)); + dataBranch = fInputBranchMap[type]; + } else { + dataBranch = dataTree->GetBranch(GetBranchName(type)); + } - if (fileId < 0 && fInputBranchMap[type] != 0) { - dataBranch = fInputBranchMap[type]; - } else if (fileId < 0) { - fInputBranchMap[type] = dataTree->GetBranch(GetBranchName(type)); - dataBranch = fInputBranchMap[type]; - } else { - dataBranch = dataTree->GetBranch(GetBranchName(type)); - } + if (dataBranch == 0) { + return 0; + } - if (dataBranch == 0) { - return 0; - } + if (entryNr > -1) { // get the right entry (if entryNr < 0 then the current entry is taken + if (entryNr < dataBranch->GetEntries()) { + dataBranch->GetEntry(entryNr); + } else { + return 0; + } + } else { // the link entry nr is negative --> take the actual one - if (entryNr > -1) { //get the right entry (if entryNr < 0 then the current entry is taken - if (entryNr < dataBranch->GetEntries()) { - dataBranch->GetEntry(entryNr); + // std::cout << "EntryNr: " << GetEntryNr() << std::endl; + // dataBranch->GetEntry(GetEntryNr()); + } + + if (index < 0) { // if index is -1 then this is not a TClonesArray so only the Object is returned + result = GetObject(GetBranchName(type))->Clone(); } else { - return 0; - } - } else { //the link entry nr is negative --> take the actual one - -// std::cout << "EntryNr: " << GetEntryNr() << std::endl; -// dataBranch->GetEntry(GetEntryNr()); - } - - if (index < 0) { //if index is -1 then this is not a TClonesArray so only the Object is returned - result = GetObject(GetBranchName(type))->Clone(); - } else { - TClonesArray* dataArray = static_cast(GetObject(GetBranchName(type))); - - std::cout << "FairRootManager::GetCloneOfLinkData() dataArray size: " << dataArray->GetEntriesFast() << std::endl; - if (index < dataArray->GetEntriesFast()) { -// std::cout << "DataArray at index " << index << " has Link: " << ((FairMultiLinkedData*)dataArray->At(index))->GetNLinks() << std::cout; - result = dataArray->At(index)->Clone(); -// std::cout << "Result: " << *((FairMultiLinkedData*)result) << std::endl; - } - } - if (entryNr > -1) { - dataBranch->GetEntry(oldEntryNr); //reset the dataBranch to the original entry - } - return result; + TClonesArray* dataArray = static_cast(GetObject(GetBranchName(type))); + + std::cout << "FairRootManager::GetCloneOfLinkData() dataArray size: " << dataArray->GetEntriesFast() + << std::endl; + if (index < dataArray->GetEntriesFast()) { + // std::cout << "DataArray at index " << index << " has Link: " << + // ((FairMultiLinkedData*)dataArray->At(index))->GetNLinks() << std::cout; + result = dataArray->At(index)->Clone(); + // std::cout << "Result: " << *((FairMultiLinkedData*)result) << std::endl; + } + } + if (entryNr > -1) { + dataBranch->GetEntry(oldEntryNr); // reset the dataBranch to the original entry + } + return result; } TClonesArray* FairRootManager::GetCloneOfTClonesArray(const FairLink link) { - TClonesArray* result = 0; - - // std::cout << "GetCloneOfLinkData: Link " << link << std::endl; - Int_t fileId = link.GetFile(); - Int_t entryNr = link.GetEntry(); - Int_t type = link.GetType(); - Int_t index = link.GetIndex(); + TClonesArray* result = 0; - Int_t oldEntryNr = GetEntryNr(); + // std::cout << "GetCloneOfLinkData: Link " << link << std::endl; + Int_t fileId = link.GetFile(); + Int_t entryNr = link.GetEntry(); + Int_t type = link.GetType(); + Int_t index = link.GetIndex(); - // std::cout << "OldEntryNr: " << GetEntryNr(); + Int_t oldEntryNr = GetEntryNr(); - // std::cout << "GetLinkData: " << link << std::endl; + // std::cout << "OldEntryNr: " << GetEntryNr(); - TTree* dataTree; //get the correct Tree - if (fileId < 0) { - dataTree = GetInTree(); - } else if (fileId == 0) { - dataTree = GetInChain(); - } else { - dataTree = GetSignalChainNo(fileId); - } + // std::cout << "GetLinkData: " << link << std::endl; - if (dataTree == 0) { - dataTree = GetInTree(); - } - - if (type < 0) { - return 0; - } + TTree* dataTree; // get the correct Tree + if (fileId < 0) { + dataTree = GetInTree(); + } else if (fileId == 0) { + dataTree = GetInChain(); + } else { + dataTree = GetSignalChainNo(fileId); + } - TBranch* dataBranch = 0; + if (dataTree == 0) { + dataTree = GetInTree(); + } - // std::cout << "DataType: " << GetBranchName(type) << std::endl; + if (type < 0) { + return 0; + } - if (fileId < 0 && fInputBranchMap[type] != 0) { - dataBranch = fInputBranchMap[type]; - } else if (fileId < 0) { - fInputBranchMap[type] = dataTree->GetBranch(GetBranchName(type)); - dataBranch = fInputBranchMap[type]; - } else { - dataBranch = dataTree->GetBranch(GetBranchName(type)); - } + TBranch* dataBranch = 0; - if (dataBranch == 0) { - return 0; - } + // std::cout << "DataType: " << GetBranchName(type) << std::endl; - if (entryNr > -1) { //get the right entry (if entryNr < 0 then the current entry is taken - if (entryNr < dataBranch->GetEntries()) { - dataBranch->GetEntry(entryNr); + if (fileId < 0 && fInputBranchMap[type] != 0) { + dataBranch = fInputBranchMap[type]; + } else if (fileId < 0) { + fInputBranchMap[type] = dataTree->GetBranch(GetBranchName(type)); + dataBranch = fInputBranchMap[type]; } else { - return 0; + dataBranch = dataTree->GetBranch(GetBranchName(type)); + } + + if (dataBranch == 0) { + return 0; } - } else { //the link entry nr is negative --> take the actual one - // std::cout << "EntryNr: " << GetEntryNr() << std::endl; - // dataBranch->GetEntry(GetEntryNr()); - } + if (entryNr > -1) { // get the right entry (if entryNr < 0 then the current entry is taken + if (entryNr < dataBranch->GetEntries()) { + dataBranch->GetEntry(entryNr); + } else { + return 0; + } + } else { // the link entry nr is negative --> take the actual one - if (index < 0) { //if index is -1 then this is not a TClonesArray so only the Object is returned - result = 0; - } else { - result = static_cast( GetObject(GetBranchName(type))->Clone() ); - } - if (entryNr > -1) { - dataBranch->GetEntry(oldEntryNr); //reset the dataBranch to the original entry - } - return result; + // std::cout << "EntryNr: " << GetEntryNr() << std::endl; + // dataBranch->GetEntry(GetEntryNr()); + } + if (index < 0) { // if index is -1 then this is not a TClonesArray so only the Object is returned + result = 0; + } else { + result = static_cast(GetObject(GetBranchName(type))->Clone()); + } + if (entryNr > -1) { + dataBranch->GetEntry(oldEntryNr); // reset the dataBranch to the original entry + } + return result; } Int_t FairRootManager::CheckBranch(const char* BrName) { - /**The first time this method is called the map is generated and then used*/ - if(!fBranchPerMap) { - CreatePerMap(); - return CheckBranchSt(BrName); - } else { - fBrPerMapIter=fBrPerMap.find(BrName); - if(fBrPerMapIter!=fBrPerMap.end()) { - return fBrPerMapIter->second; + /**The first time this method is called the map is generated and then used*/ + if (!fBranchPerMap) { + CreatePerMap(); + return CheckBranchSt(BrName); } else { - return 0; + fBrPerMapIter = fBrPerMap.find(BrName); + if (fBrPerMapIter != fBrPerMap.end()) { + return fBrPerMapIter->second; + } else { + return 0; + } } - } } -void FairRootManager::SetBranchNameList(TList* list) +void FairRootManager::SetBranchNameList(TList* list) { - if ( list == nullptr ) return; - // otherwise clear existing and add via the standard interface - fBranchNameList->Clear(); - fMCTrackBranchId = -1; - for (Int_t t=0; tGetEntries(); t++) { - AddBranchToList(static_cast(list->At(t))->GetString().Data()); - } + if (list == nullptr) + return; + // otherwise clear existing and add via the standard interface + fBranchNameList->Clear(); + fMCTrackBranchId = -1; + for (Int_t t = 0; t < list->GetEntries(); t++) { + AddBranchToList(static_cast(list->At(t))->GetString().Data()); + } } void FairRootManager::SetInChain(TChain* tempChain, Int_t ident) { - if ( ident <= 0 ) - fSourceChain = tempChain; - else - fSignalChainList[ident] = tempChain; + if (ident <= 0) + fSourceChain = tempChain; + else + fSignalChainList[ident] = tempChain; } -Double_t FairRootManager::GetEventTime() { - return fCurrentTime; -} +Double_t FairRootManager::GetEventTime() { return fCurrentTime; } -void FairRootManager::UpdateBranches() { - for ( Int_t iobj = 0 ; iobj <= fNObj ; iobj++ ) { - if ( fObj2[iobj] ) { - LOG(info) << "FairRootManager::UpdateBranches \"" << fObj2[iobj]->GetName() - << "\" (\"" << fObj2[iobj]->GetTitle() << "\")"; - TString tempBranchName = fObj2[iobj]->GetName(); - fSource->ActivateObject(&fObj2[fNObj],tempBranchName.Data()); +void FairRootManager::UpdateBranches() +{ + for (Int_t iobj = 0; iobj <= fNObj; iobj++) { + if (fObj2[iobj]) { + LOG(info) << "FairRootManager::UpdateBranches \"" << fObj2[iobj]->GetName() << "\" (\"" + << fObj2[iobj]->GetTitle() << "\")"; + TString tempBranchName = fObj2[iobj]->GetName(); + fSource->ActivateObject(&fObj2[fNObj], tempBranchName.Data()); + } } - } - } /** Private functions*/ TObject* FairRootManager::ActivateBranch(const char* BrName) { - /** Set the branch address for a given branch name and return a TObject pointer, + /** Set the branch address for a given branch name and return a TObject pointer, the user have to cast this pointer to the right type. The function has been revisited ! Now it test if in the task init() mutilple calls to activate branch is done , and then just forward the pointer. **/ - fNObj++; - fObj2[fNObj] = GetMemoryBranch ( BrName ); - if ( fObj2[fNObj] ) { - return fObj2[fNObj]; - } - /**try to find the object decribing the branch in the folder structure in file*/ - LOG(debug) << "Try to find an object " - << BrName << " describing the branch in the folder structure in file"; - if ( fListFolder ) { - for(Int_t i=0; iGetEntriesFast(); i++) { - TFolder* fold = static_cast(fListFolder->At(i)); - fObj2[fNObj] = fold->FindObjectAny(BrName); - if (fObj2[fNObj] ) { - LOG(info) << "Object " - << BrName << " describing the branch in the folder structure was found"; - break; - } - } - } - - if(!fObj2[fNObj]) { - /** if we do not find an object corresponding to the branch in the folder structure - * then we have no idea about what type of object is this and we cannot set the branch address - */ - LOG(info) << " Branch: " << BrName << " not found in Tree."; - //Fatal(" No Branch in the tree", BrName ); - return 0; - } else { - if ( fSource ) - fSource->ActivateObject(&fObj2[fNObj],BrName); - } + fNObj++; + fObj2[fNObj] = GetMemoryBranch(BrName); + if (fObj2[fNObj]) { + return fObj2[fNObj]; + } + /**try to find the object decribing the branch in the folder structure in file*/ + LOG(debug) << "Try to find an object " << BrName << " describing the branch in the folder structure in file"; + if (fListFolder) { + for (Int_t i = 0; i < fListFolder->GetEntriesFast(); i++) { + TFolder* fold = static_cast(fListFolder->At(i)); + fObj2[fNObj] = fold->FindObjectAny(BrName); + if (fObj2[fNObj]) { + LOG(info) << "Object " << BrName << " describing the branch in the folder structure was found"; + break; + } + } + } - AddMemoryBranch( BrName , fObj2[fNObj] ); - return fObj2[fNObj]; + if (!fObj2[fNObj]) { + /** if we do not find an object corresponding to the branch in the folder structure + * then we have no idea about what type of object is this and we cannot set the branch address + */ + LOG(info) << " Branch: " << BrName << " not found in Tree."; + // Fatal(" No Branch in the tree", BrName ); + return 0; + } else { + if (fSource) + fSource->ActivateObject(&fObj2[fNObj], BrName); + } + + AddMemoryBranch(BrName, fObj2[fNObj]); + return fObj2[fNObj]; } -void FairRootManager::AddMemoryBranch( const char* fName, TObject* pObj ) +void FairRootManager::AddMemoryBranch(const char* fName, TObject* pObj) { - /**branch will be available ionly in Memory, will not be written to disk */ - map < TString, TObject*>::iterator p; - TString BrName=fName; - p=fMap.find(BrName); - if(p!=fMap.end()) { - } else { - fMap.insert(pair (BrName, pObj)); - } + /**branch will be available ionly in Memory, will not be written to disk */ + map::iterator p; + TString BrName = fName; + p = fMap.find(BrName); + if (p != fMap.end()) { + } else { + fMap.insert(pair(BrName, pObj)); + } } Int_t FairRootManager::CheckBranchSt(const char* BrName) { - // cout <<"FairRootManager::CheckBranchSt : " << BrName << endl; - Int_t returnvalue=0; - TObject* Obj1 =nullptr; - - if(fListFolder==0){ - fListFolder = new TObjArray(16); - } - - //cout <<"FairRootManager::CheckBranchSt : " <Add(fRootFolder); - Obj1 = fRootFolder->FindObjectAny(BrName); - } - if(fOutFolder && !Obj1) { - fListFolder->Add(fOutFolder); - Obj1 = fOutFolder->FindObjectAny(BrName); //Branch in output folder - } - if(!Obj1) { - for(Int_t i=0; iGetEntriesFast(); i++) { - // cout << "Search in Folder: " << i << " " << fListFolder->At(i) << endl; - TFolder* fold = dynamic_cast(fListFolder->At(i)); - if(fold!=0) { - Obj1= fold->FindObjectAny(BrName); - } - if (Obj1) { - break; - } - } - } - TObject* Obj2 =nullptr; - Obj2=GetMemoryBranch(BrName); // Branch in Memory - if (Obj1!=0) { - returnvalue=1; - } else if(Obj2!=0) { - returnvalue=2; - } else { - returnvalue= 0; - } - - /** 1 : Branch is Persistance + // cout <<"FairRootManager::CheckBranchSt : " << BrName << endl; + Int_t returnvalue = 0; + TObject* Obj1 = nullptr; + + if (fListFolder == 0) { + fListFolder = new TObjArray(16); + } + + // cout <<"FairRootManager::CheckBranchSt : " <Add(fRootFolder); + Obj1 = fRootFolder->FindObjectAny(BrName); + } + if (fOutFolder && !Obj1) { + fListFolder->Add(fOutFolder); + Obj1 = fOutFolder->FindObjectAny(BrName); // Branch in output folder + } + if (!Obj1) { + for (Int_t i = 0; i < fListFolder->GetEntriesFast(); i++) { + // cout << "Search in Folder: " << i << " " << fListFolder->At(i) << endl; + TFolder* fold = dynamic_cast(fListFolder->At(i)); + if (fold != 0) { + Obj1 = fold->FindObjectAny(BrName); + } + if (Obj1) { + break; + } + } + } + TObject* Obj2 = nullptr; + Obj2 = GetMemoryBranch(BrName); // Branch in Memory + if (Obj1 != 0) { + returnvalue = 1; + } else if (Obj2 != 0) { + returnvalue = 2; + } else { + returnvalue = 0; + } + + /** 1 : Branch is Persistance 2 : Memory Branch 0 : Branch does not exist */ - return returnvalue; + return returnvalue; } -void FairRootManager::CreatePerMap() +void FairRootManager::CreatePerMap() { - // cout << " FairRootManager::CreatePerMap() " << endl; - fBranchPerMap=kTRUE; - for (Int_t i=0; i(fBranchNameList->At(i)); - // cout << " FairRootManager::CreatePerMap() Obj At " << i << " is " << name->GetString() << endl; - TString BrName=name->GetString(); - fBrPerMap.insert(pair (BrName, CheckBranchSt(BrName.Data()))); - } - + // cout << " FairRootManager::CreatePerMap() " << endl; + fBranchPerMap = kTRUE; + for (Int_t i = 0; i < fBranchSeqId; i++) { + TObjString* name = static_cast(fBranchNameList->At(i)); + // cout << " FairRootManager::CreatePerMap() Obj At " << i << " is " << name->GetString() << endl; + TString BrName = name->GetString(); + fBrPerMap.insert(pair(BrName, CheckBranchSt(BrName.Data()))); + } } -TObject* FairRootManager::GetMemoryBranch( const char* fName ) +TObject* FairRootManager::GetMemoryBranch(const char* fName) { - //return fMap[BrName]; - TString BrName=fName; - map < TString, TObject*>::iterator p; - p=fMap.find(BrName); + // return fMap[BrName]; + TString BrName = fName; + map::iterator p; + p = fMap.find(BrName); - if(p!=fMap.end()) { - return p->second; - } else { - return 0; - } + if (p != fMap.end()) { + return p->second; + } else { + return 0; + } } void FairRootManager::WriteFileHeader(FairFileHeader* f) { - if ( fSink ) fSink->WriteObject(f,"FileHeader", TObject::kSingleKey); + if (fSink) + fSink->WriteObject(f, "FileHeader", TObject::kSingleKey); } -Int_t FairRootManager::CheckMaxEventNo(Int_t EvtEnd) +Int_t FairRootManager::CheckMaxEventNo(Int_t EvtEnd) { - if ( fSource ) - return fSource->CheckMaxEventNo(EvtEnd); - return 0; + if (fSource) + return fSource->CheckMaxEventNo(EvtEnd); + return 0; } FairWriteoutBuffer* FairRootManager::RegisterWriteoutBuffer(TString branchName, FairWriteoutBuffer* buffer) { - if (fWriteoutBufferMap[branchName] == 0) { - fWriteoutBufferMap[branchName] = buffer; - } else { - LOG(warn) << "Branch " - << branchName.Data() - << " is already registered in WriteoutBufferMap"; - delete buffer; - } - - return fWriteoutBufferMap[branchName]; + if (fWriteoutBufferMap[branchName] == 0) { + fWriteoutBufferMap[branchName] = buffer; + } else { + LOG(warn) << "Branch " << branchName.Data() << " is already registered in WriteoutBufferMap"; + delete buffer; + } + + return fWriteoutBufferMap[branchName]; } void FairRootManager::UpdateListOfTimebasedBranches() { - /** - * Add branches that are time based to the proper list - */ - - for (auto& mi : fWriteoutBufferMap) { - if(mi.second->IsBufferingActivated()) fTimeBasedBranchNameList->AddLast(new TObjString(mi.first.Data())); - } + /** + * Add branches that are time based to the proper list + */ + for (auto& mi : fWriteoutBufferMap) { + if (mi.second->IsBufferingActivated()) + fTimeBasedBranchNameList->AddLast(new TObjString(mi.first.Data())); + } } -void FairRootManager::SetTimeBasedBranchNameList(TList *list) +void FairRootManager::SetTimeBasedBranchNameList(TList* list) { - /** - * Replace the list - */ - - if(list!=0){ - fTimeBasedBranchNameList->Delete(); - delete fTimeBasedBranchNameList; - fTimeBasedBranchNameList=list; - } - + /** + * Replace the list + */ + + if (list != 0) { + fTimeBasedBranchNameList->Delete(); + delete fTimeBasedBranchNameList; + fTimeBasedBranchNameList = list; + } } FairWriteoutBuffer* FairRootManager::GetWriteoutBuffer(TString branchName) { - if (fWriteoutBufferMap.count(branchName) > 0) { - return fWriteoutBufferMap[branchName]; - } else { - return 0; - } + if (fWriteoutBufferMap.count(branchName) > 0) { + return fWriteoutBufferMap[branchName]; + } else { + return 0; + } } void FairRootManager::StoreWriteoutBufferData(Double_t eventTime) { - for (auto& mi : fWriteoutBufferMap) { - mi.second->WriteOutData(eventTime); - } + for (auto& mi : fWriteoutBufferMap) { + mi.second->WriteOutData(eventTime); + } } void FairRootManager::StoreAllWriteoutBufferData() { - Bool_t dataInBuffer = kFALSE; - for (auto& mi : fWriteoutBufferMap) { - if (mi.second->GetNData() > 0) { - dataInBuffer = kTRUE; - } - mi.second->WriteOutAllData(); - } - fFillLastData = dataInBuffer; + Bool_t dataInBuffer = kFALSE; + for (auto& mi : fWriteoutBufferMap) { + if (mi.second->GetNData() > 0) { + dataInBuffer = kTRUE; + } + mi.second->WriteOutAllData(); + } + fFillLastData = dataInBuffer; } void FairRootManager::DeleteOldWriteoutBufferData() { - for (auto& mi : fWriteoutBufferMap) { - mi.second->DeleteOldData(); - } + for (auto& mi : fWriteoutBufferMap) { + mi.second->DeleteOldData(); + } } char* FairRootManager::GetTreeName() { - char* default_name = (char*)"cbmsim"; - char* workdir = getenv("VMCWORKDIR"); - if(nullptr == workdir) - { - return default_name; - } - - // Open file with output tree name - FILE* file = fopen(Form("%s/config/rootmanager.dat",workdir), "r"); - // If file does not exist -> default - if(nullptr == file) - { - return default_name; - } - - char str[100]; - while(nullptr != fgets(str, 100, file)) - { - if(TString(str).Contains("treename")) - { - char* treename = new char[100]; - if(1 == sscanf(str, "treename=%s", treename)) - { - fclose(file); - return treename; - } - delete [] treename; - } - } - - // Key "treename" was not found in file: return default - fclose(file); - return default_name; + char* default_name = (char*)"cbmsim"; + char* workdir = getenv("VMCWORKDIR"); + if (nullptr == workdir) { + return default_name; + } + + // Open file with output tree name + FILE* file = fopen(Form("%s/config/rootmanager.dat", workdir), "r"); + // If file does not exist -> default + if (nullptr == file) { + return default_name; + } + + char str[100]; + while (nullptr != fgets(str, 100, file)) { + if (TString(str).Contains("treename")) { + char* treename = new char[100]; + if (1 == sscanf(str, "treename=%s", treename)) { + fclose(file); + return treename; + } + delete[] treename; + } + } + + // Key "treename" was not found in file: return default + fclose(file); + return default_name; } char* FairRootManager::GetFolderName() { - char* default_name = (char*)"cbmout"; - if(! FairRun::Instance()->IsAna()) - { - default_name = (char*)"cbmroot"; - } - char* workdir = getenv("VMCWORKDIR"); - if(nullptr == workdir) - { - return default_name; - } - - // Open file with output tree name - FILE* file = fopen(Form("%s/config/rootmanager.dat",workdir), "r"); - // If file does not exist -> default - if(nullptr == file) - { - return default_name; - } - - char str[100]; - while(nullptr != fgets(str, 100, file)) - { - if(TString(str).Contains("foldername")) - { - char* foldername = new char[100]; - if(1 == sscanf(str, "foldername=%s", foldername)) - { - fclose(file); - return foldername; - } - delete [] foldername; - } - } - - // Key "foldername" was not found in file: return default - fclose(file); - return default_name; + char* default_name = (char*)"cbmout"; + if (!FairRun::Instance()->IsAna()) { + default_name = (char*)"cbmroot"; + } + char* workdir = getenv("VMCWORKDIR"); + if (nullptr == workdir) { + return default_name; + } + + // Open file with output tree name + FILE* file = fopen(Form("%s/config/rootmanager.dat", workdir), "r"); + // If file does not exist -> default + if (nullptr == file) { + return default_name; + } + + char str[100]; + while (nullptr != fgets(str, 100, file)) { + if (TString(str).Contains("foldername")) { + char* foldername = new char[100]; + if (1 == sscanf(str, "foldername=%s", foldername)) { + fclose(file); + return foldername; + } + delete[] foldername; + } + } + + // Key "foldername" was not found in file: return default + fclose(file); + return default_name; } -void FairRootManager::EmitMemoryBranchWrongTypeWarning(const char* brname, const char *type1, const char *type2) const { - LOG(warn) << "Trying to read from memory branch " << brname - << " with wrong type " << type1 - << " (expexted: " << type2 << " )"; +void FairRootManager::EmitMemoryBranchWrongTypeWarning(const char* brname, const char* type1, const char* type2) const +{ + LOG(warn) << "Trying to read from memory branch " << brname << " with wrong type " << type1 + << " (expexted: " << type2 << " )"; } void FairRootManager::UpdateFileName(TString& fileName) { - TString tid = "_t"; - tid += GetInstanceId(); - fileName.Insert(fileName.Index(".root"), tid); + TString tid = "_t"; + tid += GetInstanceId(); + fileName.Insert(fileName.Index(".root"), tid); } TFile* FairRootManager::GetOutFile() { - LOG(WARNING) << "FairRootManager::GetOutFile() deprecated. Use separate file to store additional data."; - auto sink = GetSink(); - assert(sink->GetSinkType() == kFILESINK); - auto rootFileSink = static_cast(sink); - return rootFileSink->GetRootFile(); + LOG(WARNING) << "FairRootManager::GetOutFile() deprecated. Use separate file to store additional data."; + auto sink = GetSink(); + assert(sink->GetSinkType() == kFILESINK); + auto rootFileSink = static_cast(sink); + return rootFileSink->GetRootFile(); } TTree* FairRootManager::GetOutTree() { - LOG(WARNING) << "FairRootManager::GetOutTree() deprecated. Use separate file to store additional data."; - auto sink = GetSink(); - assert(sink->GetSinkType() == kFILESINK); - auto rootFileSink = static_cast(sink); - return rootFileSink->GetOutTree(); + LOG(WARNING) << "FairRootManager::GetOutTree() deprecated. Use separate file to store additional data."; + auto sink = GetSink(); + assert(sink->GetSinkType() == kFILESINK); + auto rootFileSink = static_cast(sink); + return rootFileSink->GetOutTree(); } -ClassImp(FairRootManager) +ClassImp(FairRootManager); diff --git a/base/steer/FairRootManager.h b/base/steer/FairRootManager.h index d04433a2a0..995e4878c4 100644 --- a/base/steer/FairRootManager.h +++ b/base/steer/FairRootManager.h @@ -12,16 +12,15 @@ #include "FairSink.h" #include "FairSource.h" -#include // for Bool_t, Int_t, UInt_t, etc -#include // for TChain -#include // for multi-threading -#include // for TObject -#include // for TString, operator< - -#include // for map, multimap, etc +#include // for Bool_t, Int_t, UInt_t, etc +#include // for TChain +#include // for multi-threading +#include // for TObject +#include // for TString, operator< +#include // for map, multimap, etc #include #include -#include // is_pointer, remove_pointer, is_const, remove... +#include // is_pointer, remove_pointer, is_const, remove... #include #include @@ -53,9 +52,9 @@ class TTree; class FairRootManager : public TObject { public: - /**dtor*/ + /**dtor*/ virtual ~FairRootManager(); - Bool_t AllDataProcessed(); + Bool_t AllDataProcessed(); /** Add a branch name to the Branchlist and give it an id*/ Int_t AddBranchToList(const char* name); /** @@ -64,30 +63,35 @@ class FairRootManager : public TObject 1 : Branch is Persistance 2 : Memory Branch 0 : Branch does not exist */ - Int_t CheckBranch(const char* BrName); + Int_t CheckBranch(const char* BrName); - void CloseSink() { if(fSink) { fSink->Close(); }} + void CloseSink() + { + if (fSink) { + fSink->Close(); + } + } /**Create a new file and save the current TGeoManager object to it*/ - void CreateGeometryFile(const char* geofile); - void Fill(); - void LastFill(); - TClonesArray* GetEmptyTClonesArray(TString branchName); - TClonesArray* GetTClonesArray(TString branchName); + void CreateGeometryFile(const char* geofile); + void Fill(); + void LastFill(); + TClonesArray* GetEmptyTClonesArray(TString branchName); + TClonesArray* GetTClonesArray(TString branchName); /**Update the list of Memory branches from the source used*/ - void UpdateBranches(); + void UpdateBranches(); /**Return branch name by Id*/ - TString GetBranchName(Int_t id); + TString GetBranchName(Int_t id); /**Return Id of a branch named */ - Int_t GetBranchId(TString const &BrName); + Int_t GetBranchId(TString const& BrName); /**The MCTrack branch stands out since it is required by the framework algorithms**/ Int_t GetMCTrackBranchId() const { return fMCTrackBranchId; } /**Return a TList of TObjString of branch names available in this session*/ - TList* GetBranchNameList() {return fBranchNameList;} + TList* GetBranchNameList() { return fBranchNameList; } /**Return the vector of branch names that were requested by tasks as input*/ - const std::vector& GetReqBranchNames() const {return fReqBrNames;} + const std::vector& GetReqBranchNames() const { return fReqBrNames; } /** Get the Object (container) for the given branch name, this method can be used to access the data of @@ -95,7 +99,7 @@ class FairRootManager : public TObject analysis task, and not written in the tree yet. the user have to cast this pointer to the right type. Return a pointer to the object (collection) saved in the fInChain branch named BrName*/ - TObject* GetObject(const char* BrName); + TObject* GetObject(const char* BrName); /// Initializes and returns a default object for a branch or looks it up when it exists already. /// Returns nullptr when the branch does not exist or looking up with wrong type. @@ -105,9 +109,9 @@ class FairRootManager : public TObject T InitObjectAs(const char* BrName); /** Return a pointer to the object (collection) saved in the fInTree branch named BrName*/ - Double_t GetEventTime(); + Double_t GetEventTime(); /** Returns a clone of the data object the link is pointing to. The clone has to be deleted in the calling code! */ - TObject* GetCloneOfLinkData(const FairLink link); + TObject* GetCloneOfLinkData(const FairLink link); /** Get the data of the given branch name, * this method runs over multiple entries * of the tree and selects the data according @@ -117,94 +121,106 @@ class FairRootManager : public TObject TClonesArray* GetCloneOfTClonesArray(const FairLink link); void InitTSBuffer(TString branchName, BinaryFunctor* function); - TClonesArray* GetData(TString branchName, BinaryFunctor* function, Double_t parameter); - TClonesArray* GetData(TString branchName, BinaryFunctor* startFunction, Double_t startParameter, BinaryFunctor* stopFunction, Double_t stopParameter); - void RegisterTSBuffer(TString branchName, FairTSBufferFunctional* functionalBuffer) {fTSBufferMap[branchName] = functionalBuffer;} + TClonesArray* GetData(TString branchName, BinaryFunctor* function, Double_t parameter); + TClonesArray* GetData(TString branchName, + BinaryFunctor* startFunction, + Double_t startParameter, + BinaryFunctor* stopFunction, + Double_t stopParameter); + void RegisterTSBuffer(TString branchName, FairTSBufferFunctional* functionalBuffer) + { + fTSBufferMap[branchName] = functionalBuffer; + } void TerminateTSBuffer(TString branchName); void TerminateAllTSBuffer(); - FairTSBufferFunctional* GetTSBuffer(TString branchName) {return fTSBufferMap[branchName];} + FairTSBufferFunctional* GetTSBuffer(TString branchName) { return fTSBufferMap[branchName]; } /** static access method */ static FairRootManager* Instance(); /**Read a single entry from background chain*/ - Int_t ReadEvent(Int_t i=0); + Int_t ReadEvent(Int_t i = 0); /** Read a single entry from each branch that is not read via TSBuffers*/ - Int_t ReadNonTimeBasedEventFromBranches(Int_t i=0); + Int_t ReadNonTimeBasedEventFromBranches(Int_t i = 0); /**Read the tree entry on one branch**/ - void ReadBranchEvent(const char* BrName); + void ReadBranchEvent(const char* BrName); /**Read the tree entry on one branch for a specific entry**/ - void ReadBranchEvent(const char* BrName, Int_t entry); + void ReadBranchEvent(const char* BrName, Int_t entry); /**Read all entries from input tree(s) with time stamp from current time to dt (time in ns)*/ - Int_t GetRunId(); + Int_t GetRunId(); - Bool_t ReadNextEvent(Double_t dt); + Bool_t ReadNextEvent(Double_t dt); /**create a new branch in the output tree *@param name Name of the branch to create *@param Foldername Folder name containing this branch (e.g Detector name) *@param obj Pointer of type TNamed (e.g. MCStack object) *@param toFile if kTRUE, branch will be saved to the tree*/ - void Register(const char* name, const char* Foldername, TNamed* obj, Bool_t toFile); + void Register(const char* name, const char* Foldername, TNamed* obj, Bool_t toFile); /**create a new branch in the output tree - *@param name Name of the branch to create - *@param Foldername Folder name containing this branch (e.g Detector name) - *@param obj Pointer of type TCollection (e.g. TClonesArray of hits, points) - *@param toFile if kTRUE, branch will be saved to the tree*/ - void Register(const char* name,const char* Foldername ,TCollection* obj, Bool_t toFile); + *@param name Name of the branch to create + *@param Foldername Folder name containing this branch (e.g Detector name) + *@param obj Pointer of type TCollection (e.g. TClonesArray of hits, points) + *@param toFile if kTRUE, branch will be saved to the tree*/ + void Register(const char* name, const char* Foldername, TCollection* obj, Bool_t toFile); /** create a new branch based on an arbitrary type T (for which a dictionary must exist) **/ template - void RegisterAny(const char* name, T* &obj, Bool_t toFile); + void RegisterAny(const char* name, T*& obj, Bool_t toFile); /// for branches which are not managed by folders, we need a special function /// to trigger persistent branch creation /// return true if successful; false if problem bool CreatePersistentBranchesAny(); - void RegisterInputObject(const char* name, TObject* obj); + void RegisterInputObject(const char* name, TObject* obj); - TClonesArray* Register(TString branchName, TString className, TString folderName, Bool_t toFile); - /** Register a new FairWriteoutBuffer to the map. If a Buffer with the same map key already exists the given buffer will be deleted and the old will be returned!*/ + TClonesArray* Register(TString branchName, TString className, TString folderName, Bool_t toFile); + /** Register a new FairWriteoutBuffer to the map. If a Buffer with the same map key already exists the given buffer + * will be deleted and the old will be returned!*/ FairWriteoutBuffer* RegisterWriteoutBuffer(TString branchName, FairWriteoutBuffer* buffer); /**Update the list of time based branches in the output file*/ - void UpdateListOfTimebasedBranches(); + void UpdateListOfTimebasedBranches(); /**Use time stamps to read data and not tree entries*/ - void RunWithTimeStamps() {fTimeStamps = kTRUE;} + void RunWithTimeStamps() { fTimeStamps = kTRUE; } /**Set the branch name list*/ - void SetBranchNameList(TList* list); + void SetBranchNameList(TList* list); /** Replace the time based branch name list*/ - void SetTimeBasedBranchNameList(TList *list); + void SetTimeBasedBranchNameList(TList* list); - void FillEventHeader(FairEventHeader* feh) { if ( fSource ) fSource->FillEventHeader(feh); } + void FillEventHeader(FairEventHeader* feh) + { + if (fSource) + fSource->FillEventHeader(feh); + } /**Enables a last Fill command after all events are processed to store any data which is still in Buffers*/ - void SetLastFill(Bool_t val = kTRUE) { fFillLastData=val;} + void SetLastFill(Bool_t val = kTRUE) { fFillLastData = val; } /**When creating TTree from TFolder the fullpath of the objects is used as branch names * this method truncate the full path from the branch names - */ + */ - Int_t Write(const char* name=0, Int_t option=0, Int_t bufsize=0); + Int_t Write(const char* name = 0, Int_t option = 0, Int_t bufsize = 0); /** Write the current TGeoManager to file*/ - void WriteGeometry(); + void WriteGeometry(); /**Write the file header object to the output file*/ - void WriteFileHeader(FairFileHeader* f); + void WriteFileHeader(FairFileHeader* f); /**Write the folder structure used to create the tree to the output file */ - void WriteFolder() ; + void WriteFolder(); /**Check the maximum event number we can run to*/ - Int_t CheckMaxEventNo(Int_t EvtEnd=0); + Int_t CheckMaxEventNo(Int_t EvtEnd = 0); - void StoreWriteoutBufferData(Double_t eventTime); - void StoreAllWriteoutBufferData(); - void DeleteOldWriteoutBufferData(); + void StoreWriteoutBufferData(Double_t eventTime); + void StoreAllWriteoutBufferData(); + void DeleteOldWriteoutBufferData(); - Int_t GetEntryNr() {return fEntryNr;} - void SetEntryNr(Int_t val) {fEntryNr = val;} + Int_t GetEntryNr() { return fEntryNr; } + void SetEntryNr(Int_t val) { fEntryNr = val; } - void SetUseFairLinks(Bool_t val) {fUseFairLinks = val;}; - Bool_t GetUseFairLinks() const {return fUseFairLinks;}; + void SetUseFairLinks(Bool_t val) { fUseFairLinks = val; }; + Bool_t GetUseFairLinks() const { return fUseFairLinks; }; /** * @param Status : if true all inputs are mixed, i.e: each read event will take one entry from each input and put @@ -215,33 +231,48 @@ class FairRootManager : public TObject /* } */ /** These methods have been moved to the FairFileSource */ - void SetSource(FairSource* tempSource) { fSource = tempSource; } - FairSource* GetSource() { return fSource;} + void SetSource(FairSource* tempSource) { fSource = tempSource; } + FairSource* GetSource() { return fSource; } Bool_t InitSource(); - void SetSink(FairSink* tempSink) { fSink = tempSink; } - FairSink* GetSink() { return fSink;} + void SetSink(FairSink* tempSink) { fSink = tempSink; } + FairSink* GetSink() { return fSink; } Bool_t InitSink(); - void SetListOfFolders(TObjArray* ta){ fListFolder=ta; } - TChain* GetInChain () { return fSourceChain;} - TChain* GetSignalChainNo(UInt_t i) { return fSignalChainList[i]; } - TTree* GetInTree () { if ( fSourceChain ) return fSourceChain->GetTree(); return 0; } - const TFile* GetRootFile() { if ( fSourceChain ) return fSourceChain->GetFile(); return 0; } - TFile* GetInFile () { if ( fSourceChain ) return fSourceChain->GetFile(); return 0; } - void SetInChain (TChain* tempChain, Int_t ident=-1); + void SetListOfFolders(TObjArray* ta) { fListFolder = ta; } + TChain* GetInChain() { return fSourceChain; } + TChain* GetSignalChainNo(UInt_t i) { return fSignalChainList[i]; } + TTree* GetInTree() + { + if (fSourceChain) + return fSourceChain->GetTree(); + return 0; + } + const TFile* GetRootFile() + { + if (fSourceChain) + return fSourceChain->GetFile(); + return 0; + } + TFile* GetInFile() + { + if (fSourceChain) + return fSourceChain->GetFile(); + return 0; + } + void SetInChain(TChain* tempChain, Int_t ident = -1); /* /\**Set the input tree when running on PROOF worker*\/ */ - void SetFinishRun(Bool_t val = kTRUE){ fFinishRun = val;} - Bool_t FinishRun() {return fFinishRun;} + void SetFinishRun(Bool_t val = kTRUE) { fFinishRun = val; } + Bool_t FinishRun() { return fFinishRun; } static char* GetTreeName(); static char* GetFolderName(); /**public Members for multi-threading */ - Int_t GetInstanceId() const { return fId; } - void UpdateFileName(TString& fileName); + Int_t GetInstanceId() const { return fId; } + void UpdateFileName(TString& fileName); // vvvvvvvvvv depracted functions, replaced by FairSink vvvvvvvvvv /** Return a pointer to the output File of type TFile */ @@ -252,11 +283,16 @@ class FairRootManager : public TObject private: // helper struct since std::pair has problems with type_info - struct TypeAddressPair { - TypeAddressPair(const std::type_info &oi, const std::type_info &pi, void* a) : origtypeinfo(oi), persistenttypeinfo(pi), ptraddr(a) {} - const std::type_info &origtypeinfo; // type_info of type addr points to - const std::type_info &persistenttypeinfo; // type_info of ROOT persistent branch (drops pointers) - void *ptraddr; // address of a pointer (pointing to origtypeinfo); + struct TypeAddressPair + { + TypeAddressPair(const std::type_info& oi, const std::type_info& pi, void* a) + : origtypeinfo(oi) + , persistenttypeinfo(pi) + , ptraddr(a) + {} + const std::type_info& origtypeinfo; // type_info of type addr points to + const std::type_info& persistenttypeinfo; // type_info of ROOT persistent branch (drops pointers) + void* ptraddr; // address of a pointer (pointing to origtypeinfo); }; /**private methods*/ @@ -266,13 +302,13 @@ class FairRootManager : public TObject FairRootManager& operator=(const FairRootManager&); /** Set the branch address for a given branch name and return a TObject pointer, the user have to cast this pointer to the right type.*/ - TObject* ActivateBranch(const char* BrName); - void AddFriends( ); + TObject* ActivateBranch(const char* BrName); + void AddFriends(); /**Add a branch to memory, it will not be written to the output files*/ - void AddMemoryBranch(const char*, TObject* ); + void AddMemoryBranch(const char*, TObject*); template - void AddMemoryBranchAny(const char *name, T** obj); + void AddMemoryBranchAny(const char* name, T** obj); template T GetMemoryBranchAny(const char* name) const; @@ -285,192 +321,197 @@ class FairRootManager : public TObject 2 : Memory Branch 0 : Branch does not exist */ - Int_t CheckBranchSt(const char* BrName); - /**Create the Map for the branch persistency status */ - void CreatePerMap(); - TObject* GetMemoryBranch( const char* ); - // void GetRunIdInfo(TString fileName, TString inputLevel); + Int_t CheckBranchSt(const char* BrName); + /**Create the Map for the branch persistency status */ + void CreatePerMap(); + TObject* GetMemoryBranch(const char*); + // void GetRunIdInfo(TString fileName, TString inputLevel); FairWriteoutBuffer* GetWriteoutBuffer(TString branchName); // private helper function to emit a warning - void EmitMemoryBranchWrongTypeWarning(const char* brname, const char *typen1, const char *typen2) const; + void EmitMemoryBranchWrongTypeWarning(const char* brname, const char* typen1, const char* typen2) const; /**private Members*/ - Int_t fOldEntryNr; + Int_t fOldEntryNr; /**folder structure of output*/ - TFolder* fOutFolder; + TFolder* fOutFolder; /**folder structure of input*/ - TFolder* fRootFolder; + TFolder* fRootFolder; /** current time in ns*/ - Double_t fCurrentTime; - TObject** fObj2; //! + Double_t fCurrentTime; + TObject** fObj2; //! /** Counter for the number of branches activiated */ - Int_t fNObj;//! + Int_t fNObj; //! /** A list which hold the pointer to the branch * and the name of the branch in memory, it contains all branches (TClonesArrays) * persistance and Memory only branches */ - std::map < TString , TObject* > fMap; //! + std::map fMap; //! /// A map of branchnames to typeinformation + memory address; /// used for branches registered with RegisterAny; use of ptr here /// since type_info cannot be copied - std::map> fAnyBranchMap; //! + std::map> fAnyBranchMap; //! /// keeps track of branches which are supposed to be persistified std::vector fPersistentBranchesAny; /**Branch id for this run */ - Int_t fBranchSeqId; + Int_t fBranchSeqId; /**List of branch names as TObjString*/ - TList* fBranchNameList; //! + TList* fBranchNameList; //! /**Vector of (not necessarily unique) branch names requested per GetObject / InitObjectAs */ - std::vector fReqBrNames; //! + std::vector fReqBrNames; //! /**The branch ID for the special (required) MCTrack branch**/ - Int_t fMCTrackBranchId; //! + Int_t fMCTrackBranchId; //! /**List of Time based branchs names as TObjString*/ - TList* fTimeBasedBranchNameList; //! + TList* fTimeBasedBranchNameList; //! /** Internally used to compress empty slots in data buffer*/ std::map fActiveContainer; /** Internally used to read time ordered data from branches*/ - std::map fTSBufferMap; //! - std::map fWriteoutBufferMap; //! - std::map fInputBranchMap; //! //Map of input branch ID with TBranch pointer + std::map fTSBufferMap; //! + std::map fWriteoutBufferMap; //! + std::map fInputBranchMap; //! //Map of input branch ID with TBranch pointer /**if kTRUE Read data according to time and not entries*/ - Bool_t fTimeStamps; + Bool_t fTimeStamps; /**Flag for creation of Map for branch persistency list */ - Bool_t fBranchPerMap; + Bool_t fBranchPerMap; /** Map for branch persistency list */ - std::map < TString , Int_t > fBrPerMap; //! + std::map fBrPerMap; //! /**Iterator for the fBrPerMap Map*/ - std::map < TString, Int_t>::iterator fBrPerMapIter; + std::map::iterator fBrPerMapIter; /** for internal use, to return the same event time for the same entry*/ - UInt_t fCurrentEntryNo; //! + UInt_t fCurrentEntryNo; //! /** for internal use, to return the same event time for the same entry*/ - UInt_t fTimeforEntryNo; //! - Bool_t fFillLastData; //! - Int_t fEntryNr; //! + UInt_t fTimeforEntryNo; //! + Bool_t fFillLastData; //! + Int_t fEntryNr; //! - TObjArray *fListFolder; //! + TObjArray* fListFolder; //! - FairSource *fSource; + FairSource* fSource; - TChain *fSourceChain; - std::map fSignalChainList;//! + TChain* fSourceChain; + std::map fSignalChainList; //! - FairEventHeader *fEventHeader; + FairEventHeader* fEventHeader; - FairSink *fSink; + FairSink* fSink; - Bool_t fUseFairLinks; //! - Bool_t fFinishRun; //! + Bool_t fUseFairLinks; //! + Bool_t fFinishRun; //! /** List of branches from input Chain or Tree*/ - TObjArray* fListOfBranchesFromInput; //! + TObjArray* fListOfBranchesFromInput; //! /** Iterator for the list of branches from input Chain or Tree */ - TIterator* fListOfBranchesFromInputIter;//! + TIterator* fListOfBranchesFromInputIter; //! /** List of branches used with no-time stamp in time-based session */ - TRefArray* fListOfNonTimebasedBranches; //! + TRefArray* fListOfNonTimebasedBranches; //! /** Iterator for the list of branches used with no-time stamp in time-based session */ - TIterator* fListOfNonTimebasedBranchesIter; //! + TIterator* fListOfNonTimebasedBranchesIter; //! /**private Members for multi-threading */ // global static data members - static Int_t fgCounter; // The counter of instances + static Int_t fgCounter; // The counter of instances // data members - Int_t fId; // This manager ID + Int_t fId; // This manager ID - ClassDef(FairRootManager,12) // Root IO manager + ClassDef(FairRootManager, 12) // Root IO manager }; // FIXME: move to source since we can make it non-template dependent template -void FairRootManager::AddMemoryBranchAny(const char* brname, T** obj) { - if (fAnyBranchMap.find(brname) == fAnyBranchMap.end()) { - auto& ot = typeid(T*); - auto& pt = typeid(T); - fAnyBranchMap[brname]=std::unique_ptr (new TypeAddressPair(ot, pt,(void*)obj)); - } +void FairRootManager::AddMemoryBranchAny(const char* brname, T** obj) +{ + if (fAnyBranchMap.find(brname) == fAnyBranchMap.end()) { + auto& ot = typeid(T*); + auto& pt = typeid(T); + fAnyBranchMap[brname] = std::unique_ptr(new TypeAddressPair(ot, pt, (void*)obj)); + } } // try to retrieve an object address from the registered branches/names template -T FairRootManager::GetMemoryBranchAny(const char* brname) const { - static_assert(std::is_pointer::value, "Return type of GetMemoryBranchAny has to be a pointer"); - using P = typename std::remove_pointer::type; - auto iter = fAnyBranchMap.find(brname); - if(iter != fAnyBranchMap.end()) { - // verify type consistency - if(typeid(P).hash_code() != iter->second->origtypeinfo.hash_code()) { - EmitMemoryBranchWrongTypeWarning(brname, typeid(P).name(), iter->second->origtypeinfo.name()); - return nullptr; +T FairRootManager::GetMemoryBranchAny(const char* brname) const +{ + static_assert(std::is_pointer::value, "Return type of GetMemoryBranchAny has to be a pointer"); + using P = typename std::remove_pointer::type; + auto iter = fAnyBranchMap.find(brname); + if (iter != fAnyBranchMap.end()) { + // verify type consistency + if (typeid(P).hash_code() != iter->second->origtypeinfo.hash_code()) { + EmitMemoryBranchWrongTypeWarning(brname, typeid(P).name(), iter->second->origtypeinfo.name()); + return nullptr; + } + return static_cast(iter->second->ptraddr); } - return static_cast(iter->second->ptraddr); - } - return nullptr; + return nullptr; } template -void FairRootManager::RegisterAny(const char* brname, T *& obj, bool persistence) { - AddBranchToList(brname); - // we are taking the address of the passed pointer - AddMemoryBranchAny(brname, &obj); - if (persistence) { - auto& ot = typeid(T*); - auto& pt = typeid(T); - if ( fSink ) - fSink->RegisterAny(brname,ot,pt,&obj); - else - LOG(fatal) << "The sink does not exist to store persistent branches."; - } +void FairRootManager::RegisterAny(const char* brname, T*& obj, bool persistence) +{ + AddBranchToList(brname); + // we are taking the address of the passed pointer + AddMemoryBranchAny(brname, &obj); + if (persistence) { + auto& ot = typeid(T*); + auto& pt = typeid(T); + if (fSink) + fSink->RegisterAny(brname, ot, pt, &obj); + else + LOG(fatal) << "The sink does not exist to store persistent branches."; + } } // this function serves as a factory (or lookup) for memory managed // instances associated to branches // it returns a pointer to unmodifiable instance of T template -TPtr FairRootManager::InitObjectAs(const char* brname) { - static_assert(std::is_pointer::value, "Return type of GetObjectAs has to be a pointer"); - using X = typename std::remove_pointer::type; - static_assert(std::is_const::value, "Return type of GetObjectAs has to be pointer to const class"); - using T = typename std::remove_const::type; - - // is there already an object associated to the branch in memory?? - // then just return - T** obj = GetMemoryBranchAny(brname); - // obj is some address/instance holding TPtr instances - if(obj!=nullptr) return *obj; - - // it does not seem to be the case, let us create the pointer which will be initialized - // with the data (pointer to T) - T** addr = new T*; - // init the pointee to a default obj which we can return - (*addr) = new T; - // try to find and activate in the source - auto succeeded = fSource->ActivateObjectAny((void**)addr, typeid(T), brname); - - if(!succeeded) { - delete (*addr); - delete addr; - return nullptr; - } - // add into branch list - AddMemoryBranchAny(brname, addr); - // register as a **requested** branch - // (duplications are explicitely allowed) - fReqBrNames.emplace_back(brname); - - // NOTE: ideally we would do proper resource management for addr and *addr - // since the FairRootManager becomes owner of these pointers/instances; Unfortunately this - // is quite a difficult task since we would have to store something like std::unique_ptr in a member - // container which we cannot know a priori; Some solutions we could think of in the future are - // a) use the Destructor mechanism of ROOT::TClass since we still have the type info. - // b) investigate if boost::any could be of help here - // In any case, this problem is not very critical in the sense that FairRootManager is a singleton and hence - // cannot really leak memory (Assuming that the destructors of T are not doing something non-trivial). - return *addr; +TPtr FairRootManager::InitObjectAs(const char* brname) +{ + static_assert(std::is_pointer::value, "Return type of GetObjectAs has to be a pointer"); + using X = typename std::remove_pointer::type; + static_assert(std::is_const::value, "Return type of GetObjectAs has to be pointer to const class"); + using T = typename std::remove_const::type; + + // is there already an object associated to the branch in memory?? + // then just return + T** obj = GetMemoryBranchAny(brname); + // obj is some address/instance holding TPtr instances + if (obj != nullptr) + return *obj; + + // it does not seem to be the case, let us create the pointer which will be initialized + // with the data (pointer to T) + T** addr = new T*; + // init the pointee to a default obj which we can return + (*addr) = new T; + // try to find and activate in the source + auto succeeded = fSource->ActivateObjectAny((void**)addr, typeid(T), brname); + + if (!succeeded) { + delete (*addr); + delete addr; + return nullptr; + } + // add into branch list + AddMemoryBranchAny(brname, addr); + // register as a **requested** branch + // (duplications are explicitely allowed) + fReqBrNames.emplace_back(brname); + + // NOTE: ideally we would do proper resource management for addr and *addr + // since the FairRootManager becomes owner of these pointers/instances; Unfortunately this + // is quite a difficult task since we would have to store something like std::unique_ptr in a member + // container which we cannot know a priori; Some solutions we could think of in the future are + // a) use the Destructor mechanism of ROOT::TClass since we still have the type info. + // b) investigate if boost::any could be of help here + // In any case, this problem is not very critical in the sense that FairRootManager is a singleton and hence + // cannot really leak memory (Assuming that the destructors of T are not doing something non-trivial). + return *addr; } -#endif //FAIR_ROOT_MANAGER_H +#endif // FAIR_ROOT_MANAGER_H diff --git a/base/steer/FairRun.cxx b/base/steer/FairRun.cxx index 6e275d38c7..36be74531b 100644 --- a/base/steer/FairRun.cxx +++ b/base/steer/FairRun.cxx @@ -12,187 +12,177 @@ #include "FairRun.h" -#include "FairEventHeader.h" // for FairEventHeader -#include "FairFileHeader.h" // for FairFileHeader -#include "FairLogger.h" // for FairLogger, MESSAGE_ORIGIN -#include "FairRootManager.h" // for FairRootManager -#include "FairRuntimeDb.h" // for FairRuntimeDb -#include "FairTask.h" // for FairTask -#include "FairLinkManager.h" // for FairLinkManager +#include "FairEventHeader.h" // for FairEventHeader +#include "FairFileHeader.h" // for FairFileHeader +#include "FairLinkManager.h" // for FairLinkManager +#include "FairLogger.h" // for FairLogger, MESSAGE_ORIGIN +#include "FairRootFileSink.h" // only temporary, should be removed after the move to FairSink is finished +#include "FairRootManager.h" // for FairRootManager +#include "FairRuntimeDb.h" // for FairRuntimeDb +#include "FairTask.h" // for FairTask -#include "FairRootFileSink.h" // only temporary, should be removed after the move to FairSink is finished +#include // for TFile +#include // for TList +#include // for TObject +#include // for... well, assert -#include // for TFile -#include // for TList -#include // for TObject +TMCThreadLocal FairRun* FairRun::fRunInstance = 0; -#include // for... well, assert - -TMCThreadLocal FairRun* FairRun::fRunInstance= 0; - -FairRun* FairRun::Instance() -{ - return fRunInstance; -} +FairRun* FairRun::Instance() { return fRunInstance; } FairRun::FairRun(Bool_t isMaster) - :TNamed(), - fNTasks(0), - fRtdb(FairRuntimeDb::instance()), - fTask(new FairTask("FairTaskList")), - fRootManager(0), - fSink(0), - fUserOutputFileName(), - fRunId(0), - fAna(kFALSE), - fEvtHeader(nullptr), - fFileHeader(new FairFileHeader()), - fGenerateRunInfo(kFALSE), - fIsMaster(isMaster), - fMarkFill(kTRUE) -{ - if (fRunInstance) { - Fatal("FairRun", "Singleton instance already exists."); - return; - } - fRunInstance=this; + : TNamed() + , fNTasks(0) + , fRtdb(FairRuntimeDb::instance()) + , fTask(new FairTask("FairTaskList")) + , fRootManager(0) + , fSink(0) + , fUserOutputFileName() + , fRunId(0) + , fAna(kFALSE) + , fEvtHeader(nullptr) + , fFileHeader(new FairFileHeader()) + , fGenerateRunInfo(kFALSE) + , fIsMaster(isMaster) + , fMarkFill(kTRUE) +{ + if (fRunInstance) { + Fatal("FairRun", "Singleton instance already exists."); + return; + } + fRunInstance = this; fRootManager = FairRootManager::Instance(); - new FairLinkManager(); + new FairLinkManager(); } FairRun::~FairRun() { - LOG(debug) << "Enter Destructor of FairRun"; - delete fTask; // There is another tasklist in MCApplication, - // but this should be independent - delete fRtdb; // who is responsible for the RuntimeDataBase - delete fEvtHeader; - LOG(debug) << "Leave Destructor of FairRun"; + LOG(debug) << "Enter Destructor of FairRun"; + delete fTask; // There is another tasklist in MCApplication, + // but this should be independent + delete fRtdb; // who is responsible for the RuntimeDataBase + delete fEvtHeader; + LOG(debug) << "Leave Destructor of FairRun"; } void FairRun::AddTask(FairTask* task) { - fTask->Add(task); - StoreTaskNames(task); + fTask->Add(task); + StoreTaskNames(task); } void FairRun::StoreTaskNames(const FairTask* task) { - if(task) { - fFileHeader->AddTaskClassName(task->ClassName()); - fNTasks++; - - const TList* subtasks = task->GetListOfTasks(); - if(subtasks) { - for(const auto subtask : *subtasks) { - StoreTaskNames(static_cast(subtask)); - } + if (task) { + fFileHeader->AddTaskClassName(task->ClassName()); + fNTasks++; + + const TList* subtasks = task->GetListOfTasks(); + if (subtasks) { + for (const auto subtask : *subtasks) { + StoreTaskNames(static_cast(subtask)); + } + } } - } } void FairRun::SetTask(FairTask* task) { - delete fTask; - fTask = task; - fNTasks=0; - TList* tasklist = fFileHeader->GetListOfTasks(); - if(tasklist) { - tasklist->Clear(); - StoreTaskNames(task); - } + delete fTask; + fTask = task; + fNTasks = 0; + TList* tasklist = fFileHeader->GetListOfTasks(); + if (tasklist) { + tasklist->Clear(); + StoreTaskNames(task); + } } -void FairRun::CreateGeometryFile(const char* geofile) -{ - fRootManager->CreateGeometryFile(geofile); -} +void FairRun::CreateGeometryFile(const char* geofile) { fRootManager->CreateGeometryFile(geofile); } FairTask* FairRun::GetTask(const char* taskName) { - TList* taskList = fTask->GetListOfTasks(); - TObject* task = taskList->FindObject(taskName); - return dynamic_cast(task); + TList* taskList = fTask->GetListOfTasks(); + TObject* task = taskList->FindObject(taskName); + return dynamic_cast(task); } -FairEventHeader* FairRun::GetEventHeader() +FairEventHeader* FairRun::GetEventHeader() { - if ( nullptr == fEvtHeader ) { - fEvtHeader = new FairEventHeader(); - } - return fEvtHeader; + if (nullptr == fEvtHeader) { + fEvtHeader = new FairEventHeader(); + } + return fEvtHeader; } -void FairRun::SetUseFairLinks(Bool_t val) -{ - fRootManager->SetUseFairLinks(val); -} +void FairRun::SetUseFairLinks(Bool_t val) { fRootManager->SetUseFairLinks(val); } void FairRun::SetWriteRunInfoFile(Bool_t write) { - LOG(warn) << "Function FairRun::SetWriteRunInfoFile(Bool_t) is depcrecated and will vanish in future versions of FairRoot.\n"; - LOG(warn) << "Please use FairRun::SetGenerateRunInfo(Bool_t) instead."; + LOG(warn) << "Function FairRun::SetWriteRunInfoFile(Bool_t) is depcrecated and will vanish in future versions of " + "FairRoot.\n"; + LOG(warn) << "Please use FairRun::SetGenerateRunInfo(Bool_t) instead."; - fGenerateRunInfo = write; + fGenerateRunInfo = write; } Bool_t FairRun::GetWriteRunInfoFile() { - LOG(warn) << "Function FairRun::GetWriteRunInfoFile() is depcrecated and will vanish in future versions of FairRoot.\n"; - LOG(warn) << "Please use FairRun::IsRunInfoGenerated() instead."; + LOG(warn) + << "Function FairRun::GetWriteRunInfoFile() is depcrecated and will vanish in future versions of FairRoot.\n"; + LOG(warn) << "Please use FairRun::IsRunInfoGenerated() instead."; - return fGenerateRunInfo; + return fGenerateRunInfo; } void FairRun::SetOutputFile(const char* fname) { - LOG(WARNING) << "FairRun::SetOutputFile() deprecated. Use FairRootFileSink."; - fSink = new FairRootFileSink(fname); - if (fRootManager) fRootManager->SetSink(fSink); - fUserOutputFileName = fname; + LOG(WARNING) << "FairRun::SetOutputFile() deprecated. Use FairRootFileSink."; + fSink = new FairRootFileSink(fname); + if (fRootManager) + fRootManager->SetSink(fSink); + fUserOutputFileName = fname; } void FairRun::SetOutputFile(TFile* f) { - LOG(WARNING) << "FairRun::SetOutputFile() deprecated. Use FairRootFileSink."; - fSink = new FairRootFileSink(f); - if (fRootManager) fRootManager->SetSink(fSink); - if (f) fUserOutputFileName = f->GetName(); + LOG(WARNING) << "FairRun::SetOutputFile() deprecated. Use FairRootFileSink."; + fSink = new FairRootFileSink(f); + if (fRootManager) + fRootManager->SetSink(fSink); + if (f) + fUserOutputFileName = f->GetName(); } -void FairRun::SetOutputFileName(const TString& name) { - LOG(WARNING) << "FairRun::SetOutputFileName() deprecated. Use FairRootFileSink."; - fSink = new FairRootFileSink(name); - if (fRootManager) fRootManager->SetSink(fSink); - fUserOutputFileName = name; +void FairRun::SetOutputFileName(const TString& name) +{ + LOG(WARNING) << "FairRun::SetOutputFileName() deprecated. Use FairRootFileSink."; + fSink = new FairRootFileSink(name); + if (fRootManager) + fRootManager->SetSink(fSink); + fUserOutputFileName = name; } TFile* FairRun::GetOutputFile() { - LOG(WARNING) << "FairRun::GetOutputFile() deprecated. Use separate file to store additional data."; - auto sink = GetSink(); - assert(sink->GetSinkType() == kFILESINK); - auto rootFileSink = static_cast(sink); - return rootFileSink->GetRootFile(); + LOG(WARNING) << "FairRun::GetOutputFile() deprecated. Use separate file to store additional data."; + auto sink = GetSink(); + assert(sink->GetSinkType() == kFILESINK); + auto rootFileSink = static_cast(sink); + return rootFileSink->GetRootFile(); } -void FairRun::SetUserOutputFileName(const TString& name) { - fUserOutputFileName = name; -} +void FairRun::SetUserOutputFileName(const TString& name) { fUserOutputFileName = name; } -TString FairRun::GetUserOutputFileName() const -{ - return fUserOutputFileName; -} +TString FairRun::GetUserOutputFileName() const { return fUserOutputFileName; } -void FairRun::AlignGeometry() const { - fAlignmentHandler.AlignGeometry(); -} +void FairRun::AlignGeometry() const { fAlignmentHandler.AlignGeometry(); } -void FairRun::AddAlignmentMatrices(const std::map& alignmentMatrices, bool invertMatrices) { - fAlignmentHandler.AddAlignmentMatrices(alignmentMatrices, invertMatrices); +void FairRun::AddAlignmentMatrices(const std::map& alignmentMatrices, bool invertMatrices) +{ + fAlignmentHandler.AddAlignmentMatrices(alignmentMatrices, invertMatrices); } -ClassImp(FairRun) +ClassImp(FairRun); diff --git a/base/steer/FairRun.h b/base/steer/FairRun.h index 681fc014c0..977e0dc3a5 100644 --- a/base/steer/FairRun.h +++ b/base/steer/FairRun.h @@ -8,16 +8,15 @@ #ifndef FAIRRUN_H #define FAIRRUN_H -#include "FairRootManager.h" #include "FairAlignmentHandler.h" +#include "FairRootManager.h" -#include // for TNamed -#include // for Int_t, Bool_t, etc -#include // for multi-threading +#include // for Int_t, Bool_t, etc +#include // for multi-threading +#include // for TNamed #include - -#include #include +#include class FairEventHeader; class FairFileHeader; @@ -37,15 +36,16 @@ class TGeoHMatrix; class FairRun : public TNamed { - friend class FairMCApplication; + friend class FairMCApplication; + public: /** * default ctor */ FairRun(Bool_t isMaster = kTRUE); /** - * default dtor - */ + * default dtor + */ virtual ~FairRun(); /** * static instance @@ -54,88 +54,72 @@ class FairRun : public TNamed /** * Add a FAIRTask to the simulation or analysis */ - virtual void AddTask(FairTask* t); - virtual void StoreTaskNames(const FairTask* t); - virtual void SetTask(FairTask* t); + virtual void AddTask(FairTask* t); + virtual void StoreTaskNames(const FairTask* t); + virtual void SetTask(FairTask* t); /** * Initialize the Simulation or analysis */ - virtual void Init()=0; + virtual void Init() = 0; /* * Get the magnetic field * */ - virtual FairField* GetField()=0; + virtual FairField* GetField() = 0; /** - * run the analysis or simulation + * run the analysis or simulation */ - virtual void Run(Int_t NStart =0,Int_t NStop=0)=0; + virtual void Run(Int_t NStart = 0, Int_t NStop = 0) = 0; /** * Set the experiment dependent run header * for each run */ - void SetEventHeader(FairEventHeader* EvHeader) { - fEvtHeader=EvHeader; - } + void SetEventHeader(FairEventHeader* EvHeader) { fEvtHeader = EvHeader; } /** * return a pointer to the RuntimeDB */ - FairRuntimeDb* GetRuntimeDb(void) { - return fRtdb; - } + FairRuntimeDb* GetRuntimeDb(void) { return fRtdb; } /** * Set the sink */ - void SetSink(FairSink* tempSink) { - fSink = tempSink; - fRootManager->SetSink(tempSink); - fUserOutputFileName = fSink->GetFileName(); - } - /** - * return a pointer to the sink - */ - FairSink* GetSink() { - return fSink; + void SetSink(FairSink* tempSink) + { + fSink = tempSink; + fRootManager->SetSink(tempSink); + fUserOutputFileName = fSink->GetFileName(); } + /** + * return a pointer to the sink + */ + FairSink* GetSink() { return fSink; } /** * return the run ID for the actul run */ - Int_t GetRunId() { - return (static_cast(fRunId)); - } + Int_t GetRunId() { return (static_cast(fRunId)); } - /** + /** * Set the Run ID - */ - void SetRunId(UInt_t runId) - { - fRunId = runId; - } + */ + void SetRunId(UInt_t runId) { fRunId = runId; } /**Get the detector specific run header*/ - FairEventHeader* GetEventHeader(); + FairEventHeader* GetEventHeader(); /** - * return true for Anaylsis session - */ - Bool_t IsAna() { - return fAna; - } + * return true for Anaylsis session + */ + Bool_t IsAna() { return fAna; } /** - *Get task by name - */ + *Get task by name + */ FairTask* GetTask(const char* taskName); /** - *Get Main Task - */ - FairTask* GetMainTask() { - return fTask; - } + *Get Main Task + */ + FairTask* GetMainTask() { return fTask; } /** - * Return the number of Tasks added to this Run - */ - Int_t GetNTasks() { - return fNTasks; - } + * Return the number of Tasks added to this Run + */ + Int_t GetNTasks() { return fNTasks; } /**Create a new file and save the TGeoManager to it*/ void CreateGeometryFile(const char* geofile); @@ -144,38 +128,38 @@ class FairRun : public TNamed void SetWriteRunInfoFile(Bool_t write); //** Set if RunInfo should be generated */ - void SetGenerateRunInfo(Bool_t write) { fGenerateRunInfo = write;} + void SetGenerateRunInfo(Bool_t write) { fGenerateRunInfo = write; } //** Get info if RunInfo file is written */ Bool_t GetWriteRunInfoFile(); //** Get info if RunInfo file is written */ - Bool_t IsRunInfoGenerated() { return fGenerateRunInfo;} + Bool_t IsRunInfoGenerated() { return fGenerateRunInfo; } //** Switches the use of FairLinks */ void SetUseFairLinks(Bool_t val); //** Get info if run on master */ - Bool_t GetIsMaster() const { return fIsMaster;} + Bool_t GetIsMaster() const { return fIsMaster; } //** Mark/Unmark event to be filled into output. Default is TRUE. */ void MarkFill(Bool_t flag) { fMarkFill = flag; } //** Get option string */ - TString GetOptions(){return fOptions;}; + TString GetOptions() { return fOptions; }; //** Set option string */ - void SetOptions(const TString& s){fOptions=s;}; + void SetOptions(const TString& s) { fOptions = s; }; // vvvvvvvvvv depracted functions, replaced by FairSink vvvvvvvvvv /** * Set the output file name for analysis or simulation - */ - virtual void SetOutputFile(const char* fname); + */ + virtual void SetOutputFile(const char* fname); /** * Set the output file for analysis or simulation - */ - virtual void SetOutputFile(TFile* f); + */ + virtual void SetOutputFile(TFile* f); /** * Set the output file name without creating the file */ @@ -190,15 +174,11 @@ class FairRun : public TNamed void SetUserOutputFileName(const TString& name); TString GetUserOutputFileName() const; - void AddAlignmentMatrices( - const std::map& alignmentMatrices, - bool invertMatrices = false); + void AddAlignmentMatrices(const std::map& alignmentMatrices, bool invertMatrices = false); private: FairRun(const FairRun& M); - FairRun& operator= (const FairRun&) { - return *this; - } + FairRun& operator=(const FairRun&) { return *this; } /** Number of Tasks added*/ Int_t fNTasks; @@ -206,36 +186,36 @@ class FairRun : public TNamed /** static pointer to this run*/ static TMCThreadLocal FairRun* fRunInstance; /** RuntimeDb*/ - FairRuntimeDb* fRtdb; + FairRuntimeDb* fRtdb; /** Tasks used*/ - FairTask* fTask; + FairTask* fTask; /**IO manager */ - FairRootManager* fRootManager; + FairRootManager* fRootManager; /**Output sink*/ - FairSink* fSink; + FairSink* fSink; /**Output file name set by user*/ - TString fUserOutputFileName; + TString fUserOutputFileName; /**Options for derived classes, to be set & parsed by user*/ - TString fOptions; + TString fOptions; /**Run Id*/ - UInt_t fRunId;//! + UInt_t fRunId; //! /** true for Anaylsis session*/ - Bool_t fAna; //! + Bool_t fAna; //! /** MC Event Header */ - FairEventHeader* fEvtHeader; //! + FairEventHeader* fEvtHeader; //! /** File Header */ - FairFileHeader* fFileHeader; + FairFileHeader* fFileHeader; /** true if RunInfo file should be written*/ - Bool_t fGenerateRunInfo; //! + Bool_t fGenerateRunInfo; //! /** true if on master*/ - Bool_t fIsMaster; //! + Bool_t fIsMaster; //! - Bool_t fMarkFill; //! + Bool_t fMarkFill; //! FairAlignmentHandler fAlignmentHandler; void AlignGeometry() const; - ClassDef(FairRun ,5) + ClassDef(FairRun, 5) }; -#endif //FAIRRUN_H +#endif // FAIRRUN_H diff --git a/base/steer/FairRunAna.cxx b/base/steer/FairRunAna.cxx index ae5d8b9f1e..5175317f39 100644 --- a/base/steer/FairRunAna.cxx +++ b/base/steer/FairRunAna.cxx @@ -12,37 +12,35 @@ #include "FairRunAna.h" -#include "FairBaseParSet.h" // for FairBaseParSet -#include "FairEventHeader.h" // for FairEventHeader -#include "FairField.h" // for FairField -#include "FairFieldFactory.h" // for FairFieldFactory -#include "FairFileHeader.h" // for FairFileHeader -#include "FairLogger.h" // for FairLogger, MESSAGE_ORIGIN -#include "FairParSet.h" // for FairParSet -#include "FairRootManager.h" // for FairRootManager -#include "FairRunIdGenerator.h" // for FairRunIdGenerator -#include "FairRuntimeDb.h" // for FairRuntimeDb -#include "FairTask.h" // for FairTask -#include "FairTrajFilter.h" // for FairTrajFilter - -#include "FairFileSource.h" // ONLY TEMPORARILY, FOR COMPABILITY -#include "FairMixedSource.h" // ONLY TEMPORARILY, FOR COMPABILITY - -#include // for TIter -#include // for TFile, gFile -#include // for gGeoManager, TGeoManager -#include // for TKey -#include // for TList -#include // for TObjArray -#include // for TObject -#include // for TROOT, gROOT -#include // for TSeqCollection -#include // for TSystem, gSystem - -#include // for exit +#include "FairBaseParSet.h" // for FairBaseParSet +#include "FairEventHeader.h" // for FairEventHeader +#include "FairField.h" // for FairField +#include "FairFieldFactory.h" // for FairFieldFactory +#include "FairFileHeader.h" // for FairFileHeader +#include "FairFileSource.h" // ONLY TEMPORARILY, FOR COMPABILITY +#include "FairLogger.h" // for FairLogger, MESSAGE_ORIGIN +#include "FairMixedSource.h" // ONLY TEMPORARILY, FOR COMPABILITY +#include "FairParSet.h" // for FairParSet +#include "FairRootManager.h" // for FairRootManager +#include "FairRunIdGenerator.h" // for FairRunIdGenerator +#include "FairRuntimeDb.h" // for FairRuntimeDb +#include "FairTask.h" // for FairTask +#include "FairTrajFilter.h" // for FairTrajFilter #include "signal.h" -#include // for strcmp -#include // for operator<<, basic_ostream, etc + +#include // for TIter +#include // for TFile, gFile +#include // for gGeoManager, TGeoManager +#include // for TKey +#include // for TList +#include // for TObjArray +#include // for TObject +#include // for TROOT, gROOT +#include // for TSeqCollection +#include // for TSystem, gSystem +#include // for operator<<, basic_ostream, etc +#include // for exit +#include // for strcmp using std::cout; using std::endl; @@ -52,80 +50,76 @@ Bool_t gFRAIsInterrupted; //_____________________________________________________________________________ void FRA_handler_ctrlc(int) { - LOG(info) << "*********** CTRL C PRESSED *************"; - gFRAIsInterrupted = kTRUE; + LOG(info) << "*********** CTRL C PRESSED *************"; + gFRAIsInterrupted = kTRUE; } //_____________________________________________________________________________ //_____________________________________________________________________________ -FairRunAna* FairRunAna::fgRinstance= 0; +FairRunAna* FairRunAna::fgRinstance = 0; //_____________________________________________________________________________ -FairRunAna* FairRunAna::Instance() -{ - - return fgRinstance; -} +FairRunAna* FairRunAna::Instance() { return fgRinstance; } //_____________________________________________________________________________ FairRunAna::FairRunAna() - :FairRun(), - fRunInfo(), - fIsInitialized(kFALSE), - fInputGeoFile(0), - fLoadGeo( kFALSE), - fStatic(kFALSE), - fField(0), - fTimeStamps(kFALSE), - fInFileIsOpen(kFALSE), - fEventTimeMin(0), - fEventTimeMax(0), - fEventTime(0), - fEventMeanTime(0), - fTimeProb(0), - fFinishProcessingLMDFile(kFALSE), - fFileSource(0), - fMixedSource(0), - fStoreEventHeader(kTRUE) + : FairRun() + , fRunInfo() + , fIsInitialized(kFALSE) + , fInputGeoFile(0) + , fLoadGeo(kFALSE) + , fStatic(kFALSE) + , fField(0) + , fTimeStamps(kFALSE) + , fInFileIsOpen(kFALSE) + , fEventTimeMin(0) + , fEventTimeMax(0) + , fEventTime(0) + , fEventMeanTime(0) + , fTimeProb(0) + , fFinishProcessingLMDFile(kFALSE) + , fFileSource(0) + , fMixedSource(0) + , fStoreEventHeader(kTRUE) { - fgRinstance=this; - fAna=kTRUE; + fgRinstance = this; + fAna = kTRUE; } //_____________________________________________________________________________ //_____________________________________________________________________________ FairRunAna::~FairRunAna() { - // delete fFriendFileList; - delete fField; - if (gGeoManager) { - if (gROOT->GetVersionInt() >= 60602) { - gGeoManager->GetListOfVolumes()->Delete(); - gGeoManager->GetListOfShapes()->Delete(); - } - delete gGeoManager; - } + // delete fFriendFileList; + delete fField; + if (gGeoManager) { + if (gROOT->GetVersionInt() >= 60602) { + gGeoManager->GetListOfVolumes()->Delete(); + gGeoManager->GetListOfShapes()->Delete(); + } + delete gGeoManager; + } } //_____________________________________________________________________________ -void FairRunAna::SetGeomFile(const char* GeoFileName) +void FairRunAna::SetGeomFile(const char* GeoFileName) { - if (fIsInitialized) { - LOG(fatal) << "Geometry file has to be set before Run::Init !"; - exit(-1); - } else { - - TFile* CurrentFile=gFile; - fInputGeoFile= TFile::Open(GeoFileName); - if (fInputGeoFile->IsZombie()) { - LOG(error) << "Error opening Geometry Input file"; - fInputGeoFile=0; - } - LOG(info) << "Opening Geometry input file: " << GeoFileName; - fLoadGeo=kTRUE; - gFile=CurrentFile; - } + if (fIsInitialized) { + LOG(fatal) << "Geometry file has to be set before Run::Init !"; + exit(-1); + } else { + + TFile* CurrentFile = gFile; + fInputGeoFile = TFile::Open(GeoFileName); + if (fInputGeoFile->IsZombie()) { + LOG(error) << "Error opening Geometry Input file"; + fInputGeoFile = 0; + } + LOG(info) << "Opening Geometry input file: " << GeoFileName; + fLoadGeo = kTRUE; + gFile = CurrentFile; + } } //_____________________________________________________________________________ @@ -133,690 +127,663 @@ void FairRunAna::SetGeomFile(const char* GeoFileName) void FairRunAna::Init() { - if (fIsInitialized) { - LOG(fatal) << "Error Init is already called before!"; - exit(-1); - } else { - fIsInitialized=kTRUE; - } - fRtdb= GetRuntimeDb(); - - // Check if we have an input file to be used - fInFileIsOpen = fRootManager->InitSource(); - fRootManager->InitSink(); - - //Load Geometry from user file - if (fLoadGeo) { - if (fInputGeoFile!=0) { //First check if the user has a separate Geo file! - TIter next(fInputGeoFile->GetListOfKeys()); - TKey* key; - while ((key =dynamic_cast< TKey*>(next()))) { - if (strcmp(key->GetClassName(),"TGeoManager") != 0) { - continue; - } - gGeoManager = dynamic_cast(key->ReadObj()); - break; - } - } - } else { - /*** Get the container that normly has the geometry and all the basic stuff from simulation*/ - fRtdb->getContainer("FairGeoParSet"); - } - - if (fInFileIsOpen) { - //check that the geometry was loaded if not try all connected files! - if (fLoadGeo && gGeoManager==0) { - LOG(info) << "Geometry was not found in the input file we will look in the friends if any!"; - TFile* currentfile= gFile; - TFile* nextfile=0; - TSeqCollection* fileList=gROOT->GetListOfFiles(); - for (Int_t k=0; kGetEntries(); k++) { - nextfile=dynamic_cast(fileList->At(k)); - if (nextfile) { - nextfile->Get("FAIRGeom"); - } - if (gGeoManager) { - break; - } - } - gFile=currentfile; + if (fIsInitialized) { + LOG(fatal) << "Error Init is already called before!"; + exit(-1); + } else { + fIsInitialized = kTRUE; } - } else { // if(fInputFile ) - // NO input file but there is a geometry file + fRtdb = GetRuntimeDb(); + + // Check if we have an input file to be used + fInFileIsOpen = fRootManager->InitSource(); + fRootManager->InitSink(); + + // Load Geometry from user file if (fLoadGeo) { - if (fInputGeoFile!=0) { //First check if the user has a separate Geo file! - TIter next(fInputGeoFile->GetListOfKeys()); - TKey* key; - while ((key = dynamic_cast(next()))) { - if (strcmp(key->GetClassName(),"TGeoManager") != 0) { - continue; - } - gGeoManager = dynamic_cast(key->ReadObj()); - break; + if (fInputGeoFile != 0) { // First check if the user has a separate Geo file! + TIter next(fInputGeoFile->GetListOfKeys()); + TKey* key; + while ((key = dynamic_cast(next()))) { + if (strcmp(key->GetClassName(), "TGeoManager") != 0) { + continue; + } + gGeoManager = dynamic_cast(key->ReadObj()); + break; + } + } + } else { + /*** Get the container that normly has the geometry and all the basic stuff from simulation*/ + fRtdb->getContainer("FairGeoParSet"); + } + + if (fInFileIsOpen) { + // check that the geometry was loaded if not try all connected files! + if (fLoadGeo && gGeoManager == 0) { + LOG(info) << "Geometry was not found in the input file we will look in the friends if any!"; + TFile* currentfile = gFile; + TFile* nextfile = 0; + TSeqCollection* fileList = gROOT->GetListOfFiles(); + for (Int_t k = 0; k < fileList->GetEntries(); k++) { + nextfile = dynamic_cast(fileList->At(k)); + if (nextfile) { + nextfile->Get("FAIRGeom"); + } + if (gGeoManager) { + break; + } + } + gFile = currentfile; + } + } else { // if(fInputFile ) + // NO input file but there is a geometry file + if (fLoadGeo) { + if (fInputGeoFile != 0) { // First check if the user has a separate Geo file! + TIter next(fInputGeoFile->GetListOfKeys()); + TKey* key; + while ((key = dynamic_cast(next()))) { + if (strcmp(key->GetClassName(), "TGeoManager") != 0) { + continue; + } + gGeoManager = dynamic_cast(key->ReadObj()); + break; + } + } } - } } - } - gROOT->GetListOfBrowsables()->Add(fTask); + gROOT->GetListOfBrowsables()->Add(fTask); - // Init the RTDB containers + // Init the RTDB containers - FairBaseParSet* par=dynamic_cast(fRtdb->getContainer("FairBaseParSet")); + FairBaseParSet* par = dynamic_cast(fRtdb->getContainer("FairBaseParSet")); + /**Set the IO Manager to run with time stamps*/ + if (fTimeStamps) { + fRootManager->RunWithTimeStamps(); + } - /**Set the IO Manager to run with time stamps*/ - if (fTimeStamps) { - fRootManager->RunWithTimeStamps(); - } + // Assure that basic info is there for the run + // if(par && fInputFile) { + if (par && fInFileIsOpen) { + LOG(info) << "Parameter and input file are available, Assure that basic info is there for the run!"; + fRootManager->ReadEvent(0); + // fEvtHeader = GetEventHeader(); + GetEventHeader(); - // Assure that basic info is there for the run - // if(par && fInputFile) { - if (par && fInFileIsOpen) { + fRootManager->FillEventHeader(fEvtHeader); - LOG(info) << "Parameter and input file are available, Assure that basic info is there for the run!"; - fRootManager->ReadEvent(0); + fRunId = fEvtHeader->GetRunId(); -// fEvtHeader = GetEventHeader(); - GetEventHeader(); + // Copy the Event Header Info to Output + fEvtHeader->Register(fStoreEventHeader); - fRootManager->FillEventHeader(fEvtHeader); + // Init the containers in Tasks - fRunId = fEvtHeader->GetRunId(); + fRtdb->initContainers(fRunId); + fTask->SetParTask(); - //Copy the Event Header Info to Output - fEvtHeader->Register(fStoreEventHeader); + // fRtdb->initContainers( fRunId ); - // Init the containers in Tasks + } else { // end----- if(fMixedInput) + LOG(info) << "Initializing without input file or Mixed input"; + FairEventHeader* evt = GetEventHeader(); + evt->Register(fStoreEventHeader); + FairRunIdGenerator genid; + fRunId = genid.generateId(); + fRtdb->addRun(fRunId); + evt->SetRunId(fRunId); + fTask->SetParTask(); + fRtdb->initContainers(fRunId); + } + FairFieldFactory* fieldfact = FairFieldFactory::Instance(); + if (fieldfact) { + fieldfact->SetParm(); + } fRtdb->initContainers(fRunId); - fTask->SetParTask(); - - //fRtdb->initContainers( fRunId ); - - } else { //end----- if(fMixedInput) - LOG(info) << "Initializing without input file or Mixed input"; - FairEventHeader* evt = GetEventHeader(); - evt->Register(fStoreEventHeader); - FairRunIdGenerator genid; - fRunId = genid.generateId(); - fRtdb->addRun(fRunId); - evt->SetRunId( fRunId); - fTask->SetParTask(); - fRtdb->initContainers( fRunId ); - - } - FairFieldFactory* fieldfact= FairFieldFactory::Instance(); - if (fieldfact) { - fieldfact->SetParm(); - } - - fRtdb->initContainers(fRunId); - fFileHeader->SetRunId(fRunId); - - // create a field - // - // Add test for external FairField settings - if (fieldfact && !fField) { - fField= fieldfact->createFairField(); - } - // Now call the User initialize for Tasks - fTask->InitTask(); - // if the vis manager is available then initialize it! - FairTrajFilter* fTrajFilter = FairTrajFilter::Instance(); - if (fTrajFilter) { - fTrajFilter->Init(); - } - // Create a list of time based branches (if any). - - fRootManager->UpdateListOfTimebasedBranches(); - - // create the output tree after tasks initialisation - fRootManager->WriteFolder(); - fRootManager->WriteFileHeader(fFileHeader); - - AlignGeometry(); + fFileHeader->SetRunId(fRunId); + + // create a field + // + // Add test for external FairField settings + if (fieldfact && !fField) { + fField = fieldfact->createFairField(); + } + // Now call the User initialize for Tasks + fTask->InitTask(); + // if the vis manager is available then initialize it! + FairTrajFilter* fTrajFilter = FairTrajFilter::Instance(); + if (fTrajFilter) { + fTrajFilter->Init(); + } + // Create a list of time based branches (if any). + + fRootManager->UpdateListOfTimebasedBranches(); + + // create the output tree after tasks initialisation + fRootManager->WriteFolder(); + fRootManager->WriteFileHeader(fFileHeader); + + AlignGeometry(); } //_____________________________________________________________________________ //_____________________________________________________________________________ void FairRunAna::Run(Int_t Ev_start, Int_t Ev_end) { - gFRAIsInterrupted = kFALSE; - - if (fTimeStamps) { - RunTSBuffers(); - } else { - UInt_t tmpId =0; - // if (fInputFile==0) { - if (!fInFileIsOpen) { - DummyRun(Ev_start,Ev_end); - return; - } - - Int_t MaxAllowed=fRootManager->CheckMaxEventNo(Ev_end); - if ( MaxAllowed != -1 ) { - if (Ev_end==0) { - if (Ev_start==0) { - Ev_end=MaxAllowed; + gFRAIsInterrupted = kFALSE; + + if (fTimeStamps) { + RunTSBuffers(); + } else { + UInt_t tmpId = 0; + // if (fInputFile==0) { + if (!fInFileIsOpen) { + DummyRun(Ev_start, Ev_end); + return; + } + + Int_t MaxAllowed = fRootManager->CheckMaxEventNo(Ev_end); + if (MaxAllowed != -1) { + if (Ev_end == 0) { + if (Ev_start == 0) { + Ev_end = MaxAllowed; + } else { + Ev_end = Ev_start; + if (Ev_end > MaxAllowed) { + Ev_end = MaxAllowed; + } + Ev_start = 0; + } + } else { + if (Ev_end > MaxAllowed) { + cout << "-------------------Warning---------------------------" << endl; + cout << " -W FairRunAna : File has less events than requested!!" << endl; + cout << " File contains : " << MaxAllowed << " Events" << endl; + cout << " Requested number of events = " << Ev_end << " Events" << endl; + cout << " The number of events is set to " << MaxAllowed << " Events" << endl; + cout << "-----------------------------------------------------" << endl; + Ev_end = MaxAllowed; + } + } + LOG(info) << "FairRunAna::Run() After checking, the run will run from event " << Ev_start << " to " + << Ev_end << "."; } else { - Ev_end = Ev_start; - if ( Ev_end > MaxAllowed ) { - Ev_end = MaxAllowed; - } - Ev_start=0; + LOG(info) << "FairRunAna::Run() continue running without stop"; } - } else { - if (Ev_end > MaxAllowed) { - cout << "-------------------Warning---------------------------" << endl; - cout << " -W FairRunAna : File has less events than requested!!" << endl; - cout << " File contains : " << MaxAllowed << " Events" << endl; - cout << " Requested number of events = " << Ev_end << " Events"<< endl; - cout << " The number of events is set to " << MaxAllowed << " Events"<< endl; - cout << "-----------------------------------------------------" << endl; - Ev_end = MaxAllowed; + + if (fGenerateRunInfo) { + fRunInfo.Reset(); } - } - LOG(info) << "FairRunAna::Run() After checking, the run will run from event " << Ev_start << " to " << Ev_end << "."; - } - else { - LOG(info) << "FairRunAna::Run() continue running without stop"; - } - if (fGenerateRunInfo) { - fRunInfo.Reset(); - } + Int_t readEventReturn = 0; - Int_t readEventReturn = 0; + for (int i = Ev_start; i < Ev_end || MaxAllowed == -1; i++) { - for (int i=Ev_start; i< Ev_end || MaxAllowed==-1 ; i++) { + gSystem->IgnoreInterrupt(); + // gFRAIsInterrupted = kFALSE; + signal(SIGINT, FRA_handler_ctrlc); - gSystem->IgnoreInterrupt(); - // gFRAIsInterrupted = kFALSE; - signal(SIGINT, FRA_handler_ctrlc); + if (gFRAIsInterrupted) { + LOG(warn) << "FairRunAna::Run() Event loop was interrupted by the user!"; + break; + } - if ( gFRAIsInterrupted ) { - LOG(warn) << "FairRunAna::Run() Event loop was interrupted by the user!"; - break; - } + readEventReturn = fRootManager->ReadEvent(i); - readEventReturn = fRootManager->ReadEvent(i); + if (readEventReturn != 0) { + LOG(warn) << "FairRunAna::Run() fRootManager->ReadEvent(" << i << ") returned " << readEventReturn + << ". Breaking the event loop"; + break; + } - if ( readEventReturn != 0 ) { - LOG(warn) << "FairRunAna::Run() fRootManager->ReadEvent(" << i << ") returned " << readEventReturn << ". Breaking the event loop"; - break; - } + fRootManager->FillEventHeader(fEvtHeader); - fRootManager->FillEventHeader(fEvtHeader); + tmpId = fEvtHeader->GetRunId(); + if (tmpId != fRunId) { + fRunId = tmpId; + if (!fStatic) { + Reinit(fRunId); + fTask->ReInitTask(); + } + } + // std::cout << "WriteoutBufferData with time: " << fRootManager->GetEventTime(); + fRootManager->StoreWriteoutBufferData(fRootManager->GetEventTime()); + fTask->ExecuteTask(""); + Fill(); + fRootManager->DeleteOldWriteoutBufferData(); + fTask->FinishEvent(); - tmpId = fEvtHeader->GetRunId(); - if ( tmpId != fRunId ) { - fRunId = tmpId; - if ( !fStatic ) { - Reinit( fRunId ); - fTask->ReInitTask(); + if (fGenerateRunInfo) { + fRunInfo.StoreInfo(); + } + if (nullptr != FairTrajFilter::Instance()) { + FairTrajFilter::Instance()->Reset(); + } } - } - //std::cout << "WriteoutBufferData with time: " << fRootManager->GetEventTime(); - fRootManager->StoreWriteoutBufferData(fRootManager->GetEventTime()); - fTask->ExecuteTask(""); - Fill(); - fRootManager->DeleteOldWriteoutBufferData(); - fTask->FinishEvent(); - - if (fGenerateRunInfo) { - fRunInfo.StoreInfo(); - } - if (nullptr != FairTrajFilter::Instance()) { - FairTrajFilter::Instance()->Reset(); - } + fRootManager->StoreAllWriteoutBufferData(); + fTask->FinishTask(); + if (fGenerateRunInfo) { + fRunInfo.WriteInfo(); + } + fRootManager->LastFill(); + fRootManager->Write(); } - - fRootManager->StoreAllWriteoutBufferData(); - fTask->FinishTask(); - if (fGenerateRunInfo) { - fRunInfo.WriteInfo(); - } - fRootManager->LastFill(); - fRootManager->Write(); - } } //_____________________________________________________________________________ //_____________________________________________________________________________ void FairRunAna::RunEventReco(Int_t Ev_start, Int_t Ev_end) { - UInt_t tmpId =0; - - Int_t MaxAllowed=fRootManager->CheckMaxEventNo(Ev_end); - if ( MaxAllowed != -1 ) { - if (Ev_end==0) { - if (Ev_start==0) { - Ev_end=MaxAllowed; - } else { - Ev_end = Ev_start; - if ( Ev_end > MaxAllowed ) { - Ev_end = MaxAllowed; - } - Ev_start=0; - } + UInt_t tmpId = 0; + + Int_t MaxAllowed = fRootManager->CheckMaxEventNo(Ev_end); + if (MaxAllowed != -1) { + if (Ev_end == 0) { + if (Ev_start == 0) { + Ev_end = MaxAllowed; + } else { + Ev_end = Ev_start; + if (Ev_end > MaxAllowed) { + Ev_end = MaxAllowed; + } + Ev_start = 0; + } + } else { + if (Ev_end > MaxAllowed) { + cout << "-------------------Warning---------------------------" << endl; + cout << " -W FairRunAna : File has less events than requested!!" << endl; + cout << " File contains : " << MaxAllowed << " Events" << endl; + cout << " Requested number of events = " << Ev_end << " Events" << endl; + cout << " The number of events is set to " << MaxAllowed << " Events" << endl; + cout << "-----------------------------------------------------" << endl; + Ev_end = MaxAllowed; + } + } + LOG(info) << "FairRunAna::Run() After checking, the run will run from event " << Ev_start << " to " << Ev_end + << "."; } else { - if (Ev_end > MaxAllowed) { - cout << "-------------------Warning---------------------------" << endl; - cout << " -W FairRunAna : File has less events than requested!!" << endl; - cout << " File contains : " << MaxAllowed << " Events" << endl; - cout << " Requested number of events = " << Ev_end << " Events"<< endl; - cout << " The number of events is set to " << MaxAllowed << " Events"<< endl; - cout << "-----------------------------------------------------" << endl; - Ev_end = MaxAllowed; - } - } - LOG(info) << "FairRunAna::Run() After checking, the run will run from event " << Ev_start << " to " << Ev_end << "."; - } - else { - LOG(info) << "FairRunAna::Run() continue running without stop"; - } - - if (fGenerateRunInfo) { - fRunInfo.Reset(); - } - - for (int i=Ev_start; i< Ev_end; i++) { - fRootManager->ReadEvent(i); - /** - * if we have simulation files then they have MC Event Header and the Run Id is in it, any way it - * would be better to make FairMCEventHeader a subclass of FairEvtHeader. - */ - if ( tmpId != fRunId ) { - fRunId = tmpId; - if ( !fStatic ) { - Reinit( fRunId ); - fTask->ReInitTask(); - } - } - //FairMCEventHeader* header = dynamic_cast(fRootManager->GetObject("MCEventHeader."); - // std::cout << "WriteoutBufferData with time: " << fRootManager->GetEventTime(); - fRootManager->StoreWriteoutBufferData(fRootManager->GetEventTime()); - fTask->ExecuteTask(""); - - fRootManager->FillEventHeader(fEvtHeader); - // Fill(); - fTask->FinishEvent(); + LOG(info) << "FairRunAna::Run() continue running without stop"; + } if (fGenerateRunInfo) { - fRunInfo.StoreInfo(); - } - if (nullptr != FairTrajFilter::Instance()) { - FairTrajFilter::Instance()->Reset(); - } + fRunInfo.Reset(); + } + + for (int i = Ev_start; i < Ev_end; i++) { + fRootManager->ReadEvent(i); + /** + * if we have simulation files then they have MC Event Header and the Run Id is in it, any way it + * would be better to make FairMCEventHeader a subclass of FairEvtHeader. + */ + if (tmpId != fRunId) { + fRunId = tmpId; + if (!fStatic) { + Reinit(fRunId); + fTask->ReInitTask(); + } + } + // FairMCEventHeader* header = dynamic_cast(fRootManager->GetObject("MCEventHeader."); + // std::cout << "WriteoutBufferData with time: " << fRootManager->GetEventTime(); + fRootManager->StoreWriteoutBufferData(fRootManager->GetEventTime()); + fTask->ExecuteTask(""); + + fRootManager->FillEventHeader(fEvtHeader); + // Fill(); + fTask->FinishEvent(); - } + if (fGenerateRunInfo) { + fRunInfo.StoreInfo(); + } + if (nullptr != FairTrajFilter::Instance()) { + FairTrajFilter::Instance()->Reset(); + } + } - fTask->FinishTask(); - if (fGenerateRunInfo) { - fRunInfo.WriteInfo(); - } - fRootManager->LastFill(); - fRootManager->Write(); + fTask->FinishTask(); + if (fGenerateRunInfo) { + fRunInfo.WriteInfo(); + } + fRootManager->LastFill(); + fRootManager->Write(); } //_____________________________________________________________________________ //_____________________________________________________________________________ void FairRunAna::Run(Double_t delta_t) { - while (fRootManager->ReadNextEvent(delta_t)==kTRUE) { - fTask->ExecuteTask(""); - fRootManager->FillEventHeader(fEvtHeader); - Fill(); - fRootManager->DeleteOldWriteoutBufferData(); - fTask->FinishEvent(); - if (nullptr != FairTrajFilter::Instance()) { - FairTrajFilter::Instance()->Reset(); + while (fRootManager->ReadNextEvent(delta_t) == kTRUE) { + fTask->ExecuteTask(""); + fRootManager->FillEventHeader(fEvtHeader); + Fill(); + fRootManager->DeleteOldWriteoutBufferData(); + fTask->FinishEvent(); + if (nullptr != FairTrajFilter::Instance()) { + FairTrajFilter::Instance()->Reset(); + } } - } - - fRootManager->StoreAllWriteoutBufferData(); - fTask->FinishTask(); - fRootManager->LastFill(); - fRootManager->Write(); + fRootManager->StoreAllWriteoutBufferData(); + fTask->FinishTask(); + fRootManager->LastFill(); + fRootManager->Write(); } //_____________________________________________________________________________ - //_____________________________________________________________________________ void FairRunAna::RunMQ(Long64_t entry) { - /** + /** This methode is only needed and used with ZeroMQ it read a certain event and call the task exec, but no output is written */ - UInt_t tmpId =0; - fRootManager->ReadEvent(entry); - tmpId = fEvtHeader->GetRunId(); - if ( tmpId != fRunId ) { - fRunId = tmpId; - if ( !fStatic ) { - Reinit( fRunId ); - fTask->ReInitTask(); - } - } - fTask->ExecuteTask(""); - fRootManager->FillEventHeader(fEvtHeader); - fTask->FinishTask(); + UInt_t tmpId = 0; + fRootManager->ReadEvent(entry); + tmpId = fEvtHeader->GetRunId(); + if (tmpId != fRunId) { + fRunId = tmpId; + if (!fStatic) { + Reinit(fRunId); + fTask->ReInitTask(); + } + } + fTask->ExecuteTask(""); + fRootManager->FillEventHeader(fEvtHeader); + fTask->FinishTask(); } //_____________________________________________________________________________ - //_____________________________________________________________________________ void FairRunAna::Run(Long64_t entry) { - UInt_t tmpId =0; - fRootManager->ReadEvent(entry); - tmpId = fEvtHeader->GetRunId(); - if ( tmpId != fRunId ) { - fRunId = tmpId; - if ( !fStatic ) { - Reinit( fRunId ); - fTask->ReInitTask(); - } - } - fTask->ExecuteTask(""); - fRootManager->FillEventHeader(fEvtHeader); - fTask->FinishTask(); - Fill(); - fRootManager->DeleteOldWriteoutBufferData(); - fRootManager->LastFill(); - fRootManager->Write(); + UInt_t tmpId = 0; + fRootManager->ReadEvent(entry); + tmpId = fEvtHeader->GetRunId(); + if (tmpId != fRunId) { + fRunId = tmpId; + if (!fStatic) { + Reinit(fRunId); + fTask->ReInitTask(); + } + } + fTask->ExecuteTask(""); + fRootManager->FillEventHeader(fEvtHeader); + fTask->FinishTask(); + Fill(); + fRootManager->DeleteOldWriteoutBufferData(); + fRootManager->LastFill(); + fRootManager->Write(); } //_____________________________________________________________________________ //_____________________________________________________________________________ void FairRunAna::RunTSBuffers() { - Int_t globalEvent = 0; - - bool firstRun = true; - while (firstRun || fRootManager->AllDataProcessed() == kFALSE) { - firstRun = false; - if (globalEvent < fRootManager->CheckMaxEventNo(0) ) { //this step is necessary to load in all data which is not read in via TSBuffers - fRootManager->ReadNonTimeBasedEventFromBranches(globalEvent++); + Int_t globalEvent = 0; + + bool firstRun = true; + while (firstRun || fRootManager->AllDataProcessed() == kFALSE) { + firstRun = false; + if (globalEvent < fRootManager->CheckMaxEventNo( + 0)) { // this step is necessary to load in all data which is not read in via TSBuffers + fRootManager->ReadNonTimeBasedEventFromBranches(globalEvent++); + } + fTask->ExecuteTask(""); + fRootManager->FillEventHeader(fEvtHeader); + Fill(); + fRootManager->DeleteOldWriteoutBufferData(); + fTask->FinishEvent(); + if (nullptr != FairTrajFilter::Instance()) { + FairTrajFilter::Instance()->Reset(); + } } - fTask->ExecuteTask(""); - fRootManager->FillEventHeader(fEvtHeader); - Fill(); - fRootManager->DeleteOldWriteoutBufferData(); - fTask->FinishEvent(); - if (nullptr != FairTrajFilter::Instance()) { - FairTrajFilter::Instance()->Reset(); - } - } - fRootManager->StoreAllWriteoutBufferData(); - fTask->FinishTask(); - fRootManager->LastFill(); - fRootManager->Write(); + fRootManager->StoreAllWriteoutBufferData(); + fTask->FinishTask(); + fRootManager->LastFill(); + fRootManager->Write(); } //_____________________________________________________________________________ //_____________________________________________________________________________ void FairRunAna::RunOnLmdFiles(UInt_t NStart, UInt_t NStop) { - if(NStart==0 && NStop==0) { - NStart=0; - NStop=1000000000; - LOG(info) << " Maximum number of event is set to 1E9"; - } - for (UInt_t i=NStart; i< NStop; i++) { - if ( fFinishProcessingLMDFile ) { - i = NStop; ///Same result like break + if (NStart == 0 && NStop == 0) { + NStart = 0; + NStop = 1000000000; + LOG(info) << " Maximum number of event is set to 1E9"; + } + for (UInt_t i = NStart; i < NStop; i++) { + if (fFinishProcessingLMDFile) { + i = NStop; /// Same result like break + } + fTask->ExecuteTask(""); + fRootManager->FillEventHeader(fEvtHeader); + Fill(); } - fTask->ExecuteTask(""); - fRootManager->FillEventHeader(fEvtHeader); - Fill(); - } - - fTask->FinishTask(); - fRootManager->Write(); - + fTask->FinishTask(); + fRootManager->Write(); } //_____________________________________________________________________________ -void FairRunAna::RunOnTBData() { - std::cout << "FairRunAna::RunOnTBData " << std::endl; - while (fRootManager->FinishRun() != kTRUE) { - fTask->ExecuteTask(""); - Fill(); - fTask->FinishEvent(); - } +void FairRunAna::RunOnTBData() +{ + std::cout << "FairRunAna::RunOnTBData " << std::endl; + while (fRootManager->FinishRun() != kTRUE) { + fTask->ExecuteTask(""); + Fill(); + fTask->FinishEvent(); + } - fTask->FinishTask(); - fRootManager->LastFill(); - fRootManager->Write(); + fTask->FinishTask(); + fRootManager->LastFill(); + fRootManager->Write(); } //_____________________________________________________________________________ void FairRunAna::DummyRun(Int_t Ev_start, Int_t Ev_end) { - /** This methode is just for testing, if you are not sure about what you do, don't use it */ - for (int i=Ev_start; i< Ev_end; i++) { - fTask->ExecuteTask(""); - fRootManager->FillEventHeader(fEvtHeader); - Fill(); - } - fTask->FinishTask(); - fRootManager->Write(); - + /** This methode is just for testing, if you are not sure about what you do, don't use it */ + for (int i = Ev_start; i < Ev_end; i++) { + fTask->ExecuteTask(""); + fRootManager->FillEventHeader(fEvtHeader); + Fill(); + } + fTask->FinishTask(); + fRootManager->Write(); } //_____________________________________________________________________________ //_____________________________________________________________________________ void FairRunAna::TerminateRun() { - fRootManager->StoreAllWriteoutBufferData(); - fTask->FinishTask(); - // gDirectory->SetName(fRootManager->GetOutFile()->GetName()); - // fRunInfo.WriteInfo(); // CRASHES due to file ownership i guess... - // cout << ">>> SlaveTerminate fRootManager->GetInChain()->Print()" << endl; - // fRootManager->GetInChain()->Print(); - // cout << ">>>------------------------------------------------<<<" << endl; - fRootManager->LastFill(); - fRootManager->Write(); - fRootManager->CloseSink(); + fRootManager->StoreAllWriteoutBufferData(); + fTask->FinishTask(); + // gDirectory->SetName(fRootManager->GetOutFile()->GetName()); + // fRunInfo.WriteInfo(); // CRASHES due to file ownership i guess... + // cout << ">>> SlaveTerminate fRootManager->GetInChain()->Print()" << endl; + // fRootManager->GetInChain()->Print(); + // cout << ">>>------------------------------------------------<<<" << endl; + fRootManager->LastFill(); + fRootManager->Write(); + fRootManager->CloseSink(); } //_____________________________________________________________________________ void FairRunAna::Reinit(UInt_t runId) { - // reinit procedure - fRtdb->initContainers( runId ); + // reinit procedure + fRtdb->initContainers(runId); } //_____________________________________________________________________________ -void FairRunAna::RunWithTimeStamps() +void FairRunAna::RunWithTimeStamps() { - if (fIsInitialized) { - LOG(warn) << "RunWithTimeStamps has to be set before Run::Init !"; - exit(-1); - } else { - fTimeStamps=kTRUE; - fRootManager->RunWithTimeStamps(); - } + if (fIsInitialized) { + LOG(warn) << "RunWithTimeStamps has to be set before Run::Init !"; + exit(-1); + } else { + fTimeStamps = kTRUE; + fRootManager->RunWithTimeStamps(); + } } //_____________________________________________________________________________ //_____________________________________________________________________________ -void FairRunAna::SetContainerStatic(Bool_t tempBool) +void FairRunAna::SetContainerStatic(Bool_t tempBool) { - fStatic=tempBool; - if ( fStatic ) { - LOG(info) << "Parameter Cont. initialisation is static"; - } else { - LOG(info) << "Parameter Cont. initialisation is NOT static"; - } + fStatic = tempBool; + if (fStatic) { + LOG(info) << "Parameter Cont. initialisation is static"; + } else { + LOG(info) << "Parameter Cont. initialisation is NOT static"; + } } // BELOW FUNCTIONS SHOULD BE DELETED AND MOVED TO FairFileSource ONLY //_____________________________________________________________________________ void FairRunAna::SetInputFile(TString name) { - LOG(warn) << "FairRunAna::SetInputFile is obsolete. Set it by FairFileSource"; - if ( fMixedSource ) - { - LOG(error) << "Mixed input already set!"; - return; - } - if ( !fFileSource ) - { - fFileSource = new FairFileSource(name); - SetSource(fFileSource); - return; - } - fFileSource->SetInputFile(name); + LOG(warn) << "FairRunAna::SetInputFile is obsolete. Set it by FairFileSource"; + if (fMixedSource) { + LOG(error) << "Mixed input already set!"; + return; + } + if (!fFileSource) { + fFileSource = new FairFileSource(name); + SetSource(fFileSource); + return; + } + fFileSource->SetInputFile(name); } //_____________________________________________________________________________ -void FairRunAna::AddFriend (TString name) +void FairRunAna::AddFriend(TString name) { - LOG(warn) << "FairRunAna::AddFriend is obsolete. Set it by FairFileSource"; - if ( fMixedSource ) - { - LOG(error) << "Mixed input already set!"; - return; - } - if ( !fFileSource ) - { - LOG(error) << "Input file not yet set!"; - return; - } - fFileSource->AddFriend(name); + LOG(warn) << "FairRunAna::AddFriend is obsolete. Set it by FairFileSource"; + if (fMixedSource) { + LOG(error) << "Mixed input already set!"; + return; + } + if (!fFileSource) { + LOG(error) << "Input file not yet set!"; + return; + } + fFileSource->AddFriend(name); } //_____________________________________________________________________________ void FairRunAna::AddFile(TString name) { - LOG(warn) << "FairRunAna::AddFile is obsolete. Set it by FairFileSource"; - if ( fMixedSource ) - { - LOG(error) << "Mixed input already set!"; - return; - } - if ( !fFileSource ) - { - LOG(error) << "Input file not yet set!"; - return; - } - fFileSource->AddFile(name); + LOG(warn) << "FairRunAna::AddFile is obsolete. Set it by FairFileSource"; + if (fMixedSource) { + LOG(error) << "Mixed input already set!"; + return; + } + if (!fFileSource) { + LOG(error) << "Input file not yet set!"; + return; + } + fFileSource->AddFile(name); } //_____________________________________________________________________________ // ABOVE FUNCTIONS SHOULD BE DELETED AND MOVED TO FairFileSource ONLY // BELOW FUNCTIONS SHOULD BE DELETED AND MOVED TO FairMixedSource ONLY //_____________________________________________________________________________ -void FairRunAna::SetSignalFile(TString name, UInt_t identifier ) +void FairRunAna::SetSignalFile(TString name, UInt_t identifier) { - LOG(warn) << "FairRunAna::SetSignalFile is obsolete. Set it by FairMixedSource"; - if (identifier==0) { - LOG(fatal) << " ----- Identifier 0 is reserved for background files! please use other value ------ "; - } - if ( fFileSource ) - { - LOG(error) << "Standard input already set!"; - return; - } - if ( !fMixedSource ) - { - fMixedSource = new FairMixedSource(name,identifier); - SetSource(fMixedSource); - return; - } - fMixedSource->AddSignalFile(name, identifier); + LOG(warn) << "FairRunAna::SetSignalFile is obsolete. Set it by FairMixedSource"; + if (identifier == 0) { + LOG(fatal) << " ----- Identifier 0 is reserved for background files! please use other value ------ "; + } + if (fFileSource) { + LOG(error) << "Standard input already set!"; + return; + } + if (!fMixedSource) { + fMixedSource = new FairMixedSource(name, identifier); + SetSource(fMixedSource); + return; + } + fMixedSource->AddSignalFile(name, identifier); } //_____________________________________________________________________________ -void FairRunAna::AddSignalFile(TString name, UInt_t identifier ) +void FairRunAna::AddSignalFile(TString name, UInt_t identifier) { - LOG(warn) << "FairRunAna::AddSignalFile is obsolete. Set it by FairMixedSource"; - if (identifier==0) { - LOG(fatal) << " ----- Identifier 0 is reserved for background files! please use other value ------ "; - } - if ( fFileSource ) - { - LOG(error) << "Standard input already set!"; - return; - } - if ( !fMixedSource ) - { - fMixedSource = new FairMixedSource(name,identifier); - SetSource(fMixedSource); - return; - } - fMixedSource->AddSignalFile(name, identifier); + LOG(warn) << "FairRunAna::AddSignalFile is obsolete. Set it by FairMixedSource"; + if (identifier == 0) { + LOG(fatal) << " ----- Identifier 0 is reserved for background files! please use other value ------ "; + } + if (fFileSource) { + LOG(error) << "Standard input already set!"; + return; + } + if (!fMixedSource) { + fMixedSource = new FairMixedSource(name, identifier); + SetSource(fMixedSource); + return; + } + fMixedSource->AddSignalFile(name, identifier); } //_____________________________________________________________________________ void FairRunAna::SetBackgroundFile(TString name) { - LOG(warn) << "FairRunAna::SetBackgroundFile is obsolete. Set it by FairMixedSource"; - if ( fFileSource ) - { - LOG(error) << "Standard input already set!"; - return; - } - if ( !fMixedSource ) - { - fMixedSource = new FairMixedSource(name,0); - SetSource(fMixedSource); - return; - } - fMixedSource->SetBackgroundFile(name); + LOG(warn) << "FairRunAna::SetBackgroundFile is obsolete. Set it by FairMixedSource"; + if (fFileSource) { + LOG(error) << "Standard input already set!"; + return; + } + if (!fMixedSource) { + fMixedSource = new FairMixedSource(name, 0); + SetSource(fMixedSource); + return; + } + fMixedSource->SetBackgroundFile(name); } //_____________________________________________________________________________ void FairRunAna::AddBackgroundFile(TString name) { - LOG(warn) << "FairRunAna::AddBackgroundFile is obsolete. Set it by FairMixedSource"; - if ( fFileSource ) - { - LOG(error) << "Standard input already set!"; - return; - } - if ( !fMixedSource ) - { - LOG(error) << "Background file not yet set!"; - return; - } - fMixedSource->AddBackgroundFile(name); + LOG(warn) << "FairRunAna::AddBackgroundFile is obsolete. Set it by FairMixedSource"; + if (fFileSource) { + LOG(error) << "Standard input already set!"; + return; + } + if (!fMixedSource) { + LOG(error) << "Background file not yet set!"; + return; + } + fMixedSource->AddBackgroundFile(name); } //_____________________________________________________________________________ -void FairRunAna::BGWindowWidthNo(UInt_t background, UInt_t Signalid) +void FairRunAna::BGWindowWidthNo(UInt_t background, UInt_t Signalid) { - LOG(warn) << "FairRunAna::BGWindowWidthNo is obsolete. Set it by FairMixedSource"; - if ( fFileSource ) - { - LOG(error) << "Standard input already set!"; - return; - } - if ( !fMixedSource ) - { - LOG(error) << "Background file not yet set!"; - return; - } - fMixedSource->BGWindowWidthNo(background, Signalid); + LOG(warn) << "FairRunAna::BGWindowWidthNo is obsolete. Set it by FairMixedSource"; + if (fFileSource) { + LOG(error) << "Standard input already set!"; + return; + } + if (!fMixedSource) { + LOG(error) << "Background file not yet set!"; + return; + } + fMixedSource->BGWindowWidthNo(background, Signalid); } //_____________________________________________________________________________ -void FairRunAna::BGWindowWidthTime(Double_t background, UInt_t Signalid) +void FairRunAna::BGWindowWidthTime(Double_t background, UInt_t Signalid) { - LOG(warn) << "FairRunAna::BGWindowWidthTime is obsolete. Set it by FairMixedSource"; - if ( fFileSource ) - { - LOG(error) << "Standard input already set!"; - return; - } - if ( !fMixedSource ) - { - LOG(error) << "Background file not yet set!"; - return; - } - fMixedSource->BGWindowWidthTime(background, Signalid); + LOG(warn) << "FairRunAna::BGWindowWidthTime is obsolete. Set it by FairMixedSource"; + if (fFileSource) { + LOG(error) << "Standard input already set!"; + return; + } + if (!fMixedSource) { + LOG(error) << "Background file not yet set!"; + return; + } + fMixedSource->BGWindowWidthTime(background, Signalid); } //_____________________________________________________________________________ // ABOVE FUNCTIONS SHOULD BE DELETED AND MOVED TO FairMixedSource ONLY @@ -825,76 +792,64 @@ void FairRunAna::BGWindowWidthTime(Double_t background, UInt_t Signalid) //_____________________________________________________________________________ void FairRunAna::SetEventTimeInterval(Double_t min, Double_t max) { - LOG(warn) << "FairRunAna::SetEventTimeInterval is obsolete. Set it by FairSource"; - if ( fFileSource ) - { - fFileSource->SetEventTimeInterval(min,max); - return; - } - if ( fMixedSource ) - { - fMixedSource->SetEventTimeInterval(min,max); - return; - } - LOG(error) << "SetEventTimeInterval only by input source!"; + LOG(warn) << "FairRunAna::SetEventTimeInterval is obsolete. Set it by FairSource"; + if (fFileSource) { + fFileSource->SetEventTimeInterval(min, max); + return; + } + if (fMixedSource) { + fMixedSource->SetEventTimeInterval(min, max); + return; + } + LOG(error) << "SetEventTimeInterval only by input source!"; } //_____________________________________________________________________________ -void FairRunAna::SetEventMeanTime(Double_t mean) +void FairRunAna::SetEventMeanTime(Double_t mean) { - LOG(warn) << "FairRunAna::SetEventMeanTime is obsolete. Set it by FairSource"; - if ( fFileSource ) - { - fFileSource->SetEventMeanTime(mean); - return; - } - if ( fMixedSource ) - { - fMixedSource->SetEventMeanTime(mean); - return; - } - LOG(error) << "SetEventMeanTime only by input source!"; + LOG(warn) << "FairRunAna::SetEventMeanTime is obsolete. Set it by FairSource"; + if (fFileSource) { + fFileSource->SetEventMeanTime(mean); + return; + } + if (fMixedSource) { + fMixedSource->SetEventMeanTime(mean); + return; + } + LOG(error) << "SetEventMeanTime only by input source!"; } //_____________________________________________________________________________ void FairRunAna::SetBeamTime(Double_t beamTime, Double_t gapTime) { - LOG(warn) << "FairRunAna::SetBeamTime is obsolete. Set it by FairSource"; - if ( fFileSource ) - { - fFileSource->SetBeamTime(beamTime, gapTime); - return; - } - if ( fMixedSource ) - { - fMixedSource->SetBeamTime(beamTime, gapTime); - return; - } - LOG(error) << "SetBeamTime only by input source!"; + LOG(warn) << "FairRunAna::SetBeamTime is obsolete. Set it by FairSource"; + if (fFileSource) { + fFileSource->SetBeamTime(beamTime, gapTime); + return; + } + if (fMixedSource) { + fMixedSource->SetBeamTime(beamTime, gapTime); + return; + } + LOG(error) << "SetBeamTime only by input source!"; } //_____________________________________________________________________________ - //_____________________________________________________________________________ void FairRunAna::Fill() { - if(fMarkFill) - { - fRootManager->Fill(); - } - else - { - fMarkFill = kTRUE; - } + if (fMarkFill) { + fRootManager->Fill(); + } else { + fMarkFill = kTRUE; + } } //_____________________________________________________________________________ - // void FairRunAna::SetMixAllInputs(Bool_t Status) // { -// fLogger->Info(MESSAGE_ORIGIN, "Mixing for all input is choosed, in this mode one event per input file is read per step"); -// fRootManager->SetMixAllInputs(Status); +// fLogger->Info(MESSAGE_ORIGIN, "Mixing for all input is choosed, in this mode one event per input file is read per +// step"); fRootManager->SetMixAllInputs(Status); // } //_____________________________________________________________________________ // ABOVE FUNCTIONS SHOULD BE DELETED AND MOVED TO FairFileSource AND FairMixedSource ONLY - -ClassImp(FairRunAna) +ClassImp(FairRunAna); diff --git a/base/steer/FairRunAna.h b/base/steer/FairRunAna.h index 63bb892ceb..0266388062 100644 --- a/base/steer/FairRunAna.h +++ b/base/steer/FairRunAna.h @@ -8,7 +8,6 @@ #ifndef FAIRRUNANA_H #define FAIRRUNANA_H - /** * Configure and manage the Analysis * @author M. Al-Turany D. Bertini @@ -16,12 +15,12 @@ * @since 28.02.05 */ -#include "FairRun.h" // for FairRun -#include "FairRootManager.h" // for FairRootManager -#include "FairRunInfo.h" // for FairRunInfo +#include "FairRootManager.h" // for FairRootManager +#include "FairRun.h" // for FairRun +#include "FairRunInfo.h" // for FairRunInfo -#include // for Bool_t, Double_t, UInt_t, etc -#include // for TString +#include // for Bool_t, Double_t, UInt_t, etc +#include // for TString class FairField; class TF1; @@ -35,62 +34,61 @@ class FairRunAna : public FairRun { public: - static FairRunAna* Instance(); virtual ~FairRunAna(); FairRunAna(); /**initialize the run manager*/ - void Init(); + void Init(); /**Run from event number NStart to event number NStop */ - void Run(Int_t NStart=0 ,Int_t NStop=0); + void Run(Int_t NStart = 0, Int_t NStop = 0); /**Run over the whole input file with timpe window delta_t as unit (entry)*/ - void Run(Double_t delta_t); + void Run(Double_t delta_t); /**Run for the given single entry*/ - void Run(Long64_t entry); + void Run(Long64_t entry); /**Run event reconstruction from event number NStart to event number NStop */ - void RunEventReco(Int_t NStart ,Int_t NStop); + void RunEventReco(Int_t NStart, Int_t NStop); /**Run over all TSBuffers until the data is processed*/ - void RunTSBuffers(); + void RunTSBuffers(); /** the dummy run does not check the evt header or the parameters!! */ - void DummyRun(Int_t NStart ,Int_t NStop); + void DummyRun(Int_t NStart, Int_t NStop); /** This methode is only needed and used with ZeroMQ - * it read a certain event and call the task exec, but no output is written - * @param entry : entry number in the tree - */ + * it read a certain event and call the task exec, but no output is written + * @param entry : entry number in the tree + */ void RunMQ(Long64_t entry); /** Run on a list of lmd files*/ - void RunOnLmdFiles(UInt_t NStart=0, UInt_t NStop=0); + void RunOnLmdFiles(UInt_t NStart = 0, UInt_t NStop = 0); void RunOnTBData(); /** finish tasks, write output*/ - void TerminateRun(); + void TerminateRun(); /**Set the input signal file *@param name : signal file name *@param identifier : Unsigned integer which identify the signal file */ - virtual void SetSource(FairSource* tempSource) { fRootManager->SetSource(tempSource); } + virtual void SetSource(FairSource* tempSource) { fRootManager->SetSource(tempSource); } // ********************************************************* // // THE BELOW FUNCTIONS SHOULD BE MOVED TO FairFileSource /**Set the input file by name*/ - void SetInputFile(TString fname); + void SetInputFile(TString fname); /**Add a file to input chain */ - void AddFile(TString name); + void AddFile(TString name); /** Add a friend file (input) by name)*/ - void AddFriend(TString fName); + void AddFriend(TString fName); // ********************************************************* // // THE BELOW FUNCTIONS SHOULD BE MOVED TO FairMixedSource - void SetSignalFile(TString name, UInt_t identifier ); + void SetSignalFile(TString name, UInt_t identifier); /**Add signal file to input *@param name : signal file name *@param identifier : Unsigned integer which identify the signal file to which this signal should be added */ - void AddSignalFile(TString name, UInt_t identifier ); + void AddSignalFile(TString name, UInt_t identifier); /**Set the input background file by name*/ - void SetBackgroundFile(TString name); + void SetBackgroundFile(TString name); /**Add input background file by name*/ - void AddBackgroundFile(TString name); + void AddBackgroundFile(TString name); /**Set the signal to background ratio in event units *@param background : Number of background Events for one signal *@param Signalid : Signal file Id, used when adding (setting) the signal file @@ -107,7 +105,7 @@ class FairRunAna : public FairRun * This method will simply forward the call to the FairRootManager, * if true all inputs are mixed, i.e: each read event will take one entry from each input and put * them in one big event and send it to the next step - */ + */ // void SetMixAllInputs(Bool_t Status); // ********************************************************* // // THE BELOW FUNCTIONS SHOULD BE MOVED TO FairFileSource and FairMixedSource @@ -120,98 +118,77 @@ class FairRunAna : public FairRun // ********************************************************* // /** Switch On/Off the storing of FairEventHeader in output file*/ - void SetEventHeaderPersistence(Bool_t flag){ - fStoreEventHeader=flag; - } - - void Reinit(UInt_t runId); - UInt_t getRunId() { - return fRunId; - } + void SetEventHeaderPersistence(Bool_t flag) { fStoreEventHeader = flag; } + + void Reinit(UInt_t runId); + UInt_t getRunId() { return fRunId; } /** Get the magnetic field **/ - FairField* GetField() { - return fField; - } + FairField* GetField() { return fField; } /** Set the magnetic Field */ - void SetField (FairField* ffield ) { - fField=ffield ; - } + void SetField(FairField* ffield) { fField = ffield; } /** Set external geometry file */ - void SetGeomFile(const char* GeoFileName); + void SetGeomFile(const char* GeoFileName); /** Return a pointer to the geometry file */ - TFile* GetGeoFile() { - return fInputGeoFile; - } + TFile* GetGeoFile() { return fInputGeoFile; } /** Initialization of parameter container is set to static, i.e: the run id is * is not checked anymore after initialization */ - void SetContainerStatic(Bool_t tempBool=kTRUE); - Bool_t GetContainerStatic() { return fStatic; }; - void RunWithTimeStamps(); - Bool_t IsTimeStamp() { - return fTimeStamps; - } + void SetContainerStatic(Bool_t tempBool = kTRUE); + Bool_t GetContainerStatic() { return fStatic; }; + void RunWithTimeStamps(); + Bool_t IsTimeStamp() { return fTimeStamps; } /** Set the flag for proccessing lmd files */ - void StopProcessingLMD( void ) { - fFinishProcessingLMDFile = kTRUE; - } + void StopProcessingLMD(void) { fFinishProcessingLMDFile = kTRUE; } /** Get the status of lmd file proccessing */ - Bool_t GetLMDProcessingStatus( void ) { - return fFinishProcessingLMDFile; - } + Bool_t GetLMDProcessingStatus(void) { return fFinishProcessingLMDFile; } protected: /** * Virtual function which calls the Fill function of the IOManager. * Allows to override the function with an experiment specific version. - **/ + **/ virtual void Fill(); private: - FairRunAna(const FairRunAna& M); - FairRunAna& operator= (const FairRunAna&) { - return *this; - } + FairRunAna& operator=(const FairRunAna&) { return *this; } - FairRunInfo fRunInfo;//! + FairRunInfo fRunInfo; //! protected: /** This variable became true after Init is called*/ - Bool_t fIsInitialized; - TFile* fInputGeoFile; - static FairRunAna* fgRinstance; - Bool_t fLoadGeo; + Bool_t fIsInitialized; + TFile* fInputGeoFile; + static FairRunAna* fgRinstance; + Bool_t fLoadGeo; /** true for static initialisation of parameters */ - Bool_t fStatic;//! - FairField* fField; - Bool_t fTimeStamps; - Bool_t fInFileIsOpen;//! + Bool_t fStatic; //! + FairField* fField; + Bool_t fTimeStamps; + Bool_t fInFileIsOpen; //! /** min time for one event (ns) */ - Double_t fEventTimeMin; //! + Double_t fEventTimeMin; //! /** max time for one Event (ns) */ - Double_t fEventTimeMax; //! + Double_t fEventTimeMax; //! /** Time of event since th start (ns) */ - Double_t fEventTime; //! + Double_t fEventTime; //! /** EventMean time used (P(t)=1/fEventMeanTime*Exp(-t/fEventMeanTime) */ - Double_t fEventMeanTime; //! + Double_t fEventMeanTime; //! /** used to generate random numbers for event time; */ - TF1* fTimeProb; //! + TF1* fTimeProb; //! /** Flag for proccessing lmd-files*/ - Bool_t fFinishProcessingLMDFile; //! + Bool_t fFinishProcessingLMDFile; //! /** Temporary member to preserve old functionality without setting source in macro */ - FairFileSource* fFileSource; //! + FairFileSource* fFileSource; //! /** Temporary member to preserve old functionality without setting source in macro */ - FairMixedSource* fMixedSource; //! + FairMixedSource* fMixedSource; //! /** Flag for Event Header Persistency */ - Bool_t fStoreEventHeader; //! - - - ClassDef(FairRunAna ,6) + Bool_t fStoreEventHeader; //! + ClassDef(FairRunAna, 6) }; -#endif //FAIRRUNANA_H +#endif // FAIRRUNANA_H diff --git a/base/steer/FairRunAnaProof.cxx b/base/steer/FairRunAnaProof.cxx index 39920727e2..ce8b69f930 100644 --- a/base/steer/FairRunAnaProof.cxx +++ b/base/steer/FairRunAnaProof.cxx @@ -29,350 +29,345 @@ #include #include -FairRunAnaProof* FairRunAnaProof::fRAPInstance= 0; +FairRunAnaProof* FairRunAnaProof::fRAPInstance = 0; -FairRunAnaProof* FairRunAnaProof::Instance() -{ - return fRAPInstance; -} +FairRunAnaProof* FairRunAnaProof::Instance() { return fRAPInstance; } FairRunAnaProof::FairRunAnaProof(const char* proofName) - :FairRunAna(), - fProof(nullptr), - fRunOnProofWorker(kFALSE), - fProofServerName(proofName), - fProofParName("$VMCWORKDIR/gconfig/libFairRoot.par"), - fOutputDirectory(""), - fProofOutputStatus("copy"), - fProofFileSource(0) + : FairRunAna() + , fProof(nullptr) + , fRunOnProofWorker(kFALSE) + , fProofServerName(proofName) + , fProofParName("$VMCWORKDIR/gconfig/libFairRoot.par") + , fOutputDirectory("") + , fProofOutputStatus("copy") + , fProofFileSource(0) { - if ( strcmp(proofName,"RunOnProofWorker") == 0 ) { - fRunOnProofWorker = kTRUE; - } - else { - LOG(info) << "+++++++ T P R O O F +++++++++++++++++++++++++++++++++"; - LOG(info) << "creating TProof* proof = TProof::Open(\"" << fProofServerName.Data() << "\");"; - TProof::AddEnvVar("LOCALDATASERVER","file://"); - // TProof* proof = TProof::Open("lite:///?workers=1"); - fProof = TProof::Open(fProofServerName.Data()); - LOG(info) << "+++++++ C R E A T E D +++++++++++++++++++++++++++++++"; - } - - fRAPInstance=this; - fAna=kTRUE; -} + if (strcmp(proofName, "RunOnProofWorker") == 0) { + fRunOnProofWorker = kTRUE; + } else { + LOG(info) << "+++++++ T P R O O F +++++++++++++++++++++++++++++++++"; + LOG(info) << "creating TProof* proof = TProof::Open(\"" << fProofServerName.Data() << "\");"; + TProof::AddEnvVar("LOCALDATASERVER", "file://"); + // TProof* proof = TProof::Open("lite:///?workers=1"); + fProof = TProof::Open(fProofServerName.Data()); + LOG(info) << "+++++++ C R E A T E D +++++++++++++++++++++++++++++++"; + } -FairRunAnaProof::~FairRunAnaProof() -{ + fRAPInstance = this; + fAna = kTRUE; } +FairRunAnaProof::~FairRunAnaProof() {} + void FairRunAnaProof::Init() { - fInFileIsOpen = fRootManager->InitSource(); - - if (fIsInitialized) { - LOG(fatal) << "Error Init is already called before!"; - exit(-1); - } else { - fIsInitialized=kTRUE; - } - - if ( !fRunOnProofWorker ) { - // Open the input file and add other input files added by AddFile to the - // input chain. Do a check if the added files are of the same type - // as the the input file. Same type means check if they contain the - // same branch. - } - //Load Geometry from user file - - if (fLoadGeo) { - if (fInputGeoFile!=0) { //First check if the user has a separate Geo file! - TIter next(fInputGeoFile->GetListOfKeys()); - TKey* key; - while ((key = static_cast(next()))) { - if (strcmp(key->GetClassName(),"TGeoManager") != 0) { - continue; - } - gGeoManager = static_cast(key->ReadObj()); - break; - } - } - } else { -// FairGeoParSet* geopar=dynamic_cast(fRtdb->getContainer("FairGeoParSet")); - fRtdb->getContainer("FairGeoParSet"); - } - - if (fInFileIsOpen) { - if ( fRunOnProofWorker ) { - if (fLoadGeo && gGeoManager==0) { - fProofFileSource->GetInTree()->GetCurrentFile()->Get("FAIRGeom"); - } + fInFileIsOpen = fRootManager->InitSource(); + + if (fIsInitialized) { + LOG(fatal) << "Error Init is already called before!"; + exit(-1); } else { + fIsInitialized = kTRUE; + } - // Add all friend files defined by AddFriend to the correct chain - if (fLoadGeo && gGeoManager==0) { - // Check if the geometry in the first file of the Chain - fProofFileSource->GetInTree()->GetCurrentFile()->Get("FAIRGeom"); - } - //check that the geometry was loaded if not try all connected files! - if (fLoadGeo && gGeoManager==0) { - LOG(info) << "Geometry was not found in the input file we will look in the friends if any!"; - TFile* currentfile= gFile; - TFile* nextfile=0; - TSeqCollection* fileList=gROOT->GetListOfFiles(); - for (Int_t k=0; kGetEntries(); k++) { - nextfile=static_cast(fileList->At(k)); - if (nextfile) { - nextfile->Get("FAIRGeom"); - } - if (gGeoManager) { - break; - } - } - gFile=currentfile; - } + if (!fRunOnProofWorker) { + // Open the input file and add other input files added by AddFile to the + // input chain. Do a check if the added files are of the same type + // as the the input file. Same type means check if they contain the + // same branch. } - } else { // if(fInputFile ) - // NO input file but there is a geometry file + // Load Geometry from user file + if (fLoadGeo) { - if (fInputGeoFile!=0) { //First check if the user has a separate Geo file! - TIter next(fInputGeoFile->GetListOfKeys()); - TKey* key; - while ((key = static_cast(next()))) { - if (strcmp(key->GetClassName(),"TGeoManager") != 0) { - continue; - } - gGeoManager = static_cast(key->ReadObj()); - break; + if (fInputGeoFile != 0) { // First check if the user has a separate Geo file! + TIter next(fInputGeoFile->GetListOfKeys()); + TKey* key; + while ((key = static_cast(next()))) { + if (strcmp(key->GetClassName(), "TGeoManager") != 0) { + continue; + } + gGeoManager = static_cast(key->ReadObj()); + break; + } } - } + } else { + // FairGeoParSet* geopar=dynamic_cast(fRtdb->getContainer("FairGeoParSet")); + fRtdb->getContainer("FairGeoParSet"); } - } - //Init the Chain ptr - // fcurrent = fChainList.begin(); -// fOutFile = fRootManager->OpenOutFile(fOutname); - if ( !fRunOnProofWorker ) { - LOG(warn) << "QUITTING, CAUSE IT'S not running on proof worker"; - return; - } - gROOT->GetListOfBrowsables()->Add(fTask); + if (fInFileIsOpen) { + if (fRunOnProofWorker) { + if (fLoadGeo && gGeoManager == 0) { + fProofFileSource->GetInTree()->GetCurrentFile()->Get("FAIRGeom"); + } + } else { + + // Add all friend files defined by AddFriend to the correct chain + if (fLoadGeo && gGeoManager == 0) { + // Check if the geometry in the first file of the Chain + fProofFileSource->GetInTree()->GetCurrentFile()->Get("FAIRGeom"); + } + // check that the geometry was loaded if not try all connected files! + if (fLoadGeo && gGeoManager == 0) { + LOG(info) << "Geometry was not found in the input file we will look in the friends if any!"; + TFile* currentfile = gFile; + TFile* nextfile = 0; + TSeqCollection* fileList = gROOT->GetListOfFiles(); + for (Int_t k = 0; k < fileList->GetEntries(); k++) { + nextfile = static_cast(fileList->At(k)); + if (nextfile) { + nextfile->Get("FAIRGeom"); + } + if (gGeoManager) { + break; + } + } + gFile = currentfile; + } + } + } else { // if(fInputFile ) + // NO input file but there is a geometry file + if (fLoadGeo) { + if (fInputGeoFile != 0) { // First check if the user has a separate Geo file! + TIter next(fInputGeoFile->GetListOfKeys()); + TKey* key; + while ((key = static_cast(next()))) { + if (strcmp(key->GetClassName(), "TGeoManager") != 0) { + continue; + } + gGeoManager = static_cast(key->ReadObj()); + break; + } + } + } + } + // Init the Chain ptr + // fcurrent = fChainList.begin(); + // fOutFile = fRootManager->OpenOutFile(fOutname); + + if (!fRunOnProofWorker) { + LOG(warn) << "QUITTING, CAUSE IT'S not running on proof worker"; + return; + } + gROOT->GetListOfBrowsables()->Add(fTask); - // Init the RTDB containers - fRtdb= GetRuntimeDb(); - FairBaseParSet* par=static_cast - (fRtdb->getContainer("FairBaseParSet")); + // Init the RTDB containers + fRtdb = GetRuntimeDb(); + FairBaseParSet* par = static_cast(fRtdb->getContainer("FairBaseParSet")); - /**Set the IO Manager to run with time stamps*/ - if (fTimeStamps) { - fRootManager->RunWithTimeStamps(); - } + /**Set the IO Manager to run with time stamps*/ + if (fTimeStamps) { + fRootManager->RunWithTimeStamps(); + } - // create the output tree after tasks initialisation - fRootManager->InitSink(); + // create the output tree after tasks initialisation + fRootManager->InitSink(); - // Assure that basic info is there for the run + // Assure that basic info is there for the run - if (par && fInFileIsOpen) { + if (par && fInFileIsOpen) { - LOG(info) << "Parameter and input file are available, Assure that basic info is there for the run!"; - fRootManager->ReadEvent(0); + LOG(info) << "Parameter and input file are available, Assure that basic info is there for the run!"; + fRootManager->ReadEvent(0); - GetEventHeader(); + GetEventHeader(); - fRootManager->FillEventHeader(fEvtHeader); + fRootManager->FillEventHeader(fEvtHeader); - fRunId = fEvtHeader->GetRunId(); + fRunId = fEvtHeader->GetRunId(); - //Copy the Event Header Info to Output - fEvtHeader->Register(kTRUE); + // Copy the Event Header Info to Output + fEvtHeader->Register(kTRUE); - //Copy the Event Header Info to Output - fEvtHeader->Register(); + // Copy the Event Header Info to Output + fEvtHeader->Register(); - // Init the containers in Tasks + // Init the containers in Tasks - fRtdb->initContainers(fRunId); - fTask->SetParTask(); + fRtdb->initContainers(fRunId); + fTask->SetParTask(); - fRtdb->initContainers( fRunId ); - if (gGeoManager==0) { + fRtdb->initContainers(fRunId); + if (gGeoManager == 0) {} + // fRootManager->SetBranchNameList(par->GetBranchNameList()); + } else { + LOG(info) << "Initializing without input file or Mixed input"; + FairEventHeader* evt = GetEventHeader(); + evt->Register(); + FairRunIdGenerator genid; + fRunId = genid.generateId(); + fRtdb->addRun(fRunId); + evt->SetRunId(fRunId); + fTask->SetParTask(); + fRtdb->initContainers(fRunId); } - // fRootManager->SetBranchNameList(par->GetBranchNameList()); - - } else { - LOG(info) << "Initializing without input file or Mixed input"; - FairEventHeader* evt = GetEventHeader(); - evt->Register(); - FairRunIdGenerator genid; - fRunId = genid.generateId(); - fRtdb->addRun(fRunId); - evt->SetRunId( fRunId); - fTask->SetParTask(); - fRtdb->initContainers( fRunId ); - - } - FairFieldFactory* fieldfact= FairFieldFactory::Instance(); - if (fieldfact) { - fieldfact->SetParm(); - } - - fRtdb->initContainers(fRunId); - fFileHeader->SetRunId(fRunId); - - // create a field - // - // Add test for external FairField settings - if (fieldfact && !fField) { - fField= fieldfact->createFairField(); - } - // Now call the User initialize for Tasks - fTask->InitTask(); - // if the vis manager is available then initialize it! - FairTrajFilter* fTrajFilter = FairTrajFilter::Instance(); - if (fTrajFilter) { - fTrajFilter->Init(); - } - - fRootManager->UpdateListOfTimebasedBranches(); - - fRootManager->WriteFolder(); - fRootManager->WriteFileHeader(fFileHeader); + FairFieldFactory* fieldfact = FairFieldFactory::Instance(); + if (fieldfact) { + fieldfact->SetParm(); + } + + fRtdb->initContainers(fRunId); + fFileHeader->SetRunId(fRunId); + + // create a field + // + // Add test for external FairField settings + if (fieldfact && !fField) { + fField = fieldfact->createFairField(); + } + // Now call the User initialize for Tasks + fTask->InitTask(); + // if the vis manager is available then initialize it! + FairTrajFilter* fTrajFilter = FairTrajFilter::Instance(); + if (fTrajFilter) { + fTrajFilter->Init(); + } + + fRootManager->UpdateListOfTimebasedBranches(); + + fRootManager->WriteFolder(); + fRootManager->WriteFileHeader(fFileHeader); } void FairRunAnaProof::InitContainers() { - fRtdb= GetRuntimeDb(); - FairBaseParSet* par=dynamic_cast - (fRtdb->getContainer("FairBaseParSet")); + fRtdb = GetRuntimeDb(); + FairBaseParSet* par = dynamic_cast(fRtdb->getContainer("FairBaseParSet")); - if (par && fInFileIsOpen) { - fRootManager->ReadEvent(0); + if (par && fInFileIsOpen) { + fRootManager->ReadEvent(0); - fEvtHeader = dynamic_cast(fRootManager->GetObject("EventHeader.")); + fEvtHeader = dynamic_cast(fRootManager->GetObject("EventHeader.")); - if (nullptr == fEvtHeader) LOG(fatal) << "Could not read event header."; + if (nullptr == fEvtHeader) + LOG(fatal) << "Could not read event header."; - fRootManager->FillEventHeader(fEvtHeader); + fRootManager->FillEventHeader(fEvtHeader); - fRunId = fEvtHeader->GetRunId(); + fRunId = fEvtHeader->GetRunId(); - //Copy the Event Header Info to Output - fEvtHeader->Register(); + // Copy the Event Header Info to Output + fEvtHeader->Register(); - // Init the containers in Tasks - fRtdb->initContainers(fRunId); - fTask->ReInitTask(); - // fTask->SetParTask(); - fRtdb->initContainers( fRunId ); - if (gGeoManager==0) { - // par->GetGeometry(); + // Init the containers in Tasks + fRtdb->initContainers(fRunId); + fTask->ReInitTask(); + // fTask->SetParTask(); + fRtdb->initContainers(fRunId); + if (gGeoManager == 0) { + // par->GetGeometry(); + } } - } } -void FairRunAnaProof::SetSource(FairSource* tempSource) { - // FairRunAnaProof should accept only FairFileSource - if (strncmp(tempSource->GetName(), "FairFileSource", 14) != 0) { - LOG(warn) << "FairRunAnaProof. Seems you are trying to set different source than FairFileSource"; - } - fRootManager->SetSource(tempSource); - fProofFileSource = static_cast(tempSource); +void FairRunAnaProof::SetSource(FairSource* tempSource) +{ + // FairRunAnaProof should accept only FairFileSource + if (strncmp(tempSource->GetName(), "FairFileSource", 14) != 0) { + LOG(warn) << "FairRunAnaProof. Seems you are trying to set different source than FairFileSource"; + } + fRootManager->SetSource(tempSource); + fProofFileSource = static_cast(tempSource); } void FairRunAnaProof::Run(Int_t Ev_start, Int_t Ev_end) { - RunOnProof(Ev_start,Ev_end); - return; + RunOnProof(Ev_start, Ev_end); + return; } void FairRunAnaProof::RunOneEvent(Long64_t entry) { - if (fTimeStamps) { - RunTSBuffers(); - } else { - UInt_t tmpId =0; - fRootManager->ReadEvent(entry); - - fRootManager->FillEventHeader(fEvtHeader); - - tmpId = fEvtHeader->GetRunId(); - if ( tmpId != fRunId ) { - fRunId = tmpId; - if ( !fStatic ) { - Reinit( fRunId ); - fTask->ReInitTask(); - } - } - fRootManager->StoreWriteoutBufferData(fRootManager->GetEventTime()); + if (fTimeStamps) { + RunTSBuffers(); + } else { + UInt_t tmpId = 0; + fRootManager->ReadEvent(entry); + + fRootManager->FillEventHeader(fEvtHeader); + + tmpId = fEvtHeader->GetRunId(); + if (tmpId != fRunId) { + fRunId = tmpId; + if (!fStatic) { + Reinit(fRunId); + fTask->ReInitTask(); + } + } + fRootManager->StoreWriteoutBufferData(fRootManager->GetEventTime()); - fTask->ExecuteTask(""); - fRootManager->Fill(); - fRootManager->DeleteOldWriteoutBufferData(); - fTask->FinishEvent(); - } + fTask->ExecuteTask(""); + fRootManager->Fill(); + fRootManager->DeleteOldWriteoutBufferData(); + fTask->FinishEvent(); + } } -void FairRunAnaProof::RunOnProof(Int_t NStart,Int_t NStop) +void FairRunAnaProof::RunOnProof(Int_t NStart, Int_t NStop) { - fProofOutputStatus.ToLower(); - if ( !fProofOutputStatus.Contains("copy") && !fProofOutputStatus.Contains("merge") ) { - LOG(warn) << "FairRunAnaProof::RunOnProof. Do not know how to create output \"" << fProofOutputStatus.Data() << "\"."; - LOG(warn) << "FairRunAnaProof::RunOnProof. Please use SetProofOutputStatus to either \"copy\" or \"merge\"."; - LOG(warn) << "FairRunAnaProof::RunOnProof. For the current run using the \"merge\" setting."; - fProofOutputStatus = "merge"; - } - -// TChain* inChain = static_cast(fRootManager->GetInChain()); - TChain* inChain = static_cast(fProofFileSource->GetInChain()); - TString par1File = ""; - TString par2File = ""; - if ( fRtdb->getFirstInput () ) { - par1File = fRtdb->getFirstInput ()->getFilename(); - } - if ( fRtdb->getSecondInput() ) { - par2File = fRtdb->getSecondInput()->getFilename(); - } - - TString outDir = (fOutputDirectory.Length()>1?fOutputDirectory.Data():gSystem->WorkingDirectory()); - - fProof->AddInput(fTask); - - // get file name from FairSink - TString fileName = fRootManager->GetSink()->GetFileName(); - LOG(info) << " outputFileName = " << fileName.Data(); - if ( fileName.Length() < 5 ) fileName = "proofOutput.root"; - - fProof->AddInput(new TNamed("FAIRRUNANA_fContainerStatic",(fStatic?"kTRUE":"kFALSE"))); - fProof->AddInput(new TNamed("FAIRRUNANA_fProofOutputStatus",fProofOutputStatus.Data())); - fProof->AddInput(new TNamed("FAIRRUNANA_fOutputDirectory",outDir.Data())); - fProof->AddInput(new TNamed("FAIRRUNANA_fOutputFileName",fileName.Data())); - fProof->AddInput(new TNamed("FAIRRUNANA_fParInput1FName",par1File.Data())); - fProof->AddInput(new TNamed("FAIRRUNANA_fParInput2FName",par2File.Data())); - - Int_t nofChainEntries = inChain->GetEntries(); - LOG(info) << "FairRunAnaProof::RunOnProof(): The chain seems to have " << nofChainEntries << " entries."; - - TObjArray* listOfFiles = inChain->GetListOfFiles(); - LOG(info) << "FairRunAnaProof::RunOnProof(): There are " << listOfFiles->GetEntries() << " files in the chain."; - - inChain->SetProof(); - - Int_t nofEventsToAnalyze = NStop-NStart; - - if ( nofEventsToAnalyze <= 0 ) { - LOG(info) << "You requested to analyze events from " << NStart << " to " << NStop << " that is " << nofEventsToAnalyze << " events!!!"; - nofEventsToAnalyze = nofChainEntries-NStart; - LOG(info) << "It will be changed to analyze all events from " << NStart << " to the end of chain (" << nofChainEntries << "), that is to analyze " << nofEventsToAnalyze << " events."; - } - - LOG(info) << "FairRunAnaProof::RunOnProof(): Starting inChain->Process(\"FairAnaSelector\",\"\"," - << nofEventsToAnalyze << "," << NStart << ")"; - inChain->Process("FairAnaSelector","",nofEventsToAnalyze,NStart); - LOG(info) << "FairRunAnaProof::RunOnProof(): inChain->Process DONE"; - - return; + fProofOutputStatus.ToLower(); + if (!fProofOutputStatus.Contains("copy") && !fProofOutputStatus.Contains("merge")) { + LOG(warn) << "FairRunAnaProof::RunOnProof. Do not know how to create output \"" << fProofOutputStatus.Data() + << "\"."; + LOG(warn) << "FairRunAnaProof::RunOnProof. Please use SetProofOutputStatus to either \"copy\" or \"merge\"."; + LOG(warn) << "FairRunAnaProof::RunOnProof. For the current run using the \"merge\" setting."; + fProofOutputStatus = "merge"; + } + + // TChain* inChain = static_cast(fRootManager->GetInChain()); + TChain* inChain = static_cast(fProofFileSource->GetInChain()); + TString par1File = ""; + TString par2File = ""; + if (fRtdb->getFirstInput()) { + par1File = fRtdb->getFirstInput()->getFilename(); + } + if (fRtdb->getSecondInput()) { + par2File = fRtdb->getSecondInput()->getFilename(); + } + + TString outDir = (fOutputDirectory.Length() > 1 ? fOutputDirectory.Data() : gSystem->WorkingDirectory()); + + fProof->AddInput(fTask); + + // get file name from FairSink + TString fileName = fRootManager->GetSink()->GetFileName(); + LOG(info) << " outputFileName = " << fileName.Data(); + if (fileName.Length() < 5) + fileName = "proofOutput.root"; + + fProof->AddInput(new TNamed("FAIRRUNANA_fContainerStatic", (fStatic ? "kTRUE" : "kFALSE"))); + fProof->AddInput(new TNamed("FAIRRUNANA_fProofOutputStatus", fProofOutputStatus.Data())); + fProof->AddInput(new TNamed("FAIRRUNANA_fOutputDirectory", outDir.Data())); + fProof->AddInput(new TNamed("FAIRRUNANA_fOutputFileName", fileName.Data())); + fProof->AddInput(new TNamed("FAIRRUNANA_fParInput1FName", par1File.Data())); + fProof->AddInput(new TNamed("FAIRRUNANA_fParInput2FName", par2File.Data())); + + Int_t nofChainEntries = inChain->GetEntries(); + LOG(info) << "FairRunAnaProof::RunOnProof(): The chain seems to have " << nofChainEntries << " entries."; + + TObjArray* listOfFiles = inChain->GetListOfFiles(); + LOG(info) << "FairRunAnaProof::RunOnProof(): There are " << listOfFiles->GetEntries() << " files in the chain."; + + inChain->SetProof(); + + Int_t nofEventsToAnalyze = NStop - NStart; + + if (nofEventsToAnalyze <= 0) { + LOG(info) << "You requested to analyze events from " << NStart << " to " << NStop << " that is " + << nofEventsToAnalyze << " events!!!"; + nofEventsToAnalyze = nofChainEntries - NStart; + LOG(info) << "It will be changed to analyze all events from " << NStart << " to the end of chain (" + << nofChainEntries << "), that is to analyze " << nofEventsToAnalyze << " events."; + } + + LOG(info) << "FairRunAnaProof::RunOnProof(): Starting inChain->Process(\"FairAnaSelector\",\"\"," + << nofEventsToAnalyze << "," << NStart << ")"; + inChain->Process("FairAnaSelector", "", nofEventsToAnalyze, NStart); + LOG(info) << "FairRunAnaProof::RunOnProof(): inChain->Process DONE"; + + return; } // // void FairRunAnaProof::SetOutputFile(const char* fname) @@ -390,4 +385,4 @@ void FairRunAnaProof::RunOnProof(Int_t NStart,Int_t NStop) // } // -ClassImp(FairRunAnaProof) +ClassImp(FairRunAnaProof); diff --git a/base/steer/FairRunAnaProof.h b/base/steer/FairRunAnaProof.h index b0f86dc199..24aa38daec 100644 --- a/base/steer/FairRunAnaProof.h +++ b/base/steer/FairRunAnaProof.h @@ -15,8 +15,8 @@ * @since 30.04.2013 */ +#include "FairFileSource.h" // FairRunAnaProof can only accept FairFileSource as source #include "FairRunAna.h" -#include "FairFileSource.h" // FairRunAnaProof can only accept FairFileSource as source #include #include @@ -26,29 +26,29 @@ class FairRunAnaProof : public FairRunAna public: static FairRunAnaProof* Instance(); virtual ~FairRunAnaProof(); - FairRunAnaProof(const char* proofName=""); + FairRunAnaProof(const char* proofName = ""); /**initialize the run manager*/ - void Init(); + void Init(); /** Init containers executed on PROOF, which is part of Init when running locally*/ - void InitContainers(); + void InitContainers(); /** * Set the output file name for analysis or simulation - */ + */ // virtual void SetOutputFile(const char* fname); /** * Set the output file for analysis or simulation - */ + */ // virtual void SetOutputFile(TFile* f); /**Run from event number NStart to event number NStop */ - void Run(Int_t NStart=0 ,Int_t NStop=0); + void Run(Int_t NStart = 0, Int_t NStop = 0); /**Run for one event, used on PROOF nodes*/ - void RunOneEvent(Long64_t entry); + void RunOneEvent(Long64_t entry); /**Run on proof from event NStart to event NStop*/ - void RunOnProof(Int_t NStart, Int_t NStop); + void RunOnProof(Int_t NStart, Int_t NStop); /** set the input tree of fRootManager when running on PROOF worker*/ /* void SetInTree (TTree* tempTree) { */ @@ -56,44 +56,34 @@ class FairRunAnaProof : public FairRunAna /* } */ /** GetProof */ - TProof* GetProof() { - return fProof; - } + TProof* GetProof() { return fProof; } /** To be set to kTRUE only when running on PROOF worker, only by TSelector */ - void SetRunOnProofWorker(Bool_t tb = kTRUE) { - fRunOnProofWorker = tb; - } + void SetRunOnProofWorker(Bool_t tb = kTRUE) { fRunOnProofWorker = tb; } /** Set PROOF ARchive (PAR) file name*/ - void SetProofParName(TString parName) { - fProofParName = parName; - } + void SetProofParName(TString parName) { fProofParName = parName; } /** Set directory for storing output files*/ - void SetOutputDirectory(TString dirName) { - fOutputDirectory = dirName; - } + void SetOutputDirectory(TString dirName) { fOutputDirectory = dirName; } /** Set PROOF output status, possibilities: "copy","merge"*/ - void SetProofOutputStatus(TString outStat) { - fProofOutputStatus = outStat; - } + void SetProofOutputStatus(TString outStat) { fProofOutputStatus = outStat; } - virtual void SetSource(FairSource* tempSource); + virtual void SetSource(FairSource* tempSource); protected: - static FairRunAnaProof* fRAPInstance; + static FairRunAnaProof* fRAPInstance; /** PROOF **/ - TProof* fProof; + TProof* fProof; /** executing on PROOF worker*/ - Bool_t fRunOnProofWorker; //! + Bool_t fRunOnProofWorker; //! /** PROOF server name*/ - TString fProofServerName; //! + TString fProofServerName; //! /** PROOF ARchive (PAR) file name*/ - TString fProofParName; //! + TString fProofParName; //! /** Output directory*/ - TString fOutputDirectory; //! + TString fOutputDirectory; //! /** Output status indicator: "copy","merge","dataset"*/ - TString fProofOutputStatus; + TString fProofOutputStatus; private: FairRunAnaProof(const FairRunAnaProof&); @@ -101,7 +91,7 @@ class FairRunAnaProof : public FairRunAna FairFileSource* fProofFileSource; - ClassDef(FairRunAnaProof ,1) + ClassDef(FairRunAnaProof, 1) }; -#endif //FAIRRUNANAPROOF_H +#endif // FAIRRUNANAPROOF_H diff --git a/base/steer/FairRunOnline.cxx b/base/steer/FairRunOnline.cxx index f426244ab3..a7b1a55f88 100644 --- a/base/steer/FairRunOnline.cxx +++ b/base/steer/FairRunOnline.cxx @@ -12,415 +12,389 @@ #include "FairRunOnline.h" -#include "FairRootManager.h" -#include "FairTask.h" #include "FairBaseParSet.h" #include "FairEventHeader.h" -#include "FairRuntimeDb.h" -#include "FairRunIdGenerator.h" -#include "FairLogger.h" -#include "FairFileHeader.h" #include "FairField.h" +#include "FairFileHeader.h" #include "FairGeoParSet.h" -#include "FairSource.h" // for FairSource, kONLINE -#include "FairParSet.h" // for FairParSet +#include "FairLogger.h" +#include "FairParSet.h" // for FairParSet +#include "FairRootManager.h" +#include "FairRunIdGenerator.h" +#include "FairRuntimeDb.h" +#include "FairSource.h" // for FairSource, kONLINE +#include "FairTask.h" -#include -#include // for TIter -#include // for TList -#include // for TObjArray -#include // for TObjString -#include // for TObject -#include +#include // for TIter #include #include - +#include // for TList +#include // for TObjArray +#include // for TObjString +#include // for TObject +#include +#include +#include #include #include -#include using std::cout; using std::endl; FairRunOnline* FairRunOnline::fgRinstance = 0; -FairRunOnline* FairRunOnline::Instance() -{ - return fgRinstance; -} +FairRunOnline* FairRunOnline::Instance() { return fgRinstance; } FairRunOnline::FairRunOnline() - :FairRun(), - fAutomaticFinish(kTRUE), - fIsInitialized(kFALSE), - fStatic(kFALSE), - fField(0), - fNevents(0), - fServer(nullptr), - fServerRefreshRate(0) + : FairRun() + , fAutomaticFinish(kTRUE) + , fIsInitialized(kFALSE) + , fStatic(kFALSE) + , fField(0) + , fNevents(0) + , fServer(nullptr) + , fServerRefreshRate(0) { - fgRinstance = this; - fAna = kTRUE; - LOG(info) << "FairRunOnline constructed at " << this; + fgRinstance = this; + fAna = kTRUE; + LOG(info) << "FairRunOnline constructed at " << this; } FairRunOnline::FairRunOnline(FairSource* source) - :FairRun(), - fAutomaticFinish(kTRUE), - fIsInitialized(kFALSE), - fStatic(kFALSE), - fField(0), - fNevents(0), - fServer(nullptr), - fServerRefreshRate(0) + : FairRun() + , fAutomaticFinish(kTRUE) + , fIsInitialized(kFALSE) + , fStatic(kFALSE) + , fField(0) + , fNevents(0) + , fServer(nullptr) + , fServerRefreshRate(0) { - fRootManager->SetSource(source); - fgRinstance = this; - fAna = kTRUE; - LOG(info) << "FairRunOnline constructed at " << this; + fRootManager->SetSource(source); + fgRinstance = this; + fAna = kTRUE; + LOG(info) << "FairRunOnline constructed at " << this; } FairRunOnline::~FairRunOnline() { - // delete fFriendFileList; - delete fField; - if (gGeoManager) { - if (gROOT->GetVersionInt() >= 60602) { - gGeoManager->GetListOfVolumes()->Delete(); - gGeoManager->GetListOfShapes()->Delete(); + // delete fFriendFileList; + delete fField; + if (gGeoManager) { + if (gROOT->GetVersionInt() >= 60602) { + gGeoManager->GetListOfVolumes()->Delete(); + gGeoManager->GetListOfShapes()->Delete(); + } + delete gGeoManager; } - delete gGeoManager; - } - delete fServer; + delete fServer; } Bool_t gIsInterrupted; -void handler_ctrlc(int) -{ - gIsInterrupted = kTRUE; -} +void handler_ctrlc(int) { gIsInterrupted = kTRUE; } void FairRunOnline::Init() { - LOG(info)<<"FairRunOnline::Init"; - if (fIsInitialized) { - LOG(fatal) << "Error Init is already called before!"; - exit(-1); - } else { - fIsInitialized = kTRUE; - } - - fRootManager->InitSink(); - fRootManager->InitSource(); - - // FairGeoLoader* loader = new FairGeoLoader("TGeo", "Geo Loader"); - // FairGeoInterface* GeoInterFace = loader->getGeoInterface(); - // GeoInterFace->SetNoOfSets(ListOfModules->GetEntries()); - // GeoInterFace->setMediaFile(MatFname.Data()); - // GeoInterFace->readMedia(); - - // Add a Generated run ID to the FairRunTimeDb for input data which contain a FairMCEventHeader - // The call doesn't make sense for online sources which doesn't contain a FairMCEventHeader - - if (kONLINE != fRootManager->GetSource()->GetSourceType()) - { - fRootManager->ReadEvent(0); - } - - GetEventHeader(); - - fRootManager->FillEventHeader(fEvtHeader); - - if (0 == fRunId) // Run ID was not set in run manager - { - if (0 == fEvtHeader->GetRunId()) // Run ID was not set in source - { - // Generate unique Run ID - FairRunIdGenerator genid; - fRunId = genid.generateId(); - fRootManager->GetSource()->SetRunId(fRunId); + LOG(info) << "FairRunOnline::Init"; + if (fIsInitialized) { + LOG(fatal) << "Error Init is already called before!"; + exit(-1); + } else { + fIsInitialized = kTRUE; } - else + + fRootManager->InitSink(); + fRootManager->InitSource(); + + // FairGeoLoader* loader = new FairGeoLoader("TGeo", "Geo Loader"); + // FairGeoInterface* GeoInterFace = loader->getGeoInterface(); + // GeoInterFace->SetNoOfSets(ListOfModules->GetEntries()); + // GeoInterFace->setMediaFile(MatFname.Data()); + // GeoInterFace->readMedia(); + + // Add a Generated run ID to the FairRunTimeDb for input data which contain a FairMCEventHeader + // The call doesn't make sense for online sources which doesn't contain a FairMCEventHeader + + if (kONLINE != fRootManager->GetSource()->GetSourceType()) { + fRootManager->ReadEvent(0); + } + + GetEventHeader(); + + fRootManager->FillEventHeader(fEvtHeader); + + if (0 == fRunId) // Run ID was not set in run manager { - // Use Run ID from source - fRunId = fEvtHeader->GetRunId(); + if (0 == fEvtHeader->GetRunId()) // Run ID was not set in source + { + // Generate unique Run ID + FairRunIdGenerator genid; + fRunId = genid.generateId(); + fRootManager->GetSource()->SetRunId(fRunId); + } else { + // Use Run ID from source + fRunId = fEvtHeader->GetRunId(); + } + } else { + // Run ID was set in the run manager - propagate to source + fRootManager->GetSource()->SetRunId(fRunId); + } + + fRtdb->addRun(fRunId); + fFileHeader->SetRunId(fRunId); + FairBaseParSet* par = dynamic_cast(fRtdb->getContainer("FairBaseParSet")); + FairGeoParSet* geopar = dynamic_cast(fRtdb->getContainer("FairGeoParSet")); + if (geopar) { + geopar->SetGeometry(gGeoManager); + } + if (fField) { + fField->Init(); + fField->FillParContainer(); + } + TList* containerList = fRtdb->getListOfContainers(); + TIter next(containerList); + FairParSet* cont; + TObjArray* ContList = new TObjArray(); + while ((cont = dynamic_cast(next()))) { + ContList->Add(new TObjString(cont->GetName())); + } + if (par) { + par->SetContListStr(ContList); + par->setChanged(); + par->setInputVersion(fRunId, 1); + } + if (geopar) { + geopar->setChanged(); + geopar->setInputVersion(fRunId, 1); } - } - else - { - // Run ID was set in the run manager - propagate to source - fRootManager->GetSource()->SetRunId(fRunId); - } - - fRtdb->addRun(fRunId); - fFileHeader->SetRunId(fRunId); - FairBaseParSet* par = dynamic_cast(fRtdb->getContainer("FairBaseParSet")); - FairGeoParSet* geopar = dynamic_cast(fRtdb->getContainer("FairGeoParSet")); - if (geopar) { - geopar->SetGeometry(gGeoManager); - } - if (fField) { - fField->Init(); - fField->FillParContainer(); - } - TList* containerList = fRtdb->getListOfContainers(); - TIter next(containerList); - FairParSet* cont; - TObjArray* ContList= new TObjArray(); - while ((cont=dynamic_cast(next()))) { - ContList->Add(new TObjString(cont->GetName())); - } - if (par) { - par->SetContListStr(ContList); - par->setChanged(); - par->setInputVersion(fRunId,1); - } - if (geopar) { - geopar->setChanged(); - geopar->setInputVersion(fRunId,1); - } - - fRootManager->WriteFileHeader(fFileHeader); - - fRootManager->GetSource()->SetParUnpackers(); - fTask->SetParTask(); - fRtdb->initContainers(fRunId); - - // InitContainers(); - // --- Get event header from Run - if ( ! fEvtHeader ) { - LOG(fatal) << "FairRunOnline::InitContainers:No event header in run!"; - return; - } - LOG(info) << "FairRunOnline::InitContainers: event header at " << fEvtHeader; - fRootManager->Register("EventHeader.", "Event", fEvtHeader, kTRUE); - fEvtHeader->SetRunId(fRunId); - - fRootManager->GetSource()->InitUnpackers(); - - // Now call the User initialize for Tasks - fTask->InitTask(); - - // create the output tree after tasks initialisation - fRootManager->InitSink(); - fRootManager->WriteFolder(); - fRootManager->WriteFileHeader(fFileHeader); + + fRootManager->WriteFileHeader(fFileHeader); + + fRootManager->GetSource()->SetParUnpackers(); + fTask->SetParTask(); + fRtdb->initContainers(fRunId); + + // InitContainers(); + // --- Get event header from Run + if (!fEvtHeader) { + LOG(fatal) << "FairRunOnline::InitContainers:No event header in run!"; + return; + } + LOG(info) << "FairRunOnline::InitContainers: event header at " << fEvtHeader; + fRootManager->Register("EventHeader.", "Event", fEvtHeader, kTRUE); + fEvtHeader->SetRunId(fRunId); + + fRootManager->GetSource()->InitUnpackers(); + + // Now call the User initialize for Tasks + fTask->InitTask(); + + // create the output tree after tasks initialisation + fRootManager->InitSink(); + fRootManager->WriteFolder(); + fRootManager->WriteFileHeader(fFileHeader); } void FairRunOnline::InitContainers() { - fRtdb = GetRuntimeDb(); - FairBaseParSet* par=static_cast(fRtdb->getContainer("FairBaseParSet")); - LOG(info) << "FairRunOnline::InitContainers: par = " << par; - if (nullptr == par) - LOG(warn)<<"FairRunOnline::InitContainers: no 'FairBaseParSet' container !"; + fRtdb = GetRuntimeDb(); + FairBaseParSet* par = static_cast(fRtdb->getContainer("FairBaseParSet")); + LOG(info) << "FairRunOnline::InitContainers: par = " << par; + if (nullptr == par) + LOG(warn) << "FairRunOnline::InitContainers: no 'FairBaseParSet' container !"; - if (par) { - fEvtHeader = static_cast(fRootManager->GetObject("EventHeader.")); + if (par) { + fEvtHeader = static_cast(fRootManager->GetObject("EventHeader.")); - fRunId = fEvtHeader->GetRunId(); + fRunId = fEvtHeader->GetRunId(); - //Copy the Event Header Info to Output - fEvtHeader->Register(); + // Copy the Event Header Info to Output + fEvtHeader->Register(); - // Init the containers in Tasks - fRtdb->initContainers(fRunId); - fTask->ReInitTask(); - // fTask->SetParTask(); - fRtdb->initContainers( fRunId ); - // if (gGeoManager==0) { - // par->GetGeometry(); - // } - } else - { - // --- Get event header from Run - // fEvtHeader = dynamic_cast (FairRunOnline::Instance()->GetEventHeade - GetEventHeader(); - if ( ! fEvtHeader ) { - LOG(fatal) << "FairRunOnline::InitContainers:No event header in run!"; - return; - } - LOG(info) << "FairRunOnline::InitContainers: event header at " << fEvtHeader; - fRootManager->Register("EventHeader.", "Event", fEvtHeader, kTRUE); + // Init the containers in Tasks + fRtdb->initContainers(fRunId); + fTask->ReInitTask(); + // fTask->SetParTask(); + fRtdb->initContainers(fRunId); + // if (gGeoManager==0) { + // par->GetGeometry(); + // } + } else { + // --- Get event header from Run + // fEvtHeader = dynamic_cast (FairRunOnline::Instance()->GetEventHeade + GetEventHeader(); + if (!fEvtHeader) { + LOG(fatal) << "FairRunOnline::InitContainers:No event header in run!"; + return; + } + LOG(info) << "FairRunOnline::InitContainers: event header at " << fEvtHeader; + fRootManager->Register("EventHeader.", "Event", fEvtHeader, kTRUE); } } Int_t FairRunOnline::EventLoop() { - gSystem->IgnoreInterrupt(); - signal(SIGINT, handler_ctrlc); - - fRootManager->FillEventHeader(fEvtHeader); - Int_t tmpId = fEvtHeader->GetRunId(); - - if ( tmpId != -1 && tmpId != fRunId ) { - LOG(info) << "FairRunOnline::EventLoop() Call Reinit due to changed RunID (from " << fRunId << " to " << tmpId; - fRunId = tmpId; - Reinit( fRunId ); - fRootManager->GetSource()->ReInitUnpackers(); - fTask->ReInitTask(); - } - - fRootManager->StoreWriteoutBufferData(fRootManager->GetEventTime()); - fTask->ExecuteTask(""); - fRootManager->FillEventHeader(fEvtHeader); - Fill(); - fRootManager->DeleteOldWriteoutBufferData(); - fTask->FinishEvent(); - fNevents += 1; - if (fServer && 0 == (fNevents%fServerRefreshRate)) - { - fServer->ProcessRequests(); - } - - if (gIsInterrupted) - { - return 1; - } - - return 0; + gSystem->IgnoreInterrupt(); + signal(SIGINT, handler_ctrlc); + + fRootManager->FillEventHeader(fEvtHeader); + Int_t tmpId = fEvtHeader->GetRunId(); + + if (tmpId != -1 && tmpId != fRunId) { + LOG(info) << "FairRunOnline::EventLoop() Call Reinit due to changed RunID (from " << fRunId << " to " << tmpId; + fRunId = tmpId; + Reinit(fRunId); + fRootManager->GetSource()->ReInitUnpackers(); + fTask->ReInitTask(); + } + + fRootManager->StoreWriteoutBufferData(fRootManager->GetEventTime()); + fTask->ExecuteTask(""); + fRootManager->FillEventHeader(fEvtHeader); + Fill(); + fRootManager->DeleteOldWriteoutBufferData(); + fTask->FinishEvent(); + fNevents += 1; + if (fServer && 0 == (fNevents % fServerRefreshRate)) { + fServer->ProcessRequests(); + } + + if (gIsInterrupted) { + return 1; + } + + return 0; } void FairRunOnline::Run(Int_t Ev_start, Int_t Ev_end) { - fNevents = 0; - - gIsInterrupted = kFALSE; - - Int_t MaxAllowed=fRootManager->CheckMaxEventNo(Ev_end); - if ( MaxAllowed != -1 ) { - if (Ev_end==0) { - if (Ev_start==0) { - Ev_end=MaxAllowed; - } else { - Ev_end = Ev_start; - if ( Ev_end > MaxAllowed ) { - Ev_end = MaxAllowed; + fNevents = 0; + + gIsInterrupted = kFALSE; + + Int_t MaxAllowed = fRootManager->CheckMaxEventNo(Ev_end); + if (MaxAllowed != -1) { + if (Ev_end == 0) { + if (Ev_start == 0) { + Ev_end = MaxAllowed; + } else { + Ev_end = Ev_start; + if (Ev_end > MaxAllowed) { + Ev_end = MaxAllowed; + } + Ev_start = 0; + } + } else { + if (Ev_end > MaxAllowed) { + cout << "-------------------Warning---------------------------" << endl; + cout << " -W FairRunAna : File has less events than requested!!" << endl; + cout << " File contains : " << MaxAllowed << " Events" << endl; + cout << " Requested number of events = " << Ev_end << " Events" << endl; + cout << " The number of events is set to " << MaxAllowed << " Events" << endl; + cout << "-----------------------------------------------------" << endl; + Ev_end = MaxAllowed; + } } - Ev_start=0; - } - } else { - if (Ev_end > MaxAllowed) { - cout << "-------------------Warning---------------------------" << endl; - cout << " -W FairRunAna : File has less events than requested!!" << endl; - cout << " File contains : " << MaxAllowed << " Events" << endl; - cout << " Requested number of events = " << Ev_end << " Events"<< endl; - cout << " The number of events is set to " << MaxAllowed << " Events"<< endl; - cout << "-----------------------------------------------------" << endl; - Ev_end = MaxAllowed; - } - } - } - Int_t status; - if (Ev_start < 0) { - while(kTRUE) { - status = fRootManager->ReadEvent(); - if (0 == status) { - status = EventLoop(); - } - if (1 == status) { - break; - } else if (2 == status) { - continue; - } - if (gIsInterrupted) - { - break; - } } - } else { - for (Int_t i = Ev_start; i < Ev_end; i++) { - status = fRootManager->ReadEvent(i); - if (0 == status) { - status = EventLoop(); - } - if (1 == status) { - break; - } else if (2 == status) { - i -= 1; - continue; - } - - if (gIsInterrupted) - { - break; - } + Int_t status; + if (Ev_start < 0) { + while (kTRUE) { + status = fRootManager->ReadEvent(); + if (0 == status) { + status = EventLoop(); + } + if (1 == status) { + break; + } else if (2 == status) { + continue; + } + if (gIsInterrupted) { + break; + } + } + } else { + for (Int_t i = Ev_start; i < Ev_end; i++) { + status = fRootManager->ReadEvent(i); + if (0 == status) { + status = EventLoop(); + } + if (1 == status) { + break; + } else if (2 == status) { + i -= 1; + continue; + } + + if (gIsInterrupted) { + break; + } + } } - } - fRootManager->StoreAllWriteoutBufferData(); - if (fAutomaticFinish) { - Finish(); - } + fRootManager->StoreAllWriteoutBufferData(); + if (fAutomaticFinish) { + Finish(); + } } void FairRunOnline::Finish() { - fTask->FinishTask(); - fRootManager->LastFill(); - fRootManager->Write(); - fRootManager->GetSource()->Close(); + fTask->FinishTask(); + fRootManager->LastFill(); + fRootManager->Write(); + fRootManager->GetSource()->Close(); - fRootManager->CloseSink(); + fRootManager->CloseSink(); } void FairRunOnline::ActivateHttpServer(Int_t refreshRate, Int_t httpServer) { - TString serverAddress="http:"; - serverAddress+=httpServer; - fServer = new THttpServer(serverAddress); - fServerRefreshRate = refreshRate; + TString serverAddress = "http:"; + serverAddress += httpServer; + fServer = new THttpServer(serverAddress); + fServerRefreshRate = refreshRate; } void FairRunOnline::RegisterHttpCommand(TString name, TString command) { - if (fServer) - { - TString path = "/Objects/HISTO"; - fServer->RegisterCommand(name, path + command); - } + if (fServer) { + TString path = "/Objects/HISTO"; + fServer->RegisterCommand(name, path + command); + } } void FairRunOnline::Reinit(UInt_t runId) { - // reinit procedure - fRtdb->initContainers( runId ); + // reinit procedure + fRtdb->initContainers(runId); } -void FairRunOnline::SetContainerStatic(Bool_t tempBool) +void FairRunOnline::SetContainerStatic(Bool_t tempBool) { - fStatic=tempBool; - if ( fStatic ) { - LOG(info) << "Parameter Cont. initialisation is static"; - } else { - LOG(info) << "Parameter Cont. initialisation is NOT static"; - } + fStatic = tempBool; + if (fStatic) { + LOG(info) << "Parameter Cont. initialisation is static"; + } else { + LOG(info) << "Parameter Cont. initialisation is NOT static"; + } } void FairRunOnline::AddObject(TObject* object) { - if (nullptr == object) - { + if (nullptr == object) { return; } if (fServer) { TString classname = TString(object->ClassName()); - if (classname.EqualTo("TCanvas")) - { + if (classname.EqualTo("TCanvas")) { fServer->Register("CANVAS", object); - } - else if (classname.EqualTo("TFolder")) - { + } else if (classname.EqualTo("TFolder")) { fServer->Register("/", object); - } - else if (classname.Contains("TH1") || classname.Contains("TH2")) - { + } else if (classname.Contains("TH1") || classname.Contains("TH2")) { fServer->Register("HISTO", object); - } - else - { + } else { LOG(warn) << "FairRunOnline::AddObject : unrecognized object type : " << classname; } } @@ -428,14 +402,11 @@ void FairRunOnline::AddObject(TObject* object) void FairRunOnline::Fill() { - if (fMarkFill) - { - fRootManager->Fill(); - } - else - { - fMarkFill = kTRUE; - } + if (fMarkFill) { + fRootManager->Fill(); + } else { + fMarkFill = kTRUE; + } } -ClassImp(FairRunOnline) +ClassImp(FairRunOnline); diff --git a/base/steer/FairRunOnline.h b/base/steer/FairRunOnline.h index ed074a2506..f409fecee3 100644 --- a/base/steer/FairRunOnline.h +++ b/base/steer/FairRunOnline.h @@ -15,11 +15,11 @@ * @since 28.02.05 */ -#include "FairRun.h" #include "FairRootManager.h" +#include "FairRun.h" -#include #include +#include class FairField; class FairSource; @@ -35,34 +35,34 @@ class FairRunOnline : public FairRun FairRunOnline(FairSource* source); /**initialize the run manager*/ - void Init(); + void Init(); /**Run for the given number of events*/ - void Run(Int_t Ev_start, Int_t Ev_end); + void Run(Int_t Ev_start, Int_t Ev_end); - void Reinit(UInt_t runId); - UInt_t getRunId() { return fRunId; } + void Reinit(UInt_t runId); + UInt_t getRunId() { return fRunId; } /** Get the magnetic field **/ - FairField* GetField() { return fField; } + FairField* GetField() { return fField; } /** Set the magnetic Field */ - void SetField (FairField* ffield) { fField = ffield; } + void SetField(FairField* ffield) { fField = ffield; } /** Set if the run should be closed automatically after executing the run functuion **/ - void SetAutoFinish(Bool_t val) { fAutomaticFinish = val; } + void SetAutoFinish(Bool_t val) { fAutomaticFinish = val; } /** Set the source which should be used **/ - void SetSource(FairSource* source) { fRootManager->SetSource(source); } + void SetSource(FairSource* source) { fRootManager->SetSource(source); } /** Return pointer to source **/ - FairSource* GetSource() { return fRootManager->GetSource(); } + FairSource* GetSource() { return fRootManager->GetSource(); } /** Initialization of parameter container is set to static, i.e: the run id is * is not checked anymore after initialization */ /** Init containers executed on PROOF, which is part of Init when running locally*/ - void InitContainers(); - void SetContainerStatic(Bool_t tempBool=kTRUE); - Bool_t GetContainerStatic() { return fStatic; }; + void InitContainers(); + void SetContainerStatic(Bool_t tempBool = kTRUE); + Bool_t GetContainerStatic() { return fStatic; }; /** Add histogram to be displayed using THttpServer.*/ void AddObject(TObject* object); @@ -71,7 +71,7 @@ class FairRunOnline : public FairRun * @param refreshRate an interval in number of events for server update. * @param httpPort the port which is used by the http server */ - void ActivateHttpServer(Int_t refreshRate = 10000, Int_t httpPort=8080); + void ActivateHttpServer(Int_t refreshRate = 10000, Int_t httpPort = 8080); /** Register a command on the http server. * @param name a command name starting with / @@ -89,26 +89,26 @@ class FairRunOnline : public FairRun Bool_t fAutomaticFinish; FairRunOnline(const FairRunOnline& M); - FairRunOnline& operator= (const FairRunOnline&) { return *this; } + FairRunOnline& operator=(const FairRunOnline&) { return *this; } /** Main Event loop **/ Int_t EventLoop(); protected: /** This variable became true after Init is called*/ - Bool_t fIsInitialized; - static FairRunOnline* fgRinstance; + Bool_t fIsInitialized; + static FairRunOnline* fgRinstance; /** true for static initialisation of parameters */ - Bool_t fStatic;//! - FairField* fField; + Bool_t fStatic; //! + FairField* fField; - Int_t fNevents; //! - THttpServer* fServer; //! - Int_t fServerRefreshRate; //! + Int_t fNevents; //! + THttpServer* fServer; //! + Int_t fServerRefreshRate; //! virtual void Fill(); ClassDef(FairRunOnline, 0) }; -#endif //FAIRRUNONLINE_H +#endif // FAIRRUNONLINE_H diff --git a/base/steer/FairRunSim.cxx b/base/steer/FairRunSim.cxx index 4e247d7c75..d94c6b83f1 100644 --- a/base/steer/FairRunSim.cxx +++ b/base/steer/FairRunSim.cxx @@ -11,355 +11,348 @@ #include "FairRunSim.h" -#include "FairBaseParSet.h" // for FairBaseParSet -#include "FairGeoParSet.h" // for FairGeoParSet -#include "FairField.h" // for FairField -#include "FairFileHeader.h" // for FairFileHeader -#include "FairGeoInterface.h" // for FairGeoInterface -#include "FairGeoLoader.h" // for FairGeoLoader -#include "FairLogger.h" // for FairLogger, MESSAGE_ORIGIN -#include "FairMCEventHeader.h" // for FairMCEventHeader -#include "FairMesh.h" // for FairMesh -#include "FairModule.h" // for FairModule -#include "FairParSet.h" // for FairParSet -#include "FairPrimaryGenerator.h" // for FairPrimaryGenerator -#include "FairRootManager.h" // for FairRootManager -#include "FairRunIdGenerator.h" // for FairRunIdGenerator -#include "FairRuntimeDb.h" // for FairRuntimeDb -#include "FairGenericVMCConfig.h" // for FairGenericVMCConfig -#include "FairTask.h" // for FairTask -#include "FairTrajFilter.h" // for FairTrajFilter - -#include // for TIter -#include // for gGeoManager -#include // for TList -#include // for TObjString -#include // for TObject -#include // for TSystem, gSystem -#include // for gRandom - -#include // for getenv, nullptr -#include // for strcmp, strncmp -#include // for cout, endl, ostream +#include "FairBaseParSet.h" // for FairBaseParSet +#include "FairField.h" // for FairField +#include "FairFileHeader.h" // for FairFileHeader +#include "FairGenericVMCConfig.h" // for FairGenericVMCConfig +#include "FairGeoInterface.h" // for FairGeoInterface +#include "FairGeoLoader.h" // for FairGeoLoader +#include "FairGeoParSet.h" // for FairGeoParSet +#include "FairLogger.h" // for FairLogger, MESSAGE_ORIGIN +#include "FairMCEventHeader.h" // for FairMCEventHeader +#include "FairMesh.h" // for FairMesh +#include "FairModule.h" // for FairModule +#include "FairParSet.h" // for FairParSet +#include "FairPrimaryGenerator.h" // for FairPrimaryGenerator +#include "FairRootManager.h" // for FairRootManager +#include "FairRunIdGenerator.h" // for FairRunIdGenerator +#include "FairRuntimeDb.h" // for FairRuntimeDb +#include "FairTask.h" // for FairTask +#include "FairTrajFilter.h" // for FairTrajFilter + +#include // for TIter +#include // for gGeoManager +#include // for TList +#include // for TObjString +#include // for TObject +#include // for gRandom +#include // for TSystem, gSystem +#include // for cout, endl, ostream +#include // for getenv, nullptr +#include // for strcmp, strncmp using std::cout; using std::endl; -ClassImp(FairRunSim) +ClassImp(FairRunSim); FairRunSim::FairRunSim(Bool_t isMaster) - :FairRun(isMaster), - count(0), - fApp(nullptr), - fBeamMom(0), - fUseBeamMom(kFALSE), - fGen(nullptr), - fMCEvHead(nullptr), - fField(nullptr), - fMapName(""), - fIons(new TObjArray()), - fParticles( new TObjArray()), - ListOfModules(new TObjArray()), - MatFname(""), - fStoreTraj( kFALSE), - fLoaderName( new TString("TGeo")), - fPythiaDecayer(kFALSE), - fPythiaDecayerConfig(""), - fUserDecay(kFALSE), - fUserDecayConfig(""), - fRadLength(kFALSE), - fRadMap(kFALSE), - fRadGrid(kFALSE), - fMeshList( new TObjArray() ), - fSimulationConfig(nullptr), - fUserConfig(""), - fUserCuts("SetCuts.C"), - fIsMT(kFALSE), - fImportTGeoToVMC(kTRUE) + : FairRun(isMaster) + , count(0) + , fApp(nullptr) + , fBeamMom(0) + , fUseBeamMom(kFALSE) + , fGen(nullptr) + , fMCEvHead(nullptr) + , fField(nullptr) + , fMapName("") + , fIons(new TObjArray()) + , fParticles(new TObjArray()) + , ListOfModules(new TObjArray()) + , MatFname("") + , fStoreTraj(kFALSE) + , fLoaderName(new TString("TGeo")) + , fPythiaDecayer(kFALSE) + , fPythiaDecayerConfig("") + , fUserDecay(kFALSE) + , fUserDecayConfig("") + , fRadLength(kFALSE) + , fRadMap(kFALSE) + , fRadGrid(kFALSE) + , fMeshList(new TObjArray()) + , fSimulationConfig(nullptr) + , fUserConfig("") + , fUserCuts("SetCuts.C") + , fIsMT(kFALSE) + , fImportTGeoToVMC(kTRUE) { - if (fginstance) { - Fatal("FairRun", "Singleton instance already exists."); - return; - } - fginstance=this; - fRunId=0; - fAna=kFALSE; + if (fginstance) { + Fatal("FairRun", "Singleton instance already exists."); + return; + } + fginstance = this; + fRunId = 0; + fAna = kFALSE; } FairRunSim::~FairRunSim() { - LOG(debug) << "Enter Destructor of FairRunSim "; + LOG(debug) << "Enter Destructor of FairRunSim "; - // delete fApp; + // delete fApp; - /** List of Modules is filled via AddModule from the macro, but it + /** List of Modules is filled via AddModule from the macro, but it is the responsibility of FairRunSim to call the destructors of the modules- */ - LOG(debug) << "Start deleting all registered modules" ; - ListOfModules->Delete(); - delete ListOfModules; - LOG(debug) << "Finish deleting all registered modules"; - - fIons->Delete(); - delete fIons; - fParticles->Delete(); - delete fParticles; - - delete fApp; - // delete fField; - // Not owner of the field - delete fGen; - delete fMCEvHead; + LOG(debug) << "Start deleting all registered modules"; + ListOfModules->Delete(); + delete ListOfModules; + LOG(debug) << "Finish deleting all registered modules"; + + fIons->Delete(); + delete fIons; + fParticles->Delete(); + delete fParticles; + + delete fApp; + // delete fField; + // Not owner of the field + delete fGen; + delete fMCEvHead; } -FairRunSim* FairRunSim::Instance() -{ - return fginstance; -} +FairRunSim* FairRunSim::Instance() { return fginstance; } -void FairRunSim::AddModule (FairModule* Mod) +void FairRunSim::AddModule(FairModule* Mod) { - ListOfModules->Add(Mod); - Mod->SetModId(count++); + ListOfModules->Add(Mod); + Mod->SetModId(count++); } -void FairRunSim::AddMesh (FairMesh* Mesh) +void FairRunSim::AddMesh(FairMesh* Mesh) { - Mesh->print(); - Mesh->calculate(); - fMeshList->Add(Mesh); + Mesh->print(); + Mesh->calculate(); + fMeshList->Add(Mesh); } TObjArray* FairRunSim::GetUserDefIons() { - /** return the array of user defined ions*/ - return fIons; + /** return the array of user defined ions*/ + return fIons; } TObjArray* FairRunSim::GetUserDefParticles() { - /** return the array of user defined particles*/ - return fParticles; + /** return the array of user defined particles*/ + return fParticles; } void FairRunSim::Init() { - /**Initialize the simulation session*/ - fRootManager->InitSink(); - - CheckFlukaExec(); - -// fOutFile=fRootManager->OpenOutFile(fOutname); - LOG(info) << "============== FairRunSim: Initialising simulation run =============="; - - FairGeoLoader* loader=new FairGeoLoader(fLoaderName->Data(), "Geo Loader"); - FairGeoInterface* GeoInterFace=loader->getGeoInterface(); - GeoInterFace->SetNoOfSets(ListOfModules->GetEntries()); - GeoInterFace->setMediaFile(MatFname.Data()); - GeoInterFace->readMedia(); - - // gSystem->cd(flout.Data()); - - fApp= new FairMCApplication("Fair","The Fair VMC App",ListOfModules, MatFname); - fApp->SetGenerator(fGen); - - // Add a Generated run ID to the FairRunTimeDb - if ( fRunId == 0 ) { - FairRunIdGenerator genid; - // FairRuntimeDb *rtdb= GetRuntimeDb(); - fRunId = genid.generateId(); - } - fRtdb->addRun(fRunId); - - fFileHeader->SetRunId(fRunId); - /** Add Tasks to simulation if any*/ - fApp->AddTask(fTask); - /** This call will create the container if it does not exist*/ - FairBaseParSet* par=dynamic_cast(fRtdb->getContainer("FairBaseParSet")); - if (par) { - par->SetDetList(GetListOfModules()); - par->SetGen(GetPrimaryGenerator()); - par->SetBeamMom(fBeamMom); - } - - /** This call will create the container if it does not exist*/ - FairGeoParSet* geopar=dynamic_cast(fRtdb->getContainer("FairGeoParSet")); - if (geopar) { - geopar->SetGeometry(gGeoManager); - } - - // Set global Parameter Info - - if(fPythiaDecayer) { - fApp->SetPythiaDecayer(fPythiaDecayer); - if (fPythiaDecayerConfig) { - fApp->SetPythiaDecayerConfig(fPythiaDecayerConfig); + /**Initialize the simulation session*/ + fRootManager->InitSink(); + + CheckFlukaExec(); + + // fOutFile=fRootManager->OpenOutFile(fOutname); + LOG(info) << "============== FairRunSim: Initialising simulation run =============="; + + FairGeoLoader* loader = new FairGeoLoader(fLoaderName->Data(), "Geo Loader"); + FairGeoInterface* GeoInterFace = loader->getGeoInterface(); + GeoInterFace->SetNoOfSets(ListOfModules->GetEntries()); + GeoInterFace->setMediaFile(MatFname.Data()); + GeoInterFace->readMedia(); + + // gSystem->cd(flout.Data()); + + fApp = new FairMCApplication("Fair", "The Fair VMC App", ListOfModules, MatFname); + fApp->SetGenerator(fGen); + + // Add a Generated run ID to the FairRunTimeDb + if (fRunId == 0) { + FairRunIdGenerator genid; + // FairRuntimeDb *rtdb= GetRuntimeDb(); + fRunId = genid.generateId(); + } + fRtdb->addRun(fRunId); + + fFileHeader->SetRunId(fRunId); + /** Add Tasks to simulation if any*/ + fApp->AddTask(fTask); + /** This call will create the container if it does not exist*/ + FairBaseParSet* par = dynamic_cast(fRtdb->getContainer("FairBaseParSet")); + if (par) { + par->SetDetList(GetListOfModules()); + par->SetGen(GetPrimaryGenerator()); + par->SetBeamMom(fBeamMom); + } + + /** This call will create the container if it does not exist*/ + FairGeoParSet* geopar = dynamic_cast(fRtdb->getContainer("FairGeoParSet")); + if (geopar) { + geopar->SetGeometry(gGeoManager); + } + + // Set global Parameter Info + + if (fPythiaDecayer) { + fApp->SetPythiaDecayer(fPythiaDecayer); + if (fPythiaDecayerConfig) { + fApp->SetPythiaDecayerConfig(fPythiaDecayerConfig); + } + } + if (fUserDecay) { + fApp->SetUserDecay(fUserDecay); + if (fUserDecayConfig) { + fApp->SetUserDecayConfig(fUserDecayConfig); + } + } + // on/off visualisation + if (fStoreTraj) { + LOG(info) << "Create visualisation manager "; + new FairTrajFilter(); + } + if (fRadLength) { + fApp->SetRadiationLengthReg(fRadLength); + } + if (fRadMap) { + fApp->SetRadiationMapReg(fRadMap); + } + if (fRadGrid) { + fApp->AddMeshList(fMeshList); + } + + if (fField) { + fField->Init(); } - } - if(fUserDecay) { - fApp->SetUserDecay(fUserDecay); - if (fUserDecayConfig) { - fApp->SetUserDecayConfig(fUserDecayConfig); + fApp->SetField(fField); + SetFieldContainer(); + + TList* containerList = fRtdb->getListOfContainers(); + TIter next(containerList); + FairParSet* cont; + TObjArray* ContList = new TObjArray(); + while ((cont = dynamic_cast(next()))) { + ContList->Add(new TObjString(cont->GetName())); } - } - // on/off visualisation - if( fStoreTraj ) { - LOG(info) << "Create visualisation manager "; - new FairTrajFilter(); - } - if(fRadLength) { - fApp->SetRadiationLengthReg(fRadLength); - } - if(fRadMap) { - fApp->SetRadiationMapReg(fRadMap); - } - if(fRadGrid) { - fApp->AddMeshList(fMeshList); - } - - if(fField) { fField->Init(); } - fApp->SetField(fField); - SetFieldContainer(); - - TList* containerList=fRtdb->getListOfContainers(); - TIter next(containerList); - FairParSet* cont; - TObjArray* ContList= new TObjArray(); - while ((cont=dynamic_cast(next()))) { - ContList->Add(new TObjString(cont->GetName())); - } - if(par){ - par->SetContListStr(ContList); - par->SetRndSeed(gRandom->GetSeed()); - par->setChanged(); - par->setInputVersion(fRunId,1); - } - if(geopar){ - geopar->setChanged(); - geopar->setInputVersion(fRunId,1); - } - - /**Set the configuration for MC engine*/ - SetMCConfig(); - fRootManager->WriteFileHeader(fFileHeader); + if (par) { + par->SetContListStr(ContList); + par->SetRndSeed(gRandom->GetSeed()); + par->setChanged(); + par->setInputVersion(fRunId, 1); + } + if (geopar) { + geopar->setChanged(); + geopar->setInputVersion(fRunId, 1); + } + + /**Set the configuration for MC engine*/ + SetMCConfig(); + fRootManager->WriteFileHeader(fFileHeader); } void FairRunSim::SetFieldContainer() { - if (fField) { - fField->FillParContainer(); - } + if (fField) { + fField->FillParContainer(); + } } void FairRunSim::CheckFlukaExec() { - /** Private method for setting FLUKA simulation*/ - TString work = getenv("VMCWORKDIR"); - TString work_config=work+"/gconfig/"; - work_config.ReplaceAll("//","/"); - - TString config_dir= getenv("CONFIG_DIR"); - config_dir.ReplaceAll("//","/"); - if (!config_dir.EndsWith("/")) { config_dir+="/"; } - - TString flout; - if(strcmp(GetName(),"TFluka") == 0 ) { - TString flexec="run_fluka.sh"; - if (TString(gSystem->FindFile(config_dir.Data(),flexec)) != TString("")) { - LOG(info) << "---User path for Configuration is used: " - << config_dir.Data(); - } else { - flexec=work_config+"run_fluka.sh"; + /** Private method for setting FLUKA simulation*/ + TString work = getenv("VMCWORKDIR"); + TString work_config = work + "/gconfig/"; + work_config.ReplaceAll("//", "/"); + + TString config_dir = getenv("CONFIG_DIR"); + config_dir.ReplaceAll("//", "/"); + if (!config_dir.EndsWith("/")) { + config_dir += "/"; + } + + TString flout; + if (strcmp(GetName(), "TFluka") == 0) { + TString flexec = "run_fluka.sh"; + if (TString(gSystem->FindFile(config_dir.Data(), flexec)) != TString("")) { + LOG(info) << "---User path for Configuration is used: " << config_dir.Data(); + } else { + flexec = work_config + "run_fluka.sh"; + } + gSystem->Exec(flexec.Data()); + // More generic for different macro + // dir layout + TString macrodir = getenv("PWD"); + cout << macrodir << endl; + flout = macrodir + "/fluka_out"; + flout.ReplaceAll("//", "/"); + gSystem->cd(flout.Data()); } - gSystem->Exec(flexec.Data()); - // More generic for different macro - // dir layout - TString macrodir = getenv("PWD"); - cout << macrodir << endl; - flout = macrodir + "/fluka_out" ; - flout.ReplaceAll("//","/"); - gSystem->cd(flout.Data()); - } } void FairRunSim::SetMCConfig() { - // Either setup the simulation with the provided user hook - if (fUseSimSetupFunction) { - fSimSetup(); - } - else { - if ( fSimulationConfig == nullptr ) // RKRKRK COMMENT - fSimulationConfig = new FairGenericVMCConfig(); - fSimulationConfig->Setup(GetName()); - } - - fApp->InitMC("foo", "bar"); -} + // Either setup the simulation with the provided user hook + if (fUseSimSetupFunction) { + fSimSetup(); + } else { + if (fSimulationConfig == nullptr) // RKRKRK COMMENT + fSimulationConfig = new FairGenericVMCConfig(); + fSimulationConfig->Setup(GetName()); + } -void FairRunSim::Run(Int_t NEvents, Int_t) -{ - fApp->RunMC(NEvents); + fApp->InitMC("foo", "bar"); } -void FairRunSim::SetField(FairField* field) -{ - fField=field; -} +void FairRunSim::Run(Int_t NEvents, Int_t) { fApp->RunMC(NEvents); } -void FairRunSim::SetGenerator(FairPrimaryGenerator* Gen) -{ - fGen=Gen; -} +void FairRunSim::SetField(FairField* field) { fField = field; } + +void FairRunSim::SetGenerator(FairPrimaryGenerator* Gen) { fGen = Gen; } void FairRunSim::SetMaterials(const char* MatFileName) { - TString Mat=""; - TString work = getenv("GEOMPATH"); - work.ReplaceAll("//","/"); - if (work.IsNull()) { - work = getenv("VMCWORKDIR"); - Mat=work+"/geometry/"; - Mat.ReplaceAll("//","/"); - } else { - Mat=work; - if (!Mat.EndsWith("/")) { Mat+="/"; } - } - MatFname=Mat+MatFileName; - LOG(info) << "Media file used: " << MatFname.Data(); + TString Mat = ""; + TString work = getenv("GEOMPATH"); + work.ReplaceAll("//", "/"); + if (work.IsNull()) { + work = getenv("VMCWORKDIR"); + Mat = work + "/geometry/"; + Mat.ReplaceAll("//", "/"); + } else { + Mat = work; + if (!Mat.EndsWith("/")) { + Mat += "/"; + } + } + MatFname = Mat + MatFileName; + LOG(info) << "Media file used: " << MatFname.Data(); } -void FairRunSim::SetGeoModel( char* name ) +void FairRunSim::SetGeoModel(char* name) { - if ( strncmp(fName,"TGeant3",7) == 0 ) { - delete fLoaderName; - fLoaderName = new TString(name); - LOG(info) << "FairRun::SetGeoModel(): G3 native geometry model used "; - } else { - LOG(info) << "FairRun::SetGeoModel(): Geant3 MC engine only !"; - LOG(info) << "FairRun::SetGeoModel(): Method skipped ... "; - } + if (strncmp(fName, "TGeant3", 7) == 0) { + delete fLoaderName; + fLoaderName = new TString(name); + LOG(info) << "FairRun::SetGeoModel(): G3 native geometry model used "; + } else { + LOG(info) << "FairRun::SetGeoModel(): Geant3 MC engine only !"; + LOG(info) << "FairRun::SetGeoModel(): Method skipped ... "; + } } -void FairRunSim::SetPythiaDecayer(const TString& Config ) +void FairRunSim::SetPythiaDecayer(const TString& Config) { - /**switch On external decayer (Pythia). Config macro will be used */ - fPythiaDecayerConfig = Config; - fPythiaDecayer =kTRUE; + /**switch On external decayer (Pythia). Config macro will be used */ + fPythiaDecayerConfig = Config; + fPythiaDecayer = kTRUE; } -void FairRunSim::SetUserDecay(const TString& Config) +void FairRunSim::SetUserDecay(const TString& Config) { - /**switch On user defined decay, Config macro will be called */ - fUserDecayConfig = Config; - fUserDecay = kTRUE; + /**switch On user defined decay, Config macro will be called */ + fUserDecayConfig = Config; + fUserDecay = kTRUE; } -FairMCEventHeader* FairRunSim::GetMCEventHeader() +FairMCEventHeader* FairRunSim::GetMCEventHeader() { - if ( nullptr == fMCEvHead ) { fMCEvHead = new FairMCEventHeader(); } - return fMCEvHead; + if (nullptr == fMCEvHead) { + fMCEvHead = new FairMCEventHeader(); + } + return fMCEvHead; } -TMCThreadLocal FairRunSim* FairRunSim::fginstance= 0; +TMCThreadLocal FairRunSim* FairRunSim::fginstance = 0; diff --git a/base/steer/FairRunSim.h b/base/steer/FairRunSim.h index 99c4b88954..339dfabf36 100644 --- a/base/steer/FairRunSim.h +++ b/base/steer/FairRunSim.h @@ -8,17 +8,15 @@ #ifndef FAIRRUNSIM_H #define FAIRRUNSIM_H -#include "FairRun.h" // for FairRun - -#include "FairIon.h" // for FairIon -#include "FairMCApplication.h" // for FairMCApplication -#include "FairParticle.h" // for FairParticle - -#include // for Bool_t, Double_t, Int_t, etc -#include // for TObjArray -#include // for TString -#include // for multi-threading - +#include "FairIon.h" // for FairIon +#include "FairMCApplication.h" // for FairMCApplication +#include "FairParticle.h" // for FairParticle +#include "FairRun.h" // for FairRun + +#include // for Bool_t, Double_t, Int_t, etc +#include // for multi-threading +#include // for TObjArray +#include // for TString #include class FairField; @@ -45,125 +43,138 @@ class FairRunSim : public FairRun static FairRunSim* Instance(); /** * Add a module to the simulation (e.g. PIPE, Magnet, ..etc) - */ - void AddModule (FairModule* Mod); + */ + void AddModule(FairModule* Mod); /** * Add a user defined ion to the simulation - */ - void AddNewIon(FairIon* ion) {fIons->Add(ion);} + */ + void AddNewIon(FairIon* ion) { fIons->Add(ion); } /** * Add a user defined ion to the simulation - */ - void AddNewParticle(FairParticle* Particle) {fParticles->Add(Particle);} + */ + void AddNewParticle(FairParticle* Particle) { fParticles->Add(Particle); } /** * this method is used by the FAIRMCApplication - */ - TObjArray* GetUserDefIons(); + */ + TObjArray* GetUserDefIons(); /** * this method is used by the FAIRMCApplication - */ - TObjArray* GetUserDefParticles(); + */ + TObjArray* GetUserDefParticles(); /** - * Initialize the Simulation - */ - virtual void Init(); + * Initialize the Simulation + */ + virtual void Init(); /** - * run the simulation - */ - virtual void Run(Int_t NEvents =0, Int_t NotUsed=0); + * run the simulation + */ + virtual void Run(Int_t NEvents = 0, Int_t NotUsed = 0); /** - * Set the magnetic that has to be used for simulation field - */ - void SetField(FairField* field); + * Set the magnetic that has to be used for simulation field + */ + void SetField(FairField* field); /** * Set the event generator that has to be used for simulation field - */ - void SetGenerator(FairPrimaryGenerator* Gen); + */ + void SetGenerator(FairPrimaryGenerator* Gen); /** * Set the experiment dependent event header * for each Monte Carlo Event */ - void SetMCEventHeader(FairMCEventHeader* McHeader) {fMCEvHead=McHeader;} + void SetMCEventHeader(FairMCEventHeader* McHeader) { fMCEvHead = McHeader; } /** Set the material file name to be used */ - void SetMaterials(const char* MatFileName); + void SetMaterials(const char* MatFileName); /**switch On/Off the track visualisation */ - void SetStoreTraj(Bool_t storeTraj=kTRUE) {fStoreTraj = storeTraj;} + void SetStoreTraj(Bool_t storeTraj = kTRUE) { fStoreTraj = storeTraj; } /**Return the switch for the track visualisation */ - Bool_t GetStoreTraj() const {return fStoreTraj;} + Bool_t GetStoreTraj() const { return fStoreTraj; } /**switch On/Off the debug mode */ - void SetTrackingDebugMode( Bool_t set ) { if (fApp) { fApp->SetTrackingDebugMode( set ); } } + void SetTrackingDebugMode(Bool_t set) + { + if (fApp) { + fApp->SetTrackingDebugMode(set); + } + } /**Set geometry builder*/ - void SetGeoModel( char* name ); + void SetGeoModel(char* name); /**return the geometry loader used in this session*/ - TString* GetGeoModel () { return fLoaderName; } + TString* GetGeoModel() { return fLoaderName; } /**Get the field used in simulation*/ - FairField* GetField() { return fField;} + FairField* GetField() { return fField; } /**Get the detector specific event header*/ - FairMCEventHeader* GetMCEventHeader(); + FairMCEventHeader* GetMCEventHeader(); /**return the full list of modules used in simulation*/ - TObjArray* GetListOfModules() { return ListOfModules;} + TObjArray* GetListOfModules() { return ListOfModules; } /**Get the used primary generator*/ - FairPrimaryGenerator* GetPrimaryGenerator() { return fGen;} + FairPrimaryGenerator* GetPrimaryGenerator() { return fGen; } /**switch On/Off external decayer (Pythia) */ - void SetPythiaDecayer(Bool_t decayer) {fPythiaDecayer = decayer;} + void SetPythiaDecayer(Bool_t decayer) { fPythiaDecayer = decayer; } /**switch On external decayer (Pythia). Config macro will be used */ - void SetPythiaDecayer(const TString& Config ); + void SetPythiaDecayer(const TString& Config); /**switch On user defined decay, Config macro will be called */ void SetUserDecay(const TString& Config); /**switch On/Off user defined decay if true gconfig/UserDecay.C macro will be called */ - void SetUserDecay(Bool_t decay) {fUserDecay = decay;} + void SetUserDecay(Bool_t decay) { fUserDecay = decay; } /**Flag for external decayer*/ - Bool_t IsExtDecayer() {return fPythiaDecayer; } + Bool_t IsExtDecayer() { return fPythiaDecayer; } /**Flag for User decay*/ - Bool_t IsUserDecay() {return fUserDecay; } + Bool_t IsUserDecay() { return fUserDecay; } /**Switch on/off Radiation length register */ - void SetRadLenRegister(Bool_t value) {fRadLength= value;} + void SetRadLenRegister(Bool_t value) { fRadLength = value; } - void SetRadMapRegister(Bool_t value) { fRadMap=value; } + void SetRadMapRegister(Bool_t value) { fRadMap = value; } - void SetRadGridRegister(Bool_t value) {fRadGrid= value;} + void SetRadGridRegister(Bool_t value) { fRadGrid = value; } - void AddMesh (FairMesh* Mesh); + void AddMesh(FairMesh* Mesh); - void SetUserConfig(const TString& Config) {fUserConfig = Config;} - TString GetUserConfig() {return fUserConfig;} + void SetUserConfig(const TString& Config) { fUserConfig = Config; } + TString GetUserConfig() { return fUserConfig; } - void SetUserCuts(const TString& Cuts) {fUserCuts= Cuts;} - TString GetUserCuts() {return fUserCuts;} + void SetUserCuts(const TString& Cuts) { fUserCuts = Cuts; } + TString GetUserCuts() { return fUserCuts; } /** Set Beam energy in GeV/c */ - void SetBeamMom(Double_t BeamMom) { fBeamMom= BeamMom; fUseBeamMom=kTRUE;} + void SetBeamMom(Double_t BeamMom) + { + fBeamMom = BeamMom; + fUseBeamMom = kTRUE; + } /** Get the Beam energy */ - Double_t GetBeamMom() {return fBeamMom;} + Double_t GetBeamMom() { return fBeamMom; } /**Get beam energy flag */ - Bool_t UseBeamMom() {return fUseBeamMom;} + Bool_t UseBeamMom() { return fUseBeamMom; } void SetFieldContainer(); - void SetSimSetup(std::function f) { fSimSetup = f; fUseSimSetupFunction = true; } + void SetSimSetup(std::function f) + { + fSimSetup = f; + fUseSimSetupFunction = true; + } void SetSimulationConfig(FairGenericVMCConfig* tconf) { fSimulationConfig = tconf; } - FairGenericVMCConfig* GetSimulationConfig() { return fSimulationConfig; } + FairGenericVMCConfig* GetSimulationConfig() { return fSimulationConfig; } void SetIsMT(Bool_t isMT) { fIsMT = isMT; } Bool_t IsMT() const { return fIsMT; } @@ -172,45 +183,47 @@ class FairRunSim : public FairRun Bool_t IsImportTGeoToVMC() const { return fImportTGeoToVMC; } void StopMCRun() { fApp->StopMCRun(); } + private: FairRunSim(const FairRunSim& M); - FairRunSim& operator= (const FairRunSim&) {return *this;} + FairRunSim& operator=(const FairRunSim&) { return *this; } void SetMCConfig(); void CheckFlukaExec(); protected: - Int_t count;//! /** Internal counter*/ - FairMCApplication* fApp; //! /** Main VMC application */ - Double_t fBeamMom; //! /** Beam Energy in GeV/c */ - Bool_t fUseBeamMom; //! /** flag for use Beam Energy */ - FairPrimaryGenerator* fGen; //! /** Primary Event Generator */ - FairMCEventHeader* fMCEvHead; //! /** MC Event Header */ - static TMCThreadLocal FairRunSim* fginstance;//! /** Singleton Instance */ - FairField* fField; /** Magnetic Field */ - const char* fMapName; //! /** Input file name map*/ - TObjArray* fIons; //! /** Array of user defined ions */ - TObjArray* fParticles; //! /** Array of user defined particles*/ - TObjArray* ListOfModules;//! /** Array of used modules */ - TString MatFname; //! /** Material file name */ - Bool_t fStoreTraj; //! /** Trajectory store flags */ - TString* fLoaderName; //! /** Geometry Model (TGeo or G3)*/ - Bool_t fPythiaDecayer; //! /** flag for using Pythia decayer*/ - TString fPythiaDecayerConfig; //! /** Macro for Pythia decay configuration*/ - Bool_t fUserDecay; /** flag for setting user decay */ - TString fUserDecayConfig; //! /** Macro for decay configuration*/ - Bool_t fRadLength; //! /** flag for registring radiation length*/ - Bool_t fRadMap; //! /** flag for RadiationMapManager - Bool_t fRadGrid; //! - TObjArray* fMeshList; //! /** radiation grid scoring - TString fUserConfig; //! /** Macro for geant configuration*/ - TString fUserCuts; //! /** Macro for geant cuts*/ - Bool_t fIsMT; //! /** MT mode option (Geant4 only)*/ - Bool_t fImportTGeoToVMC; //! /** Allow importing TGeometry to VMC */ - std::function fSimSetup; //! /** A user provided function to do sim setup / instead of using macros **/ - bool fUseSimSetupFunction = false; - FairGenericVMCConfig* fSimulationConfig; //! /** Simulation configuration */ - - ClassDef(FairRunSim ,2) + Int_t count; //! /** Internal counter*/ + FairMCApplication* fApp; //! /** Main VMC application */ + Double_t fBeamMom; //! /** Beam Energy in GeV/c */ + Bool_t fUseBeamMom; //! /** flag for use Beam Energy */ + FairPrimaryGenerator* fGen; //! /** Primary Event Generator */ + FairMCEventHeader* fMCEvHead; //! /** MC Event Header */ + static TMCThreadLocal FairRunSim* fginstance; //! /** Singleton Instance */ + FairField* fField; /** Magnetic Field */ + const char* fMapName; //! /** Input file name map*/ + TObjArray* fIons; //! /** Array of user defined ions */ + TObjArray* fParticles; //! /** Array of user defined particles*/ + TObjArray* ListOfModules; //! /** Array of used modules */ + TString MatFname; //! /** Material file name */ + Bool_t fStoreTraj; //! /** Trajectory store flags */ + TString* fLoaderName; //! /** Geometry Model (TGeo or G3)*/ + Bool_t fPythiaDecayer; //! /** flag for using Pythia decayer*/ + TString fPythiaDecayerConfig; //! /** Macro for Pythia decay configuration*/ + Bool_t fUserDecay; /** flag for setting user decay */ + TString fUserDecayConfig; //! /** Macro for decay configuration*/ + Bool_t fRadLength; //! /** flag for registring radiation length*/ + Bool_t fRadMap; //! /** flag for RadiationMapManager + Bool_t fRadGrid; //! + TObjArray* fMeshList; //! /** radiation grid scoring + TString fUserConfig; //! /** Macro for geant configuration*/ + TString fUserCuts; //! /** Macro for geant cuts*/ + Bool_t fIsMT; //! /** MT mode option (Geant4 only)*/ + Bool_t fImportTGeoToVMC; //! /** Allow importing TGeometry to VMC */ + std::function fSimSetup; //! /** A user provided function to do sim setup / + //! instead of using macros **/ + bool fUseSimSetupFunction = false; + FairGenericVMCConfig* fSimulationConfig; //! /** Simulation configuration */ + + ClassDef(FairRunSim, 2) }; -#endif //FAIRRUNSIM_H +#endif // FAIRRUNSIM_H diff --git a/base/steer/FairTSBufferFunctional.cxx b/base/steer/FairTSBufferFunctional.cxx index 5133efed62..22c2463b2c 100644 --- a/base/steer/FairTSBufferFunctional.cxx +++ b/base/steer/FairTSBufferFunctional.cxx @@ -7,269 +7,288 @@ ********************************************************************************/ #include "FairTSBufferFunctional.h" -#include "FairLink.h" // for FairLink -#include "FairRootManager.h" // for FairRootManager -#include "FairTimeStamp.h" // for FairTimeStamp +#include "FairLink.h" // for FairLink +#include "FairRootManager.h" // for FairRootManager +#include "FairTimeStamp.h" // for FairTimeStamp -#include // for TBranch -#include // for TClass -#include // for TClonesArray -#include // for TTree +#include // for TBranch +#include // for TClass +#include // for TClonesArray +#include // for TTree ClassImp(FairTSBufferFunctional); -FairTSBufferFunctional::FairTSBufferFunctional(TString branchName, TTree* sourceTree, BinaryFunctor* stopFunction, BinaryFunctor* startFunction) - :TObject(), - fOutputArray(nullptr), - fBufferArray(nullptr), - fInputArray(nullptr), - fStartFunction(startFunction), - fStopFunction (stopFunction), - fBranch(nullptr), - fBranchIndex(-1), - fTerminate(kFALSE), - fVerbose(0) +FairTSBufferFunctional::FairTSBufferFunctional(TString branchName, + TTree* sourceTree, + BinaryFunctor* stopFunction, + BinaryFunctor* startFunction) + : TObject() + , fOutputArray(nullptr) + , fBufferArray(nullptr) + , fInputArray(nullptr) + , fStartFunction(startFunction) + , fStopFunction(stopFunction) + , fBranch(nullptr) + , fBranchIndex(-1) + , fTerminate(kFALSE) + , fVerbose(0) { - fBranch = sourceTree->GetBranch(branchName.Data()); - if (fBranch == 0) { - std::cout << "-E- FairTSBufferFunctional::FairTSBufferFunctional Branch " << branchName << " does not exist!" << std::endl; - } - FairRootManager* ioman = FairRootManager::Instance(); - fInputArray = static_cast(ioman->GetObject(branchName.Data())); - fBufferArray = new TClonesArray(fInputArray->GetClass()->GetName()); - fOutputArray = new TClonesArray(fInputArray->GetClass()->GetName()); - + fBranch = sourceTree->GetBranch(branchName.Data()); + if (fBranch == 0) { + std::cout << "-E- FairTSBufferFunctional::FairTSBufferFunctional Branch " << branchName << " does not exist!" + << std::endl; + } + FairRootManager* ioman = FairRootManager::Instance(); + fInputArray = static_cast(ioman->GetObject(branchName.Data())); + fBufferArray = new TClonesArray(fInputArray->GetClass()->GetName()); + fOutputArray = new TClonesArray(fInputArray->GetClass()->GetName()); } TClonesArray* FairTSBufferFunctional::GetData(Double_t stopParameter) { - Double_t actualTime = 0.; - int posBuffer = 0; - - if (fStopFunction == 0) { //no function is given ==> read in data in traditional way event by event - ReadInNextEntry(); - fOutputArray->AbsorbObjects(static_cast(fInputArray), 0, fInputArray->GetEntriesFast() - 1); - return fOutputArray; - } - if (fVerbose > 1) { - std::cout << "-I- FairTSBufferFunctional::GetData for stopParameter: " << stopParameter << std::endl; - } + Double_t actualTime = 0.; + int posBuffer = 0; - //if the BufferArray is empty fill it - if (fBufferArray->GetEntriesFast() == 0) { + if (fStopFunction == 0) { // no function is given ==> read in data in traditional way event by event + ReadInNextEntry(); + fOutputArray->AbsorbObjects(static_cast(fInputArray), 0, fInputArray->GetEntriesFast() - 1); + return fOutputArray; + } if (fVerbose > 1) { - std::cout << "-I- FairTSBufferFunctional::GetData fBufferArray is empty: Read in Data" << std::endl; + std::cout << "-I- FairTSBufferFunctional::GetData for stopParameter: " << stopParameter << std::endl; } - ReadInNextFilledEntry(); - AbsorbDataBufferArray(); - } - //if the BufferArray is still empty you have reached the end of your data set - if (fVerbose > 1) { - std::cout << "-I- FairTSBufferFunctional::GetData fBufferArray->GetEntriesFast(): " << fBufferArray->GetEntriesFast() << std::endl; - } - FairTimeStamp* dataPoint = static_cast(fBufferArray->Last()); - if (dataPoint == 0) { - if (fVerbose > 0) { - std::cout << "-I- FairTSBufferFunctional::GetData dataPoint is empty ==> All Data read in" << std::endl; + // if the BufferArray is empty fill it + if (fBufferArray->GetEntriesFast() == 0) { + if (fVerbose > 1) { + std::cout << "-I- FairTSBufferFunctional::GetData fBufferArray is empty: Read in Data" << std::endl; + } + ReadInNextFilledEntry(); + AbsorbDataBufferArray(); + } + + // if the BufferArray is still empty you have reached the end of your data set + if (fVerbose > 1) { + std::cout << "-I- FairTSBufferFunctional::GetData fBufferArray->GetEntriesFast(): " + << fBufferArray->GetEntriesFast() << std::endl; + } + FairTimeStamp* dataPoint = static_cast(fBufferArray->Last()); + if (dataPoint == 0) { + if (fVerbose > 0) { + std::cout << "-I- FairTSBufferFunctional::GetData dataPoint is empty ==> All Data read in" << std::endl; + } + return fOutputArray; } - return fOutputArray; - } - dataPoint = static_cast(fBufferArray->First()); + dataPoint = static_cast(fBufferArray->First()); - while (!(*fStopFunction)(dataPoint, stopParameter)) { //check if you have reached end of requested data - posBuffer++; - //if you have reached the end of the BufferArray fill it with new data from tree - if (posBuffer == fBufferArray->GetEntriesFast()) { - ReadInNextFilledEntry(); - AbsorbDataBufferArray(); + while (!(*fStopFunction)(dataPoint, stopParameter)) { // check if you have reached end of requested data + posBuffer++; + // if you have reached the end of the BufferArray fill it with new data from tree + if (posBuffer == fBufferArray->GetEntriesFast()) { + ReadInNextFilledEntry(); + AbsorbDataBufferArray(); + } + // if you are still at the end of the BufferArray than break (no new data in tree) + if (posBuffer == fBufferArray->GetEntriesFast()) { + break; + } + dataPoint = static_cast(fBufferArray->At(posBuffer)); + if (fVerbose > 1) { + std::cout << posBuffer << " TimeStampData: " << dataPoint->GetTimeStamp() << std::endl; + } } - //if you are still at the end of the BufferArray than break (no new data in tree) - if (posBuffer == fBufferArray->GetEntriesFast()) { - break; + + if (fVerbose > 1) { + std::cout << "-I- FairTSBufferFunctional::GetData Index for Absorb: " << posBuffer + << " BufferArray size: " << fBufferArray->GetEntriesFast() << std::endl; + } + if (posBuffer < fBufferArray->GetEntriesFast() && posBuffer > 0) { + if (fVerbose > 1) { + std::cout << "-I- FairTSBufferFunctional::GetData absorb BufferArray up to posBuffer " << posBuffer + << " into fOutputArray" << std::endl; + } + fOutputArray->AbsorbObjects(fBufferArray, 0, posBuffer - 1); + posBuffer = 0; + return fOutputArray; } - dataPoint = static_cast(fBufferArray->At(posBuffer)); if (fVerbose > 1) { - std::cout << posBuffer << " TimeStampData: " << dataPoint->GetTimeStamp() << std::endl; + std::cout << "Index: " << posBuffer << " BranchIndex: " << fBranchIndex << " NBranch " << fBranch->GetEntries() + << std::endl; } - } - if (fVerbose > 1) { - std::cout << "-I- FairTSBufferFunctional::GetData Index for Absorb: " << posBuffer << " BufferArray size: " << fBufferArray->GetEntriesFast() << std::endl; - } - if (posBuffer < fBufferArray->GetEntriesFast() && posBuffer > 0) { - if (fVerbose > 1) { - std::cout << "-I- FairTSBufferFunctional::GetData absorb BufferArray up to posBuffer " << posBuffer << " into fOutputArray" << std::endl; + if (posBuffer >= fBufferArray->GetEntriesFast() && posBuffer != 0 && fBranchIndex + 1 >= fBranch->GetEntries()) { + if (fVerbose > 1) { + std::cout << "-I- FairTSBufferFunctional::GetData end of data reached. Send the rest to the OutputArray!" + << std::endl; + } + fOutputArray->AbsorbObjects(fBufferArray, 0, fBufferArray->GetEntries() - 1); } - fOutputArray->AbsorbObjects(fBufferArray, 0, posBuffer - 1); - posBuffer = 0; - return fOutputArray; - } - if (fVerbose > 1) { - std::cout << "Index: " << posBuffer << " BranchIndex: " << fBranchIndex << " NBranch " << fBranch->GetEntries() << std::endl; - } - if (posBuffer >= fBufferArray->GetEntriesFast() && posBuffer != 0 && fBranchIndex + 1 >= fBranch->GetEntries()) { if (fVerbose > 1) { - std::cout << "-I- FairTSBufferFunctional::GetData end of data reached. Send the rest to the OutputArray!" << std::endl; + std::cout << "-I- FairTSBufferFunctional::GetData: Read in up to entry: " << fBranchIndex << " with actualTime " + << actualTime << " and requested stopParameter " << stopParameter << std::endl; } - fOutputArray->AbsorbObjects(fBufferArray, 0, fBufferArray->GetEntries() - 1); - } - if (fVerbose > 1) { - std::cout << "-I- FairTSBufferFunctional::GetData: Read in up to entry: " << fBranchIndex << " with actualTime " << actualTime << " and requested stopParameter " << stopParameter << std::endl; - } - - return fOutputArray; + return fOutputArray; } TClonesArray* FairTSBufferFunctional::GetData(Double_t startParameter, Double_t stopParameter) { - if (fStartFunction != 0) { - fBufferArray->Delete(); - fOutputArray->Delete(); - Int_t startIndex = FindStartIndex(startParameter); -// std::cout << "StartParameter : " << startParameter << " StartIndex: " << startIndex << "/" << GetBranchIndex() << " size BufferArray " << fBufferArray->GetEntries() < -1) { - ReadInEntry(fBranchIndex); - fBufferArray->AbsorbObjects(fInputArray, startIndex, fInputArray->GetEntries() -1); + if (fStartFunction != 0) { + fBufferArray->Delete(); + fOutputArray->Delete(); + Int_t startIndex = FindStartIndex(startParameter); + // std::cout << "StartParameter : " << startParameter << " StartIndex: " << startIndex << "/" << + // GetBranchIndex() << " size BufferArray " << fBufferArray->GetEntries() < -1) { + ReadInEntry(fBranchIndex); + fBufferArray->AbsorbObjects(fInputArray, startIndex, fInputArray->GetEntries() - 1); + } } - } - return GetData(stopParameter); + return GetData(stopParameter); } Int_t FairTSBufferFunctional::FindStartIndex(Double_t startParameter) { - FairTimeStamp* dataPoint; - Int_t tempIndex = fBranchIndex; -// Bool_t runBackwards = kTRUE; - Int_t previousIndex = -1; - Int_t previousBranchIndex = -1; + FairTimeStamp* dataPoint; + Int_t tempIndex = fBranchIndex; + // Bool_t runBackwards = kTRUE; + Int_t previousIndex = -1; + Int_t previousBranchIndex = -1; - ReadInEntry(tempIndex); //< Get Data out of Tree + ReadInEntry(tempIndex); //< Get Data out of Tree - while (fInputArray->GetEntries() == 0 && tempIndex > 0) { //< If the entry of the tree was empty read in previous entries until you find one which is filled - tempIndex--; - ReadInEntry(tempIndex); - } + while (fInputArray->GetEntries() == 0 && tempIndex > 0) { //< If the entry of the tree was empty read in previous + // entries until you find one which is filled + tempIndex--; + ReadInEntry(tempIndex); + } - if (fInputArray->GetEntries() == 0) { //If the previous entries in the tree are also empty run in the forward direction - ReadInNextFilledEntry(); -// runBackwards = kFALSE; - } + if (fInputArray->GetEntries() + == 0) { // If the previous entries in the tree are also empty run in the forward direction + ReadInNextFilledEntry(); + // runBackwards = kFALSE; + } - if (fInputArray->GetEntries() == 0) { //If there is still no data the branch is empty! - std::cout << "-I- FairTSBufferFunctional::FindStartIndex: All entries are empty!" << std::endl; - return -1; - } - fBranchIndex = tempIndex; - //Now we have data or FindStartIndex already returned -1 + if (fInputArray->GetEntries() == 0) { // If there is still no data the branch is empty! + std::cout << "-I- FairTSBufferFunctional::FindStartIndex: All entries are empty!" << std::endl; + return -1; + } + fBranchIndex = tempIndex; + // Now we have data or FindStartIndex already returned -1 - dataPoint = static_cast(fInputArray->Last()); - //std::cout << "DataPoint: " << *dataPoint << std::endl; - while(!(*fStartFunction)(dataPoint, startParameter)) { - //std::cout << "DataPoint Search Entry: " << fBranchIndex << ": " << *dataPoint << std::endl; - ReadInNextFilledEntry(); - if (fInputArray->GetEntries() != 0) { - dataPoint = static_cast(fInputArray->Last()); - } else { - return -1; + dataPoint = static_cast(fInputArray->Last()); + // std::cout << "DataPoint: " << *dataPoint << std::endl; + while (!(*fStartFunction)(dataPoint, startParameter)) { + // std::cout << "DataPoint Search Entry: " << fBranchIndex << ": " << *dataPoint << std::endl; + ReadInNextFilledEntry(); + if (fInputArray->GetEntries() != 0) { + dataPoint = static_cast(fInputArray->Last()); + } else { + return -1; + } } - } - //Now you have data where the last element in the array does not fit to your request - Int_t startPos = fInputArray->GetEntries() - 1; - while ((*fStartFunction)(dataPoint, startParameter)) { - //std::cout << "DataPoint Search in Entry: " << fBranchIndex << ": " << *dataPoint << std::endl; - previousIndex = startPos; - previousBranchIndex = fBranchIndex; - startPos--; - if (startPos == -1) { - fBranchIndex = ReadInPreviousFilledEntry(fBranchIndex); - startPos = fInputArray->GetEntries() - 1; - if (startPos < 0) { - if (fBranchIndex == 0) { - return 0; + // Now you have data where the last element in the array does not fit to your request + Int_t startPos = fInputArray->GetEntries() - 1; + while ((*fStartFunction)(dataPoint, startParameter)) { + // std::cout << "DataPoint Search in Entry: " << fBranchIndex << ": " << *dataPoint << std::endl; + previousIndex = startPos; + previousBranchIndex = fBranchIndex; + startPos--; + if (startPos == -1) { + fBranchIndex = ReadInPreviousFilledEntry(fBranchIndex); + startPos = fInputArray->GetEntries() - 1; + if (startPos < 0) { + if (fBranchIndex == 0) { + return 0; + } + return -1; + } } - return -1; - } + dataPoint = static_cast(fInputArray->At(startPos)); } - dataPoint = static_cast(fInputArray->At(startPos)); - } - fBranchIndex = previousBranchIndex; - return previousIndex; + fBranchIndex = previousBranchIndex; + return previousIndex; } void FairTSBufferFunctional::ReadInNextFilledEntry() { - fInputArray->Delete(); + fInputArray->Delete(); - if (fVerbose > 1) { - std::cout << "-I- FairTSBufferFunctional::ReadInNextFilledEntry: Entries in InputArray " << fInputArray->GetEntriesFast() << " Branch Entries: " << fBranch->GetEntries() << std::endl; - } - while (fInputArray->GetEntriesFast() == 0 && fBranchIndex + 1 < fBranch->GetEntries()) { - fBranchIndex++; - ReadInEntry(fBranchIndex); - } + if (fVerbose > 1) { + std::cout << "-I- FairTSBufferFunctional::ReadInNextFilledEntry: Entries in InputArray " + << fInputArray->GetEntriesFast() << " Branch Entries: " << fBranch->GetEntries() << std::endl; + } + while (fInputArray->GetEntriesFast() == 0 && fBranchIndex + 1 < fBranch->GetEntries()) { + fBranchIndex++; + ReadInEntry(fBranchIndex); + } } Int_t FairTSBufferFunctional::ReadInPreviousFilledEntry(Int_t startEntry) { - Int_t tempIndex = startEntry; + Int_t tempIndex = startEntry; - fInputArray->Delete(); - while (fInputArray->GetEntriesFast() == 0 && tempIndex > 0) { - tempIndex--; - ReadInEntry(tempIndex); - } - return tempIndex; + fInputArray->Delete(); + while (fInputArray->GetEntriesFast() == 0 && tempIndex > 0) { + tempIndex--; + ReadInEntry(tempIndex); + } + return tempIndex; } void FairTSBufferFunctional::AbsorbDataBufferArray() { - if (fInputArray->GetEntriesFast() > 0) { - if (fVerbose > 1) { - std::cout << "-I- FairTSBufferFunctional::ReadInNextFilledEntry: Absorb InputArray into Buffer" << std::endl; + if (fInputArray->GetEntriesFast() > 0) { + if (fVerbose > 1) { + std::cout << "-I- FairTSBufferFunctional::ReadInNextFilledEntry: Absorb InputArray into Buffer" + << std::endl; + } + fBufferArray->AbsorbObjects(fInputArray, 0, fInputArray->GetEntries() - 1); } - fBufferArray->AbsorbObjects(fInputArray, 0, fInputArray->GetEntries() - 1); - } } void FairTSBufferFunctional::ReadInNextEntry() { - if (fBranchIndex + 1 < fBranch->GetEntries()) { - fBranchIndex++; - ReadInEntry(fBranchIndex); - } + if (fBranchIndex + 1 < fBranch->GetEntries()) { + fBranchIndex++; + ReadInEntry(fBranchIndex); + } } void FairTSBufferFunctional::ReadInEntry(Int_t number) { - fInputArray->Delete(); - if (number < fBranch->GetEntries()) { - fBranch->GetEntry(number); - for (int i = 0; i < fInputArray->GetEntriesFast(); i++) { - (static_cast( fInputArray->At(i)))->SetEntryNr(FairLink(0, number, FairRootManager::Instance()->GetBranchId(fBranch->GetName()), i, 1)); + fInputArray->Delete(); + if (number < fBranch->GetEntries()) { + fBranch->GetEntry(number); + for (int i = 0; i < fInputArray->GetEntriesFast(); i++) { + (static_cast(fInputArray->At(i))) + ->SetEntryNr(FairLink(0, number, FairRootManager::Instance()->GetBranchId(fBranch->GetName()), i, 1)); + } + if (fVerbose > 1) + std::cout << "-I- FairTSBufferFunctional::ReadInEntry BranchIndex: " << number + << " Entries: " << fInputArray->GetEntriesFast() << std::endl; } - if (fVerbose > 1) - std::cout - << "-I- FairTSBufferFunctional::ReadInEntry BranchIndex: " - << number << " Entries: " - << fInputArray->GetEntriesFast() << std::endl; - } } Bool_t FairTSBufferFunctional::AllDataProcessed() { - if (fTerminate == kTRUE){ - return kTRUE; - } - if (fBranchIndex + 1 >= fBranch->GetEntries()) { - if(fBufferArray->GetEntriesFast() == 0) { - if (fOutputArray->GetEntriesFast() == 0) { + if (fTerminate == kTRUE) { return kTRUE; - } else { return kFALSE; } - } else { return kFALSE; } - } else { return kFALSE; } + } + if (fBranchIndex + 1 >= fBranch->GetEntries()) { + if (fBufferArray->GetEntriesFast() == 0) { + if (fOutputArray->GetEntriesFast() == 0) { + return kTRUE; + } else { + return kFALSE; + } + } else { + return kFALSE; + } + } else { + return kFALSE; + } } diff --git a/base/steer/FairTSBufferFunctional.h b/base/steer/FairTSBufferFunctional.h index 70733690d0..5d27c63ed1 100644 --- a/base/steer/FairTSBufferFunctional.h +++ b/base/steer/FairTSBufferFunctional.h @@ -8,14 +8,13 @@ #ifndef FairTSBufferFunctionalFunctional_H_ #define FairTSBufferFunctionalFunctional_H_ -#include "FairTimeStamp.h" // for FairTimeStamp +#include "FairTimeStamp.h" // for FairTimeStamp -#include // for Int_t, Bool_t, Double_t, etc -#include // for TObject -#include // for TString - -#include // for binary_function -#include // for operator<<, basic_ostream, etc +#include // for Int_t, Bool_t, Double_t, etc +#include // for TObject +#include // for TString +#include // for binary_function +#include // for operator<<, basic_ostream, etc class TBranch; class TClonesArray; @@ -36,12 +35,12 @@ class TTree; class BinaryFunctor : public std::binary_function { public: - virtual bool operator() (FairTimeStamp* a, double b) {return Call(a,b);}; + virtual bool operator()(FairTimeStamp* a, double b) { return Call(a, b); }; virtual bool Call(FairTimeStamp* a, double b) = 0; - virtual bool TimeOut() {return false;} - virtual void ResetTimeOut() {}; + virtual bool TimeOut() { return false; } + virtual void ResetTimeOut(){}; - virtual ~BinaryFunctor() {}; + virtual ~BinaryFunctor(){}; }; /** @@ -53,36 +52,45 @@ class BinaryFunctor : public std::binary_function class StopTime : public BinaryFunctor { public: - StopTime():fRequestTime(-1), fOldTime(-1), fSameTimeRequestCounter(0) {}; + StopTime() + : fRequestTime(-1) + , fOldTime(-1) + , fSameTimeRequestCounter(0){}; /** * \parameter b: StopTime: All data older than StopTime is returned */ - bool Call(FairTimeStamp* a, double b) { - fRequestTime = b; - //std::cout << "StopTime: " << a->GetTimeStamp() << " > " << b << std::endl; - return a->GetTimeStamp() > b; + bool Call(FairTimeStamp* a, double b) + { + fRequestTime = b; + // std::cout << "StopTime: " << a->GetTimeStamp() << " > " << b << std::endl; + return a->GetTimeStamp() > b; }; - bool TimeOut() { - if (fRequestTime != fOldTime) { - fOldTime = fRequestTime; - fSameTimeRequestCounter = 0; - //std::cout << "RequestedTime: " << fRequestTime << std::endl; - return false; - } else if (fRequestTime == fOldTime) { - std::cout << "-I- FairTSBufferFunctional StopTime has requested the same data as before: " << fRequestTime << std::endl; - fSameTimeRequestCounter++; - } else { - std::cout << "-E- FairTSBufferFunctional StopTime Functor has requested time " << fRequestTime << " smaller than old time " << fOldTime << std::endl; - return true; - } - if (fSameTimeRequestCounter > 9) { - return true; - } else { return false; } + bool TimeOut() + { + if (fRequestTime != fOldTime) { + fOldTime = fRequestTime; + fSameTimeRequestCounter = 0; + // std::cout << "RequestedTime: " << fRequestTime << std::endl; + return false; + } else if (fRequestTime == fOldTime) { + std::cout << "-I- FairTSBufferFunctional StopTime has requested the same data as before: " << fRequestTime + << std::endl; + fSameTimeRequestCounter++; + } else { + std::cout << "-E- FairTSBufferFunctional StopTime Functor has requested time " << fRequestTime + << " smaller than old time " << fOldTime << std::endl; + return true; + } + if (fSameTimeRequestCounter > 9) { + return true; + } else { + return false; + } } - void ResetTimeOut() {fSameTimeRequestCounter = 0;} + void ResetTimeOut() { fSameTimeRequestCounter = 0; } private: double fRequestTime; @@ -98,25 +106,27 @@ class StopTime : public BinaryFunctor class TimeGap : public BinaryFunctor { public: - TimeGap():fOldTime(-1.) {}; + TimeGap() + : fOldTime(-1.){}; /** * \parameter b : TimeGap: All data between two time gaps which are larger than TimeGap are returned */ - bool Call(FairTimeStamp* a, double b) { - double aTime = a->GetTimeStamp(); - - if (fOldTime < 0) { - fOldTime = aTime; - return false; - } - if (aTime - fOldTime > b) { - fOldTime = aTime; - return true; - } else { - fOldTime = aTime; - return false; - } + bool Call(FairTimeStamp* a, double b) + { + double aTime = a->GetTimeStamp(); + + if (fOldTime < 0) { + fOldTime = aTime; + return false; + } + if (aTime - fOldTime > b) { + fOldTime = aTime; + return true; + } else { + fOldTime = aTime; + return false; + } }; private: @@ -128,16 +138,16 @@ class TimeGap : public BinaryFunctor * \brief A class to access time ordered data in a root branch * * In the constructor of the class one has to give the branch name of the data, the tree the data is stored in - * and a BinaryFunctor which contains the method how the data should be extracted. Several example functors already exists. - * To extract the data one has to call GetData with a parameter which fits to the selected functor. - * GetData returns a TClonesArray which contains the data. + * and a BinaryFunctor which contains the method how the data should be extracted. Several example functors already + * exists. To extract the data one has to call GetData with a parameter which fits to the selected functor. GetData + * returns a TClonesArray which contains the data. * * - * Be careful! The buffer runs through the time ordered data in one time direction only. This means that you cannot request data which is older than the - * data you have requested before. + * Be careful! The buffer runs through the time ordered data in one time direction only. This means that you cannot + * request data which is older than the data you have requested before. * - * Addition: This is not true anymore. GetData(Double_t, Double_t) is able to get also data which is older but this only works if you request a fixed time - * via StopTime functor. For other functors the behavior is unpredictable. + * Addition: This is not true anymore. GetData(Double_t, Double_t) is able to get also data which is older but this only + * works if you request a fixed time via StopTime functor. For other functors the behavior is unpredictable. * * Created on: Feb 18, 201 * Author: stockman @@ -146,32 +156,36 @@ class TimeGap : public BinaryFunctor class FairTSBufferFunctional : public TObject { public: - FairTSBufferFunctional(TString branchName, TTree* sourceTree, BinaryFunctor* stopFunction, BinaryFunctor* startFunction = 0); + FairTSBufferFunctional(TString branchName, + TTree* sourceTree, + BinaryFunctor* stopFunction, + BinaryFunctor* startFunction = 0); - virtual ~FairTSBufferFunctional() {}; + virtual ~FairTSBufferFunctional(){}; TClonesArray* GetData(Double_t stopParameter); TClonesArray* GetData(Double_t startParameter, Double_t stopParameter); - Int_t GetBranchIndex() {return fBranchIndex;} + Int_t GetBranchIndex() { return fBranchIndex; } void SetBranchIndex(const Int_t val) { fBranchIndex = val; } - void SetStartFunction(BinaryFunctor* function) { fStartFunction = function;} - void SetStopFunction(BinaryFunctor* function) { fStopFunction = function;} + void SetStartFunction(BinaryFunctor* function) { fStartFunction = function; } + void SetStopFunction(BinaryFunctor* function) { fStopFunction = function; } Bool_t AllDataProcessed(); - void Terminate(){ fTerminate = kTRUE; } - - Bool_t TimeOut() { - Bool_t stopTimeOut = fStopFunction->TimeOut(); - Bool_t startTimeOut = kTRUE; - if (fStartFunction != 0) { - startTimeOut = fStartFunction->TimeOut(); -// if (startTimeOut == kTRUE && stopTimeOut == kFALSE){ -// fStartFunction->ResetTimeOut(); -// } -// else if (startTimeOut == kFALSE && stopTimeOut == kTRUE){ -// fStopFunction->ResetTimeOut(); -// } - } - return (stopTimeOut && startTimeOut); + void Terminate() { fTerminate = kTRUE; } + + Bool_t TimeOut() + { + Bool_t stopTimeOut = fStopFunction->TimeOut(); + Bool_t startTimeOut = kTRUE; + if (fStartFunction != 0) { + startTimeOut = fStartFunction->TimeOut(); + // if (startTimeOut == kTRUE && stopTimeOut == kFALSE){ + // fStartFunction->ResetTimeOut(); + // } + // else if (startTimeOut == kFALSE && stopTimeOut == kTRUE){ + // fStopFunction->ResetTimeOut(); + // } + } + return (stopTimeOut && startTimeOut); } Int_t FindStartIndex(Double_t startParameter); @@ -179,9 +193,10 @@ class FairTSBufferFunctional : public TObject private: void ReadInNextFilledEntry(); Int_t ReadInPreviousFilledEntry(Int_t startEntry); - void ReadInNextEntry(); //** used only if no function is given and input data is directly passed through to the OutputArray + void ReadInNextEntry(); //** used only if no function is given and input data is directly passed through to the + // OutputArray void ReadInEntry(Int_t number); - void AbsorbDataBufferArray(); //< Absorbs the complete data from fInputArray to fBufferArray + void AbsorbDataBufferArray(); //< Absorbs the complete data from fInputArray to fBufferArray TClonesArray* fOutputArray; TClonesArray* fBufferArray; @@ -200,7 +215,7 @@ class FairTSBufferFunctional : public TObject FairTSBufferFunctional(const FairTSBufferFunctional&); FairTSBufferFunctional& operator=(const FairTSBufferFunctional&); - ClassDef(FairTSBufferFunctional,0); + ClassDef(FairTSBufferFunctional, 0); }; #endif diff --git a/base/steer/FairTask.cxx b/base/steer/FairTask.cxx index b81e121160..accb54c048 100644 --- a/base/steer/FairTask.cxx +++ b/base/steer/FairTask.cxx @@ -10,215 +10,242 @@ #include "FairTask.h" -#include "FairLogger.h" // for FairLogger, MESSAGE_ORIGIN -#include "FairMonitor.h" // for FairMonitor +#include "FairLogger.h" // for FairLogger, MESSAGE_ORIGIN +#include "FairMonitor.h" // for FairMonitor -#include // for TIter -#include // for TList -#include // for TObject - -#include // pair -#include // printf +#include // for TIter +#include // for TList +#include // for TObject +#include // printf +#include // pair FairTask::FairTask() - : TTask(), - fVerbose(0), - fInputPersistance(-1), - fLogger(FairLogger::GetLogger()), - fStreamProcessing(kFALSE), - fOutputPersistance() -{ -} + : TTask() + , fVerbose(0) + , fInputPersistance(-1) + , fLogger(FairLogger::GetLogger()) + , fStreamProcessing(kFALSE) + , fOutputPersistance() +{} FairTask::FairTask(const char* name, Int_t iVerbose) - : TTask(name, "FairTask"), - fVerbose(iVerbose), - fInputPersistance(-1), - fLogger(FairLogger::GetLogger()), - fOutputPersistance() -{ -} + : TTask(name, "FairTask") + , fVerbose(iVerbose) + , fInputPersistance(-1) + , fLogger(FairLogger::GetLogger()) + , fOutputPersistance() +{} -FairTask::~FairTask() { } +FairTask::~FairTask() {} void FairTask::InitTask() { - FairMonitor::GetMonitor()->SetCurrentTask(this); - if ( ! fActive ) { return; } - InitStatus tStat = Init(); - if ( tStat == kFATAL ) { - LOG(fatal) << "Initialization of Task " << fName.Data() << " failed fatally"; - } - if ( tStat == kERROR ) { fActive = kFALSE; } - FairMonitor::GetMonitor()->SetCurrentTask(0); - InitTasks(); + FairMonitor::GetMonitor()->SetCurrentTask(this); + if (!fActive) { + return; + } + InitStatus tStat = Init(); + if (tStat == kFATAL) { + LOG(fatal) << "Initialization of Task " << fName.Data() << " failed fatally"; + } + if (tStat == kERROR) { + fActive = kFALSE; + } + FairMonitor::GetMonitor()->SetCurrentTask(0); + InitTasks(); } void FairTask::ReInitTask() { - if ( ! fActive ) { return; } - InitStatus tStat = ReInit(); - if ( tStat == kFATAL ) { - LOG(fatal) << "Reinitialization of Task " << fName.Data() << " failed fatally"; - } - if ( tStat == kERROR ) { fActive = kFALSE; } - ReInitTasks(); + if (!fActive) { + return; + } + InitStatus tStat = ReInit(); + if (tStat == kFATAL) { + LOG(fatal) << "Reinitialization of Task " << fName.Data() << " failed fatally"; + } + if (tStat == kERROR) { + fActive = kFALSE; + } + ReInitTasks(); } void FairTask::SetParTask() { - if ( ! fActive ) { return; } - SetParContainers(); - SetParTasks(); + if (!fActive) { + return; + } + SetParContainers(); + SetParTasks(); } void FairTask::FinishEvent() { - if ( ! fActive ) { return; } - FinishEvents(); + if (!fActive) { + return; + } + FinishEvents(); } void FairTask::FinishTask() { - if ( ! fActive ) { return; } - Finish(); - FinishTasks(); + if (!fActive) { + return; + } + Finish(); + FinishTasks(); } void FairTask::SetVerbose(Int_t iVerbose) { - fVerbose = iVerbose; - TIter next(GetListOfTasks()); - FairTask* task; - while((task=dynamic_cast (next()))) { task->SetVerbose(iVerbose); } + fVerbose = iVerbose; + TIter next(GetListOfTasks()); + FairTask* task; + while ((task = dynamic_cast(next()))) { + task->SetVerbose(iVerbose); + } } void FairTask::InitTasks() { - TIter next(GetListOfTasks()); - FairTask* task; - while( ( task=dynamic_cast(next()) ) ) { task->InitTask(); } + TIter next(GetListOfTasks()); + FairTask* task; + while ((task = dynamic_cast(next()))) { + task->InitTask(); + } } -void FairTask::ExecuteTask(Option_t *option) +void FairTask::ExecuteTask(Option_t* option) { - // Execute main task and its subtasks. - // When calling this function, the Exec function of the corresponding class - // is invoked, then the list of its subtasks is executed calling recursively - // all the subtasks, etc. - // - // The option parameter may be used to select different execution steps - // within a task. This parameter is passed also to all the subtasks. - - if (fgBeginTask) { - Error("ExecuteTask","Cannot execute task:%s, already running task: %s",GetName(),fgBeginTask->GetName()); - return; - } - if (!IsActive()) return; - - fOption = option; - fgBeginTask = this; - fgBreakPoint = 0; - - if (fBreakin) return; - if (gDebug > 1) { - LOG(info)<<"Execute task:"<StartMonitoring(this,"EXEC"); - Exec(option); - FairMonitor::GetMonitor()->StopMonitoring(this,"EXEC"); - - - fHasExecuted = kTRUE; - ExecuteTasks(option); - - if (fBreakout) return; - - if (!fgBreakPoint) { - fgBeginTask->CleanTasks(); - fgBeginTask = 0; - } -} + // Execute main task and its subtasks. + // When calling this function, the Exec function of the corresponding class + // is invoked, then the list of its subtasks is executed calling recursively + // all the subtasks, etc. + // + // The option parameter may be used to select different execution steps + // within a task. This parameter is passed also to all the subtasks. -void FairTask::ExecuteTasks(Option_t *option) -{ - // Execute all the subtasks of a task. - - TIter next(fTasks); - FairTask *task; - while((task=static_cast(next()))) { - if (fgBreakPoint) return; - if (!task->IsActive()) continue; - if (task->fHasExecuted) { - task->ExecuteTasks(option); - continue; - } - if (task->fBreakin == 1) { - printf("Break at entry of task: %s\n",task->GetName()); - fgBreakPoint = this; - task->fBreakin++; - return; - } - - if (gDebug > 1) { - LOG(info)<<"Execute task:"<GetName()<<" : "<GetTitle(); - } - FairMonitor::GetMonitor()->StartMonitoring(task,"EXEC"); - task->Exec(option); - FairMonitor::GetMonitor()->StopMonitoring(task,"EXEC"); - - task->fHasExecuted = kTRUE; - task->ExecuteTasks(option); - if (task->fBreakout == 1) { - printf("Break at exit of task: %s\n",task->GetName()); - fgBreakPoint = this; - task->fBreakout++; + if (fgBeginTask) { + Error("ExecuteTask", "Cannot execute task:%s, already running task: %s", GetName(), fgBeginTask->GetName()); + return; + } + if (!IsActive()) + return; + + fOption = option; + fgBeginTask = this; + fgBreakPoint = 0; + + if (fBreakin) return; - } - } + if (gDebug > 1) { + LOG(info) << "Execute task:" << GetName() << " : " << GetTitle(); + } + FairMonitor::GetMonitor()->StartMonitoring(this, "EXEC"); + Exec(option); + FairMonitor::GetMonitor()->StopMonitoring(this, "EXEC"); + + fHasExecuted = kTRUE; + ExecuteTasks(option); + + if (fBreakout) + return; + + if (!fgBreakPoint) { + fgBeginTask->CleanTasks(); + fgBeginTask = 0; + } +} + +void FairTask::ExecuteTasks(Option_t* option) +{ + // Execute all the subtasks of a task. + + TIter next(fTasks); + FairTask* task; + while ((task = static_cast(next()))) { + if (fgBreakPoint) + return; + if (!task->IsActive()) + continue; + if (task->fHasExecuted) { + task->ExecuteTasks(option); + continue; + } + if (task->fBreakin == 1) { + printf("Break at entry of task: %s\n", task->GetName()); + fgBreakPoint = this; + task->fBreakin++; + return; + } + + if (gDebug > 1) { + LOG(info) << "Execute task:" << task->GetName() << " : " << task->GetTitle(); + } + FairMonitor::GetMonitor()->StartMonitoring(task, "EXEC"); + task->Exec(option); + FairMonitor::GetMonitor()->StopMonitoring(task, "EXEC"); + + task->fHasExecuted = kTRUE; + task->ExecuteTasks(option); + if (task->fBreakout == 1) { + printf("Break at exit of task: %s\n", task->GetName()); + fgBreakPoint = this; + task->fBreakout++; + return; + } + } } void FairTask::ReInitTasks() { - TIter next(GetListOfTasks()); - FairTask* task; - while( ( task=dynamic_cast(next()) ) ) { task->ReInitTask(); } + TIter next(GetListOfTasks()); + FairTask* task; + while ((task = dynamic_cast(next()))) { + task->ReInitTask(); + } } void FairTask::SetParTasks() { - TIter next(GetListOfTasks()); - FairTask* task; - while( ( task=dynamic_cast(next()) ) ) { task->SetParTask(); } + TIter next(GetListOfTasks()); + FairTask* task; + while ((task = dynamic_cast(next()))) { + task->SetParTask(); + } } void FairTask::FinishTasks() { - TIter next(GetListOfTasks()); - FairTask* task; - while( ( task=dynamic_cast(next()) ) ) { task->FinishTask(); } + TIter next(GetListOfTasks()); + FairTask* task; + while ((task = dynamic_cast(next()))) { + task->FinishTask(); + } } void FairTask::FinishEvents() { - TIter next(GetListOfTasks()); - FairTask* task; - while( ( task=dynamic_cast(next()) ) ) { task->FinishEvent(); } + TIter next(GetListOfTasks()); + FairTask* task; + while ((task = dynamic_cast(next()))) { + task->FinishEvent(); + } } void FairTask::SetOutputBranchPersistent(TString branchName, Bool_t persistence) { - fOutputPersistance.insert ( std::pair(branchName, persistence) ); + fOutputPersistance.insert(std::pair(branchName, persistence)); } Bool_t FairTask::IsOutputBranchPersistent(TString branchName) { - std::map::iterator it = fOutputPersistance.find(branchName); - if (it != fOutputPersistance.end()) { - return it->second; - } else { - return kTRUE; - } + std::map::iterator it = fOutputPersistance.find(branchName); + if (it != fOutputPersistance.end()) { + return it->second; + } else { + return kTRUE; + } } -ClassImp(FairTask) +ClassImp(FairTask); diff --git a/base/steer/FairTask.h b/base/steer/FairTask.h index 3efaf11158..445affe349 100644 --- a/base/steer/FairTask.h +++ b/base/steer/FairTask.h @@ -21,17 +21,21 @@ #ifndef FAIRTASK_H #define FAIRTASK_H -#include "FairRootManager.h" // for FairRootManager - -#include // for TTask -#include // for Int_t, FairTask::Class, etc -#include // for TString +#include "FairRootManager.h" // for FairRootManager +#include // for Int_t, FairTask::Class, etc +#include // for TString +#include // for TTask #include class FairLogger; -enum InitStatus {kSUCCESS, kERROR, kFATAL}; +enum InitStatus +{ + kSUCCESS, + kERROR, + kFATAL +}; class FairTask : public TTask { @@ -40,9 +44,9 @@ class FairTask : public TTask FairTask(); /** Standard constructor - *@param name Name of task - *@param iVerbose Verbosity level - **/ + *@param name Name of task + *@param iVerbose Verbosity level + **/ FairTask(const char* name, Int_t iVerbose = 1); /** Destructor **/ @@ -70,52 +74,53 @@ class FairTask : public TTask /** Set verbosity level. For this task and all of the subtasks. **/ void SetVerbose(Int_t iVerbose); - void SetInputPersistance(Bool_t val) {fInputPersistance = val;} + void SetInputPersistance(Bool_t val) { fInputPersistance = val; } - void CheckInputPersistance(TString branchName) { - FairRootManager* ioman = FairRootManager::Instance(); - fInputPersistance = ioman->CheckBranch(branchName); + void CheckInputPersistance(TString branchName) + { + FairRootManager* ioman = FairRootManager::Instance(); + fInputPersistance = ioman->CheckBranch(branchName); } - virtual void ExecuteTask(Option_t *option="0"); // *MENU* + virtual void ExecuteTask(Option_t* option = "0"); // *MENU* /** Set persistency of branch with given name true or false * In case is is set to false the branch will not be written to the output. - **/ + **/ void SetOutputBranchPersistent(TString, Bool_t); /** Check if the branch with the given name is persistent. * If the branch is not in the map, the default return value is true. - **/ + **/ Bool_t IsOutputBranchPersistent(TString); - void SetStreamProcessing(Bool_t val=kTRUE) {fStreamProcessing=val;} + void SetStreamProcessing(Bool_t val = kTRUE) { fStreamProcessing = val; } protected: - Int_t fVerbose; // Verbosity level - Int_t fInputPersistance; ///< Indicates if input branch is persistant - FairLogger* fLogger; //! - Bool_t fStreamProcessing; + Int_t fVerbose; // Verbosity level + Int_t fInputPersistance; ///< Indicates if input branch is persistant + FairLogger* fLogger; //! + Bool_t fStreamProcessing; /** Intialisation at begin of run. To be implemented in the derived class. - *@value Success If not kSUCCESS, task will be set inactive. - **/ + *@value Success If not kSUCCESS, task will be set inactive. + **/ virtual InitStatus Init() { return kSUCCESS; }; /** Reinitialisation. To be implemented in the derived class. - *@value Success If not kSUCCESS, task will be set inactive. - **/ + *@value Success If not kSUCCESS, task will be set inactive. + **/ virtual InitStatus ReInit() { return kSUCCESS; }; /** Intialise parameter containers. To be implemented in the derived class. **/ - virtual void SetParContainers() { }; + virtual void SetParContainers(){}; /** Action at end of run. For this task and all of the subtasks. To be implemented in the derived class. **/ - virtual void Finish() { }; + virtual void Finish(){}; /** Recursive intialisation of subtasks at begin of run **/ void InitTasks(); @@ -123,7 +128,7 @@ class FairTask : public TTask /** Recursive reinitialisation of subtasks **/ void ReInitTasks(); - virtual void ExecuteTasks(Option_t *option); + virtual void ExecuteTasks(Option_t* option); /** Recursive parameter initialisation for subtasks **/ void SetParTasks(); @@ -140,7 +145,7 @@ class FairTask : public TTask FairTask(const FairTask&); FairTask& operator=(const FairTask&); - ClassDef(FairTask,4); + ClassDef(FairTask, 4); }; #endif diff --git a/base/steer/FairTrajFilter.cxx b/base/steer/FairTrajFilter.cxx index 6eb3de4049..bb15b005fc 100644 --- a/base/steer/FairTrajFilter.cxx +++ b/base/steer/FairTrajFilter.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ********************************************* // @@ -12,318 +12,326 @@ #include "FairTrajFilter.h" -#include "FairRootManager.h" // for FairRootManager +#include "FairRootManager.h" // for FairRootManager -#include // for TClonesArray -#include // for Fatal -#include // for Pi, TwoPi, Log -#include // for Abs -#include // for TParticle +#include // for TClonesArray +#include // for Fatal +#include #include #include -#include - -#include // for operator<<, basic_ostream, etc +#include // for Pi, TwoPi, Log +#include // for Abs +#include // for TParticle +#include // for operator<<, basic_ostream, etc using namespace std; -ClassImp(FairTrajFilter) +ClassImp(FairTrajFilter); TMCThreadLocal FairTrajFilter* FairTrajFilter::fgInstance = nullptr; -FairTrajFilter* FairTrajFilter::Instance() -{ - return fgInstance; -} +FairTrajFilter* FairTrajFilter::Instance() { return fgInstance; } FairTrajFilter::FairTrajFilter() - : fVxMin(-2000.), - fVxMax(2000.), - fVyMin(-2000.), - fVyMax(2000.), - fVzMin(-2000.), - fVzMax(2000.), - fPMin(0.), - fPMax(1e10), - fThetaMin(0.), - fThetaMax(TMath::Pi()), - fPhiMin(0.), - fPhiMax(TMath::TwoPi()), - fPxMin(-1e10), - fPxMax(1e10), - fPyMin(-1e10), - fPyMax(1e10), - fPzMin(-1e10), - fPzMax(1e10), - fPtMin(0.), - fPtMax(1e10), - fRapidityMin(-1e10), - fRapidityMax(1e10), - fKinCutType(0), // polar system by default - fEtotMin(0.), - fEtotMax(1e10), - fStorePrim(kTRUE), - fStoreSec(kTRUE), - fStepSizeMin(0.1), // 1mm by default - fTrackCollection(new TClonesArray("TGeoTrack")), - fCurrentTrk(nullptr) + : fVxMin(-2000.) + , fVxMax(2000.) + , fVyMin(-2000.) + , fVyMax(2000.) + , fVzMin(-2000.) + , fVzMax(2000.) + , fPMin(0.) + , fPMax(1e10) + , fThetaMin(0.) + , fThetaMax(TMath::Pi()) + , fPhiMin(0.) + , fPhiMax(TMath::TwoPi()) + , fPxMin(-1e10) + , fPxMax(1e10) + , fPyMin(-1e10) + , fPyMax(1e10) + , fPzMin(-1e10) + , fPzMax(1e10) + , fPtMin(0.) + , fPtMax(1e10) + , fRapidityMin(-1e10) + , fRapidityMax(1e10) + , fKinCutType(0) + , // polar system by default + fEtotMin(0.) + , fEtotMax(1e10) + , fStorePrim(kTRUE) + , fStoreSec(kTRUE) + , fStepSizeMin(0.1) + , // 1mm by default + fTrackCollection(new TClonesArray("TGeoTrack")) + , fCurrentTrk(nullptr) { - if (nullptr != fgInstance) { - Fatal("FairTrajFilter", "Singleton class already exists."); - return; - } + if (nullptr != fgInstance) { + Fatal("FairTrajFilter", "Singleton class already exists."); + return; + } - fgInstance = this; + fgInstance = this; } -FairTrajFilter::~FairTrajFilter() -{ - fgInstance = nullptr; -} +FairTrajFilter::~FairTrajFilter() { fgInstance = nullptr; } void FairTrajFilter::Init(TString brName, TString folderName) { - FairRootManager::Instance()->Register(brName.Data(), folderName.Data(), fTrackCollection, kTRUE); + FairRootManager::Instance()->Register(brName.Data(), folderName.Data(), fTrackCollection, kTRUE); } -void FairTrajFilter::Reset() -{ - fTrackCollection->Delete(); -} +void FairTrajFilter::Reset() { fTrackCollection->Delete(); } Bool_t FairTrajFilter::IsAccepted(const TParticle* p) const { - if (nullptr == p ) { - return kFALSE; - } - - // Apply vertex cut - if ((p->Vx()Vx()>fVxMax) || - (p->Vy()Vy()>fVyMax) || - (p->Vz()Vz()>fVzMax) ) { - return kFALSE; - } - - // Apply cut on kinematics - if (0 == fKinCutType ) { - if ((p->P()P()>fPMax) || - (p->Theta()Theta()>fThetaMax) || - (p->Phi()Phi()>fPhiMax) ) { - return kFALSE; - } - } else if (1 == fKinCutType ) { - if ((p->Px()Px()>fPxMax) || - (p->Py()Py()>fPyMax) || - (p->Pz()Pz()>fPzMax) ) { - return kFALSE; + if (nullptr == p) { + return kFALSE; } - } else { - Double_t rapidity = 0.5*TMath::Log((p->Energy()+p->Pz()) / - (p->Energy()-p->Pz()) ); - if ((p->Pt()Pt()>fPtMax) || - (rapidityfRapidityMax) ) { - return kFALSE; + + // Apply vertex cut + if ((p->Vx() < fVxMin) || (p->Vx() > fVxMax) || (p->Vy() < fVyMin) || (p->Vy() > fVyMax) || (p->Vz() < fVzMin) + || (p->Vz() > fVzMax)) { + return kFALSE; } - } - // Apply energy cut - if ((p->Energy()Energy()>fEtotMax) ) { - return kFALSE; - } + // Apply cut on kinematics + if (0 == fKinCutType) { + if ((p->P() < fPMin) || (p->P() > fPMax) || (p->Theta() < fThetaMin) || (p->Theta() > fThetaMax) + || (p->Phi() < fPhiMin) || (p->Phi() > fPhiMax)) { + return kFALSE; + } + } else if (1 == fKinCutType) { + if ((p->Px() < fPxMin) || (p->Px() > fPxMax) || (p->Py() < fPyMin) || (p->Py() > fPyMax) || (p->Pz() < fPzMin) + || (p->Pz() > fPzMax)) { + return kFALSE; + } + } else { + Double_t rapidity = 0.5 * TMath::Log((p->Energy() + p->Pz()) / (p->Energy() - p->Pz())); + if ((p->Pt() < fPtMin) || (p->Pt() > fPtMax) || (rapidity < fRapidityMin) || (rapidity > fRapidityMax)) { + return kFALSE; + } + } - // Apply generation cut - if (-1 == p->GetFirstMother()) { - if (kFALSE == fStorePrim) { - return kFALSE; + // Apply energy cut + if ((p->Energy() < fEtotMin) || (p->Energy() > fEtotMax)) { + return kFALSE; } - } else { - if (kFALSE == fStoreSec) { - return kFALSE; + + // Apply generation cut + if (-1 == p->GetFirstMother()) { + if (kFALSE == fStorePrim) { + return kFALSE; + } + } else { + if (kFALSE == fStoreSec) { + return kFALSE; + } } - } - return kTRUE; + return kTRUE; } -void FairTrajFilter::SetVertexCut(Double_t vxMin, Double_t vyMin, Double_t vzMin, - Double_t vxMax, Double_t vyMax, Double_t vzMax) +void FairTrajFilter::SetVertexCut(Double_t vxMin, + Double_t vyMin, + Double_t vzMin, + Double_t vxMax, + Double_t vyMax, + Double_t vzMax) { - TGeoBBox* cave = static_cast(gGeoManager->GetTopVolume()->GetShape()); - cave->ComputeBBox(); - Double_t caveX = 2.*cave->GetDX(); - Double_t caveY = 2.*cave->GetDY(); - Double_t caveZ = 2.*cave->GetDZ(); - if ((vxMaxcaveX) || (TMath::Abs(vxMax)>caveX) || - (TMath::Abs(vyMin)>caveY) || (TMath::Abs(vyMax)>caveY) || - (TMath::Abs(vzMin)>caveZ) || (TMath::Abs(vzMax)>caveZ) ) { - cout << "-E- FairTrajFilter::SetVertexCut() : invalid region, ignoring." << endl; - return; - } - fVxMin = vxMin; - fVxMax = vxMax; - fVyMin = vyMin; - fVyMax = vyMax; - fVzMin = vzMin; - fVzMax = vzMax; + TGeoBBox* cave = static_cast(gGeoManager->GetTopVolume()->GetShape()); + cave->ComputeBBox(); + Double_t caveX = 2. * cave->GetDX(); + Double_t caveY = 2. * cave->GetDY(); + Double_t caveZ = 2. * cave->GetDZ(); + if ((vxMax < vxMin) || (vyMax < vyMin) || (vzMax < vzMin) || (TMath::Abs(vxMin) > caveX) + || (TMath::Abs(vxMax) > caveX) || (TMath::Abs(vyMin) > caveY) || (TMath::Abs(vyMax) > caveY) + || (TMath::Abs(vzMin) > caveZ) || (TMath::Abs(vzMax) > caveZ)) { + cout << "-E- FairTrajFilter::SetVertexCut() : invalid region, ignoring." << endl; + return; + } + fVxMin = vxMin; + fVxMax = vxMax; + fVyMin = vyMin; + fVyMax = vyMax; + fVzMin = vzMin; + fVzMax = vzMax; } -void FairTrajFilter::SetMomentumCutP(Double_t pMin, Double_t thetaMin, Double_t phiMin, - Double_t pMax, Double_t thetaMax, Double_t phiMax) +void FairTrajFilter::SetMomentumCutP(Double_t pMin, + Double_t thetaMin, + Double_t phiMin, + Double_t pMax, + Double_t thetaMax, + Double_t phiMax) { - if ((pMaxTMath::Pi()) || - (phiMin<0.) || (phiMax>TMath::TwoPi()) ) { - cout << "-E- FairTrajFilter::SetMomentumCutP() : invalid region, ignoring." << endl; - return; - } - fPMin = pMin; - fPMax = pMax; - fThetaMin = thetaMin; - fThetaMax = thetaMax; - fPhiMin = phiMin; - fPhiMax = phiMax; - fKinCutType = 0; + if ((pMax < pMin) || (thetaMax < thetaMin) || (phiMax < phiMin) || (pMin < 0.) || (pMax < 0.) || (thetaMin < 0.) + || (thetaMax > TMath::Pi()) || (phiMin < 0.) || (phiMax > TMath::TwoPi())) { + cout << "-E- FairTrajFilter::SetMomentumCutP() : invalid region, ignoring." << endl; + return; + } + fPMin = pMin; + fPMax = pMax; + fThetaMin = thetaMin; + fThetaMax = thetaMax; + fPhiMin = phiMin; + fPhiMax = phiMax; + fKinCutType = 0; } -void FairTrajFilter::SetMomentumCutD(Double_t pxMin, Double_t pyMin, Double_t pzMin, - Double_t pxMax, Double_t pyMax, Double_t pzMax) +void FairTrajFilter::SetMomentumCutD(Double_t pxMin, + Double_t pyMin, + Double_t pzMin, + Double_t pxMax, + Double_t pyMax, + Double_t pzMax) { - if ((pxMaxGetId(); } - Int_t pdgCode = p->GetPdgCode(); - TClonesArray& clref = *fTrackCollection; - Int_t tsize = clref.GetEntriesFast(); - fCurrentTrk = new(clref[tsize]) TGeoTrack(++trackId,pdgCode,0,p); - return fCurrentTrk; + Int_t trackId = 0; + // cout << "FairTrajFilter::AddTrack" << endl; + if (fCurrentTrk) { + trackId = fCurrentTrk->GetId(); + } + Int_t pdgCode = p->GetPdgCode(); + TClonesArray& clref = *fTrackCollection; + Int_t tsize = clref.GetEntriesFast(); + fCurrentTrk = new (clref[tsize]) TGeoTrack(++trackId, pdgCode, 0, p); + return fCurrentTrk; } TGeoTrack* FairTrajFilter::CheckAddTrack(Int_t trackId, TParticle* p) { TClonesArray& clref = *fTrackCollection; Int_t tsize = clref.GetEntriesFast(); - for (Int_t itr = tsize-1 ; itr >= 0 ; --itr ) { + for (Int_t itr = tsize - 1; itr >= 0; --itr) { TGeoTrack* tempTrack = dynamic_cast(clref.At(itr)); - if (tempTrack->GetId() == trackId ) { + if (tempTrack->GetId() == trackId) { fCurrentTrk = tempTrack; return fCurrentTrk; } } // track with given trackId not found, creating new one Int_t pdgCode = p->GetPdgCode(); - fCurrentTrk = new(clref[tsize]) TGeoTrack(trackId,pdgCode,0,p); + fCurrentTrk = new (clref[tsize]) TGeoTrack(trackId, pdgCode, 0, p); return fCurrentTrk; } -TGeoTrack* FairTrajFilter::GetTrack(Int_t trackId) -{ - return static_cast(fTrackCollection->At(trackId)); -} +TGeoTrack* FairTrajFilter::GetTrack(Int_t trackId) { return static_cast(fTrackCollection->At(trackId)); } diff --git a/base/steer/FairTrajFilter.h b/base/steer/FairTrajFilter.h index c69dbc8c5d..ff158ca0dc 100644 --- a/base/steer/FairTrajFilter.h +++ b/base/steer/FairTrajFilter.h @@ -13,11 +13,11 @@ #ifndef FAIR_TRAJ_FILTER_H #define FAIR_TRAJ_FILTER_H 1 -#include // for Double_t, Bool_t, Int_t, etc -#include // IWYU pragma: keep needed by cint // TODO: is this still relevant for CINT? -#include // for Pi, TwoPi -#include // for TString -#include // for multi-threading +#include // for Double_t, Bool_t, Int_t, etc +#include // IWYU pragma: keep needed by cint // TODO: is this still relevant for CINT? +#include // for multi-threading +#include // for Pi, TwoPi +#include // for TString class TClonesArray; class TParticle; @@ -58,7 +58,7 @@ class FairTrajFilter /** * Class definition. */ - ClassDef(FairTrajFilter,1); + ClassDef(FairTrajFilter, 1); private: FairTrajFilter(const FairTrajFilter&); @@ -92,7 +92,7 @@ class FairTrajFilter Double_t fRapidityMin; Double_t fRapidityMax; - Int_t fKinCutType; + Int_t fKinCutType; Double_t fEtotMin; Double_t fEtotMax; @@ -113,9 +113,9 @@ class FairTrajFilter TGeoTrack* AddTrack(Int_t trackId, Int_t pdgCode); TGeoTrack* AddTrack(TParticle* p); TGeoTrack* CheckAddTrack(Int_t trackId, TParticle* p); - TGeoTrack* GetCurrentTrk() {return fCurrentTrk;} + TGeoTrack* GetCurrentTrk() { return fCurrentTrk; } - void Init(TString brName="GeoTracks", TString folderName="MCGeoTrack"); + void Init(TString brName = "GeoTracks", TString folderName = "MCGeoTrack"); void Reset(); /** * This function is used to access the methods of the class. @@ -138,8 +138,12 @@ class FairTrajFilter * @param Box in coordinate space. Only trajectories, created inside this box * will be stored. Default values - the cave dimensions. */ - void SetVertexCut(Double_t vxMin=-2000., Double_t vyMin=-2000., Double_t vzMin=-2000., - Double_t vxMax= 2000., Double_t vyMax= 2000., Double_t vzMax= 2000.); + void SetVertexCut(Double_t vxMin = -2000., + Double_t vyMin = -2000., + Double_t vzMin = -2000., + Double_t vxMax = 2000., + Double_t vyMax = 2000., + Double_t vzMax = 2000.); /** * This function enables the momentum cut (polar reference system). @@ -149,9 +153,12 @@ class FairTrajFilter * inside this region will be stored. * Default values - whole momentum range. */ - void SetMomentumCutP(Double_t pMin= 0., Double_t thetaMin=0., Double_t phiMin=0., - Double_t pMax=1e10, Double_t thetaMax=TMath::Pi(), - Double_t phiMax=TMath::TwoPi()); + void SetMomentumCutP(Double_t pMin = 0., + Double_t thetaMin = 0., + Double_t phiMin = 0., + Double_t pMax = 1e10, + Double_t thetaMax = TMath::Pi(), + Double_t phiMax = TMath::TwoPi()); /** * This function enables the momentum cut (decart reference system). @@ -161,8 +168,12 @@ class FairTrajFilter * inside this region will be stored. * Default values - whole momentum range. */ - void SetMomentumCutD(Double_t pxMin=-1e10, Double_t pyMin=-1e10, Double_t pzMin=-1e10, - Double_t pxMax= 1e10, Double_t pyMax= 1e10, Double_t pzMax= 1e10); + void SetMomentumCutD(Double_t pxMin = -1e10, + Double_t pyMin = -1e10, + Double_t pzMin = -1e10, + Double_t pxMax = 1e10, + Double_t pyMax = 1e10, + Double_t pzMax = 1e10); /** * This function enables the cut in phase space (pt-rapidity). @@ -170,62 +181,75 @@ class FairTrajFilter * inside this region will be stored. * Default values - whole pt-rapidity range. */ - void SetPtRapidityCut(Double_t ptMin=0., Double_t ptMax=1e10, - Double_t rapidityMin=-1e10, Double_t rapidityMax=1e10); + void SetPtRapidityCut(Double_t ptMin = 0., + Double_t ptMax = 1e10, + Double_t rapidityMin = -1e10, + Double_t rapidityMax = 1e10); /** * This function enables the cut on total energy. * @param Total energy range. Only particles with total energy value * inside this range will be stored. Deafult values - whole energy range. */ - void SetEnergyCut(Double_t etotMin=0., Double_t etotMax=1e10); + void SetEnergyCut(Double_t etotMin = 0., Double_t etotMax = 1e10); /** * This function controls the storing of primaries. * @param storePrim - boolean flag to control the storing of primaries. */ - inline void SetStorePrimaries(Bool_t storePrim=kTRUE) {fStorePrim = storePrim;}; + inline void SetStorePrimaries(Bool_t storePrim = kTRUE) { fStorePrim = storePrim; }; /** * This function controls the storing of secondaries. * @param storeSec - boolean flag to control the storing of secondaries. */ - inline void SetStoreSecondaries(Bool_t storeSec=kTRUE) {fStoreSec = storeSec;}; + inline void SetStoreSecondaries(Bool_t storeSec = kTRUE) { fStoreSec = storeSec; }; /** * This function controls the process of adding the points to the trajectory. * @param stepSizeMin - minimum value of step size, wich will be added to * the trajectory. */ - void SetStepSizeCut(Double_t stepSizeMin=0.); + void SetStepSizeCut(Double_t stepSizeMin = 0.); /** * This is the getter for the vertex cut. * @param References to the variables where return values should be stored. */ - void GetVertexCut(Double_t& vxMin, Double_t& vyMin, Double_t& vzMin, - Double_t& vxMax, Double_t& vyMax, Double_t& vzMax) const; + void GetVertexCut(Double_t& vxMin, + Double_t& vyMin, + Double_t& vzMin, + Double_t& vxMax, + Double_t& vyMax, + Double_t& vzMax) const; /** * This is the getter for the momentum cut (polar reference system). * @param References to the variables where return values should be stored. */ - void GetMomentumCutP(Double_t& pMin, Double_t& thetaMin, Double_t& phiMin, - Double_t& pMax, Double_t& thetaMax, Double_t& phiMax) const; + void GetMomentumCutP(Double_t& pMin, + Double_t& thetaMin, + Double_t& phiMin, + Double_t& pMax, + Double_t& thetaMax, + Double_t& phiMax) const; /** * This is the getter for the momentum cut (decart reference system). * @param References to the variables where return values should be stored. */ - void GetMomentumCutD(Double_t& pxMin, Double_t& pyMin, Double_t& pzMin, - Double_t& pxMax, Double_t& pyMax, Double_t& pzMax) const; + void GetMomentumCutD(Double_t& pxMin, + Double_t& pyMin, + Double_t& pzMin, + Double_t& pxMax, + Double_t& pyMax, + Double_t& pzMax) const; /** * This is the getter for the space phase cut. * @param References to the variables where return values should be stored. */ - void GetPtRapidityCut(Double_t& ptMin, Double_t& ptMax, - Double_t& rapidityMin, Double_t& rapidityMax) const; + void GetPtRapidityCut(Double_t& ptMin, Double_t& ptMax, Double_t& rapidityMin, Double_t& rapidityMax) const; /** * This is the getter for the total energy cut. @@ -237,13 +261,13 @@ class FairTrajFilter * This is the getter for flag of storing of primaries. * @return kTRUE if primaries should be stored. */ - inline Bool_t IsPrimariesStored() const {return fStorePrim;}; + inline Bool_t IsPrimariesStored() const { return fStorePrim; }; /** * This is the getter for flag of storing of secondaries. * @return kTRUE if secondaries should be stored. */ - inline Bool_t IsSecondariesStored() const {return fStoreSec;}; + inline Bool_t IsSecondariesStored() const { return fStoreSec; }; /** * This is the getter for the step size cut. diff --git a/base/steer/FairWriteoutBuffer.cxx b/base/steer/FairWriteoutBuffer.cxx index 65ed452308..2037ae7b08 100644 --- a/base/steer/FairWriteoutBuffer.cxx +++ b/base/steer/FairWriteoutBuffer.cxx @@ -14,256 +14,269 @@ #include "FairWriteoutBuffer.h" -#include "FairLogger.h" // for FairLogger -#include "FairRootManager.h" // for FairRootManager +#include "FairLogger.h" // for FairLogger +#include "FairRootManager.h" // for FairRootManager -#include // for operator<<, ostream, cout, etc -#include // for reverse_iterator +#include // for operator<<, ostream, cout, etc +#include // for reverse_iterator FairWriteoutBuffer::FairWriteoutBuffer(TString branchName, TString className, TString folderName, Bool_t persistance) - : TObject(), - fStartTime_map(), - fDeadTime_map(), - fBranchName(branchName), - fClassName(className), - fTreeSave(true), - fActivateBuffering(kTRUE), - fVerbose(0), - fLogger(FairLogger::GetLogger()) + : TObject() + , fStartTime_map() + , fDeadTime_map() + , fBranchName(branchName) + , fClassName(className) + , fTreeSave(true) + , fActivateBuffering(kTRUE) + , fVerbose(0) + , fLogger(FairLogger::GetLogger()) { - FairRootManager::Instance()->Register(branchName, className, folderName, persistance); - if (fBranchName == "" || fClassName == "") { - fTreeSave = false; - } else { - fTreeSave = true; - } + FairRootManager::Instance()->Register(branchName, className, folderName, persistance); + if (fBranchName == "" || fClassName == "") { + fTreeSave = false; + } else { + fTreeSave = true; + } } void FairWriteoutBuffer::WriteOutData(double time) { - if (fActivateBuffering) { - if (fVerbose > 0) { - std::cout << "Before removing: "; - PrintStartTimeMap(); - PrintDeadTimeMap(); - } - - MoveDataFromStartTimeMapToDeadTimeMap(time); + if (fActivateBuffering) { + if (fVerbose > 0) { + std::cout << "Before removing: "; + PrintStartTimeMap(); + PrintDeadTimeMap(); + } - if (fVerbose > 0) { - std::cout << "After removing: "; - PrintStartTimeMap(); - PrintDeadTimeMap(); - } + MoveDataFromStartTimeMapToDeadTimeMap(time); - WriteOutDataDeadTimeMap(time); + if (fVerbose > 0) { + std::cout << "After removing: "; + PrintStartTimeMap(); + PrintDeadTimeMap(); + } - if (fVerbose > 0) { - std::cout << "DeadTime map after readout time: " << time << std::endl; - PrintDeadTimeMap(); - } + WriteOutDataDeadTimeMap(time); - } else { - FairRootManager::Instance()->GetTClonesArray(fBranchName); - } + if (fVerbose > 0) { + std::cout << "DeadTime map after readout time: " << time << std::endl; + PrintDeadTimeMap(); + } + } else { + FairRootManager::Instance()->GetTClonesArray(fBranchName); + } } void FairWriteoutBuffer::WriteOutDataDeadTimeMap(double time) { - FairRootManager* ioman = FairRootManager::Instance(); - std::vector data; - if (fActivateBuffering) { - if (fVerbose > 0) { - std::cout << "-I- FairWriteoutBuffer::WriteOutData for time: " << time << std::endl; - } - data = GetRemoveOldData(time); - if (fTreeSave && data.size() > 0) { - TClonesArray* myArray = ioman->GetTClonesArray(fBranchName); - if (!myArray) { - std::cout << "-E- FairWriteoutBuffer::WriteOutData " << fBranchName << " array is not available!" << std::endl; - } - if (fVerbose > 0) { - std::cout << "-I- FairWriteoutBuffer::WriteOutData size: " << data.size() << std::endl; - } - for (unsigned int i = 0; i < data.size(); i++) { - AddNewDataToTClonesArray(data[i]); - if (fVerbose > 1) { - std::cout << i << " : "; - data[i]->Print(); - std::cout << std::endl; + FairRootManager* ioman = FairRootManager::Instance(); + std::vector data; + if (fActivateBuffering) { + if (fVerbose > 0) { + std::cout << "-I- FairWriteoutBuffer::WriteOutData for time: " << time << std::endl; + } + data = GetRemoveOldData(time); + if (fTreeSave && data.size() > 0) { + TClonesArray* myArray = ioman->GetTClonesArray(fBranchName); + if (!myArray) { + std::cout << "-E- FairWriteoutBuffer::WriteOutData " << fBranchName << " array is not available!" + << std::endl; + } + if (fVerbose > 0) { + std::cout << "-I- FairWriteoutBuffer::WriteOutData size: " << data.size() << std::endl; + } + for (unsigned int i = 0; i < data.size(); i++) { + AddNewDataToTClonesArray(data[i]); + if (fVerbose > 1) { + std::cout << i << " : "; + data[i]->Print(); + std::cout << std::endl; + } + delete data[i]; + } } - delete data[i]; - } + } else { + ioman->GetTClonesArray(fBranchName); } - } else { - ioman->GetTClonesArray(fBranchName); - } } void FairWriteoutBuffer::WriteOutAllData() { - double ultimateTime = 0; + double ultimateTime = 0; - if (fStartTime_map.size() > 0) { - ultimateTime = fStartTime_map.rbegin()->first + 1; - MoveDataFromStartTimeMapToDeadTimeMap(ultimateTime); - } + if (fStartTime_map.size() > 0) { + ultimateTime = fStartTime_map.rbegin()->first + 1; + MoveDataFromStartTimeMapToDeadTimeMap(ultimateTime); + } - if (fDeadTime_map.size() > 0) { - if (fDeadTime_map.rbegin()->first > ultimateTime) { - ultimateTime = fDeadTime_map.rbegin()->first + 1; + if (fDeadTime_map.size() > 0) { + if (fDeadTime_map.rbegin()->first > ultimateTime) { + ultimateTime = fDeadTime_map.rbegin()->first + 1; + } } - } - if (ultimateTime > 0) { - WriteOutData(ultimateTime); - } + if (ultimateTime > 0) { + WriteOutData(ultimateTime); + } } std::vector FairWriteoutBuffer::GetRemoveOldData(double time) { - typedef std::multimap::iterator DTMapIter; - std::vector result; - for(DTMapIter it = fDeadTime_map.begin(); it != fDeadTime_map.lower_bound(time); it++) { - if (fVerbose > 1) { - std::cout << "-I- GetRemoveOldData: DeadTime: " << it->first << " Data: " << it->second << std::endl; + typedef std::multimap::iterator DTMapIter; + std::vector result; + for (DTMapIter it = fDeadTime_map.begin(); it != fDeadTime_map.lower_bound(time); ++it) { + if (fVerbose > 1) { + std::cout << "-I- GetRemoveOldData: DeadTime: " << it->first << " Data: " << it->second << std::endl; + } + result.push_back(it->second); + EraseDataFromDataMap(it->second); } - result.push_back(it->second); - EraseDataFromDataMap(it->second); - } - fDeadTime_map.erase(fDeadTime_map.begin(), fDeadTime_map.lower_bound(time)); - return result; + fDeadTime_map.erase(fDeadTime_map.begin(), fDeadTime_map.lower_bound(time)); + return result; } std::vector FairWriteoutBuffer::GetAllData() { - return GetRemoveOldData(fDeadTime_map.rbegin()->first + 1); + return GetRemoveOldData(fDeadTime_map.rbegin()->first + 1); } void FairWriteoutBuffer::FillNewData(FairTimeStamp* data, double startTime, double activeTime) { - FairTimeStamp* dataClone = static_cast(data->Clone()); + FairTimeStamp* dataClone = static_cast(data->Clone()); - if (fActivateBuffering) { - if (fVerbose > 0) { - std::cout << "StartTime: " << startTime << std::endl; + if (fActivateBuffering) { + if (fVerbose > 0) { + std::cout << "StartTime: " << startTime << std::endl; + } + std::pair timeData(activeTime, dataClone); + fStartTime_map.insert(std::pair>(startTime, timeData)); + } else { + AddNewDataToTClonesArray(dataClone); + delete dataClone; } - std::pair timeData(activeTime, dataClone); - fStartTime_map.insert(std::pair >(startTime, timeData)); - } else { - AddNewDataToTClonesArray(dataClone); - delete dataClone; - } - } void FairWriteoutBuffer::FillDataToDeadTimeMap(FairTimeStamp* data, double activeTime, double startTime) { - if (fActivateBuffering) { - typedef std::multimap::iterator DTMapIter; -// typedef std::map::iterator DataMapIter; - if (activeTime < 0) activeTime = 0; // to avoid errors due to wrong (negative) returnvalues of overwritten modify function by subdetector groups. A negative (-1) aktiveTime already indicate empty data maps! - double timeOfOldData = FindTimeForData(data); - // PrintDeadTimeMap(); - if(timeOfOldData > -1) { //if an older active data object is already present - if (fVerbose > 1) { - std::cout << " OldData found! " << timeOfOldData << std::endl; - } - if (fVerbose > 1) { - std::cout << "New Data: " << activeTime << " : " << data << std::endl; - } - double currentdeadtime = timeOfOldData; - FairTimeStamp* oldData; - bool dataFound = false; + if (fActivateBuffering) { + typedef std::multimap::iterator DTMapIter; + // typedef std::map::iterator DataMapIter; + if (activeTime < 0) + activeTime = 0; // to avoid errors due to wrong (negative) returnvalues of overwritten modify function by + // subdetector groups. A negative (-1) aktiveTime already indicate empty data maps! + double timeOfOldData = FindTimeForData(data); + // PrintDeadTimeMap(); + if (timeOfOldData > -1) { // if an older active data object is already present + if (fVerbose > 1) { + std::cout << " OldData found! " << timeOfOldData << std::endl; + } + if (fVerbose > 1) { + std::cout << "New Data: " << activeTime << " : " << data << std::endl; + } + double currentdeadtime = timeOfOldData; + FairTimeStamp* oldData; + bool dataFound = false; - // PrintDeadTimeMap(); - for (DTMapIter it = fDeadTime_map.lower_bound(currentdeadtime); it != fDeadTime_map.upper_bound(currentdeadtime); it++) { - oldData = it->second; - if (fVerbose > 1) { - std::cout << "Check Data: " << it->first << " : " << oldData << std::endl; - } - if (oldData->equal(data)) { - if (fVerbose > 1) { - std::cout << " oldData == data " << std::endl; - } - if (fVerbose > 1) { - std::cout << it->first << " : " << it->second << std::endl; - } - fDeadTime_map.erase(it); - EraseDataFromDataMap(oldData); - dataFound = true; - break; - } - } + // PrintDeadTimeMap(); + for (DTMapIter it = fDeadTime_map.lower_bound(currentdeadtime); + it != fDeadTime_map.upper_bound(currentdeadtime); + ++it) { + oldData = it->second; + if (fVerbose > 1) { + std::cout << "Check Data: " << it->first << " : " << oldData << std::endl; + } + if (oldData->equal(data)) { + if (fVerbose > 1) { + std::cout << " oldData == data " << std::endl; + } + if (fVerbose > 1) { + std::cout << it->first << " : " << it->second << std::endl; + } + fDeadTime_map.erase(it); + EraseDataFromDataMap(oldData); + dataFound = true; + break; + } + } - if (dataFound == true) { - if (timeOfOldData > startTime) { //if older active data can interference with the new data call modify function - std::vector > modifiedData = Modify(std::pair(currentdeadtime, oldData), std::pair(activeTime, data)); - for (unsigned int i = 0; i < modifiedData.size(); i++) { - FillDataToDeadTimeMap(modifiedData[i].second, modifiedData[i].first,0);//startTime = 0 since the Maps are already empty and the startTime therefore doesn't matter anymore + if (dataFound == true) { + if (timeOfOldData + > startTime) { // if older active data can interference with the new data call modify function + std::vector> modifiedData = + Modify(std::pair(currentdeadtime, oldData), + std::pair(activeTime, data)); + for (unsigned int i = 0; i < modifiedData.size(); i++) { + FillDataToDeadTimeMap(modifiedData[i].second, + modifiedData[i].first, + 0); // startTime = 0 since the Maps are already empty and the startTime + // therefore doesn't matter anymore + if (fVerbose > 1) { + std::cout << i << " :Modified Data: " << modifiedData[i].first << " : " + << modifiedData[i].second << std::endl; + } + } + } else { // no interference can happen between old hit and new hit + AddNewDataToTClonesArray(oldData); // therefore the old hit is written out + fDeadTime_map.insert( + std::pair(activeTime, data)); // and the new hit is stored + FillDataMap(data, activeTime); + } + } else { + std::cout << "-E- FairWriteoutBuffer::FillDataToDeadTimeMap: old data present in dataMap but not in " + "deadTimeMap!" + << std::endl; + } + + } else { if (fVerbose > 1) { - std::cout << i << " :Modified Data: " << modifiedData[i].first << " : " << modifiedData[i].second << std::endl; + std::cout << "-I- FairWriteoutBuffer::FillDataToDeadTimeMap Data Inserted: " << activeTime << " : "; + data->Print(); + std::cout << std::endl; } - } - } else { //no interference can happen between old hit and new hit - AddNewDataToTClonesArray(oldData); //therefore the old hit is written out - fDeadTime_map.insert(std::pair(activeTime, data)); //and the new hit is stored - FillDataMap(data, activeTime); + fDeadTime_map.insert(std::pair(activeTime, data)); + FillDataMap(data, activeTime); } - } else { - std::cout << "-E- FairWriteoutBuffer::FillDataToDeadTimeMap: old data present in dataMap but not in deadTimeMap!" << std::endl; - } - } else { - if (fVerbose > 1) { - std::cout << "-I- FairWriteoutBuffer::FillDataToDeadTimeMap Data Inserted: " << activeTime << " : "; - data->Print(); - std::cout << std::endl; - } - fDeadTime_map.insert(std::pair(activeTime, data)); - FillDataMap(data, activeTime); + AddNewDataToTClonesArray(data); + delete data; } - } else { - AddNewDataToTClonesArray(data); - delete data; - } } void FairWriteoutBuffer::MoveDataFromStartTimeMapToDeadTimeMap(double time) { - typedef std::multimap >::iterator startTimeMapIter; + typedef std::multimap>::iterator startTimeMapIter; - startTimeMapIter stopTime = fStartTime_map.lower_bound(time); - for (startTimeMapIter iter = fStartTime_map.begin(); iter != stopTime; iter++) { - std::pair data = iter->second; - double startTime = iter->first; - FillDataToDeadTimeMap(data.second, data.first, startTime); - } - fStartTime_map.erase(fStartTime_map.begin(), stopTime); + startTimeMapIter stopTime = fStartTime_map.lower_bound(time); + for (startTimeMapIter iter = fStartTime_map.begin(); iter != stopTime; ++iter) { + std::pair data = iter->second; + double startTime = iter->first; + FillDataToDeadTimeMap(data.second, data.first, startTime); + } + fStartTime_map.erase(fStartTime_map.begin(), stopTime); } void FairWriteoutBuffer::PrintStartTimeMap() { - typedef std::multimap >::iterator startTimeMapIter; - std::cout << "StartTimeMap: " << std::endl; - for (startTimeMapIter iter = fStartTime_map.begin(); iter != fStartTime_map.end(); iter++) { - FairTimeStamp* data = iter->second.second; - std::cout << " | " << iter->first << "/" << data->GetTimeStamp(); - } - std::cout << " |" << std::endl; + typedef std::multimap>::iterator startTimeMapIter; + std::cout << "StartTimeMap: " << std::endl; + for (startTimeMapIter iter = fStartTime_map.begin(); iter != fStartTime_map.end(); ++iter) { + FairTimeStamp* data = iter->second.second; + std::cout << " | " << iter->first << "/" << data->GetTimeStamp(); + } + std::cout << " |" << std::endl; } void FairWriteoutBuffer::PrintDeadTimeMap() { - typedef std::multimap::iterator DTMapIter; - std::cout << "DeadTimeMap: " << std::endl; - for (DTMapIter it = fDeadTime_map.begin(); it != fDeadTime_map.end(); it++) { - std::cout << it->first << " / "; - PrintData(it->second); + typedef std::multimap::iterator DTMapIter; + std::cout << "DeadTimeMap: " << std::endl; + for (DTMapIter it = fDeadTime_map.begin(); it != fDeadTime_map.end(); ++it) { + std::cout << it->first << " / "; + PrintData(it->second); + std::cout << std::endl; + } std::cout << std::endl; - } - std::cout << std::endl; } ClassImp(FairWriteoutBuffer); diff --git a/base/steer/FairWriteoutBuffer.h b/base/steer/FairWriteoutBuffer.h index cd97887da2..bdb74ff018 100644 --- a/base/steer/FairWriteoutBuffer.h +++ b/base/steer/FairWriteoutBuffer.h @@ -25,92 +25,111 @@ * The data which should be stored in the buffer has to be derived from FairTimeStamp. * It needs an operator< and a method equal if the same detector element is hit. * - * To use this buffer one has to derive his own buffer class from FairWriteoutBuffer and overwrite the pure virtual functions. + * To use this buffer one has to derive his own buffer class from FairWriteoutBuffer and overwrite the pure virtual + * functions. */ #ifndef FairWriteoutBuffer_H_ #define FairWriteoutBuffer_H_ -#include "FairLogger.h" // for FairLogger -#include "FairRootManager.h" // for FairRootManager -#include "FairTimeStamp.h" // for FairTimeStamp +#include "FairLogger.h" // for FairLogger +#include "FairRootManager.h" // for FairRootManager +#include "FairTimeStamp.h" // for FairTimeStamp -#include // for TObject -#include // for Bool_t, Int_t, etc -#include // for TClonesArray -#include // for TString +#include // for Bool_t, Int_t, etc +#include // for TClonesArray +#include // for TObject +#include // for TString +#include // for cout, ostream +#include // for multimap +#include // for pair +#include // for vector -#include // for cout, ostream -#include // for multimap -#include // for pair -#include // for vector - -class FairWriteoutBuffer: public TObject +class FairWriteoutBuffer : public TObject { public: - FairWriteoutBuffer() : TObject(), fStartTime_map(), fDeadTime_map(), fBranchName(), fClassName(), - fTreeSave(false), fActivateBuffering(kFALSE), fVerbose(0), fLogger(FairLogger::GetLogger()) {}; + FairWriteoutBuffer() + : TObject() + , fStartTime_map() + , fDeadTime_map() + , fBranchName() + , fClassName() + , fTreeSave(false) + , fActivateBuffering(kFALSE) + , fVerbose(0) + , fLogger(FairLogger::GetLogger()){}; FairWriteoutBuffer(TString branchName, TString className, TString folderName, Bool_t persistance); - virtual ~FairWriteoutBuffer() {}; + virtual ~FairWriteoutBuffer(){}; - virtual void SaveDataToTree(Bool_t val = kTRUE) { - fTreeSave = val; ///< If SaveDataToTree is set the data is stored at the end of the buffering into the given TClonesArray. + virtual void SaveDataToTree(Bool_t val = kTRUE) + { + fTreeSave = val; ///< If SaveDataToTree is set the data is stored at the end of the buffering into the given + ///< TClonesArray. } - virtual void ActivateBuffering(Bool_t val = kTRUE) { - fActivateBuffering=val; ///< fActivateBuffering has to be set to kTRUE to use the buffering. Otherwise the data is directly stored in the given TClonesArray. + virtual void ActivateBuffering(Bool_t val = kTRUE) + { + fActivateBuffering = val; ///< fActivateBuffering has to be set to kTRUE to use the buffering. Otherwise the + ///< data is directly stored in the given TClonesArray. } - Bool_t IsBufferingActivated(){ return fActivateBuffering;} + Bool_t IsBufferingActivated() { return fActivateBuffering; } -/// Fills a pointer to a data object into the buffer. StartTime gives the time when the data can influence later data, activeTime gives the time how long the data can influence later data. -/// Both time data has to be given as an absolute time! + /// Fills a pointer to a data object into the buffer. StartTime gives the time when the data can influence later + /// data, activeTime gives the time how long the data can influence later data. Both time data has to be given as an + /// absolute time! virtual void FillNewData(FairTimeStamp* data, double startTime, double activeTime); - virtual Int_t GetNData() { - return fDeadTime_map.size(); - } + virtual Int_t GetNData() { return fDeadTime_map.size(); } virtual std::vector GetRemoveOldData(double time); virtual std::vector GetAllData(); - virtual void SetVerbose(Int_t val) { - fVerbose = val; - } + virtual void SetVerbose(Int_t val) { fVerbose = val; } - virtual void DeleteOldData() { - if ( fBranchName.Length() > 0 ) { - TClonesArray* myArray = FairRootManager::Instance()->GetTClonesArray(fBranchName); - myArray->Delete(); - } + virtual void DeleteOldData() + { + if (fBranchName.Length() > 0) { + TClonesArray* myArray = FairRootManager::Instance()->GetTClonesArray(fBranchName); + myArray->Delete(); + } } virtual void WriteOutData(double time); virtual void WriteOutAllData(); protected: - virtual void AddNewDataToTClonesArray(FairTimeStamp* data) = 0; ///< store the data from the FairTimeStamp pointer in a TClonesArray (you have to cast it to your type of data) - virtual double FindTimeForData(FairTimeStamp* data) = 0; ///< if the same data object (like a pad or a pixel) is already present in the buffer, the time of this object has to be returned otherwise -1 - virtual void FillDataMap(FairTimeStamp* data, double activeTime) = 0; ///< add a new element in the search buffer - virtual void EraseDataFromDataMap(FairTimeStamp* data) = 0; ///< delete the element from the search buffer (see PndSdsDigiPixelWriteoutBuffer) - - ///Modify defines the behavior of the buffer if data should be stored which is already in the buffer. Parameters are the old data with the active time, the new data with an active time. - ///Modify returns than a vector with the new data which should be stored. - virtual std::vector > Modify(std::pair oldData, std::pair) { - std::vector > result; - result.push_back(oldData); - return result; + virtual void AddNewDataToTClonesArray( + FairTimeStamp* data) = 0; ///< store the data from the FairTimeStamp pointer in a TClonesArray (you have to + ///< cast it to your type of data) + virtual double FindTimeForData( + FairTimeStamp* data) = 0; ///< if the same data object (like a pad or a pixel) is already present in the + ///< buffer, the time of this object has to be returned otherwise -1 + virtual void FillDataMap(FairTimeStamp* data, double activeTime) = 0; ///< add a new element in the search buffer + virtual void EraseDataFromDataMap( + FairTimeStamp* data) = 0; ///< delete the element from the search buffer (see PndSdsDigiPixelWriteoutBuffer) + + /// Modify defines the behavior of the buffer if data should be stored which is already in the buffer. Parameters + /// are the old data with the active time, the new data with an active time. Modify returns than a vector with the + /// new data which should be stored. + virtual std::vector> Modify(std::pair oldData, + std::pair) + { + std::vector> result; + result.push_back(oldData); + return result; } virtual void WriteOutDataDeadTimeMap(double time); virtual void MoveDataFromStartTimeMapToDeadTimeMap(double time); virtual void FillDataToDeadTimeMap(FairTimeStamp* data, double activeTime, double startTime); - virtual void PrintData(FairTimeStamp* data) { - std::cout << data->GetTimeStamp(); - }; ///< Method should be overwritten in derived classes to print the data of an object stored in the buffer + virtual void PrintData(FairTimeStamp* data) + { + std::cout << data->GetTimeStamp(); + }; ///< Method should be overwritten in derived classes to print the data of an object stored in the buffer virtual void PrintDeadTimeMap(); virtual void PrintStartTimeMap(); - std::multimap > fStartTime_map; + std::multimap> fStartTime_map; std::multimap fDeadTime_map; TString fBranchName; @@ -118,7 +137,7 @@ class FairWriteoutBuffer: public TObject Bool_t fTreeSave; Bool_t fActivateBuffering; Int_t fVerbose; - FairLogger* fLogger; //! /// FairLogger + FairLogger* fLogger; //! /// FairLogger private: FairWriteoutBuffer(const FairWriteoutBuffer&); diff --git a/base/steer/FairWriteoutBufferAbsBasis.h b/base/steer/FairWriteoutBufferAbsBasis.h index fe17a0d062..145855f390 100644 --- a/base/steer/FairWriteoutBufferAbsBasis.h +++ b/base/steer/FairWriteoutBufferAbsBasis.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* @@ -20,12 +20,12 @@ class FairWriteoutBufferAbsBasis : public TObject { public: - virtual ~FairWriteoutBufferAbsBasis() {}; + virtual ~FairWriteoutBufferAbsBasis(){}; virtual void WriteOutData(double time) = 0; virtual void WriteOutAllData() = 0; - ClassDef(FairWriteoutBufferAbsBasis,1) + ClassDef(FairWriteoutBufferAbsBasis, 1) }; #endif /* FAIRWRITEOUTBUFFERABSBASIS_H_ */ diff --git a/check-format.sh b/check-format.sh new file mode 100755 index 0000000000..05dffd4db9 --- /dev/null +++ b/check-format.sh @@ -0,0 +1,16 @@ +#!/bin/bash + +BASE_COMMIT=${FAIRROOT_FORMAT_BASE:-HEAD} +GIT_CLANG_FORMAT_BIN=${FAIRROOT_GIT_CLANG_FORMAT_BIN:-git-clang-format} + +FILES=$(git diff --name-only $BASE_COMMIT | grep -E '*\.(h|hpp|c|C|cpp|cxx|tpl)$' | grep -viE '*LinkDef.h$') +RESULT=$($GIT_CLANG_FORMAT_BIN --commit $BASE_COMMIT --diff $FILES --extensions h,hpp,c,C,cpp,cxx,tpl) + +if [ "$RESULT" == "no modified files to format" ] || [ "$RESULT" == "clang-format did not modify any files" ]; then + echo "format check passed." + exit 0 +else + echo "ERROR: format check failed. Suggested changes:" + echo "$RESULT" + exit 1 +fi diff --git a/cmake/modules/FindClangFormat.cmake b/cmake/modules/FindClangFormat.cmake new file mode 100644 index 0000000000..faed2f6563 --- /dev/null +++ b/cmake/modules/FindClangFormat.cmake @@ -0,0 +1,52 @@ +################################################################################ +# Copyright (C) 2020 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" # +################################################################################ + +# Defines the following variables: +# +# ClangFormat_FOUND - Found clang-format and git-clang-format +# CLANG_FORMAT_BIN - clang-format executable +# GIT_CLANG_FORMAT_BIN - git-clang-format executable + +find_program(CLANG_FORMAT_BIN + NAMES clang-format + clang-format-9 + clang-format-8 + clang-format-7 + clang-format-6.0 + clang-format-5.0 + clang-format-4.0 + clang-format-3.9 + clang-format-3.8 + clang-format-3.7 + clang-format-3.6 + clang-format-3.5 + clang-format-3.4 + clang-format-3.3 +) + +find_program(GIT_CLANG_FORMAT_BIN + NAMES git-clang-format + git-clang-format-9 + git-clang-format-8 + git-clang-format-7 + git-clang-format-6.0 + git-clang-format-5.0 + git-clang-format-4.0 + git-clang-format-3.9 + git-clang-format-3.8 + git-clang-format-3.7 + git-clang-format-3.6 + git-clang-format-3.5 + git-clang-format-3.4 + git-clang-format-3.3 +) + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(ClangFormat + REQUIRED_VARS CLANG_FORMAT_BIN GIT_CLANG_FORMAT_BIN +) diff --git a/datamatch/FairMCDataCrawler.cxx b/datamatch/FairMCDataCrawler.cxx index 76889ec9c5..8a5f3633e0 100644 --- a/datamatch/FairMCDataCrawler.cxx +++ b/datamatch/FairMCDataCrawler.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* @@ -13,33 +13,30 @@ */ #include "FairMCDataCrawler.h" -#include "FairLink.h" // for FairLink, operator<< -#include "FairRootManager.h" // for FairRootManager -#include // for operator<<, ostream, cout, etc +#include "FairLink.h" // for FairLink, operator<< +#include "FairRootManager.h" // for FairRootManager + +#include // for operator<<, ostream, cout, etc ClassImp(FairMCDataCrawler); FairMCDataCrawler::FairMCDataCrawler() - : fIoman(FairRootManager::Instance()), - fFinalStage(), - fUltimateStage(0), - fVerbose(0), - fStoreAllEndpoints(kTRUE), - fStoreIntermediate(kTRUE) -{ -} + : fIoman(FairRootManager::Instance()) + , fFinalStage() + , fUltimateStage(0) + , fVerbose(0) + , fStoreAllEndpoints(kTRUE) + , fStoreIntermediate(kTRUE) +{} -FairMCDataCrawler::~FairMCDataCrawler() -{ -} +FairMCDataCrawler::~FairMCDataCrawler() {} void FairMCDataCrawler::Init() { - - InitDataObjects(); - /* + InitDataObjects(); + /* fIoman->GetObject("MVDPoint"); fIoman->GetObject("MVDStripDigis"); fIoman->GetObject("MVDPixelDigis"); @@ -103,141 +100,154 @@ void FairMCDataCrawler::Init() FairMultiLinkedData FairMCDataCrawler::GetInfo(FairMultiLinkedData startLink, TString stopStage) { - return GetInfo(startLink, fIoman->GetBranchId(stopStage)); + return GetInfo(startLink, fIoman->GetBranchId(stopStage)); } FairMultiLinkedData FairMCDataCrawler::GetInfo(FairMultiLinkedData startLink, Int_t stopStageId) { - fFinalStage.ResetLinks(); - if (fVerbose > 1) { - std::cout << "-------------------------------------" << std::endl; - std::cout << "StartLink: " << startLink; - } - if (fVerbose > 1) { std::cout << "StopStageLink: " << fIoman->GetBranchName(stopStageId) << std::endl; } - GetNextStage(startLink, stopStageId); - if (fVerbose > 1) { std::cout << "FinalStage: " << fFinalStage << std::endl; } - return fFinalStage; + fFinalStage.ResetLinks(); + if (fVerbose > 1) { + std::cout << "-------------------------------------" << std::endl; + std::cout << "StartLink: " << startLink; + } + if (fVerbose > 1) { + std::cout << "StopStageLink: " << fIoman->GetBranchName(stopStageId) << std::endl; + } + GetNextStage(startLink, stopStageId); + if (fVerbose > 1) { + std::cout << "FinalStage: " << fFinalStage << std::endl; + } + return fFinalStage; } FairMultiLinkedData* FairMCDataCrawler::GetEntry(FairLink link) { - return static_cast(FairRootManager::Instance()->GetCloneOfLinkData(link)); + return static_cast(FairRootManager::Instance()->GetCloneOfLinkData(link)); } FairMultiLinkedData* FairMCDataCrawler::GetEntry(Int_t fileId, Int_t eventNr, Int_t type, Int_t index) { - return GetEntry(FairLink(fileId, eventNr, type, index)); + return GetEntry(FairLink(fileId, eventNr, type, index)); } void FairMCDataCrawler::GetNextStage(FairMultiLinkedData& startStage, Int_t stopStage) { - FairMultiLinkedData* tempStage; - for (int i = 0; i < startStage.GetNLinks(); i++) { - FairLink actualLink = startStage.GetLink(i); -// if (fVerbose > 0) { std::cout << "Actual Link: " << actualLink << std::endl; } - if (actualLink.GetType() < 0) { - if (fStoreAllEndpoints) { AddToFinalStage(actualLink, 1); } - if (fVerbose > 2) { - std::cout << "ActualLink.Type < 0" << std::endl; - std::cout << "FinalStage: " << fFinalStage << std::endl; - std::cout << "---------------------" << std::endl; - } - if (fVerbose > 1) { - std::cout << std::endl; - } - } else if (actualLink.GetType() == stopStage) { - AddToFinalStage(actualLink, 1); - if (fVerbose > 2) { - std::cout << "ActualLink.Type == stopStage" << std::endl; - std::cout << "FinalStage: " << fFinalStage << std::endl; - std::cout << "---------------------" << std::endl; - } - if (fVerbose > 1) { - std::cout << std::endl; - } - } else if (actualLink.GetType() == fUltimateStage) { - if (fStoreAllEndpoints) { AddToFinalStage(actualLink, 1); } - if (fVerbose > 2) { - std::cout << "ActualLink.Type == UltimateStage" << std::endl; - std::cout << "FinalStage: " << fFinalStage << std::endl; - std::cout << "---------------------" << std::endl; - } - if (fVerbose > 1) { - std::cout << std::endl; - } - } else if (actualLink.GetType() == FairRootManager::Instance()->GetBranchId("EventHeader.")) { - if (fStoreAllEndpoints) { AddToFinalStage(actualLink, 1); } - if (fVerbose > 2) { - std::cout << "ActualLink.Type == EventHeader" << std::endl; - std::cout << "FinalStage: " << fFinalStage << std::endl; - std::cout << "---------------------" << std::endl; - } - if (fVerbose > 1) { - std::cout << std::endl; - } - } else { - tempStage = GetEntry(actualLink); - if (tempStage == 0) { - if (fStoreAllEndpoints) { AddToFinalStage(actualLink, 1); } - if (fVerbose > 2) { - std::cout << "TempStage == 0" << std::endl; - std::cout << "FinalStage: " << fFinalStage << std::endl; - std::cout << "---------------------" << std::endl; - } - if (fVerbose > 1) { - std::cout << std::endl; - } - continue; - } - if (fVerbose > 0) { -// std::cout << "TempStage Start"; - std::cout << " // "; - std::cout << actualLink; - std::cout << " --> " << *tempStage; - } - if (tempStage->GetNLinks() == 0) { - if (fStoreAllEndpoints) { AddToFinalStage(actualLink,1); } - if (fVerbose > 0) { - std::cout << "tempStage->GetNLinks == 0" << std::endl; - std::cout << "FinalStage: " << fFinalStage << std::endl; - std::cout << "---------------------" << std::endl; - } - } else { - if(fStoreIntermediate) { AddToFinalStage(actualLink, 1); } - double tempStageWeight = 1; - double startLinkWeight = startStage.GetLink(i).GetWeight(); - - if (fVerbose > 2) { - //std::cout << "Tempstage " << tempStage.GetSource() << ": weight " << tempStageWeight << std::endl; - std::cout << "StartLinkWeight " << startLinkWeight << std::endl; - } - //std::cout << " StageWeight: " << tempStageWeight << " startLinkWeight: " << startLinkWeight; - tempStage->MultiplyAllWeights(tempStageWeight); - - if ((tempStageWeight * startLinkWeight) == 0) { - tempStage->MultiplyAllWeights(tempStageWeight); - tempStage->AddAllWeights(startLinkWeight/startStage.GetNLinks()); - if (fVerbose > 2) { - std::cout << " NLinks: " << tempStage->GetNLinks() << " "; - std::cout << "AddAllWeights: " << startLinkWeight/startStage.GetNLinks() << std::endl; - } + FairMultiLinkedData* tempStage; + for (int i = 0; i < startStage.GetNLinks(); i++) { + FairLink actualLink = startStage.GetLink(i); + // if (fVerbose > 0) { std::cout << "Actual Link: " << actualLink << std::endl; } + if (actualLink.GetType() < 0) { + if (fStoreAllEndpoints) { + AddToFinalStage(actualLink, 1); + } + if (fVerbose > 2) { + std::cout << "ActualLink.Type < 0" << std::endl; + std::cout << "FinalStage: " << fFinalStage << std::endl; + std::cout << "---------------------" << std::endl; + } + if (fVerbose > 1) { + std::cout << std::endl; + } + } else if (actualLink.GetType() == stopStage) { + AddToFinalStage(actualLink, 1); + if (fVerbose > 2) { + std::cout << "ActualLink.Type == stopStage" << std::endl; + std::cout << "FinalStage: " << fFinalStage << std::endl; + std::cout << "---------------------" << std::endl; + } + if (fVerbose > 1) { + std::cout << std::endl; + } + } else if (actualLink.GetType() == fUltimateStage) { + if (fStoreAllEndpoints) { + AddToFinalStage(actualLink, 1); + } + if (fVerbose > 2) { + std::cout << "ActualLink.Type == UltimateStage" << std::endl; + std::cout << "FinalStage: " << fFinalStage << std::endl; + std::cout << "---------------------" << std::endl; + } + if (fVerbose > 1) { + std::cout << std::endl; + } + } else if (actualLink.GetType() == FairRootManager::Instance()->GetBranchId("EventHeader.")) { + if (fStoreAllEndpoints) { + AddToFinalStage(actualLink, 1); + } + if (fVerbose > 2) { + std::cout << "ActualLink.Type == EventHeader" << std::endl; + std::cout << "FinalStage: " << fFinalStage << std::endl; + std::cout << "---------------------" << std::endl; + } + if (fVerbose > 1) { + std::cout << std::endl; + } } else { - tempStage->MultiplyAllWeights(startLinkWeight); - if (fVerbose > 2) { - std::cout << "MultiplyAllWeights: " << startLinkWeight << std::endl; - } + tempStage = GetEntry(actualLink); + if (tempStage == 0) { + if (fStoreAllEndpoints) { + AddToFinalStage(actualLink, 1); + } + if (fVerbose > 2) { + std::cout << "TempStage == 0" << std::endl; + std::cout << "FinalStage: " << fFinalStage << std::endl; + std::cout << "---------------------" << std::endl; + } + if (fVerbose > 1) { + std::cout << std::endl; + } + continue; + } + if (fVerbose > 0) { + // std::cout << "TempStage Start"; + std::cout << " // "; + std::cout << actualLink; + std::cout << " --> " << *tempStage; + } + if (tempStage->GetNLinks() == 0) { + if (fStoreAllEndpoints) { + AddToFinalStage(actualLink, 1); + } + if (fVerbose > 0) { + std::cout << "tempStage->GetNLinks == 0" << std::endl; + std::cout << "FinalStage: " << fFinalStage << std::endl; + std::cout << "---------------------" << std::endl; + } + } else { + if (fStoreIntermediate) { + AddToFinalStage(actualLink, 1); + } + double tempStageWeight = 1; + double startLinkWeight = startStage.GetLink(i).GetWeight(); + + if (fVerbose > 2) { + // std::cout << "Tempstage " << tempStage.GetSource() << ": weight " << tempStageWeight << + // std::endl; + std::cout << "StartLinkWeight " << startLinkWeight << std::endl; + } + // std::cout << " StageWeight: " << tempStageWeight << " startLinkWeight: " << startLinkWeight; + tempStage->MultiplyAllWeights(tempStageWeight); + + if ((tempStageWeight * startLinkWeight) == 0) { + tempStage->MultiplyAllWeights(tempStageWeight); + tempStage->AddAllWeights(startLinkWeight / startStage.GetNLinks()); + if (fVerbose > 2) { + std::cout << " NLinks: " << tempStage->GetNLinks() << " "; + std::cout << "AddAllWeights: " << startLinkWeight / startStage.GetNLinks() << std::endl; + } + } else { + tempStage->MultiplyAllWeights(startLinkWeight); + if (fVerbose > 2) { + std::cout << "MultiplyAllWeights: " << startLinkWeight << std::endl; + } + } + } + // if (fVerbose > 0) + // std::cout<< "TempStage Stop: " << *tempStage << std::endl; + + GetNextStage(*tempStage, stopStage); } - - } - // if (fVerbose > 0) - // std::cout<< "TempStage Stop: " << *tempStage << std::endl; - - GetNextStage(*tempStage, stopStage); } - } } -void FairMCDataCrawler::AddToFinalStage(FairLink hitPair, Float_t mult) -{ - fFinalStage.AddLink(hitPair, false, mult); -} +void FairMCDataCrawler::AddToFinalStage(FairLink hitPair, Float_t mult) { fFinalStage.AddLink(hitPair, false, mult); } diff --git a/datamatch/FairMCDataCrawler.h b/datamatch/FairMCDataCrawler.h index 2cf72ea35a..e64112d6d6 100644 --- a/datamatch/FairMCDataCrawler.h +++ b/datamatch/FairMCDataCrawler.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* @@ -15,12 +15,11 @@ #ifndef FAIRMCDATACRAWLER_H_ #define FAIRMCDATACRAWLER_H_ -#include // for TObject +#include "FairMultiLinkedData.h" // for FairMultiLinkedData -#include "FairMultiLinkedData.h" // for FairMultiLinkedData - -#include // for Int_t, Bool_t, etc -#include // for TString +#include // for Int_t, Bool_t, etc +#include // for TObject +#include // for TString class FairLink; class FairRootManager; @@ -37,12 +36,12 @@ class FairMCDataCrawler : public TObject FairMultiLinkedData* GetEntry(Int_t fileId, Int_t eventNr, Int_t type, Int_t index); FairMultiLinkedData* GetEntry(FairLink link); - void SetStoreIntermediate(Bool_t val = kTRUE) {fStoreIntermediate = val;} - void SetStoreAllEndpoints(Bool_t val = kTRUE) {fStoreAllEndpoints = val;} + void SetStoreIntermediate(Bool_t val = kTRUE) { fStoreIntermediate = val; } + void SetStoreAllEndpoints(Bool_t val = kTRUE) { fStoreAllEndpoints = val; } void Init(); - void SetVerbose(Int_t val) {fVerbose = val;}; + void SetVerbose(Int_t val) { fVerbose = val; }; virtual void InitDataObjects() = 0; @@ -51,11 +50,11 @@ class FairMCDataCrawler : public TObject private: FairMultiLinkedData fFinalStage; - Int_t fUltimateStage; ///< last stage in link chain. Here all recursive operations must stop. + Int_t fUltimateStage; ///< last stage in link chain. Here all recursive operations must stop. Int_t fVerbose; - Bool_t fStoreAllEndpoints; ///< true if non-stop-stage data is stored in results - Bool_t fStoreIntermediate; ///< true if all intermediate steps should be stored + Bool_t fStoreAllEndpoints; ///< true if non-stop-stage data is stored in results + Bool_t fStoreIntermediate; ///< true if all intermediate steps should be stored void GetNextStage(FairMultiLinkedData& startEntry, Int_t stopStage); void AddToFinalStage(FairLink link, Float_t mult); diff --git a/datamatch/FairMCEntry.cxx b/datamatch/FairMCEntry.cxx index fff02b7706..e8e50433bd 100644 --- a/datamatch/FairMCEntry.cxx +++ b/datamatch/FairMCEntry.cxx @@ -17,28 +17,25 @@ ClassImp(FairMCEntry); FairMCEntry::FairMCEntry() - : FairMultiLinkedData(), - fSource(-1), - fPos(-1) + : FairMultiLinkedData() + , fSource(-1) + , fPos(-1) { - SetPersistanceCheck(kFALSE); + SetPersistanceCheck(kFALSE); } -FairMCEntry::~FairMCEntry() -{ -} +FairMCEntry::~FairMCEntry() {} void FairMCEntry::RemoveType(Int_t type) { - // std::set::iterator endIter = fLinks.end(); - std::set::iterator it = fLinks.begin(); - for (; it!=fLinks.end();) { - if (it->GetType() == type) { - fLinks.erase(it); - it = fLinks.begin(); - } else { - ++it; + // std::set::iterator endIter = fLinks.end(); + std::set::iterator it = fLinks.begin(); + for (; it != fLinks.end();) { + if (it->GetType() == type) { + fLinks.erase(it); + it = fLinks.begin(); + } else { + ++it; + } } - } } - diff --git a/datamatch/FairMCEntry.h b/datamatch/FairMCEntry.h index 5dc6ab259f..c0c7f63b64 100644 --- a/datamatch/FairMCEntry.h +++ b/datamatch/FairMCEntry.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* @@ -15,49 +15,49 @@ #ifndef FAIRMCENTRY_H_ #define FAIRMCENTRY_H_ -#include "FairMultiLinkedData.h" // for FairMultiLinkedData -#include "FairLink.h" // for FairLink +#include "FairLink.h" // for FairLink +#include "FairMultiLinkedData.h" // for FairMultiLinkedData -#include // for Int_t, FairMCEntry::Class, etc - -#include // for ostream -#include // for set +#include // for Int_t, FairMCEntry::Class, etc +#include // for ostream +#include // for set class FairMCEntry : public FairMultiLinkedData { public: FairMCEntry(); FairMCEntry(std::set links, Int_t source = -1, Int_t pos = -1) - : FairMultiLinkedData(links), - fSource(source), - fPos(pos) { - SetPersistanceCheck(kFALSE); + : FairMultiLinkedData(links) + , fSource(source) + , fPos(pos) + { + SetPersistanceCheck(kFALSE); } FairMCEntry(FairMultiLinkedData links, Int_t source = -1, Int_t pos = -1) - : FairMultiLinkedData(links), - fSource(source), - fPos(pos) { - SetPersistanceCheck(kFALSE); + : FairMultiLinkedData(links) + , fSource(source) + , fPos(pos) + { + SetPersistanceCheck(kFALSE); } - void SetSource(Int_t source) {fSource = source;} - void SetPos(Int_t pos) {fPos = pos;} + void SetSource(Int_t source) { fSource = source; } + void SetPos(Int_t pos) { fPos = pos; } - Int_t GetSource() const {return fSource;} - Int_t GetPos() const {return fPos;} + Int_t GetSource() const { return fSource; } + Int_t GetPos() const { return fPos; } void RemoveType(Int_t type); virtual ~FairMCEntry(); - virtual void PrintInfo(std::ostream& out) { - out << *this; - } + virtual void PrintInfo(std::ostream& out) { out << *this; } - friend std::ostream& operator<< (std::ostream& out, const FairMCEntry& link) { - (static_cast(link)).PrintLinkInfo(out); - return out; + friend std::ostream& operator<<(std::ostream& out, const FairMCEntry& link) + { + (static_cast(link)).PrintLinkInfo(out); + return out; } private: diff --git a/datamatch/FairMCList.cxx b/datamatch/FairMCList.cxx index fa5fdd7d81..46b7498fb7 100644 --- a/datamatch/FairMCList.cxx +++ b/datamatch/FairMCList.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* @@ -17,13 +17,10 @@ ClassImp(FairMCList); FairMCList::FairMCList() - : TObject(), - fList(), - fEntry(-1), - fType(-1) -{ -} + : TObject() + , fList() + , fEntry(-1) + , fType(-1) +{} -FairMCList::~FairMCList() -{ -} +FairMCList::~FairMCList() {} diff --git a/datamatch/FairMCList.h b/datamatch/FairMCList.h index f22480a2ee..ea76b498bc 100644 --- a/datamatch/FairMCList.h +++ b/datamatch/FairMCList.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* @@ -15,42 +15,41 @@ #ifndef FAIRMCLIST_H_ #define FAIRMCLIST_H_ -#include // for TObject -#include // for Int_t, FairMCList::Class, etc - -#include // for vector +#include // for Int_t, FairMCList::Class, etc +#include // for TObject +#include // for vector class FairMCList : public TObject { public: FairMCList(); FairMCList(Int_t type, Int_t entry) - : TObject(), - fList(), - fEntry(entry), - fType(type) { - } + : TObject() + , fList() + , fEntry(entry) + , fType(type) + {} FairMCList(Int_t type, Int_t entry, std::vector list) - : TObject(), - fList(list), - fEntry(entry), - fType(type) { - } + : TObject() + , fList(list) + , fEntry(entry) + , fType(type) + {} virtual ~FairMCList(); - void SetType(Int_t type) { fType = type;} - void SetEntry(Int_t entry) { fEntry = entry;} - void AddElement(Int_t element) {fList.push_back(element);} + void SetType(Int_t type) { fType = type; } + void SetEntry(Int_t entry) { fEntry = entry; } + void AddElement(Int_t element) { fList.push_back(element); } - Int_t GetType() const {return fType;} - Int_t GetEntry() const {return fEntry;} - Int_t GetNElements() const {return fList.size();} - Int_t GetElement(Int_t index)const {return fList.at(index);} - std::vector GetElements() const {return fList;} + Int_t GetType() const { return fType; } + Int_t GetEntry() const { return fEntry; } + Int_t GetNElements() const { return fList.size(); } + Int_t GetElement(Int_t index) const { return fList.at(index); } + std::vector GetElements() const { return fList; } - void Reset() {fList.clear();} + void Reset() { fList.clear(); } private: std::vector fList; diff --git a/datamatch/FairMCMatch.cxx b/datamatch/FairMCMatch.cxx index db311252c6..04cddd1c7c 100644 --- a/datamatch/FairMCMatch.cxx +++ b/datamatch/FairMCMatch.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* @@ -14,392 +14,373 @@ #include "FairMCMatch.h" -#include "FairLink.h" // for FairLink -#include "FairRootManager.h" // for FairRootManager +#include "FairLink.h" // for FairLink +#include "FairRootManager.h" // for FairRootManager -#include // for TClonesArray - -#include // for operator<<, basic_ostream, etc +#include // for TClonesArray +#include // for operator<<, basic_ostream, etc ClassImp(FairMCMatch); FairMCMatch::FairMCMatch() - : TNamed(), - fUltimateStage(0), - fList(), - fFinalStageML(), - fVerbose(0) + : TNamed() + , fUltimateStage(0) + , fList() + , fFinalStageML() + , fVerbose(0) { - fFinalStageML.SetPersistanceCheck(kFALSE); + fFinalStageML.SetPersistanceCheck(kFALSE); } FairMCMatch::~FairMCMatch() { - for (TListIterator iter = fList.begin(); iter != fList.end(); iter++) { - delete(iter->second); - } - fList.clear(); + for (TListIterator iter = fList.begin(); iter != fList.end(); iter++) { + delete (iter->second); + } + fList.clear(); } void FairMCMatch::AddElement(Int_t sourceType, int index, Int_t targetType, int link) { - FairLink myPair(targetType, link); - AddElement(sourceType, index, myPair); -} - -void FairMCMatch::AddElement(Int_t type, int index, FairLink link) -{ - fList[type]->AddLink(link, index); + FairLink myPair(targetType, link); + AddElement(sourceType, index, myPair); } - +void FairMCMatch::AddElement(Int_t type, int index, FairLink link) { fList[type]->AddLink(link, index); } void FairMCMatch::SetElements(Int_t sourceType, int index, FairMultiLinkedData* links) { - fList[sourceType]->SetEntry(links, index); + fList[sourceType]->SetEntry(links, index); } void FairMCMatch::InitStage(Int_t type, const std::string& fileName, const std::string& branchName) { - if (fList[type] == 0) { - FairMCStage* newStage = new FairMCStage(type, fileName, branchName); - fList[type] = newStage; - if (fVerbose > 1) { - std::cout << "InitStages: " << *newStage; + if (fList[type] == 0) { + FairMCStage* newStage = new FairMCStage(type, fileName, branchName); + fList[type] = newStage; + if (fVerbose > 1) { + std::cout << "InitStages: " << *newStage; + } + } else { + std::cout << "-W- FairMCMatch::InitStage: Stage " << type << " exists already!" << std::endl; } - } else { - std::cout << "-W- FairMCMatch::InitStage: Stage " << type << " exists already!" << std::endl; - } } void FairMCMatch::InitStage(const std::string& branchName, const std::string& fileName) { - FairRootManager* ioman = FairRootManager::Instance(); - if (ioman->CheckBranch(branchName.c_str()) == 1) { - Int_t type = ioman->GetBranchId(branchName.c_str()); - if (type > -1) { - InitStage(type, fileName, branchName); + FairRootManager* ioman = FairRootManager::Instance(); + if (ioman->CheckBranch(branchName.c_str()) == 1) { + Int_t type = ioman->GetBranchId(branchName.c_str()); + if (type > -1) { + InitStage(type, fileName, branchName); + } else { + std::cout << "-W- FairMCMatch::InitStage: Branch name " << branchName << " not registered!" << std::endl; + } } else { - std::cout << "-W- FairMCMatch::InitStage: Branch name " << branchName << " not registered!" << std::endl; + std::cout << "-W- FairMCMatch::InitStage: Branch name " << branchName << " not persistant!" << std::endl; } - } else { - std::cout << "-W- FairMCMatch::InitStage: Branch name " << branchName << " not persistant!" << std::endl; - } -} - -void FairMCMatch::RemoveStage(Int_t type) -{ - fList.erase(type); } +void FairMCMatch::RemoveStage(Int_t type) { fList.erase(type); } void FairMCMatch::SetCommonWeightStages(Float_t weight) { - for (int i = 0; i < GetNMCStages(); i++) { - if (GetMCStage(i)) { - GetMCStage(i)->SetWeight(weight); + for (int i = 0; i < GetNMCStages(); i++) { + if (GetMCStage(i)) { + GetMCStage(i)->SetWeight(weight); + } } - } } FairMCResult FairMCMatch::GetMCInfo(TString start, TString stop) { - FairRootManager* ioman = FairRootManager::Instance(); - return GetMCInfo(ioman->GetBranchId(start), ioman->GetBranchId(stop)); + FairRootManager* ioman = FairRootManager::Instance(); + return GetMCInfo(ioman->GetBranchId(start), ioman->GetBranchId(stop)); } FairMCResult FairMCMatch::GetMCInfo(Int_t start, Int_t stop) { - FairMCResult result(start, stop); - if(!IsTypeInList(start)) { - return result; - } - if (start < stop) { - return GetMCInfoForward(start, stop); - } else { - return GetMCInfoBackward(start, stop); - } + FairMCResult result(start, stop); + if (!IsTypeInList(start)) { + return result; + } + if (start < stop) { + return GetMCInfoForward(start, stop); + } else { + return GetMCInfoBackward(start, stop); + } } FairMCEntry FairMCMatch::GetMCInfoSingle(FairLink aLink, TString stop) { - FairRootManager* ioman = FairRootManager::Instance(); - return GetMCInfoSingle(aLink, ioman->GetBranchId(stop)); + FairRootManager* ioman = FairRootManager::Instance(); + return GetMCInfoSingle(aLink, ioman->GetBranchId(stop)); } FairMCEntry FairMCMatch::GetMCInfoSingle(FairLink aLink, Int_t stop) { - FairMCEntry result; - if(!IsTypeInList(static_cast(aLink.GetType()))) { - return result; - } - if(!(fList[static_cast(aLink.GetType())]->GetNEntries() > aLink.GetIndex())) { - return result; - } + FairMCEntry result; + if (!IsTypeInList(static_cast(aLink.GetType()))) { + return result; + } + if (!(fList[static_cast(aLink.GetType())]->GetNEntries() > aLink.GetIndex())) { + return result; + } - if (aLink.GetType() < stop) { - return GetMCInfoForwardSingle(aLink, stop); - } else { - return GetMCInfoBackwardSingle(aLink, stop); - } + if (aLink.GetType() < stop) { + return GetMCInfoForwardSingle(aLink, stop); + } else { + return GetMCInfoBackwardSingle(aLink, stop); + } } FairMCResult FairMCMatch::GetMCInfoForward(Int_t start, Int_t stop) { - FairMCResult result(start, stop); - FairMCStage startVec = *(fList[start]); - for (int i = 0; i < startVec.GetNEntries(); i++) { - FairLink tempLink(startVec.GetStageId(), i); - - FairMCEntry tempEntry(GetMCInfoForwardSingle(tempLink, stop)); - if (tempEntry.GetNLinks() > 0) - if (tempEntry.GetLink(0).GetType() == start) { - tempEntry.DeleteLink(tempEntry.GetLink(0)); - } - tempEntry.SetSource(start); - tempEntry.SetPos(i); - result.SetEntry(tempEntry); - } - return result; + FairMCResult result(start, stop); + FairMCStage startVec = *(fList[start]); + for (int i = 0; i < startVec.GetNEntries(); i++) { + FairLink tempLink(startVec.GetStageId(), i); + + FairMCEntry tempEntry(GetMCInfoForwardSingle(tempLink, stop)); + if (tempEntry.GetNLinks() > 0) + if (tempEntry.GetLink(0).GetType() == start) { + tempEntry.DeleteLink(tempEntry.GetLink(0)); + } + tempEntry.SetSource(start); + tempEntry.SetPos(i); + result.SetEntry(tempEntry); + } + return result; } FairMCEntry FairMCMatch::GetMCInfoForwardSingle(FairLink link, Int_t stop) { - FairMCEntry result; - ClearFinalStage(); - - FairMultiLinkedData tempStage; - tempStage.SetPersistanceCheck(kFALSE); - tempStage.AddLink(link, true); - FindStagesPointingToLinks(tempStage, stop); - result.SetLinks(fFinalStageML); - return result; + FairMCEntry result; + ClearFinalStage(); + + FairMultiLinkedData tempStage; + tempStage.SetPersistanceCheck(kFALSE); + tempStage.AddLink(link, true); + FindStagesPointingToLinks(tempStage, stop); + result.SetLinks(fFinalStageML); + return result; } FairMCResult FairMCMatch::GetMCInfoBackward(Int_t start, Int_t stop) { - FairMCResult result(start, stop); - FairMCStage startVec = *(fList[start]); - for (int i = 0; i < startVec.GetNEntries(); i++) { - FairLink tempLink(start, i); - GetMCInfoBackwardSingle(tempLink, stop, startVec.GetWeight()); - result.SetEntry(&fFinalStageML, result.GetNEntries()); - } - return result; + FairMCResult result(start, stop); + FairMCStage startVec = *(fList[start]); + for (int i = 0; i < startVec.GetNEntries(); i++) { + FairLink tempLink(start, i); + GetMCInfoBackwardSingle(tempLink, stop, startVec.GetWeight()); + result.SetEntry(&fFinalStageML, result.GetNEntries()); + } + return result; } FairMCEntry FairMCMatch::GetMCInfoBackwardSingle(FairLink aLink, Int_t stop, Double_t weight) { - FairMCEntry result; - FairMultiLinkedData multiLink = fList[static_cast(aLink.GetType())]->GetEntry(aLink.GetIndex()); + FairMCEntry result; + FairMultiLinkedData multiLink = fList[static_cast(aLink.GetType())]->GetEntry(aLink.GetIndex()); - ClearFinalStage(); - multiLink.MultiplyAllWeights(weight); - GetNextStage(multiLink, stop); - result.SetLinks(fFinalStageML); + ClearFinalStage(); + multiLink.MultiplyAllWeights(weight); + GetNextStage(multiLink, stop); + result.SetLinks(fFinalStageML); - return result; + return result; } - void FairMCMatch::FindStagesPointingToLinks(FairMultiLinkedData links, Int_t stop) { - FairMultiLinkedData tempLinks; - tempLinks.SetPersistanceCheck(kFALSE); - for (int i = 0; i < links.GetNLinks(); i++) { - FairLink myLink = links.GetLink(i); - FairMultiLinkedData myNewLinks = FindStagesPointingToLink(myLink); - myNewLinks.SetPersistanceCheck(kFALSE); - if (myNewLinks.GetNLinks() == 0) { - fFinalStageML.AddLink(myLink, true); - } else { - for (int j = 0; j < myNewLinks.GetNLinks(); j++) { - if (myNewLinks.GetLink(j).GetType() == static_cast(stop)) { - fFinalStageML.AddLink(myNewLinks.GetLink(j), true); - } else if (myNewLinks.GetLink(j).GetType() > static_cast(stop)) { - fFinalStageML.AddLink(myLink, true); + FairMultiLinkedData tempLinks; + tempLinks.SetPersistanceCheck(kFALSE); + for (int i = 0; i < links.GetNLinks(); i++) { + FairLink myLink = links.GetLink(i); + FairMultiLinkedData myNewLinks = FindStagesPointingToLink(myLink); + myNewLinks.SetPersistanceCheck(kFALSE); + if (myNewLinks.GetNLinks() == 0) { + fFinalStageML.AddLink(myLink, true); } else { - tempLinks.AddLink(myNewLinks.GetLink(j), true); + for (int j = 0; j < myNewLinks.GetNLinks(); j++) { + if (myNewLinks.GetLink(j).GetType() == static_cast(stop)) { + fFinalStageML.AddLink(myNewLinks.GetLink(j), true); + } else if (myNewLinks.GetLink(j).GetType() > static_cast(stop)) { + fFinalStageML.AddLink(myLink, true); + } else { + tempLinks.AddLink(myNewLinks.GetLink(j), true); + } + } } - } } - } - if (tempLinks.GetNLinks() != 0) { - FindStagesPointingToLinks(tempLinks, stop); - } + if (tempLinks.GetNLinks() != 0) { + FindStagesPointingToLinks(tempLinks, stop); + } } - FairMultiLinkedData FairMCMatch::FindStagesPointingToLink(FairLink link) { - FairMultiLinkedData result; - result.SetPersistanceCheck(kFALSE); - TListIteratorConst iter = fList.find(static_cast(link.GetType())); - for(; iter!= fList.end(); iter++) { - if (iter->second->PosInList(link).GetNLinks() > 0) { - result.AddLinks(iter->second->PosInList(link), true); + FairMultiLinkedData result; + result.SetPersistanceCheck(kFALSE); + TListIteratorConst iter = fList.find(static_cast(link.GetType())); + for (; iter != fList.end(); iter++) { + if (iter->second->PosInList(link).GetNLinks() > 0) { + result.AddLinks(iter->second->PosInList(link), true); + } } - } - return result; + return result; } - FairMultiLinkedData FairMCMatch::FindLinksToStage(Int_t stage) { - FairMultiLinkedData result; - result.SetPersistanceCheck(kFALSE); - for (int i = 0; i < GetNMCStages(); i++) { - result.AddLinks(GetMCStage(i)->GetLinksWithType(stage), true); - } - return result; + FairMultiLinkedData result; + result.SetPersistanceCheck(kFALSE); + for (int i = 0; i < GetNMCStages(); i++) { + result.AddLinks(GetMCStage(i)->GetLinksWithType(stage), true); + } + return result; } void FairMCMatch::CreateArtificialStage(const TString& branchName, const std::string& fileName) { - FairRootManager* ioman = FairRootManager::Instance(); - std::cout << "Create Artificial Stage for " << branchName; - std::cout << " with ID " << ioman->GetBranchId(branchName) << std::endl; - if (ioman->GetBranchId(branchName) > -1) { - CreateArtificialStage(ioman->GetBranchId(branchName), fileName, branchName.Data()); - } else { - std::cout << "-E- FairMCMatch::CreateArtificialStage: Branch does not exist: " << branchName << std::endl; - } + FairRootManager* ioman = FairRootManager::Instance(); + std::cout << "Create Artificial Stage for " << branchName; + std::cout << " with ID " << ioman->GetBranchId(branchName) << std::endl; + if (ioman->GetBranchId(branchName) > -1) { + CreateArtificialStage(ioman->GetBranchId(branchName), fileName, branchName.Data()); + } else { + std::cout << "-E- FairMCMatch::CreateArtificialStage: Branch does not exist: " << branchName << std::endl; + } } void FairMCMatch::CreateArtificialStage(Int_t stage, const std::string& fileName, const std::string& branchName) { - FairMultiLinkedData stageLinks = FindLinksToStage(stage); - stageLinks.SetPersistanceCheck(kFALSE); - if (stageLinks.GetNLinks() > 0) { - InitStage(stage, fileName, branchName); - FairMultiLinkedData artData; - artData.SetLink(FairLink(static_cast(-1), -1)); - for (int i = 0; i < stageLinks.GetNLinks(); i++) { - if (stageLinks.GetLink(i).GetIndex() > -1) { - fList[stage]->SetEntry(&artData, stageLinks.GetLink(i).GetIndex()); - } + FairMultiLinkedData stageLinks = FindLinksToStage(stage); + stageLinks.SetPersistanceCheck(kFALSE); + if (stageLinks.GetNLinks() > 0) { + InitStage(stage, fileName, branchName); + FairMultiLinkedData artData; + artData.SetLink(FairLink(static_cast(-1), -1)); + for (int i = 0; i < stageLinks.GetNLinks(); i++) { + if (stageLinks.GetLink(i).GetIndex() > -1) { + fList[stage]->SetEntry(&artData, stageLinks.GetLink(i).GetIndex()); + } + } + fList[stage]->SetLoaded(kTRUE); } - fList[stage]->SetLoaded(kTRUE); - - } } void FairMCMatch::GetNextStage(FairMultiLinkedData& startStage, Int_t stopStage) { - FairMCEntry tempStage; - - for (int i = 0; i < startStage.GetNLinks(); i++) { - if (startStage.GetLink(i).GetType() == stopStage) { - AddToFinalStage(startStage.GetLink(i),1); - if (fVerbose > 0) { - std::cout << "FinalStage: " << fFinalStageML << std::endl; - std::cout << "---------------------" << std::endl; - } - } else if (startStage.GetLink(i).GetType() == fUltimateStage) { - } else { - tempStage = GetEntry(startStage.GetLink(i)); - if (fVerbose > 0) { - std::cout << "TempStage Start"; - startStage.GetLink(i).PrintLinkInfo(); - std::cout << " --> " << tempStage << std::endl; - } - if (tempStage.GetNLinks() == 0) { - AddToFinalStage(startStage.GetLink(i),1); - if (fVerbose > 0) { - std::cout << "FinalStage: " << fFinalStageML << std::endl; - std::cout << "---------------------" << std::endl; - } - } else { - double tempStageWeight = GetMCStageType(static_cast(tempStage.GetSource()))->GetWeight(); - double startLinkWeight = startStage.GetLink(i).GetWeight(); + FairMCEntry tempStage; - if (fVerbose > 0) { - std::cout << "Tempstage " << tempStage.GetSource() << ": weight " << tempStageWeight << std::endl; - std::cout << "StartLinkWeight " << startLinkWeight << std::endl; - } - tempStage.MultiplyAllWeights(tempStageWeight); - - if ((tempStageWeight * startLinkWeight) == 0) { - tempStage.MultiplyAllWeights(tempStageWeight); - tempStage.AddAllWeights(startLinkWeight/startStage.GetNLinks()); - if (fVerbose > 0) { - std::cout << " NLinks: " << tempStage.GetNLinks() << " "; - std::cout << "AddAllWeights: " << startLinkWeight/startStage.GetNLinks() << std::endl; - } + for (int i = 0; i < startStage.GetNLinks(); i++) { + if (startStage.GetLink(i).GetType() == stopStage) { + AddToFinalStage(startStage.GetLink(i), 1); + if (fVerbose > 0) { + std::cout << "FinalStage: " << fFinalStageML << std::endl; + std::cout << "---------------------" << std::endl; + } + } else if (startStage.GetLink(i).GetType() == fUltimateStage) { } else { - tempStage.MultiplyAllWeights(startLinkWeight); - if (fVerbose > 0) { - std::cout << "MultiplyAllWeights: " << startLinkWeight << std::endl; - } + tempStage = GetEntry(startStage.GetLink(i)); + if (fVerbose > 0) { + std::cout << "TempStage Start"; + startStage.GetLink(i).PrintLinkInfo(); + std::cout << " --> " << tempStage << std::endl; + } + if (tempStage.GetNLinks() == 0) { + AddToFinalStage(startStage.GetLink(i), 1); + if (fVerbose > 0) { + std::cout << "FinalStage: " << fFinalStageML << std::endl; + std::cout << "---------------------" << std::endl; + } + } else { + double tempStageWeight = GetMCStageType(static_cast(tempStage.GetSource()))->GetWeight(); + double startLinkWeight = startStage.GetLink(i).GetWeight(); + + if (fVerbose > 0) { + std::cout << "Tempstage " << tempStage.GetSource() << ": weight " << tempStageWeight << std::endl; + std::cout << "StartLinkWeight " << startLinkWeight << std::endl; + } + tempStage.MultiplyAllWeights(tempStageWeight); + + if ((tempStageWeight * startLinkWeight) == 0) { + tempStage.MultiplyAllWeights(tempStageWeight); + tempStage.AddAllWeights(startLinkWeight / startStage.GetNLinks()); + if (fVerbose > 0) { + std::cout << " NLinks: " << tempStage.GetNLinks() << " "; + std::cout << "AddAllWeights: " << startLinkWeight / startStage.GetNLinks() << std::endl; + } + } else { + tempStage.MultiplyAllWeights(startLinkWeight); + if (fVerbose > 0) { + std::cout << "MultiplyAllWeights: " << startLinkWeight << std::endl; + } + } + } + if (fVerbose > 0) { + std::cout << "TempStage Stop: " << tempStage << std::endl; + } + + GetNextStage(tempStage, stopStage); } - - } - if (fVerbose > 0) { - std::cout<< "TempStage Stop: " << tempStage << std::endl; - } - - GetNextStage(tempStage, stopStage); } - } } FairMCEntry FairMCMatch::GetEntry(Int_t type, int index) { - FairMCEntry empty; - if (index < 0) { return empty; } - if (fList[type] == 0) { + FairMCEntry empty; + if (index < 0) { + return empty; + } + if (fList[type] == 0) { + return empty; + } + if (fList[type]->GetNEntries() > index) { + return fList[type]->GetEntry(index); + } return empty; - } - if (fList[type]->GetNEntries() > index) { - return fList[type]->GetEntry(index); - } - return empty; } FairMCEntry FairMCMatch::GetEntry(FairLink link) { - return GetEntry(static_cast(link.GetType()), link.GetIndex()); + return GetEntry(static_cast(link.GetType()), link.GetIndex()); } -void FairMCMatch::AddToFinalStage(FairLink hitPair, Float_t mult) -{ - fFinalStageML.AddLink(hitPair, true, mult); -} +void FairMCMatch::AddToFinalStage(FairLink hitPair, Float_t mult) { fFinalStageML.AddLink(hitPair, true, mult); } -void FairMCMatch::ClearFinalStage() -{ - fFinalStageML.Reset(); -} +void FairMCMatch::ClearFinalStage() { fFinalStageML.Reset(); } void FairMCMatch::ClearMCList() { - for (TListIterator iter = fList.begin(); iter != fList.end(); iter++) { - if (iter->second != 0) { - iter->second->ClearEntries(); - } - } - fList.clear(); + for (TListIterator iter = fList.begin(); iter != fList.end(); iter++) { + if (iter->second != 0) { + iter->second->ClearEntries(); + } + } + fList.clear(); } bool FairMCMatch::IsTypeInList(Int_t type) { - for(TListIterator iter = fList.begin(); iter != fList.end(); iter++) { - if (iter->first == type) { - return true; + for (TListIterator iter = fList.begin(); iter != fList.end(); iter++) { + if (iter->first == type) { + return true; + } } - } - return false; + return false; } void FairMCMatch::LoadInMCLists(TClonesArray* myLinkArray) { - for (int i = 0; i < myLinkArray->GetEntriesFast(); i++) { - FairMCEntry* myLink = static_cast(myLinkArray->At(i)); - if (IsTypeInList(static_cast(myLink->GetSource()))) { - fList[static_cast(myLink->GetSource())]->SetEntry(*myLink); - fList[static_cast(myLink->GetSource())]->SetLoaded(kTRUE); + for (int i = 0; i < myLinkArray->GetEntriesFast(); i++) { + FairMCEntry* myLink = static_cast(myLinkArray->At(i)); + if (IsTypeInList(static_cast(myLink->GetSource()))) { + fList[static_cast(myLink->GetSource())]->SetEntry(*myLink); + fList[static_cast(myLink->GetSource())]->SetLoaded(kTRUE); + } } - } } diff --git a/datamatch/FairMCMatch.h b/datamatch/FairMCMatch.h index bc8034b20a..366523cb44 100644 --- a/datamatch/FairMCMatch.h +++ b/datamatch/FairMCMatch.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* @@ -15,21 +15,19 @@ #ifndef FAIRMCMATCH_H_ #define FAIRMCMATCH_H_ +#include "FairMCEntry.h" // for FairMCEntry +#include "FairMCResult.h" // for FairMCResult +#include "FairMCStage.h" // for FairMCStage +#include "FairMultiLinkedData.h" // for FairMultiLinkedData +#include "FairRootManager.h" // for FairRootManager -#include "FairMCEntry.h" // for FairMCEntry -#include "FairMCResult.h" // for FairMCResult -#include "FairMCStage.h" // for FairMCStage -#include "FairMultiLinkedData.h" // for FairMultiLinkedData -#include "FairRootManager.h" // for FairRootManager - -#include // for Int_t, FairMCMatch::Class, etc -#include // for TNamed -#include // for TString - -#include // for ostream, cout, endl -#include // for map, etc -#include // for string -#include // for pair +#include // for Int_t, FairMCMatch::Class, etc +#include // for TNamed +#include // for TString +#include // for ostream, cout, endl +#include // for map, etc +#include // for string +#include // for pair class FairLink; class TClonesArray; @@ -37,17 +35,18 @@ class TClonesArray; typedef std::map::iterator TListIterator; typedef std::map::const_iterator TListIteratorConst; -class FairMCMatch: public TNamed +class FairMCMatch : public TNamed { public: FairMCMatch(); FairMCMatch(const char* name, const char* title) - : TNamed(name, title), - fUltimateStage(0), - fList(), - fFinalStageML(), - fVerbose(0) { - fFinalStageML.SetPersistanceCheck(kFALSE); + : TNamed(name, title) + , fUltimateStage(0) + , fList() + , fFinalStageML() + , fVerbose(0) + { + fFinalStageML.SetPersistanceCheck(kFALSE); } virtual ~FairMCMatch(); @@ -68,31 +67,31 @@ class FairMCMatch: public TNamed FairMCResult GetMCInfo(Int_t start, Int_t stop); FairMCResult GetMCInfo(TString start, TString stop); - FairMCEntry GetMCInfoSingle(FairLink aLink, Int_t stop); - FairMCEntry GetMCInfoSingle(FairLink aLink, TString stop); + FairMCEntry GetMCInfoSingle(FairLink aLink, Int_t stop); + FairMCEntry GetMCInfoSingle(FairLink aLink, TString stop); - int GetNMCStages() const {return fList.size();} + int GetNMCStages() const { return fList.size(); } - FairMCStage* GetMCStage(int index) const { - TListIteratorConst iter = fList.begin(); - for (int i = 0; i < index; i++) { - iter++; - } - return (iter->second); + FairMCStage* GetMCStage(int index) const + { + TListIteratorConst iter = fList.begin(); + for (int i = 0; i < index; i++) { + iter++; + } + return (iter->second); } - FairMCStage* GetMCStageType(TString branch) { - FairRootManager* ioman = FairRootManager::Instance(); - if (ioman->GetBranchId(branch) > 0) { - return fList[ioman->GetBranchId(branch)]; - } else { - return 0; - } + FairMCStage* GetMCStageType(TString branch) + { + FairRootManager* ioman = FairRootManager::Instance(); + if (ioman->GetBranchId(branch) > 0) { + return fList[ioman->GetBranchId(branch)]; + } else { + return 0; + } } - FairMCStage* GetMCStageType(Int_t type) { - return fList[type]; - } + FairMCStage* GetMCStageType(Int_t type) { return fList[type]; } void CreateArtificialStage(const TString& branchName, const std::string& fileName = ""); void CreateArtificialStage(Int_t stage, const std::string& fileName = "", const std::string& branchName = ""); @@ -101,21 +100,21 @@ class FairMCMatch: public TNamed bool IsTypeInList(Int_t type); - void PrintInfo(std::ostream& out = std::cout) {out << *this;} + void PrintInfo(std::ostream& out = std::cout) { out << *this; } - friend std::ostream& operator<< (std::ostream& out, const FairMCMatch& match) { - for (int i = 0; i < match.GetNMCStages(); i++) { - if (match.GetMCStage(i)->GetLoaded() == kTRUE) { - match.GetMCStage(i)->PrintInfo(out); - out << std::endl; + friend std::ostream& operator<<(std::ostream& out, const FairMCMatch& match) + { + for (int i = 0; i < match.GetNMCStages(); i++) { + if (match.GetMCStage(i)->GetLoaded() == kTRUE) { + match.GetMCStage(i)->PrintInfo(out); + out << std::endl; + } } - } - return out; + return out; } private: - - Int_t fUltimateStage; ///< last stage in link chain. Here all recursive operations must stop. + Int_t fUltimateStage; ///< last stage in link chain. Here all recursive operations must stop. std::map fList; FairMultiLinkedData fFinalStageML; Int_t fVerbose; diff --git a/datamatch/FairMCMatchCreatorTask.cxx b/datamatch/FairMCMatchCreatorTask.cxx index 43025fb26d..61d763186e 100644 --- a/datamatch/FairMCMatchCreatorTask.cxx +++ b/datamatch/FairMCMatchCreatorTask.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -11,129 +11,127 @@ // ------------------------------------------------------------------------- #include "FairMCMatchCreatorTask.h" -#include "FairLink.h" // for FairLink -#include "FairMCEntry.h" // for FairMCEntry -#include "FairMCMatch.h" // for FairMCMatch -#include "FairMCStage.h" // for FairMCStage -#include "FairMultiLinkedData.h" // for FairMultiLinkedData -#include "FairRootManager.h" // for FairRootManager +#include "FairLink.h" // for FairLink +#include "FairMCEntry.h" // for FairMCEntry +#include "FairMCMatch.h" // for FairMCMatch +#include "FairMCStage.h" // for FairMCStage +#include "FairMultiLinkedData.h" // for FairMultiLinkedData +#include "FairRootManager.h" // for FairRootManager -#include // for TClonesArray - -#include // for operator<<, basic_ostream, etc +#include // for TClonesArray +#include // for operator<<, basic_ostream, etc FairMCMatchCreatorTask::FairMCMatchCreatorTask() - : FairTask("Creates FairMCMatch"), - fMCMatch(nullptr), - fBranches(), - fPersistance(kTRUE), - fMCLink(nullptr), - fEventNr(0) -{ -} + : FairTask("Creates FairMCMatch") + , fMCMatch(nullptr) + , fBranches() + , fPersistance(kTRUE) + , fMCLink(nullptr) + , fEventNr(0) +{} -FairMCMatchCreatorTask::~FairMCMatchCreatorTask() -{ -} +FairMCMatchCreatorTask::~FairMCMatchCreatorTask() {} InitStatus FairMCMatchCreatorTask::Init() { - fMCMatch = new FairMCMatch("FairMCMatch", "FairMCMatch"); + fMCMatch = new FairMCMatch("FairMCMatch", "FairMCMatch"); - InitDataStages(); + InitDataStages(); - InitStatus status = InitBranches(); + InitStatus status = InitBranches(); - FairRootManager* ioman = FairRootManager::Instance(); - if (!ioman) { - std::cout << "-E- FairMCMatchCreatorTask::Init: " - << "RootManager not instantiated!" << std::endl; - return kFATAL; - } + FairRootManager* ioman = FairRootManager::Instance(); + if (!ioman) { + std::cout << "-E- FairMCMatchCreatorTask::Init: " + << "RootManager not instantiated!" << std::endl; + return kFATAL; + } - fMCLink = new TClonesArray("FairMCEntry"); - ioman->Register("MCLink", "MCInfo", fMCLink, kTRUE); + fMCLink = new TClonesArray("FairMCEntry"); + ioman->Register("MCLink", "MCInfo", fMCLink, kTRUE); - ioman->Register("MCMatch", "MCInfo", fMCMatch, kFALSE); + ioman->Register("MCMatch", "MCInfo", fMCMatch, kFALSE); - std::cout << "-I- FairMCMatchCreatorTask::Init: Initialization successfull" << std::endl; + std::cout << "-I- FairMCMatchCreatorTask::Init: Initialization successfull" << std::endl; - return status; + return status; } InitStatus FairMCMatchCreatorTask::InitBranches() { - // Get RootManager - FairRootManager* ioman = FairRootManager::Instance(); - if (!ioman) { - std::cout << "-E- FairMCMatchCreatorTask::Init: " - << "RootManager not instantiated!" << std::endl; - return kFATAL; - } - - int NStages = fMCMatch->GetNMCStages(); - for (int i = NStages-1; i > -1; i--) { - TClonesArray* myBranch = static_cast(ioman->GetObject(fMCMatch->GetMCStage(i)->GetBranchName().c_str())); - if (!myBranch) { - //std::cout << "NMCStages: " << fMCMatch->GetNMCStages() << std::endl; - std::cout << "-W- FairMCMatchCreatorTask::Init: "<< "No "<GetMCStage(i)->GetBranchName() << " array!" << std::endl; - fMCMatch->GetMCStage(i)->SetFill(kFALSE); //RemoveStage(fMCMatch->GetMCStage(i)->GetStageId()); - - continue; - } else { fMCMatch->GetMCStage(i)->SetFill(kTRUE); } - fBranches[fMCMatch->GetMCStage(i)->GetBranchName()] = myBranch; - } - return kSUCCESS; -} + // Get RootManager + FairRootManager* ioman = FairRootManager::Instance(); + if (!ioman) { + std::cout << "-E- FairMCMatchCreatorTask::Init: " + << "RootManager not instantiated!" << std::endl; + return kFATAL; + } -void FairMCMatchCreatorTask::SetParContainers() -{ + int NStages = fMCMatch->GetNMCStages(); + for (int i = NStages - 1; i > -1; i--) { + TClonesArray* myBranch = + static_cast(ioman->GetObject(fMCMatch->GetMCStage(i)->GetBranchName().c_str())); + if (!myBranch) { + // std::cout << "NMCStages: " << fMCMatch->GetNMCStages() << std::endl; + std::cout << "-W- FairMCMatchCreatorTask::Init: " + << "No " << fMCMatch->GetMCStage(i)->GetBranchName() << " array!" << std::endl; + fMCMatch->GetMCStage(i)->SetFill(kFALSE); // RemoveStage(fMCMatch->GetMCStage(i)->GetStageId()); + + continue; + } else { + fMCMatch->GetMCStage(i)->SetFill(kTRUE); + } + fBranches[fMCMatch->GetMCStage(i)->GetBranchName()] = myBranch; + } + return kSUCCESS; } +void FairMCMatchCreatorTask::SetParContainers() {} + void FairMCMatchCreatorTask::Exec(Option_t* /*opt*/) { - if (!fMCLink) { Fatal("Exec", "No fMCLinkDet"); } - fMCLink->Delete(); - fMCMatch->ClearMCList(); - - fMCMatch->LoadInMCLists(fMCLink); - - for (int i = 0; i < fMCMatch->GetNMCStages(); i++) { - if (fMCMatch->GetMCStage(i)->GetFill() == kTRUE && fMCMatch->GetMCStage(i)->GetLoaded() == kFALSE) { - TClonesArray* clArray = fBranches[fMCMatch->GetMCStage(i)->GetBranchName()]; - for (int j = 0; j < clArray->GetEntries(); j++) { - FairMultiLinkedData* myData = static_cast(clArray->At(j)); - fMCMatch->SetElements(fMCMatch->GetMCStage(i)->GetStageId(), j, myData); - } - if (fMCMatch->GetMCStage(i)->GetNEntries() > 0) { - fMCMatch->GetMCStage(i)->SetLoaded(kTRUE); - } + if (!fMCLink) { + Fatal("Exec", "No fMCLinkDet"); + } + fMCLink->Delete(); + fMCMatch->ClearMCList(); + + fMCMatch->LoadInMCLists(fMCLink); + + for (int i = 0; i < fMCMatch->GetNMCStages(); i++) { + if (fMCMatch->GetMCStage(i)->GetFill() == kTRUE && fMCMatch->GetMCStage(i)->GetLoaded() == kFALSE) { + TClonesArray* clArray = fBranches[fMCMatch->GetMCStage(i)->GetBranchName()]; + for (int j = 0; j < clArray->GetEntries(); j++) { + FairMultiLinkedData* myData = static_cast(clArray->At(j)); + fMCMatch->SetElements(fMCMatch->GetMCStage(i)->GetStageId(), j, myData); + } + if (fMCMatch->GetMCStage(i)->GetNEntries() > 0) { + fMCMatch->GetMCStage(i)->SetLoaded(kTRUE); + } + } } - } - int i = 0; - if (fPersistance) { - for (int index = 0; index < fMCMatch->GetNMCStages(); index++) { - FairMCStage myStage(*(fMCMatch->GetMCStage(index))); + int i = 0; + if (fPersistance) { + for (int index = 0; index < fMCMatch->GetNMCStages(); index++) { + FairMCStage myStage(*(fMCMatch->GetMCStage(index))); - for (int indStage = 0; indStage < myStage.GetNEntries(); indStage++) { + for (int indStage = 0; indStage < myStage.GetNEntries(); indStage++) { - FairMCEntry myLink(myStage.GetMCLink(indStage)); - new((*fMCLink)[i]) FairMCEntry(myLink.GetLinks(), myLink.GetSource(), myLink.GetPos()); - i++; - } + FairMCEntry myLink(myStage.GetMCLink(indStage)); + new ((*fMCLink)[i]) FairMCEntry(myLink.GetLinks(), myLink.GetSource(), myLink.GetPos()); + i++; + } + } } - } - if (fVerbose > 0) { - fMCMatch->Print(); - std::cout << std::endl; - } + if (fVerbose > 0) { + fMCMatch->Print(); + std::cout << std::endl; + } } -void FairMCMatchCreatorTask::Finish() -{ -} +void FairMCMatchCreatorTask::Finish() {} ClassImp(FairMCMatchCreatorTask); diff --git a/datamatch/FairMCMatchCreatorTask.h b/datamatch/FairMCMatchCreatorTask.h index 614f2a47b5..e907646fc7 100644 --- a/datamatch/FairMCMatchCreatorTask.h +++ b/datamatch/FairMCMatchCreatorTask.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -10,7 +10,6 @@ // ----- Created 20/03/07 by R.Kliemt ----- // ------------------------------------------------------------------------- - /** FAIRMCMATCHCREATORTASK.h *@author T.Stockmanns ** @@ -20,12 +19,11 @@ #ifndef FAIRMCMATCHCREATORTASK_H #define FAIRMCMATCHCREATORTASK_H -#include "FairTask.h" // for InitStatus, FairTask - -#include // for Bool_t, etc +#include "FairTask.h" // for InitStatus, FairTask -#include // for map -#include // for string +#include // for Bool_t, etc +#include // for map +#include // for string class FairMCMatch; class TClonesArray; @@ -39,15 +37,13 @@ class FairMCMatchCreatorTask : public FairTask /** Destructor **/ virtual ~FairMCMatchCreatorTask(); - /** Virtual method Init **/ virtual void SetParContainers(); - void SetPersistance(Bool_t pers) {fPersistance = pers;} - Bool_t GetPersistance() {return fPersistance;} + void SetPersistance(Bool_t pers) { fPersistance = pers; } + Bool_t GetPersistance() { return fPersistance; } virtual InitStatus Init(); - /** Virtual method Exec **/ virtual void Exec(Option_t* opt); @@ -61,7 +57,7 @@ class FairMCMatchCreatorTask : public FairTask private: std::map fBranches; Bool_t fPersistance; - TClonesArray* fMCLink;//-> + TClonesArray* fMCLink; //-> Int_t fEventNr; InitStatus InitBranches(); @@ -75,8 +71,7 @@ class FairMCMatchCreatorTask : public FairTask FairMCMatchCreatorTask(const FairMCMatchCreatorTask&); FairMCMatchCreatorTask& operator=(const FairMCMatchCreatorTask&); - ClassDef(FairMCMatchCreatorTask,1); - + ClassDef(FairMCMatchCreatorTask, 1); }; #endif diff --git a/datamatch/FairMCMatchLoaderTask.cxx b/datamatch/FairMCMatchLoaderTask.cxx index 08bdba009b..094f7b9f7a 100644 --- a/datamatch/FairMCMatchLoaderTask.cxx +++ b/datamatch/FairMCMatchLoaderTask.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -11,32 +11,28 @@ // ------------------------------------------------------------------------- #include "FairMCMatchLoaderTask.h" -#include "FairMCMatch.h" // for FairMCMatch -#include "FairRootManager.h" // for FairRootManager +#include "FairMCMatch.h" // for FairMCMatch +#include "FairRootManager.h" // for FairRootManager -#include // for TClonesArray - -#include // for operator<<, basic_ostream, etc +#include // for TClonesArray +#include // for operator<<, basic_ostream, etc FairMCMatchLoaderTask::FairMCMatchLoaderTask() - : FairTask("Creates FairMCMatch"), - fMCMatch(nullptr), - fMCLink(nullptr), - fEventNr(0) -{ -} + : FairTask("Creates FairMCMatch") + , fMCMatch(nullptr) + , fMCLink(nullptr) + , fEventNr(0) +{} -FairMCMatchLoaderTask::~FairMCMatchLoaderTask() -{ -} +FairMCMatchLoaderTask::~FairMCMatchLoaderTask() {} InitStatus FairMCMatchLoaderTask::Init() { - fMCMatch = new FairMCMatch("FairMCMatch", "FairMCMatch"); + fMCMatch = new FairMCMatch("FairMCMatch", "FairMCMatch"); - InitDataStages(); + InitDataStages(); - /* + /* fMCMatch->InitStage("MVDPoint"); fMCMatch->InitStage("MVDStripDigis"); fMCMatch->InitStage("MVDPixelDigis"); @@ -92,38 +88,36 @@ InitStatus FairMCMatchLoaderTask::Init() fMCMatch->InitStage("PidNeutralCand"); */ - FairRootManager* ioman = FairRootManager::Instance(); - if (!ioman) { - std::cout << "-E- FairMCMatchLoaderTask::Init: " - << "RootManager not instantiated!" << std::endl; - return kFATAL; - } + FairRootManager* ioman = FairRootManager::Instance(); + if (!ioman) { + std::cout << "-E- FairMCMatchLoaderTask::Init: " + << "RootManager not instantiated!" << std::endl; + return kFATAL; + } - fMCLink = static_cast(ioman->GetObject("MCLink")); - ioman->Register("MCMatch", "MCInfo", fMCMatch, kFALSE); + fMCLink = static_cast(ioman->GetObject("MCLink")); + ioman->Register("MCMatch", "MCInfo", fMCMatch, kFALSE); - return kSUCCESS; + return kSUCCESS; } -void FairMCMatchLoaderTask::SetParContainers() -{ -} +void FairMCMatchLoaderTask::SetParContainers() {} void FairMCMatchLoaderTask::Exec(Option_t* /*opt*/) { - if (!fMCLink) { Fatal("Exec", "No fMCLink"); } - fMCMatch->ClearMCList(); + if (!fMCLink) { + Fatal("Exec", "No fMCLink"); + } + fMCMatch->ClearMCList(); - fMCMatch->LoadInMCLists(fMCLink); - fMCMatch->CreateArtificialStage("MCTrack"); + fMCMatch->LoadInMCLists(fMCLink); + fMCMatch->CreateArtificialStage("MCTrack"); - fMCMatch->Print(); - std::cout << std::endl; + fMCMatch->Print(); + std::cout << std::endl; } -void FairMCMatchLoaderTask::Finish() -{ -} +void FairMCMatchLoaderTask::Finish() {} ClassImp(FairMCMatchLoaderTask); diff --git a/datamatch/FairMCMatchLoaderTask.h b/datamatch/FairMCMatchLoaderTask.h index 6bf48077fc..28e3324846 100644 --- a/datamatch/FairMCMatchLoaderTask.h +++ b/datamatch/FairMCMatchLoaderTask.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -10,20 +10,18 @@ // ----- Created 20/03/07 by R.Kliemt ----- // ------------------------------------------------------------------------- - /** PNDMCMATCHCREATORTASK.h *@author T.Stockmanns ** ** Displays all available informations for a given event **/ - #ifndef FAIRMCMATCHLOADERTASK_H #define FAIRMCMATCHLOADERTASK_H -#include "FairTask.h" // for FairTask, InitStatus +#include "FairTask.h" // for FairTask, InitStatus -#include // for ClassDef +#include // for ClassDef class FairMCMatch; class TClonesArray; @@ -37,12 +35,10 @@ class FairMCMatchLoaderTask : public FairTask /** Destructor **/ virtual ~FairMCMatchLoaderTask(); - /** Virtual method Init **/ virtual void SetParContainers(); virtual InitStatus Init(); - /** Virtual method Exec **/ virtual void Exec(Option_t* opt); @@ -66,7 +62,7 @@ class FairMCMatchLoaderTask : public FairTask FairMCMatchLoaderTask(const FairMCMatchLoaderTask&); FairMCMatchLoaderTask& operator=(const FairMCMatchLoaderTask&); - ClassDef(FairMCMatchLoaderTask,1); + ClassDef(FairMCMatchLoaderTask, 1); }; #endif diff --git a/datamatch/FairMCMatchSelectorTask.cxx b/datamatch/FairMCMatchSelectorTask.cxx index 1bf62efa5d..0a005f3dfb 100644 --- a/datamatch/FairMCMatchSelectorTask.cxx +++ b/datamatch/FairMCMatchSelectorTask.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -11,108 +11,95 @@ // ------------------------------------------------------------------------- #include "FairMCMatchSelectorTask.h" -#include "FairMCMatch.h" // for FairMCMatch -#include "FairMCResult.h" // for operator<< -#include "FairMCStage.h" // for FairMCStage -#include "FairRootManager.h" // for FairRootManager +#include "FairMCMatch.h" // for FairMCMatch +#include "FairMCResult.h" // for operator<< +#include "FairMCStage.h" // for FairMCStage +#include "FairRootManager.h" // for FairRootManager -#include // for operator<<, ostream, etc +#include // for operator<<, ostream, etc // ----- Default constructor ------------------------------------------- FairMCMatchSelectorTask::FairMCMatchSelectorTask() - : FairTask("Creates FairMCMatch"), - fMCMatch(nullptr), - fStart(-1), - fStop(-1), - fStartString(""), - fStopString(""), - fStageWeights(), - fCommonWeight(0) -{ -} + : FairTask("Creates FairMCMatch") + , fMCMatch(nullptr) + , fStart(-1) + , fStop(-1) + , fStartString("") + , fStopString("") + , fStageWeights() + , fCommonWeight(0) +{} // ------------------------------------------------------------------------- FairMCMatchSelectorTask::FairMCMatchSelectorTask(TString start, TString stop) - : FairTask("Creates FairMCMatch"), - fMCMatch(nullptr), - fStart(-1), - fStop(-1), - fStartString(start), - fStopString(stop), - fStageWeights(), - fCommonWeight(0) -{ -} + : FairTask("Creates FairMCMatch") + , fMCMatch(nullptr) + , fStart(-1) + , fStop(-1) + , fStartString(start) + , fStopString(stop) + , fStageWeights() + , fCommonWeight(0) +{} FairMCMatchSelectorTask::FairMCMatchSelectorTask(Int_t start, Int_t stop) - : FairTask("Creates FairMCMatch"), - fMCMatch(nullptr), - fStart(start), - fStop(stop), - fStartString(""), - fStopString(""), - fStageWeights(), - fCommonWeight(0) -{ -} + : FairTask("Creates FairMCMatch") + , fMCMatch(nullptr) + , fStart(start) + , fStop(stop) + , fStartString("") + , fStopString("") + , fStageWeights() + , fCommonWeight(0) +{} // ----- Destructor ---------------------------------------------------- -FairMCMatchSelectorTask::~FairMCMatchSelectorTask() -{ -} +FairMCMatchSelectorTask::~FairMCMatchSelectorTask() {} // ----- Public method Init -------------------------------------------- InitStatus FairMCMatchSelectorTask::Init() { - FairRootManager* ioman = FairRootManager::Instance(); - if (!ioman) { - std::cout << "-E- FairMCMatchSelectorTask::Init: " - << "RootManager not instantiated!" << std::endl; - return kFATAL; - } + FairRootManager* ioman = FairRootManager::Instance(); + if (!ioman) { + std::cout << "-E- FairMCMatchSelectorTask::Init: " + << "RootManager not instantiated!" << std::endl; + return kFATAL; + } - fMCMatch = static_cast(ioman->GetObject("MCMatch")); - if (fStart < 0 && fStop < 0) { - fStart = ioman->GetBranchId(fStartString); - fStop = ioman->GetBranchId(fStopString); - std::cout << fStartString << ": " << fStart << " / " << fStopString << ": " << fStop << std::endl; - } + fMCMatch = static_cast(ioman->GetObject("MCMatch")); + if (fStart < 0 && fStop < 0) { + fStart = ioman->GetBranchId(fStartString); + fStop = ioman->GetBranchId(fStopString); + std::cout << fStartString << ": " << fStart << " / " << fStopString << ": " << fStop << std::endl; + } - std::cout << "-I- FairMCMatchSelectorTask::Init: Initialization successfull" << std::endl; + std::cout << "-I- FairMCMatchSelectorTask::Init: Initialization successfull" << std::endl; - - return kSUCCESS; + return kSUCCESS; } - // ------------------------------------------------------------------------- -void FairMCMatchSelectorTask::SetParContainers() -{ -} - +void FairMCMatchSelectorTask::SetParContainers() {} // ----- Public method Exec -------------------------------------------- void FairMCMatchSelectorTask::Exec(Option_t* /*opt*/) { - std::cout << "Output Selector: " << std::endl; - SetWeights(); - fMCMatch->CreateArtificialStage("MCTrack"); - std::cout << fMCMatch->GetMCInfo(fStart, fStop); - std::cout << std::endl; + std::cout << "Output Selector: " << std::endl; + SetWeights(); + fMCMatch->CreateArtificialStage("MCTrack"); + std::cout << fMCMatch->GetMCInfo(fStart, fStop); + std::cout << std::endl; } void FairMCMatchSelectorTask::SetWeights() { - fMCMatch->SetCommonWeightStages(fCommonWeight); - for (unsigned int i = 0; i < fStageWeights.size(); i++) { - fMCMatch->GetMCStageType(fStageWeights[i].first)->SetWeight(fStageWeights[i].second); - } -} - -void FairMCMatchSelectorTask::Finish() -{ + fMCMatch->SetCommonWeightStages(fCommonWeight); + for (unsigned int i = 0; i < fStageWeights.size(); i++) { + fMCMatch->GetMCStageType(fStageWeights[i].first)->SetWeight(fStageWeights[i].second); + } } +void FairMCMatchSelectorTask::Finish() {} ClassImp(FairMCMatchSelectorTask); diff --git a/datamatch/FairMCMatchSelectorTask.h b/datamatch/FairMCMatchSelectorTask.h index 8fb125b34e..020556792d 100644 --- a/datamatch/FairMCMatchSelectorTask.h +++ b/datamatch/FairMCMatchSelectorTask.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -10,24 +10,21 @@ // ----- Created 18/01/10 by T.Stockmanns ----- // ------------------------------------------------------------------------- - /** FAIRMCMATCHSELECTORTASK.h *@author T.Stockmanns ** ** Displays all available informations for a given event **/ - #ifndef FAIRMCMATCHSELECTORTASK_H #define FAIRMCMATCHSELECTORTASK_H -#include "FairTask.h" // for FairTask, InitStatus - -#include // for Int_t, Float_t, etc -#include // for TString +#include "FairTask.h" // for FairTask, InitStatus -#include // for pair -#include // for vector +#include // for Int_t, Float_t, etc +#include // for TString +#include // for pair +#include // for vector class FairMCMatch; @@ -44,23 +41,22 @@ class FairMCMatchSelectorTask : public FairTask /** Destructor **/ virtual ~FairMCMatchSelectorTask(); - /** Virtual method Init **/ virtual void SetParContainers(); virtual InitStatus Init(); - /** Virtual method Exec **/ virtual void Exec(Option_t* opt); virtual void Finish(); - virtual void SetStart(Int_t type) {fStart = type;} - virtual void SetStop(Int_t type) {fStop = type;} + virtual void SetStart(Int_t type) { fStart = type; } + virtual void SetStop(Int_t type) { fStop = type; } - virtual void SetAllWeights(Float_t weight) {fCommonWeight = weight;} - virtual void SetWeightStage(Int_t type, Float_t weight) { - fStageWeights.push_back(std::pair(static_cast(type), weight)); + virtual void SetAllWeights(Float_t weight) { fCommonWeight = weight; } + virtual void SetWeightStage(Int_t type, Float_t weight) + { + fStageWeights.push_back(std::pair(static_cast(type), weight)); } virtual void SetWeights(); @@ -85,7 +81,7 @@ class FairMCMatchSelectorTask : public FairTask FairMCMatchSelectorTask(const FairMCMatchSelectorTask&); FairMCMatchSelectorTask& operator=(const FairMCMatchSelectorTask&); - ClassDef(FairMCMatchSelectorTask,1); + ClassDef(FairMCMatchSelectorTask, 1); }; #endif diff --git a/datamatch/FairMCObject.cxx b/datamatch/FairMCObject.cxx index 02d372bcfb..edbb0c4d59 100644 --- a/datamatch/FairMCObject.cxx +++ b/datamatch/FairMCObject.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* @@ -17,86 +17,82 @@ ClassImp(FairMCObject); FairMCObject::FairMCObject() - : TObject(), - fStage(0), - fStageId() -{ -} + : TObject() + , fStage(0) + , fStageId() +{} -FairMCObject::~FairMCObject() -{ -} +FairMCObject::~FairMCObject() {} void FairMCObject::SetEntry(FairMCEntry entry) { - if (entry.GetPos() < 0) { - std::cout << "-E- FairMCObject::SetEntry(FairMCEntry): pos " << entry.GetPos() << std::endl; - return; - } - AdoptSize(entry.GetPos()); - fStage[entry.GetPos()] = entry; + if (entry.GetPos() < 0) { + std::cout << "-E- FairMCObject::SetEntry(FairMCEntry): pos " << entry.GetPos() << std::endl; + return; + } + AdoptSize(entry.GetPos()); + fStage[entry.GetPos()] = entry; } void FairMCObject::SetEntry(std::vector type, std::vector link, int index) { - FairMCEntry myEntry; - myEntry.SetPos(index); - myEntry.SetPersistanceCheck(kFALSE); - for (unsigned int i = 0; i < type.size(); i++) { - myEntry.AddLink(FairLink(type[i],link[i])); - } - SetEntry(myEntry); + FairMCEntry myEntry; + myEntry.SetPos(index); + myEntry.SetPersistanceCheck(kFALSE); + for (unsigned int i = 0; i < type.size(); i++) { + myEntry.AddLink(FairLink(type[i], link[i])); + } + SetEntry(myEntry); } void FairMCObject::SetEntry(FairMultiLinkedData* data, int index) { - AdoptSize(index); - fStage[index].SetLinks(data->GetLinks()); + AdoptSize(index); + fStage[index].SetLinks(data->GetLinks()); } void FairMCObject::SetLink(FairLink link, int index) { - if (index < static_cast(fStage.size())) { - fStage[index].ResetLinks(); - } - AddLink(link, index); + if (index < static_cast(fStage.size())) { + fStage[index].ResetLinks(); + } + AddLink(link, index); } - void FairMCObject::AddLink(FairLink link, int index) { - AdoptSize(index); - fStage[index].AddLink(link); + AdoptSize(index); + fStage[index].AddLink(link); } void FairMCObject::AdoptSize(int index) { - int start = fStage.size(); - while ( static_cast(fStage.size()) < index+1) { - FairMCEntry myVec; - myVec.SetPos(fStage.size()); - myVec.SetSource(GetStageId()); - myVec.SetPersistanceCheck(kFALSE); - fStage.push_back(myVec); - start++; - } + int start = fStage.size(); + while (static_cast(fStage.size()) < index + 1) { + FairMCEntry myVec; + myVec.SetPos(fStage.size()); + myVec.SetSource(GetStageId()); + myVec.SetPersistanceCheck(kFALSE); + fStage.push_back(myVec); + start++; + } } FairMultiLinkedData FairMCObject::PosInList(FairLink link) { - FairMultiLinkedData result; - result.SetPersistanceCheck(kFALSE); - for (unsigned int i = 0; i < fStage.size(); i++) { - if (fStage[i].IsLinkInList(link.GetType(), link.GetIndex())) { - result.AddLink(FairLink(GetStageId(), i)); + FairMultiLinkedData result; + result.SetPersistanceCheck(kFALSE); + for (unsigned int i = 0; i < fStage.size(); i++) { + if (fStage[i].IsLinkInList(link.GetType(), link.GetIndex())) { + result.AddLink(FairLink(GetStageId(), i)); + } } - } - return result; + return result; } void FairMCObject::RemoveType(Int_t type) { - for (unsigned int i = 0; i < fStage.size(); i++) { - fStage[i].RemoveType(type); - } + for (unsigned int i = 0; i < fStage.size(); i++) { + fStage[i].RemoveType(type); + } } diff --git a/datamatch/FairMCObject.h b/datamatch/FairMCObject.h index 1cf627511d..aef6932101 100644 --- a/datamatch/FairMCObject.h +++ b/datamatch/FairMCObject.h @@ -15,88 +15,89 @@ #ifndef FAIRMCOBJECT_H_ #define FAIRMCOBJECT_H_ -#include "FairLink.h" // for FairLink -#include "FairMCEntry.h" // for FairMCEntry -#include "FairMultiLinkedData.h" // for FairMultiLinkedData +#include "FairLink.h" // for FairLink +#include "FairMCEntry.h" // for FairMCEntry +#include "FairMultiLinkedData.h" // for FairMultiLinkedData -#include // for TObject -#include // for Int_t, FairMCObject::Class, etc +#include // for Int_t, FairMCObject::Class, etc +#include // for TObject +#include // for ostream, etc +#include // for pair +#include // for vector -#include // for ostream, etc -#include // for pair -#include // for vector - -class FairMCObject: public TObject +class FairMCObject : public TObject { public: FairMCObject(); FairMCObject(Int_t type) - : TObject(), - fStage(), - fStageId(type) + : TObject() + , fStage() + , fStageId(type) {} FairMCObject(const FairMCObject& obj) - : TObject(obj), - fStage(obj.GetEntryVector()), - fStageId(obj.GetStageId()) + : TObject(obj) + , fStage(obj.GetEntryVector()) + , fStageId(obj.GetStageId()) {} FairMCObject(Int_t type, std::vector stage) - : TObject(), - fStage(stage), - fStageId(type) + : TObject() + , fStage(stage) + , fStageId(type) {} - FairMCObject& operator=(const FairMCObject& from) { - if (this == &from) { return *this; } + FairMCObject& operator=(const FairMCObject& from) + { + if (this == &from) { + return *this; + } - TObject::operator=(from); - fStage=from.fStage; - fStageId=from.fStageId; + TObject::operator=(from); + fStage = from.fStage; + fStageId = from.fStageId; - return *this; + return *this; } virtual ~FairMCObject(); - void SetStageId(Int_t type) {fStageId = type;} + void SetStageId(Int_t type) { fStageId = type; } void SetEntry(std::vector type, std::vector link, int index); void SetEntry(FairMultiLinkedData* data, int index); void SetEntry(FairMCEntry link); - void SetStage(std::vector stage) {fStage = stage;} + void SetStage(std::vector stage) { fStage = stage; } void SetLink(FairLink link, int index); void AddLink(FairLink link, int index); - FairMCEntry GetEntry(int index) const {return fStage[index];} - FairLink GetSingleLink(int entryIndex, int linkIndex) const { - return fStage.at(entryIndex).GetLink(linkIndex); - } + FairMCEntry GetEntry(int index) const { return fStage[index]; } + FairLink GetSingleLink(int entryIndex, int linkIndex) const { return fStage.at(entryIndex).GetLink(linkIndex); } - Int_t GetStageId(void) const {return fStageId;} + Int_t GetStageId(void) const { return fStageId; } - FairMCEntry GetMCLink(Int_t index) {return fStage.at(index);} + FairMCEntry GetMCLink(Int_t index) { return fStage.at(index); } - int GetNEntries() const {return fStage.size();} - int GetNLinks(int entryIndex)const {return fStage.at(entryIndex).GetNLinks();} - std::vector GetEntryVector() const {return fStage;} + int GetNEntries() const { return fStage.size(); } + int GetNLinks(int entryIndex) const { return fStage.at(entryIndex).GetNLinks(); } + std::vector GetEntryVector() const { return fStage; } FairMultiLinkedData PosInList(std::pair link); FairMultiLinkedData PosInList(FairLink link); - FairMultiLinkedData GetLinksWithType(Int_t type) { - FairMultiLinkedData result; - for (int i = 0; i < GetNEntries(); i++) { - result.AddLinks(GetMCLink(i).GetLinksWithType(type)); - } - return result; + FairMultiLinkedData GetLinksWithType(Int_t type) + { + FairMultiLinkedData result; + for (int i = 0; i < GetNEntries(); i++) { + result.AddLinks(GetMCLink(i).GetLinksWithType(type)); + } + return result; } void RemoveType(Int_t type); - virtual void ClearEntries() {fStage.clear();} + virtual void ClearEntries() { fStage.clear(); } - virtual void PrintInfo(std::ostream& out = std::cout) {out << *this;} + virtual void PrintInfo(std::ostream& out = std::cout) { out << *this; } /* void operator=(const FairMCObject& obj) { @@ -105,16 +106,17 @@ class FairMCObject: public TObject } */ - friend std::ostream& operator<< (std::ostream& out, const FairMCObject& obj) { - std::vector stages = obj.GetEntryVector(); - for (unsigned int i = 0; i < stages.size(); i++) { - if (stages[i].GetNLinks() > 0) { - out << i << ": "; - stages[i].PrintInfo(out); - out << std::endl; + friend std::ostream& operator<<(std::ostream& out, const FairMCObject& obj) + { + std::vector stages = obj.GetEntryVector(); + for (unsigned int i = 0; i < stages.size(); i++) { + if (stages[i].GetNLinks() > 0) { + out << i << ": "; + stages[i].PrintInfo(out); + out << std::endl; + } } - } - return out; + return out; } private: diff --git a/datamatch/FairMCResult.cxx b/datamatch/FairMCResult.cxx index 973b5d2810..2fca65868c 100644 --- a/datamatch/FairMCResult.cxx +++ b/datamatch/FairMCResult.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* @@ -17,20 +17,15 @@ ClassImp(FairMCResult); FairMCResult::FairMCResult() - : FairMCObject(), - fStartType(-1), - fStopType(-1) -{ -} + : FairMCObject() + , fStartType(-1) + , fStopType(-1) +{} -FairMCResult::~FairMCResult() -{ -} +FairMCResult::~FairMCResult() {} FairMCResult::FairMCResult(Int_t start, Int_t stop) - : FairMCObject(), - fStartType(start), - fStopType(stop) -{ -} - + : FairMCObject() + , fStartType(start) + , fStopType(stop) +{} diff --git a/datamatch/FairMCResult.h b/datamatch/FairMCResult.h index de86948142..25562aeea2 100644 --- a/datamatch/FairMCResult.h +++ b/datamatch/FairMCResult.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* @@ -15,54 +15,55 @@ #ifndef FAIRMCRESULT_H_ #define FAIRMCRESULT_H_ -#include "FairMCObject.h" // for FairMCObject -#include "FairMCEntry.h" // for FairMCEntry +#include "FairMCEntry.h" // for FairMCEntry +#include "FairMCObject.h" // for FairMCObject -#include // for Int_t, FairMCResult::Class, etc +#include // for Int_t, FairMCResult::Class, etc +#include // for operator<<, ostream, etc -#include // for operator<<, ostream, etc - -class FairMCResult: public FairMCObject +class FairMCResult : public FairMCObject { public: FairMCResult(); FairMCResult(Int_t start, Int_t stop); FairMCResult(const FairMCResult& result) - : FairMCObject(result.GetStartType(), result.GetEntryVector()), - fStartType(result.GetStartType()), - fStopType(result.GetStopType()) { - } + : FairMCObject(result.GetStartType(), result.GetEntryVector()) + , fStartType(result.GetStartType()) + , fStopType(result.GetStopType()) + {} + FairMCResult& operator=(const FairMCResult& result) + { - FairMCResult& operator=(const FairMCResult& result) { + if (this == &result) { + return *this; + } - if (this == &result) { return *this; } + FairMCObject::operator=(result); + fStartType = result.fStartType; + fStopType = result.fStopType; - FairMCObject::operator=(result); - fStartType = result.fStartType; - fStopType = result.fStopType; - - return *this; + return *this; } virtual ~FairMCResult(); - void SetStartType(Int_t start) {fStartType = start;} - void SetStopType(Int_t stop) {fStopType = stop;} + void SetStartType(Int_t start) { fStartType = start; } + void SetStopType(Int_t stop) { fStopType = stop; } - Int_t GetStartType(void) const {return fStartType;} - Int_t GetStopType(void) const {return fStopType;} + Int_t GetStartType(void) const { return fStartType; } + Int_t GetStopType(void) const { return fStopType; } - virtual void PrintInfo(std::ostream& out = std::cout) { out << *this;} + virtual void PrintInfo(std::ostream& out = std::cout) { out << *this; } - friend std::ostream& operator<< (std::ostream& out, const FairMCResult& result) { - out << "MC Link from: " << result.GetStartType() << " to " << result.GetStopType() << ":" << std::endl; - (static_cast(result)).PrintInfo(out); - return out; + friend std::ostream& operator<<(std::ostream& out, const FairMCResult& result) + { + out << "MC Link from: " << result.GetStartType() << " to " << result.GetStopType() << ":" << std::endl; + (static_cast(result)).PrintInfo(out); + return out; } - private: Int_t fStartType; Int_t fStopType; diff --git a/datamatch/FairMCStage.cxx b/datamatch/FairMCStage.cxx index b7fa7c7023..a2b1329ec5 100644 --- a/datamatch/FairMCStage.cxx +++ b/datamatch/FairMCStage.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* @@ -17,26 +17,21 @@ ClassImp(FairMCStage); FairMCStage::FairMCStage() - : FairMCObject(), - fBranchName(""), - fFileName(""), - fWeight(1.0), - fLoaded(kFALSE), - fFill(kFALSE) -{ -} + : FairMCObject() + , fBranchName("") + , fFileName("") + , fWeight(1.0) + , fLoaded(kFALSE) + , fFill(kFALSE) +{} -FairMCStage::~FairMCStage() -{ -} +FairMCStage::~FairMCStage() {} FairMCStage::FairMCStage(Int_t id, const std::string& fileName, const std::string& branchName, Double_t weight) - : FairMCObject(id), - fBranchName(branchName), - fFileName(fileName), - fWeight(weight), - fLoaded(kFALSE), - fFill(kFALSE) -{ -} - + : FairMCObject(id) + , fBranchName(branchName) + , fFileName(fileName) + , fWeight(weight) + , fLoaded(kFALSE) + , fFill(kFALSE) +{} diff --git a/datamatch/FairMCStage.h b/datamatch/FairMCStage.h index a10c49301e..201de9bca2 100644 --- a/datamatch/FairMCStage.h +++ b/datamatch/FairMCStage.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* @@ -15,75 +15,80 @@ #ifndef FAIRMCSTAGE_H_ #define FAIRMCSTAGE_H_ -#include "FairMCObject.h" // for FairMCObject +#include "FairMCObject.h" // for FairMCObject -#include // for Bool_t, Double_t, etc +#include // for Bool_t, Double_t, etc +#include // for ostream, basic_ostream, etc +#include // for string, operator<<, etc -#include // for ostream, basic_ostream, etc -#include // for string, operator<<, etc - -class FairMCStage: public FairMCObject +class FairMCStage : public FairMCObject { public: FairMCStage(); FairMCStage(Int_t id, const std::string& fileName, const std::string& branchName, Double_t weight = 1.0); FairMCStage(const FairMCStage& mcStage) - : FairMCObject(mcStage), - fBranchName(mcStage.fBranchName), - fFileName(mcStage.fFileName), - fWeight(mcStage.fWeight), - fLoaded(mcStage.fLoaded), - fFill(mcStage.fFill) { - } - - FairMCStage& operator=(const FairMCStage& result) { - - if (this == &result) { return *this; } - - FairMCObject::operator=(result); - fBranchName = result.fBranchName; - fFileName = result.fFileName; - fWeight = result.fWeight; - fLoaded = result.fLoaded; - fFill = result.fFill; - - return *this; + : FairMCObject(mcStage) + , fBranchName(mcStage.fBranchName) + , fFileName(mcStage.fFileName) + , fWeight(mcStage.fWeight) + , fLoaded(mcStage.fLoaded) + , fFill(mcStage.fFill) + {} + + FairMCStage& operator=(const FairMCStage& result) + { + + if (this == &result) { + return *this; + } + + FairMCObject::operator=(result); + fBranchName = result.fBranchName; + fFileName = result.fFileName; + fWeight = result.fWeight; + fLoaded = result.fLoaded; + fFill = result.fFill; + + return *this; } virtual ~FairMCStage(); - void SetBranchName(const std::string& branchName) { fBranchName = branchName; } - void SetFileName(const std::string& fileName) { fFileName = fileName; } - void SetWeight(Double_t weight) { fWeight = weight; } - void SetLoaded(Bool_t loaded) { fLoaded = loaded; } - void SetFill(Bool_t fill) { fFill = fill; } - - std::string GetBranchName(void) const {return fBranchName;} - std::string GetFileName(void) const {return fFileName;} - Double_t GetWeight(void) const {return fWeight;} - Bool_t GetLoaded(void) const {return fLoaded;} - Bool_t GetFill(void) const {return fFill;} - - virtual void ClearEntries() { - FairMCObject::ClearEntries(); - fLoaded = kFALSE; + void SetBranchName(const std::string& branchName) { fBranchName = branchName; } + void SetFileName(const std::string& fileName) { fFileName = fileName; } + void SetWeight(Double_t weight) { fWeight = weight; } + void SetLoaded(Bool_t loaded) { fLoaded = loaded; } + void SetFill(Bool_t fill) { fFill = fill; } + + std::string GetBranchName(void) const { return fBranchName; } + std::string GetFileName(void) const { return fFileName; } + Double_t GetWeight(void) const { return fWeight; } + Bool_t GetLoaded(void) const { return fLoaded; } + Bool_t GetFill(void) const { return fFill; } + + virtual void ClearEntries() + { + FairMCObject::ClearEntries(); + fLoaded = kFALSE; } - virtual void PrintInfo(std::ostream& out) {out << *this;} + virtual void PrintInfo(std::ostream& out) { out << *this; } - friend std::ostream& operator<< (std::ostream& out, const FairMCStage& stage) { - out << stage.GetStageId() << ": " << stage.GetBranchName() << " // " << stage.GetFileName() << std::endl; //" with weight: " << stage.GetWeight() << std::endl; - (static_cast(stage)).PrintInfo(out); - return out; + friend std::ostream& operator<<(std::ostream& out, const FairMCStage& stage) + { + out << stage.GetStageId() << ": " << stage.GetBranchName() << " // " << stage.GetFileName() + << std::endl; //" with weight: " << stage.GetWeight() << std::endl; + (static_cast(stage)).PrintInfo(out); + return out; } private: std::string fBranchName; std::string fFileName; Double_t fWeight; - Bool_t fLoaded; ///< indicates if this stage was loaded already from a Link file - Bool_t fFill; ///< indicates if a corresponding DataFile with FairLinks exists to fill this stage + Bool_t fLoaded; ///< indicates if this stage was loaded already from a Link file + Bool_t fFill; ///< indicates if a corresponding DataFile with FairLinks exists to fill this stage ClassDef(FairMCStage, 1); }; diff --git a/eventdisplay/FairBoxSet.cxx b/eventdisplay/FairBoxSet.cxx index 872b251edc..cc62e1044f 100644 --- a/eventdisplay/FairBoxSet.cxx +++ b/eventdisplay/FairBoxSet.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -13,7 +13,8 @@ #include "FairBoxSet.h" FairBoxSet::FairBoxSet(FairBoxSetDraw* drawer, const char* name, const char* t) - : TEveBoxSet(name, t), fDraw(drawer) + : TEveBoxSet(name, t) + , fDraw(drawer) {} -ClassImp(FairBoxSet) +ClassImp(FairBoxSet); diff --git a/eventdisplay/FairBoxSet.h b/eventdisplay/FairBoxSet.h index 4d1303b6f6..bfd98f78b7 100644 --- a/eventdisplay/FairBoxSet.h +++ b/eventdisplay/FairBoxSet.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -14,36 +14,36 @@ * @author T. Stockmanns * @since 26.3.2009 * Base class to display 3D Points in Eve as a BoxSet - * One has to overwrite the method GetVector which takes a TObject and writes out a TVector3 which is then taken as an input - * to place the points. - * If one wants to change the color of the points one has to overwrite the method GetValue. This method takes a TObject and - * an integer and translates this into an integer as input for the EveBoxSet method DigitValue + * One has to overwrite the method GetVector which takes a TObject and writes out a TVector3 which is then taken as an + *input to place the points. If one wants to change the color of the points one has to overwrite the method GetValue. + *This method takes a TObject and an integer and translates this into an integer as input for the EveBoxSet method + *DigitValue ** **/ #ifndef FAIRBOXSET_H #define FAIRBOXSET_H -#include "FairBoxSetDraw.h" // for FairBoxSetDraw +#include "FairBoxSetDraw.h" // for FairBoxSetDraw -#include // for Double_t, FairBoxSet::Class, etc -#include // for TEveBoxSet +#include // for Double_t, FairBoxSet::Class, etc +#include // for TEveBoxSet class FairBoxSet : public TEveBoxSet { public: /** Standard constructor - **/ + **/ FairBoxSet(FairBoxSetDraw* drawer, const char* name = "FairBoxSet", const char* t = ""); - void SetTimeWindowPlus(Double_t time) {fDraw->SetTimeWindowPlus(time);} - void SetTimeWindowMinus(Double_t time) {fDraw->SetTimeWindowMinus(time);} + void SetTimeWindowPlus(Double_t time) { fDraw->SetTimeWindowPlus(time); } + void SetTimeWindowMinus(Double_t time) { fDraw->SetTimeWindowMinus(time); } - Double_t GetTimeWindowPlus() {return fDraw->GetTimeWindowPlus();} - Double_t GetTimeWindowMinus() {return fDraw->GetTimeWindowMinus();} + Double_t GetTimeWindowPlus() { return fDraw->GetTimeWindowPlus(); } + Double_t GetTimeWindowMinus() { return fDraw->GetTimeWindowMinus(); } /** Destructor **/ - virtual ~FairBoxSet() {}; + virtual ~FairBoxSet(){}; private: FairBoxSetDraw* fDraw; @@ -51,7 +51,7 @@ class FairBoxSet : public TEveBoxSet FairBoxSet(const FairBoxSet&); FairBoxSet operator=(const FairBoxSet&); - ClassDef(FairBoxSet,1); + ClassDef(FairBoxSet, 1); }; #endif diff --git a/eventdisplay/FairBoxSetDraw.cxx b/eventdisplay/FairBoxSetDraw.cxx index 85cedf5533..d485a613b3 100644 --- a/eventdisplay/FairBoxSetDraw.cxx +++ b/eventdisplay/FairBoxSetDraw.cxx @@ -11,185 +11,173 @@ // ------------------------------------------------------------------------- #include "FairBoxSetDraw.h" -#include "FairBoxSet.h" // for FairBoxSet -#include "FairEventManager.h" // for FairEventManager -#include "FairRootManager.h" // for FairRootManager -#include "FairRunAna.h" // for FairRunAna -#include "FairTSBufferFunctional.h" // for StopTime -#include "FairTimeStamp.h" // for FairTimeStamp - -#include // for TClonesArray +#include "FairBoxSet.h" // for FairBoxSet +#include "FairEventManager.h" // for FairEventManager +#include "FairRootManager.h" // for FairRootManager +#include "FairRunAna.h" // for FairRunAna +#include "FairTSBufferFunctional.h" // for StopTime +#include "FairTimeStamp.h" // for FairTimeStamp + +#include // for TClonesArray #include -#include // for TEveManager, gEve -#include // for TVector3 - -#include // for operator<<, basic_ostream, etc +#include // for TEveManager, gEve +#include // for TVector3 +#include // for operator<<, basic_ostream, etc using std::cout; using std::endl; -FairBoxSet* fq; //! +FairBoxSet* fq; //! Double_t fX, fY, fZ; FairBoxSetDraw::FairBoxSetDraw() - : FairTask("FairBoxSetDraw",0), - fVerbose(0), - fList(nullptr), - fEventManager(nullptr), - fManager(nullptr), - fq(nullptr), - fX(0.3), - fY(0.3), - fZ(0.3), - fTimeWindowPlus(0.), - fTimeWindowMinus(0.), - fStartTime(0.), - fUseEventTime(kTRUE), - fStartFunctor(), - fStopFunctor() -{ -} + : FairTask("FairBoxSetDraw", 0) + , fVerbose(0) + , fList(nullptr) + , fEventManager(nullptr) + , fManager(nullptr) + , fq(nullptr) + , fX(0.3) + , fY(0.3) + , fZ(0.3) + , fTimeWindowPlus(0.) + , fTimeWindowMinus(0.) + , fStartTime(0.) + , fUseEventTime(kTRUE) + , fStartFunctor() + , fStopFunctor() +{} FairBoxSetDraw::FairBoxSetDraw(const char* name, Int_t iVerbose) - : FairTask(name, iVerbose), - fVerbose(iVerbose), - fList(nullptr), - fEventManager(nullptr), - fManager(nullptr), - fq(nullptr), - fX(0.3), - fY(0.3), - fZ(0.3), - fTimeWindowPlus(0.), - fTimeWindowMinus(0.), - fStartTime(0.), - fUseEventTime(kTRUE), - fStartFunctor(), - fStopFunctor() -{ -} + : FairTask(name, iVerbose) + , fVerbose(iVerbose) + , fList(nullptr) + , fEventManager(nullptr) + , fManager(nullptr) + , fq(nullptr) + , fX(0.3) + , fY(0.3) + , fZ(0.3) + , fTimeWindowPlus(0.) + , fTimeWindowMinus(0.) + , fStartTime(0.) + , fUseEventTime(kTRUE) + , fStartFunctor() + , fStopFunctor() +{} InitStatus FairBoxSetDraw::Init() { - if (fVerbose>1) { - cout<< "FairBoxSetDraw::Init()" << endl; - } - fManager = FairRootManager::Instance(); - - fList = static_cast(FairRootManager::Instance()->GetObject(GetName())); - //std::cout << fList << std::endl; - if (fList==0) { - cout << "FairBoxSetDraw::Init() branch " << GetName() << " Not found! Task will be deactivated "<< endl; - SetActive(kFALSE); - return kERROR; - } - if (fVerbose>2) { - cout<< "FairBoxSetDraw::Init() get track list" << fList<< endl; - } - fEventManager =FairEventManager::Instance(); - if (fVerbose>2) { - cout<< "FairBoxSetDraw::Init() get instance of FairEventManager " << endl; - } - fq=0; - - fStartFunctor = new StopTime(); - fStopFunctor = new StopTime(); - - return kSUCCESS; + if (fVerbose > 1) { + cout << "FairBoxSetDraw::Init()" << endl; + } + fManager = FairRootManager::Instance(); + + fList = static_cast(FairRootManager::Instance()->GetObject(GetName())); + // std::cout << fList << std::endl; + if (fList == 0) { + cout << "FairBoxSetDraw::Init() branch " << GetName() << " Not found! Task will be deactivated " << endl; + SetActive(kFALSE); + return kERROR; + } + if (fVerbose > 2) { + cout << "FairBoxSetDraw::Init() get track list" << fList << endl; + } + fEventManager = FairEventManager::Instance(); + if (fVerbose > 2) { + cout << "FairBoxSetDraw::Init() get instance of FairEventManager " << endl; + } + fq = 0; + + fStartFunctor = new StopTime(); + fStopFunctor = new StopTime(); + + return kSUCCESS; } void FairBoxSetDraw::Exec(Option_t* /*option*/) { - if (IsActive()) { - TObject* p; - Reset(); - // cout<< "FairBoxSetDraw::Init() Exec! " << fList->GetEntriesFast() << endl; - CreateBoxSet(); - if (FairRunAna::Instance()->IsTimeStamp()) { - fList->Clear(); - Double_t eventTime = FairRootManager::Instance()->GetEventTime(); - if (fUseEventTime) { fStartTime = eventTime - fTimeWindowMinus; } - cout << "EventTime: " << eventTime << " TimeWindow: " << fStartTime << " - " << eventTime + fTimeWindowPlus << std::endl; - - fList = FairRootManager::Instance()->GetData(GetName(), fStartFunctor, fStartTime, fStopFunctor, eventTime + fTimeWindowPlus); //FairRootManager::Instance()->GetEventTime() + - - } - - //fList = (TClonesArray *)fManager->GetObject(GetName()); - if (fVerbose > 1) { - std::cout << GetName() << " fList: " << fList->GetEntries() << std::endl; - } - for (Int_t i=0; iGetEntriesFast(); ++i) { - p=fList->At(i); - if (fVerbose > 2) { -// FairTimeStamp* data = (FairTimeStamp*)p; -// cout << "TimeStamp: " << data->GetTimeStamp() << std::endl; - } - AddBoxes(fq, p, i); + if (IsActive()) { + TObject* p; + Reset(); + // cout<< "FairBoxSetDraw::Init() Exec! " << fList->GetEntriesFast() << endl; + CreateBoxSet(); + if (FairRunAna::Instance()->IsTimeStamp()) { + fList->Clear(); + Double_t eventTime = FairRootManager::Instance()->GetEventTime(); + if (fUseEventTime) { + fStartTime = eventTime - fTimeWindowMinus; + } + cout << "EventTime: " << eventTime << " TimeWindow: " << fStartTime << " - " << eventTime + fTimeWindowPlus + << std::endl; + + fList = FairRootManager::Instance()->GetData( + GetName(), + fStartFunctor, + fStartTime, + fStopFunctor, + eventTime + fTimeWindowPlus); // FairRootManager::Instance()->GetEventTime() + + } + + // fList = (TClonesArray *)fManager->GetObject(GetName()); + if (fVerbose > 1) { + std::cout << GetName() << " fList: " << fList->GetEntries() << std::endl; + } + for (Int_t i = 0; i < fList->GetEntriesFast(); ++i) { + p = fList->At(i); + if (fVerbose > 2) { + // FairTimeStamp* data = (FairTimeStamp*)p; + // cout << "TimeStamp: " << data->GetTimeStamp() << std::endl; + } + AddBoxes(fq, p, i); + } + gEve->AddElement(fq, fEventManager); + gEve->Redraw3D(kFALSE); } - gEve->AddElement(fq, fEventManager ); - gEve->Redraw3D(kFALSE); - } } void FairBoxSetDraw::AddBoxes(FairBoxSet* set, TObject* obj, Int_t i) { - TVector3 point = GetVector(obj); - set->AddBox(point.X(),point.Y(),point.Z()); - set->DigitValue(GetValue(obj, i)); - if (fVerbose>2) { - cout<< "FairBoxSetDraw::Init() Add point " << i << ": " <AddBox(point.X(), point.Y(), point.Z()); + set->DigitValue(GetValue(obj, i)); + if (fVerbose > 2) { + cout << "FairBoxSetDraw::Init() Add point " << i << ": " << point.X() << " " << point.Y() << " " << point.Z() + << " " << endl; + } } - -Int_t FairBoxSetDraw::GetValue(TObject* /*obj*/, Int_t i) -{ - return i; -} +Int_t FairBoxSetDraw::GetValue(TObject* /*obj*/, Int_t i) { return i; } FairBoxSet* FairBoxSetDraw::CreateBoxSet() { - FairBoxSet* aBoxSet = new FairBoxSet(this, GetName()); - aBoxSet->Reset(FairBoxSet::kBT_AABoxFixedDim, kFALSE, 64); - aBoxSet->SetDefWidth(fX); - aBoxSet->SetDefHeight(fY); - aBoxSet->SetDefDepth(fZ); - fq = aBoxSet; - - return aBoxSet; + FairBoxSet* aBoxSet = new FairBoxSet(this, GetName()); + aBoxSet->Reset(FairBoxSet::kBT_AABoxFixedDim, kFALSE, 64); + aBoxSet->SetDefWidth(fX); + aBoxSet->SetDefHeight(fY); + aBoxSet->SetDefDepth(fZ); + fq = aBoxSet; + + return aBoxSet; } -void FairBoxSetDraw::SetTimeWindowMinus(Double_t val) -{ - fTimeWindowMinus = val; -} - -void FairBoxSetDraw::SetTimeWindowPlus(Double_t val) -{ - fTimeWindowPlus = val; -} +void FairBoxSetDraw::SetTimeWindowMinus(Double_t val) { fTimeWindowMinus = val; } -FairBoxSetDraw::~FairBoxSetDraw() -{ -} +void FairBoxSetDraw::SetTimeWindowPlus(Double_t val) { fTimeWindowPlus = val; } -void FairBoxSetDraw::SetParContainers() -{ +FairBoxSetDraw::~FairBoxSetDraw() {} -} +void FairBoxSetDraw::SetParContainers() {} /** Action after each event**/ -void FairBoxSetDraw::Finish() -{ -} +void FairBoxSetDraw::Finish() {} void FairBoxSetDraw::Reset() { - if (fq!=0) { - fq->Reset(); - gEve->RemoveElement(fq, fEventManager ); - } + if (fq != 0) { + fq->Reset(); + gEve->RemoveElement(fq, fEventManager); + } } -ClassImp(FairBoxSetDraw) +ClassImp(FairBoxSetDraw); diff --git a/eventdisplay/FairBoxSetDraw.h b/eventdisplay/FairBoxSetDraw.h index 0f34a371e6..6fce244b02 100644 --- a/eventdisplay/FairBoxSetDraw.h +++ b/eventdisplay/FairBoxSetDraw.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -10,26 +10,24 @@ // ----- Created 26/03/09 by T. Stockmanns ----- // ------------------------------------------------------------------------- - /** FairBoxSetDraw * @author T. Stockmanns * @since 26.3.2009 * Base class to display 3D Points in Eve as a BoxSet - * One has to overwrite the method GetVector which takes a TObject and writes out a TVector3 which is then taken as an input - * to place the points. - * If one wants to change the color of the points one has to overwrite the method GetValue. This method takes a TObject and - * an integer and translates this into an integer as input for the EveBoxSet method DigitValue + * One has to overwrite the method GetVector which takes a TObject and writes out a TVector3 which is then taken as an + *input to place the points. If one wants to change the color of the points one has to overwrite the method GetValue. + *This method takes a TObject and an integer and translates this into an integer as input for the EveBoxSet method + *DigitValue ** **/ #ifndef FAIRBOXSETDRAW_H #define FAIRBOXSETDRAW_H -#include "FairTask.h" // for FairTask, InitStatus - -#include "FairTSBufferFunctional.h" // IWYU pragma: keep needed for cint +#include "FairTSBufferFunctional.h" // IWYU pragma: keep needed for cint +#include "FairTask.h" // for FairTask, InitStatus -#include // for Double_t, Int_t, Bool_t, etc +#include // for Double_t, Int_t, Bool_t, etc class FairBoxSet; class FairEventManager; @@ -45,29 +43,30 @@ class FairBoxSetDraw : public FairTask FairBoxSetDraw(); /** Standard constructor - *@param name Name of task - *@param iVerbose Verbosity level - **/ + *@param name Name of task + *@param iVerbose Verbosity level + **/ FairBoxSetDraw(const char* name, Int_t iVerbose = 1); /** Destructor **/ virtual ~FairBoxSetDraw(); - virtual Double_t GetTimeWindowPlus() {return fTimeWindowPlus;} - virtual Double_t GetTimeWindowMinus() {return fTimeWindowMinus;} + virtual Double_t GetTimeWindowPlus() { return fTimeWindowPlus; } + virtual Double_t GetTimeWindowMinus() { return fTimeWindowMinus; } /** Set verbosity level. For this task and all of the subtasks. **/ - virtual void SetVerbose(Int_t iVerbose) {fVerbose = iVerbose;}; - virtual void SetBoxDimensions(Double_t x, Double_t y, Double_t z) { - fX = x; - fY = y; - fZ = z; + virtual void SetVerbose(Int_t iVerbose) { fVerbose = iVerbose; }; + virtual void SetBoxDimensions(Double_t x, Double_t y, Double_t z) + { + fX = x; + fY = y; + fZ = z; } virtual void SetTimeWindowMinus(Double_t val); virtual void SetTimeWindowPlus(Double_t val); - virtual void SetStartTime(Double_t val) {fStartTime = val;} - virtual void UseEventTimeAsStartTime(Bool_t val = kTRUE) {fUseEventTime = val;} + virtual void SetStartTime(Double_t val) { fStartTime = val; } + virtual void UseEventTimeAsStartTime(Bool_t val = kTRUE) { fUseEventTime = val; } /** Executed task **/ virtual void Exec(Option_t* option); @@ -77,20 +76,20 @@ class FairBoxSetDraw : public FairTask void Reset(); protected: - Int_t fVerbose; // Verbosity level - virtual void SetParContainers() ; + Int_t fVerbose; // Verbosity level + virtual void SetParContainers(); virtual InitStatus Init(); /** Action after each event**/ virtual void Finish(); virtual TVector3 GetVector(TObject* obj) = 0; - virtual Int_t GetValue(TObject* obj,Int_t i); + virtual Int_t GetValue(TObject* obj, Int_t i); virtual void AddBoxes(FairBoxSet* set, TObject* obj, Int_t i = 0); - TClonesArray* fList; //! + TClonesArray* fList; //! FairEventManager* fEventManager; //! FairRootManager* fManager; - FairBoxSet* fq; //! + FairBoxSet* fq; //! Double_t fX, fY, fZ; Double_t fTimeWindowPlus; @@ -104,7 +103,7 @@ class FairBoxSetDraw : public FairTask BinaryFunctor* fStartFunctor; BinaryFunctor* fStopFunctor; - ClassDef(FairBoxSetDraw,1); + ClassDef(FairBoxSetDraw, 1); }; #endif diff --git a/eventdisplay/FairBoxSetEditor.cxx b/eventdisplay/FairBoxSetEditor.cxx index a58d89b267..a282eee191 100644 --- a/eventdisplay/FairBoxSetEditor.cxx +++ b/eventdisplay/FairBoxSetEditor.cxx @@ -1,85 +1,92 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "FairBoxSetEditor.h" -#include "FairEventManager.h" // for FairEventManager +#include "FairEventManager.h" // for FairEventManager -#include // for TGLabel -#include // for TGLayoutHints, etc -#include // for TGNumberEntry, etc +#include // for TGLabel +#include // for TGLayoutHints, etc +#include // for TGNumberEntry, etc class TGWindow; -#include // for operator<<, basic_ostream, etc +#include // for operator<<, basic_ostream, etc // FairBoxSetEditor // // Specialization of TGedEditor for proper update propagation to // TEveManager. -ClassImp(FairBoxSetEditor) +ClassImp(FairBoxSetEditor); -FairBoxSetEditor::FairBoxSetEditor(const TGWindow* p, Int_t width, Int_t height, - UInt_t options, Pixel_t back) - :TGedFrame(p, width, height, options | kVerticalFrame, back), - fInfoFrame(nullptr), fTimeWindowPlus(nullptr), fTimeWindowMinus(nullptr), - fObject(nullptr), fM(nullptr) +FairBoxSetEditor::FairBoxSetEditor(const TGWindow* p, Int_t width, Int_t height, UInt_t options, Pixel_t back) + : TGedFrame(p, width, height, options | kVerticalFrame, back) + , fInfoFrame(nullptr) + , fTimeWindowPlus(nullptr) + , fTimeWindowMinus(nullptr) + , fObject(nullptr) + , fM(nullptr) { - std::cout << "FairBoxSetEditor called!" << std::endl; - Init(); + std::cout << "FairBoxSetEditor called!" << std::endl; + Init(); } void FairBoxSetEditor::Init() { -// FairRootManager* fRootManager=FairRootManager::Instance(); -// TChain* chain =fRootManager->GetInChain(); -// Int_t Entries= chain->GetEntriesFast(); - - MakeTitle("FairBoxSet Editor"); - fInfoFrame= CreateEditorTabSubFrame("Time"); - - TGCompositeFrame* title1 = new TGCompositeFrame(fInfoFrame, 250, 10, - kVerticalFrame | kLHintsExpandX | - kFixedWidth | kOwnBackground); - - TGLabel* label1 = new TGLabel(title1,"Time window after event time [ns]: "); - title1->AddFrame(label1, new TGLayoutHints(kLHintsLeft | kLHintsCenterY, 1, 2, 1, 1)); - - fTimeWindowPlus = new TGNumberEntry(title1);//, 0, 5, -1, TGNumberFormat::kNESRealTwo); //, TGNumberFormat::kNEANonNegative); -// fTimeWindow->SetLimits(0, MAXE, 2501, TGNumberFormat::kNESRealOne); - fTimeWindowPlus->GetNumberEntry()->SetToolTipText("Time window in ns for which points are shown"); - fTimeWindowPlus->Connect("ValueSet(Long_t)", "FairBoxSetEditor",this, "TimeWindow()"); - title1->AddFrame(fTimeWindowPlus, new TGLayoutHints(kLHintsTop, 1, 1, 1, 0)); - - fInfoFrame->AddFrame(title1); - - TGCompositeFrame* title2 = new TGCompositeFrame(fInfoFrame, 250, 10, - kVerticalFrame | kLHintsExpandX | - kFixedWidth | kOwnBackground); - - TGLabel* label2 = new TGLabel(title2, "Time window before event time [ns]: "); - title2->AddFrame(label2, new TGLayoutHints(kLHintsLeft | kLHintsCenterY, 1, 2, 1, 1)); - fTimeWindowMinus = new TGNumberEntry(title2, 0., 6, -1, TGNumberFormat::kNESInteger, TGNumberFormat::kNEANonNegative);//, 1, 5, -1, TGNumberFormat::kNESRealTwo, TGNumberFormat::kNEANonNegative); -// fTimeWindow->SetLimits(0, MAXE, 2501, TGNumberFormat::kNESRealOne); - fTimeWindowMinus->GetNumberEntry()->SetToolTipText("Time window in ns for which points are shown"); - fTimeWindowMinus->Connect("ValueSet(Long_t)", "FairBoxSetEditor",this, "TimeWindow()"); - title2->AddFrame(fTimeWindowMinus, new TGLayoutHints(kLHintsTop, 1, 1, 1, 0)); - - fInfoFrame->AddFrame(title2); + // FairRootManager* fRootManager=FairRootManager::Instance(); + // TChain* chain =fRootManager->GetInChain(); + // Int_t Entries= chain->GetEntriesFast(); + + MakeTitle("FairBoxSet Editor"); + fInfoFrame = CreateEditorTabSubFrame("Time"); + + TGCompositeFrame* title1 = + new TGCompositeFrame(fInfoFrame, 250, 10, kVerticalFrame | kLHintsExpandX | kFixedWidth | kOwnBackground); + + TGLabel* label1 = new TGLabel(title1, "Time window after event time [ns]: "); + title1->AddFrame(label1, new TGLayoutHints(kLHintsLeft | kLHintsCenterY, 1, 2, 1, 1)); + + fTimeWindowPlus = + new TGNumberEntry(title1); //, 0, 5, -1, TGNumberFormat::kNESRealTwo); //, TGNumberFormat::kNEANonNegative); + // fTimeWindow->SetLimits(0, MAXE, 2501, TGNumberFormat::kNESRealOne); + fTimeWindowPlus->GetNumberEntry()->SetToolTipText("Time window in ns for which points are shown"); + fTimeWindowPlus->Connect("ValueSet(Long_t)", "FairBoxSetEditor", this, "TimeWindow()"); + title1->AddFrame(fTimeWindowPlus, new TGLayoutHints(kLHintsTop, 1, 1, 1, 0)); + + fInfoFrame->AddFrame(title1); + + TGCompositeFrame* title2 = + new TGCompositeFrame(fInfoFrame, 250, 10, kVerticalFrame | kLHintsExpandX | kFixedWidth | kOwnBackground); + + TGLabel* label2 = new TGLabel(title2, "Time window before event time [ns]: "); + title2->AddFrame(label2, new TGLayoutHints(kLHintsLeft | kLHintsCenterY, 1, 2, 1, 1)); + fTimeWindowMinus = new TGNumberEntry( + title2, + 0., + 6, + -1, + TGNumberFormat::kNESInteger, + TGNumberFormat::kNEANonNegative); //, 1, 5, -1, TGNumberFormat::kNESRealTwo, TGNumberFormat::kNEANonNegative); + // fTimeWindow->SetLimits(0, MAXE, 2501, TGNumberFormat::kNESRealOne); + fTimeWindowMinus->GetNumberEntry()->SetToolTipText("Time window in ns for which points are shown"); + fTimeWindowMinus->Connect("ValueSet(Long_t)", "FairBoxSetEditor", this, "TimeWindow()"); + title2->AddFrame(fTimeWindowMinus, new TGLayoutHints(kLHintsTop, 1, 1, 1, 0)); + + fInfoFrame->AddFrame(title2); } void FairBoxSetEditor::TimeWindow() { - std::cout << "FairBoxSetEditor::TimeWindowPlus " << fTimeWindowPlus->GetNumber() << std::endl; - std::cout << "FairBoxSetEditor::TimeWindowMinus " << fTimeWindowMinus->GetNumber() << std::endl; - fM->SetTimeWindowPlus(fTimeWindowPlus->GetNumber()); - fM->SetTimeWindowMinus(fTimeWindowMinus->GetNumber()); - FairEventManager* man = FairEventManager::Instance(); - man->GotoEvent(man->GetCurrentEvent()); - Update(); + std::cout << "FairBoxSetEditor::TimeWindowPlus " << fTimeWindowPlus->GetNumber() << std::endl; + std::cout << "FairBoxSetEditor::TimeWindowMinus " << fTimeWindowMinus->GetNumber() << std::endl; + fM->SetTimeWindowPlus(fTimeWindowPlus->GetNumber()); + fM->SetTimeWindowMinus(fTimeWindowMinus->GetNumber()); + FairEventManager* man = FairEventManager::Instance(); + man->GotoEvent(man->GetCurrentEvent()); + Update(); } diff --git a/eventdisplay/FairBoxSetEditor.h b/eventdisplay/FairBoxSetEditor.h index 96faf464b7..265263b006 100644 --- a/eventdisplay/FairBoxSetEditor.h +++ b/eventdisplay/FairBoxSetEditor.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -10,47 +10,50 @@ // ----- Created 26/03/09 by T. Stockmanns ----- // ------------------------------------------------------------------------- - /** FairBoxSetEditor * @author T. Stockmanns * @since 26.3.2009 * Base class to display 3D Points in Eve as a BoxSet - * One has to overwrite the method GetVector which takes a TObject and writes out a TVector3 which is then taken as an input - * to place the points. - * If one wants to change the color of the points one has to overwrite the method GetValue. This method takes a TObject and - * an integer and translates this into an integer as input for the EveBoxSet method DigitValue + * One has to overwrite the method GetVector which takes a TObject and writes out a TVector3 which is then taken as an + *input to place the points. If one wants to change the color of the points one has to overwrite the method GetValue. + *This method takes a TObject and an integer and translates this into an integer as input for the EveBoxSet method + *DigitValue ** **/ #ifndef FairBoxSetEditor_H #define FairBoxSetEditor_H -#include // for TGedFrame - -#include "FairBoxSet.h" // for FairBoxSet +#include "FairBoxSet.h" // for FairBoxSet -#include // for Pixel_t -#include // for FairBoxSetEditor::Class, etc -#include // for EFrameType::kChildFrame, etc -#include // for TGNumberEntry -#include // for TObject +#include // for Pixel_t +#include // for FairBoxSetEditor::Class, etc +#include // for EFrameType::kChildFrame, etc +#include // for TGNumberEntry +#include // for TGedFrame +#include // for TObject class TGWindow; class FairBoxSetEditor : public TGedFrame { public: - FairBoxSetEditor(const TGWindow* p=0, Int_t width=170, Int_t height=30, UInt_t options = kChildFrame, Pixel_t back=GetDefaultFrameBackground()); - virtual ~FairBoxSetEditor() {}; + FairBoxSetEditor(const TGWindow* p = 0, + Int_t width = 170, + Int_t height = 30, + UInt_t options = kChildFrame, + Pixel_t back = GetDefaultFrameBackground()); + virtual ~FairBoxSetEditor(){}; virtual void Init(); - virtual void SetModel(TObject* obj) { - fM = dynamic_cast(obj); - if (fM) { - fTimeWindowPlus->SetNumber(fM->GetTimeWindowPlus()); - fTimeWindowMinus->SetNumber(fM->GetTimeWindowMinus()); - } + virtual void SetModel(TObject* obj) + { + fM = dynamic_cast(obj); + if (fM) { + fTimeWindowPlus->SetNumber(fM->GetTimeWindowPlus()); + fTimeWindowMinus->SetNumber(fM->GetTimeWindowMinus()); + } } virtual void TimeWindow(); @@ -67,7 +70,7 @@ class FairBoxSetEditor : public TGedFrame FairBoxSetEditor(const FairBoxSetEditor&); FairBoxSetEditor& operator=(const FairBoxSetEditor&); - ClassDef(FairBoxSetEditor,2); + ClassDef(FairBoxSetEditor, 2); }; #endif diff --git a/eventdisplay/FairEventManager.cxx b/eventdisplay/FairEventManager.cxx index 75449895d1..f446e3d771 100644 --- a/eventdisplay/FairEventManager.cxx +++ b/eventdisplay/FairEventManager.cxx @@ -1,456 +1,444 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ //______________________________________________________________________________ /** FairEventManager -* class for event management and navigation. -* M. Al-Turany 06.12.2007 -**/ + * class for event management and navigation. + * M. Al-Turany 06.12.2007 + **/ #include "FairEventManager.h" -#include "FairRootManager.h" // for FairRootManager -#include "FairRunAna.h" // for FairRunAna + +#include "FairRootManager.h" // for FairRootManager +#include "FairRunAna.h" // for FairRunAna #include "FairXMLNode.h" -#include // for TDatabasePDG +#include // for TDatabasePDG #include -#include // for TEveGeoTopNode -#include // for TEveManager, gEve +#include // for TEveGeoTopNode +#include // for TEveManager, gEve #include -#include // for TEveProjection, TEveProjection::k... +#include // for TEveProjection, TEveProjection::k... #include #include -#include // for TEveWindowPack, TEveWindowSlot -#include // for gGeoManager, TGeoManager -#include -#include // for TGeoVolume +#include // for TEveWindowPack, TEveWindowSlot #include -#include // for TGLClip, TGLClip::kClipPlane, TGL... +#include // for TGLClip, TGLClip::kClipPlane, TGL... #include #include +#include // for gGeoManager, TGeoManager +#include +#include // for TGeoVolume -ClassImp(FairEventManager) - -FairEventManager* FairEventManager::fgRinstance= 0; +ClassImp(FairEventManager); -FairEventManager* FairEventManager::Instance() -{ +FairEventManager *FairEventManager::fgRinstance = 0; - return fgRinstance; -} +FairEventManager *FairEventManager::Instance() { return fgRinstance; } FairEventManager::FairEventManager() - :TEveEventManager("FairEventManager", ""), - fRootManager(FairRootManager::Instance()), - fEntry(0), - fRunAna(FairRunAna::Instance()), - fEvent(0), - fPriOnly(kFALSE), - fCurrentPDG(0), - fMinEnergy(0), - fMaxEnergy(25), - fEvtMinEnergy(0), - fEvtMaxEnergy(10), - fRPhiPlane{0,0,10,0}, - fRhoZPlane{-1,0,0,0}, - fRphiCam(TGLViewer::kCameraOrthoXOY), - fRhoCam(TGLViewer::kCameraOrthoZOY), - fRPhiView(nullptr), - fRhoZView(nullptr), - fMultiView(nullptr), - fMultiRPhiView(nullptr), - fMultiRhoZView(nullptr), - fRPhiScene(nullptr), - fRhoZScene(nullptr), - fRPhiProjManager(nullptr), - fRhoZProjManager(nullptr), - fAxesPhi(nullptr), - fAxesRho(nullptr), - fXMLConfig("") + : TEveEventManager("FairEventManager", "") + , fRootManager(FairRootManager::Instance()) + , fEntry(0) + , fRunAna(FairRunAna::Instance()) + , fEvent(0) + , fPriOnly(kFALSE) + , fCurrentPDG(0) + , fMinEnergy(0) + , fMaxEnergy(25) + , fEvtMinEnergy(0) + , fEvtMaxEnergy(10) + , fRPhiPlane{0, 0, 10, 0} + , fRhoZPlane{-1, 0, 0, 0} + , fRphiCam(TGLViewer::kCameraOrthoXOY) + , fRhoCam(TGLViewer::kCameraOrthoZOY) + , fRPhiView(nullptr) + , fRhoZView(nullptr) + , fMultiView(nullptr) + , fMultiRPhiView(nullptr) + , fMultiRhoZView(nullptr) + , fRPhiScene(nullptr) + , fRhoZScene(nullptr) + , fRPhiProjManager(nullptr) + , fRhoZProjManager(nullptr) + , fAxesPhi(nullptr) + , fAxesRho(nullptr) + , fXMLConfig("") { - fgRinstance=this; - AddParticlesToPdgDataBase(); - fPDGToColor[22] = 623; // photon - fPDGToColor[-2112] = 2; // anti-neutron - fPDGToColor[-11] = 3; // e+ - fPDGToColor[-3122] = 4; // anti-lambda - fPDGToColor[11] = 5; // e- - fPDGToColor[-3222] = 6; // Sigma - - fPDGToColor[12] = 7; // e-neutrino - fPDGToColor[-3212] = 8; // Sigma0 - fPDGToColor[-13] = 9; // mu+ - fPDGToColor[-3112] = 10; // Sigma+ (PB - fPDGToColor[13] = 11; // mu- - fPDGToColor[-3322] = 12; // Xi0 - fPDGToColor[111] = 13; // pi0 - fPDGToColor[-3312] = 14; // Xi+ - fPDGToColor[211] = 15; // pi+ - fPDGToColor[-3334] = 16; // Omega+ (PB) - fPDGToColor[-211] = 17; // pi- - fPDGToColor[-15] = 18; // tau+ - fPDGToColor[130] = 19; // K long - fPDGToColor[15] = 20; // tau - - fPDGToColor[321] = 21; // K+ - fPDGToColor[411] = 22; // D+ - fPDGToColor[-321] = 23; // K- - fPDGToColor[-411] = 24; // D- - fPDGToColor[2112] = 25; // n - fPDGToColor[421] = 26; // D0 - fPDGToColor[2212] = 27; // p - fPDGToColor[-421] = 28; // D0 - fPDGToColor[-2212] = 29; // anti-proton - fPDGToColor[431] = 30; // Ds+ - fPDGToColor[310] = 31; // K short - fPDGToColor[-431] = 32; // anti Ds- - fPDGToColor[221] = 33; // eta - fPDGToColor[4122] = 34; // Lambda_C+ - fPDGToColor[3122] = 35; // Lambda - fPDGToColor[24] = 36; // W+ - fPDGToColor[3222] = 37; // Sigma+ - fPDGToColor[-24] = 38; // W- - fPDGToColor[3212] = 39; //Sigma0 - fPDGToColor[23] = 40; // Z - fPDGToColor[3112] = 41; // Sigma - - fPDGToColor[3322] = 42; // Xi0 - fPDGToColor[3312] = 43; // Xi- - fPDGToColor[3334] = 44; // Omega- (PB) - fPDGToColor[50000050] = 801; //Cerenkov - fPDGToColor[1000010020] = 45; - fPDGToColor[1000010030] = 48; - fPDGToColor[1000020040] = 50; - fPDGToColor[1000020030] = 55; + fgRinstance = this; + AddParticlesToPdgDataBase(); + fPDGToColor[22] = 623; // photon + fPDGToColor[-2112] = 2; // anti-neutron + fPDGToColor[-11] = 3; // e+ + fPDGToColor[-3122] = 4; // anti-lambda + fPDGToColor[11] = 5; // e- + fPDGToColor[-3222] = 6; // Sigma - + fPDGToColor[12] = 7; // e-neutrino + fPDGToColor[-3212] = 8; // Sigma0 + fPDGToColor[-13] = 9; // mu+ + fPDGToColor[-3112] = 10; // Sigma+ (PB + fPDGToColor[13] = 11; // mu- + fPDGToColor[-3322] = 12; // Xi0 + fPDGToColor[111] = 13; // pi0 + fPDGToColor[-3312] = 14; // Xi+ + fPDGToColor[211] = 15; // pi+ + fPDGToColor[-3334] = 16; // Omega+ (PB) + fPDGToColor[-211] = 17; // pi- + fPDGToColor[-15] = 18; // tau+ + fPDGToColor[130] = 19; // K long + fPDGToColor[15] = 20; // tau - + fPDGToColor[321] = 21; // K+ + fPDGToColor[411] = 22; // D+ + fPDGToColor[-321] = 23; // K- + fPDGToColor[-411] = 24; // D- + fPDGToColor[2112] = 25; // n + fPDGToColor[421] = 26; // D0 + fPDGToColor[2212] = 27; // p + fPDGToColor[-421] = 28; // D0 + fPDGToColor[-2212] = 29; // anti-proton + fPDGToColor[431] = 30; // Ds+ + fPDGToColor[310] = 31; // K short + fPDGToColor[-431] = 32; // anti Ds- + fPDGToColor[221] = 33; // eta + fPDGToColor[4122] = 34; // Lambda_C+ + fPDGToColor[3122] = 35; // Lambda + fPDGToColor[24] = 36; // W+ + fPDGToColor[3222] = 37; // Sigma+ + fPDGToColor[-24] = 38; // W- + fPDGToColor[3212] = 39; // Sigma0 + fPDGToColor[23] = 40; // Z + fPDGToColor[3112] = 41; // Sigma - + fPDGToColor[3322] = 42; // Xi0 + fPDGToColor[3312] = 43; // Xi- + fPDGToColor[3334] = 44; // Omega- (PB) + fPDGToColor[50000050] = 801; // Cerenkov + fPDGToColor[1000010020] = 45; + fPDGToColor[1000010030] = 48; + fPDGToColor[1000020040] = 50; + fPDGToColor[1000020030] = 55; } void FairEventManager::Init(Int_t visopt, Int_t vislvl, Int_t maxvisnds) { - TEveManager::Create(); - fRunAna->Init(); - if(gGeoManager==nullptr) return; - TGeoNode* N= gGeoManager->GetTopNode(); - TEveGeoTopNode* TNod=new TEveGeoTopNode(gGeoManager, N, visopt, vislvl, maxvisnds); - if(!fXMLConfig.EqualTo("")) - LoadXMLSettings(); - gEve->AddGlobalElement(TNod); - gEve->FullRedraw3D(kTRUE); - fEvent= gEve->AddEvent(this); - - fRPhiProjManager = new TEveProjectionManager(TEveProjection::kPT_RPhi); - fRhoZProjManager = new TEveProjectionManager(TEveProjection::kPT_RhoZ); - gEve->AddToListTree(fRPhiProjManager,kFALSE); - gEve->AddToListTree(fRhoZProjManager,kFALSE); - fAxesPhi= new TEveProjectionAxes(fRPhiProjManager); - fAxesRho = new TEveProjectionAxes(fRhoZProjManager); - - TEveWindowSlot *RPhiSlot = TEveWindow::CreateWindowInTab(gEve->GetBrowser()->GetTabRight()); - TEveWindowPack *RPhiPack = RPhiSlot->MakePack(); - RPhiPack->SetElementName("RPhi View"); - RPhiPack->SetShowTitleBar(kFALSE); - RPhiPack->NewSlot()->MakeCurrent(); - fRPhiView = gEve->SpawnNewViewer("RPhi View", ""); - fRPhiScene = gEve->SpawnNewScene("RPhi","Scene holding axis."); - fRPhiScene->AddElement(fAxesPhi); - - TEveWindowSlot *RhoZSlot = TEveWindow::CreateWindowInTab(gEve->GetBrowser()->GetTabRight()); - TEveWindowPack *RhoZPack = RhoZSlot->MakePack(); - RhoZPack->SetElementName("RhoZ View"); - RhoZPack->SetShowTitleBar(kFALSE); - RhoZPack->NewSlot()->MakeCurrent(); - fRhoZView = gEve->SpawnNewViewer("RhoZ View", ""); - fRhoZScene = gEve->SpawnNewScene("RhoZ", "Scene holding axis."); - fRhoZScene->AddElement(fAxesRho); - - SetViewers(fRPhiView,fRhoZView); - - TEveWindowSlot *MultiSlot = TEveWindow::CreateWindowInTab(gEve->GetBrowser()->GetTabRight()); - TEveWindowPack *MultiPack = MultiSlot->MakePack(); - MultiPack->SetElementName("Multi View"); - MultiPack->SetHorizontal(); - MultiPack->SetShowTitleBar(kFALSE); - MultiPack->NewSlot()->MakeCurrent(); - fMultiView = gEve->SpawnNewViewer("3D View (multi)", ""); - // switch off left and right light sources for 3D MultiView - fMultiView->GetGLViewer()->GetLightSet()->SetLight(TGLLightSet::kLightLeft, false); - fMultiView->GetGLViewer()->GetLightSet()->SetLight(TGLLightSet::kLightRight, false); - // add 3D scenes (first tab) to 3D MultiView - fMultiView->AddScene(gEve->GetGlobalScene()); - fMultiView->AddScene(gEve->GetEventScene()); - - // add slot for RPhi projection on Multi View tab - MultiPack = MultiPack->NewSlot()->MakePack(); - MultiPack->SetShowTitleBar(kFALSE); - MultiPack->NewSlot()->MakeCurrent(); - fMultiRPhiView = gEve->SpawnNewViewer("RPhi View (multi)", ""); - MultiPack->NewSlot()->MakeCurrent(); - fMultiRhoZView = gEve->SpawnNewViewer("RhoZ View (multi)", ""); - - SetViewers(fMultiRPhiView,fMultiRhoZView); - - - // don't change reposition camera on each update - fRPhiView->GetGLViewer()->SetResetCamerasOnUpdate(kFALSE); - fRhoZView->GetGLViewer()->SetResetCamerasOnUpdate(kFALSE); - fMultiView->GetGLViewer()->SetResetCamerasOnUpdate(kFALSE); - fMultiRPhiView->GetGLViewer()->SetResetCamerasOnUpdate(kFALSE); - fMultiRhoZView->GetGLViewer()->SetResetCamerasOnUpdate(kFALSE); - fMultiView->GetEveFrame()->HideAllDecorations(); - fMultiRPhiView->GetEveFrame()->HideAllDecorations(); - fMultiRhoZView->GetEveFrame()->HideAllDecorations(); - + TEveManager::Create(); + fRunAna->Init(); + if (gGeoManager == nullptr) + return; + TGeoNode *N = gGeoManager->GetTopNode(); + TEveGeoTopNode *TNod = new TEveGeoTopNode(gGeoManager, N, visopt, vislvl, maxvisnds); + if (!fXMLConfig.EqualTo("")) + LoadXMLSettings(); + gEve->AddGlobalElement(TNod); + gEve->FullRedraw3D(kTRUE); + fEvent = gEve->AddEvent(this); + + fRPhiProjManager = new TEveProjectionManager(TEveProjection::kPT_RPhi); + fRhoZProjManager = new TEveProjectionManager(TEveProjection::kPT_RhoZ); + gEve->AddToListTree(fRPhiProjManager, kFALSE); + gEve->AddToListTree(fRhoZProjManager, kFALSE); + fAxesPhi = new TEveProjectionAxes(fRPhiProjManager); + fAxesRho = new TEveProjectionAxes(fRhoZProjManager); + + TEveWindowSlot *RPhiSlot = TEveWindow::CreateWindowInTab(gEve->GetBrowser()->GetTabRight()); + TEveWindowPack *RPhiPack = RPhiSlot->MakePack(); + RPhiPack->SetElementName("RPhi View"); + RPhiPack->SetShowTitleBar(kFALSE); + RPhiPack->NewSlot()->MakeCurrent(); + fRPhiView = gEve->SpawnNewViewer("RPhi View", ""); + fRPhiScene = gEve->SpawnNewScene("RPhi", "Scene holding axis."); + fRPhiScene->AddElement(fAxesPhi); + + TEveWindowSlot *RhoZSlot = TEveWindow::CreateWindowInTab(gEve->GetBrowser()->GetTabRight()); + TEveWindowPack *RhoZPack = RhoZSlot->MakePack(); + RhoZPack->SetElementName("RhoZ View"); + RhoZPack->SetShowTitleBar(kFALSE); + RhoZPack->NewSlot()->MakeCurrent(); + fRhoZView = gEve->SpawnNewViewer("RhoZ View", ""); + fRhoZScene = gEve->SpawnNewScene("RhoZ", "Scene holding axis."); + fRhoZScene->AddElement(fAxesRho); + + SetViewers(fRPhiView, fRhoZView); + + TEveWindowSlot *MultiSlot = TEveWindow::CreateWindowInTab(gEve->GetBrowser()->GetTabRight()); + TEveWindowPack *MultiPack = MultiSlot->MakePack(); + MultiPack->SetElementName("Multi View"); + MultiPack->SetHorizontal(); + MultiPack->SetShowTitleBar(kFALSE); + MultiPack->NewSlot()->MakeCurrent(); + fMultiView = gEve->SpawnNewViewer("3D View (multi)", ""); + // switch off left and right light sources for 3D MultiView + fMultiView->GetGLViewer()->GetLightSet()->SetLight(TGLLightSet::kLightLeft, false); + fMultiView->GetGLViewer()->GetLightSet()->SetLight(TGLLightSet::kLightRight, false); + // add 3D scenes (first tab) to 3D MultiView + fMultiView->AddScene(gEve->GetGlobalScene()); + fMultiView->AddScene(gEve->GetEventScene()); + + // add slot for RPhi projection on Multi View tab + MultiPack = MultiPack->NewSlot()->MakePack(); + MultiPack->SetShowTitleBar(kFALSE); + MultiPack->NewSlot()->MakeCurrent(); + fMultiRPhiView = gEve->SpawnNewViewer("RPhi View (multi)", ""); + MultiPack->NewSlot()->MakeCurrent(); + fMultiRhoZView = gEve->SpawnNewViewer("RhoZ View (multi)", ""); + + SetViewers(fMultiRPhiView, fMultiRhoZView); + + // don't change reposition camera on each update + fRPhiView->GetGLViewer()->SetResetCamerasOnUpdate(kFALSE); + fRhoZView->GetGLViewer()->SetResetCamerasOnUpdate(kFALSE); + fMultiView->GetGLViewer()->SetResetCamerasOnUpdate(kFALSE); + fMultiRPhiView->GetGLViewer()->SetResetCamerasOnUpdate(kFALSE); + fMultiRhoZView->GetGLViewer()->SetResetCamerasOnUpdate(kFALSE); + fMultiView->GetEveFrame()->HideAllDecorations(); + fMultiRPhiView->GetEveFrame()->HideAllDecorations(); + fMultiRhoZView->GetEveFrame()->HideAllDecorations(); } -void FairEventManager::UpdateEditor() -{ -} +void FairEventManager::UpdateEditor() {} -FairEventManager::~FairEventManager() -{ -} +FairEventManager::~FairEventManager() {} -void FairEventManager::Open() -{ -} +void FairEventManager::Open() {} void FairEventManager::GotoEvent(Int_t event) { - fEntry=event; - fRunAna->Run(static_cast(event)); + fEntry = event; + fRunAna->Run(static_cast(event)); } void FairEventManager::NextEvent() { - fEntry+=1; - fRunAna->Run(static_cast(fEntry)); + fEntry += 1; + fRunAna->Run(static_cast(fEntry)); } void FairEventManager::PrevEvent() { - fEntry-=1; - fRunAna->Run(static_cast(fEntry)); + fEntry -= 1; + fRunAna->Run(static_cast(fEntry)); } -void FairEventManager::Close() -{ -} +void FairEventManager::Close() {} -void FairEventManager::DisplaySettings() -{ -} +void FairEventManager::DisplaySettings() {} -Int_t FairEventManager::Color( int pdg) +Int_t FairEventManager::Color(int pdg) { - if(fPDGToColor.find(pdg)!=fPDGToColor.end()){ - return fPDGToColor[pdg]; - } - return 0; + if (fPDGToColor.find(pdg) != fPDGToColor.end()) { + return fPDGToColor[pdg]; + } + return 0; } void FairEventManager::AddParticlesToPdgDataBase(Int_t /*pdg*/) { -// Add particles to the PDG data base + // Add particles to the PDG data base - TDatabasePDG* pdgDB = TDatabasePDG::Instance(); + TDatabasePDG *pdgDB = TDatabasePDG::Instance(); - const Double_t kAu2Gev=0.9314943228; - const Double_t khSlash = 1.0545726663e-27; - const Double_t kErg2Gev = 1/1.6021773349e-3; - const Double_t khShGev = khSlash*kErg2Gev; - const Double_t kYear2Sec = 3600*24*365.25; + const Double_t kAu2Gev = 0.9314943228; + const Double_t khSlash = 1.0545726663e-27; + const Double_t kErg2Gev = 1 / 1.6021773349e-3; + const Double_t khShGev = khSlash * kErg2Gev; + const Double_t kYear2Sec = 3600 * 24 * 365.25; -// Ions + // Ions - if ( !pdgDB->GetParticle(1000010020) ) - pdgDB->AddParticle("Deuteron","Deuteron",2*kAu2Gev+8.071e-3,kTRUE, - 0,3,"Ion",1000010020); + if (!pdgDB->GetParticle(1000010020)) + pdgDB->AddParticle("Deuteron", "Deuteron", 2 * kAu2Gev + 8.071e-3, kTRUE, 0, 3, "Ion", 1000010020); - if ( !pdgDB->GetParticle(1000010030) ) - pdgDB->AddParticle("Triton","Triton",3*kAu2Gev+14.931e-3,kFALSE, - khShGev/(12.33*kYear2Sec),3,"Ion",1000010030); + if (!pdgDB->GetParticle(1000010030)) + pdgDB->AddParticle( + "Triton", "Triton", 3 * kAu2Gev + 14.931e-3, kFALSE, khShGev / (12.33 * kYear2Sec), 3, "Ion", 1000010030); - if ( !pdgDB->GetParticle(1000020040) ) - pdgDB->AddParticle("Alpha","Alpha",4*kAu2Gev+2.424e-3,kTRUE, - khShGev/(12.33*kYear2Sec),6,"Ion",1000020040); + if (!pdgDB->GetParticle(1000020040)) + pdgDB->AddParticle( + "Alpha", "Alpha", 4 * kAu2Gev + 2.424e-3, kTRUE, khShGev / (12.33 * kYear2Sec), 6, "Ion", 1000020040); - if ( !pdgDB->GetParticle(1000020030) ) - pdgDB->AddParticle("HE3","HE3",3*kAu2Gev+14.931e-3,kFALSE, - 0,6,"Ion",1000020030); + if (!pdgDB->GetParticle(1000020030)) + pdgDB->AddParticle("HE3", "HE3", 3 * kAu2Gev + 14.931e-3, kFALSE, 0, 6, "Ion", 1000020030); -// Special particles -// - if ( !pdgDB->GetParticle(50000050) ) - pdgDB->AddParticle("Cherenkov","Cherenkov",0,kFALSE, - 0,0,"Special",50000050); + // Special particles + // + if (!pdgDB->GetParticle(50000050)) + pdgDB->AddParticle("Cherenkov", "Cherenkov", 0, kFALSE, 0, 0, "Special", 50000050); - if ( !pdgDB->GetParticle(50000051) ) - pdgDB->AddParticle("FeedbackPhoton","FeedbackPhoton",0,kFALSE, - 0,0,"Special",50000051); + if (!pdgDB->GetParticle(50000051)) + pdgDB->AddParticle("FeedbackPhoton", "FeedbackPhoton", 0, kFALSE, 0, 0, "Special", 50000051); } -void FairEventManager::SetViewers(TEveViewer* RPhi, TEveViewer* RhoZ) { - RPhi->GetGLViewer()->SetCurrentCamera(fRphiCam); - // set clip plane and camera parameters - RPhi->GetGLViewer()->GetClipSet()->SetClipType(TGLClip::kClipPlane); - RPhi->GetGLViewer()->GetClipSet()->SetClipState(TGLClip::kClipPlane, fRPhiPlane); - RPhi->GetGLViewer()->GetCameraOverlay()->SetOrthographicMode(TGLCameraOverlay::kAxis); - RPhi->GetGLViewer()->GetCameraOverlay()->SetShowOrthographic(kTRUE); - // switch off left, right, top and bottom light sources - RPhi->GetGLViewer()->GetLightSet()->SetLight(TGLLightSet::kLightLeft, false); - RPhi->GetGLViewer()->GetLightSet()->SetLight(TGLLightSet::kLightRight, false); - RPhi->GetGLViewer()->GetLightSet()->SetLight(TGLLightSet::kLightTop, false); - RPhi->GetGLViewer()->GetLightSet()->SetLight(TGLLightSet::kLightBottom, false); - - RhoZ->GetGLViewer()->SetCurrentCamera(fRhoCam); - // set clip plane and camera parameters - RhoZ->GetGLViewer()->GetClipSet()->SetClipType(TGLClip::kClipPlane); - RhoZ->GetGLViewer()->GetClipSet()->SetClipState(TGLClip::kClipPlane, fRhoZPlane); - RhoZ->GetGLViewer()->GetCameraOverlay()->SetOrthographicMode(TGLCameraOverlay::kAxis); - RhoZ->GetGLViewer()->GetCameraOverlay()->SetShowOrthographic(kTRUE); - // switch off left, right and front light sources - RhoZ->GetGLViewer()->GetLightSet()->SetLight(TGLLightSet::kLightLeft, false); - RhoZ->GetGLViewer()->GetLightSet()->SetLight(TGLLightSet::kLightRight, false); - RhoZ->GetGLViewer()->GetLightSet()->SetLight(TGLLightSet::kLightFront, false); - - RPhi->AddScene(fRPhiScene); - RPhi->AddScene(gEve->GetGlobalScene()); - RPhi->AddScene(gEve->GetEventScene()); - RhoZ->AddScene(fRhoZScene); - RhoZ->AddScene(gEve->GetGlobalScene()); - RhoZ->AddScene(gEve->GetEventScene()); +void FairEventManager::SetViewers(TEveViewer *RPhi, TEveViewer *RhoZ) +{ + RPhi->GetGLViewer()->SetCurrentCamera(fRphiCam); + // set clip plane and camera parameters + RPhi->GetGLViewer()->GetClipSet()->SetClipType(TGLClip::kClipPlane); + RPhi->GetGLViewer()->GetClipSet()->SetClipState(TGLClip::kClipPlane, fRPhiPlane); + RPhi->GetGLViewer()->GetCameraOverlay()->SetOrthographicMode(TGLCameraOverlay::kAxis); + RPhi->GetGLViewer()->GetCameraOverlay()->SetShowOrthographic(kTRUE); + // switch off left, right, top and bottom light sources + RPhi->GetGLViewer()->GetLightSet()->SetLight(TGLLightSet::kLightLeft, false); + RPhi->GetGLViewer()->GetLightSet()->SetLight(TGLLightSet::kLightRight, false); + RPhi->GetGLViewer()->GetLightSet()->SetLight(TGLLightSet::kLightTop, false); + RPhi->GetGLViewer()->GetLightSet()->SetLight(TGLLightSet::kLightBottom, false); + + RhoZ->GetGLViewer()->SetCurrentCamera(fRhoCam); + // set clip plane and camera parameters + RhoZ->GetGLViewer()->GetClipSet()->SetClipType(TGLClip::kClipPlane); + RhoZ->GetGLViewer()->GetClipSet()->SetClipState(TGLClip::kClipPlane, fRhoZPlane); + RhoZ->GetGLViewer()->GetCameraOverlay()->SetOrthographicMode(TGLCameraOverlay::kAxis); + RhoZ->GetGLViewer()->GetCameraOverlay()->SetShowOrthographic(kTRUE); + // switch off left, right and front light sources + RhoZ->GetGLViewer()->GetLightSet()->SetLight(TGLLightSet::kLightLeft, false); + RhoZ->GetGLViewer()->GetLightSet()->SetLight(TGLLightSet::kLightRight, false); + RhoZ->GetGLViewer()->GetLightSet()->SetLight(TGLLightSet::kLightFront, false); + + RPhi->AddScene(fRPhiScene); + RPhi->AddScene(gEve->GetGlobalScene()); + RPhi->AddScene(gEve->GetEventScene()); + RhoZ->AddScene(fRhoZScene); + RhoZ->AddScene(gEve->GetGlobalScene()); + RhoZ->AddScene(gEve->GetEventScene()); } -void FairEventManager::SetRPhiPlane(Double_t a, Double_t b, Double_t c, - Double_t d,TGLViewer::ECameraType camtype) { - fRPhiPlane[0] =a; - fRPhiPlane[1] =b; - fRPhiPlane[2] =c; - fRPhiPlane[3] =d; - fRphiCam =camtype; +void FairEventManager::SetRPhiPlane(Double_t a, Double_t b, Double_t c, Double_t d, TGLViewer::ECameraType camtype) +{ + fRPhiPlane[0] = a; + fRPhiPlane[1] = b; + fRPhiPlane[2] = c; + fRPhiPlane[3] = d; + fRphiCam = camtype; } -void FairEventManager::SetRhoZPlane(Double_t a, Double_t b, Double_t c, - Double_t d,TGLViewer::ECameraType camtype) { - fRhoZPlane[0] =a; - fRhoZPlane[1] =b; - fRhoZPlane[2] =c; - fRhoZPlane[3] =d; - fRhoCam = camtype; +void FairEventManager::SetRhoZPlane(Double_t a, Double_t b, Double_t c, Double_t d, TGLViewer::ECameraType camtype) +{ + fRhoZPlane[0] = a; + fRhoZPlane[1] = b; + fRhoZPlane[2] = c; + fRhoZPlane[3] = d; + fRhoCam = camtype; } -void FairEventManager::LoadXMLSettings() { - FairXMLFile xmlfile(fXMLConfig,"read"); - FairXMLNode *xml = xmlfile.GetRootNode(); - for(int i =0;iGetNChildren();i++){ - TString nodename = xml->GetChild(i)->GetName(); - if(nodename.EqualTo("Detectors")){ - TGeoNode *top = gGeoManager->GetTopNode(); - FairXMLNode *top_xml = xml->GetChild(i)->GetChild(0); - if(top_xml!=nullptr) - LoadXMLDetector(top,top_xml); - }else if(nodename.EqualTo("MCTracksColors")){ - FairXMLNode *colors = xml->GetChild(i); - for(int j=0;jGetNChildren();j++){ - FairXMLNode *color = colors->GetChild(j); - TString pgd_code = color->GetAttrib("pdg")->GetValue(); - TString color_code = color->GetAttrib("color")->GetValue(); - fPDGToColor[pgd_code.Atoi()] = StringToColor(color_code); - } - } - } - gEve->Redraw3D(); +void FairEventManager::LoadXMLSettings() +{ + FairXMLFile xmlfile(fXMLConfig, "read"); + FairXMLNode *xml = xmlfile.GetRootNode(); + for (int i = 0; i < xml->GetNChildren(); i++) { + TString nodename = xml->GetChild(i)->GetName(); + if (nodename.EqualTo("Detectors")) { + TGeoNode *top = gGeoManager->GetTopNode(); + FairXMLNode *top_xml = xml->GetChild(i)->GetChild(0); + if (top_xml != nullptr) + LoadXMLDetector(top, top_xml); + } else if (nodename.EqualTo("MCTracksColors")) { + FairXMLNode *colors = xml->GetChild(i); + for (int j = 0; j < colors->GetNChildren(); j++) { + FairXMLNode *color = colors->GetChild(j); + TString pgd_code = color->GetAttrib("pdg")->GetValue(); + TString color_code = color->GetAttrib("color")->GetValue(); + fPDGToColor[pgd_code.Atoi()] = StringToColor(color_code); + } + } + } + gEve->Redraw3D(); } -void FairEventManager::LoadXMLDetector(TGeoNode* node, FairXMLNode* xml,Int_t depth) { - TString name = xml->GetAttrib("name")->GetValue(); - TString node_name = node->GetName(); - Bool_t recursive = (xml->GetAttrib("recursive")->GetValue().Length()!=0&&!name.EqualTo(node_name)); - if(recursive&&depth==0) return; - TString transparency = xml->GetAttrib("transparency")->GetValue(); - TString color = xml->GetAttrib("color")->GetValue(); - if(!color.EqualTo("")){ - node->GetVolume()->SetFillColor(StringToColor(color)); - node->GetVolume()->SetLineColor(StringToColor(color)); - } - if(!transparency.EqualTo("")){ - node->GetVolume()->SetTransparency((Char_t)(transparency.Atoi())); - } - if(xml->GetAttrib("recursive")->GetValue().Length()>0){ - TString val = xml->GetAttrib("recursive")->GetValue(); - Int_t xml_depth = val.Atoi(); - if(recursive){ - xml_depth =depth-1; - } - for(int i=0;iGetNdaughters();i++){ - TGeoNode *daughter_node = node->GetDaughter(i); - LoadXMLDetector(daughter_node,xml,xml_depth); - } - } - if(xml->GetNChildren()>0&&!recursive){ - for(int i=0;iGetNdaughters();i++){ - TString subdetector_name = node->GetDaughter(i)->GetName(); - for(int j=0;jGetNChildren();j++){ - FairXMLNode *subnode = xml->GetChild(j); - TString subnode_name = subnode->GetAttrib("name")->GetValue(); - if(subnode_name==subdetector_name){ - LoadXMLDetector(node->GetDaughter(i),subnode); - } - } - } - } +void FairEventManager::LoadXMLDetector(TGeoNode *node, FairXMLNode *xml, Int_t depth) +{ + TString name = xml->GetAttrib("name")->GetValue(); + TString node_name = node->GetName(); + Bool_t recursive = (xml->GetAttrib("recursive")->GetValue().Length() != 0 && !name.EqualTo(node_name)); + if (recursive && depth == 0) + return; + TString transparency = xml->GetAttrib("transparency")->GetValue(); + TString color = xml->GetAttrib("color")->GetValue(); + if (!color.EqualTo("")) { + node->GetVolume()->SetFillColor(StringToColor(color)); + node->GetVolume()->SetLineColor(StringToColor(color)); + } + if (!transparency.EqualTo("")) { + node->GetVolume()->SetTransparency((Char_t)(transparency.Atoi())); + } + if (xml->GetAttrib("recursive")->GetValue().Length() > 0) { + TString val = xml->GetAttrib("recursive")->GetValue(); + Int_t xml_depth = val.Atoi(); + if (recursive) { + xml_depth = depth - 1; + } + for (int i = 0; i < node->GetNdaughters(); i++) { + TGeoNode *daughter_node = node->GetDaughter(i); + LoadXMLDetector(daughter_node, xml, xml_depth); + } + } + if (xml->GetNChildren() > 0 && !recursive) { + for (int i = 0; i < node->GetNdaughters(); i++) { + TString subdetector_name = node->GetDaughter(i)->GetName(); + for (int j = 0; j < xml->GetNChildren(); j++) { + FairXMLNode *subnode = xml->GetChild(j); + TString subnode_name = subnode->GetAttrib("name")->GetValue(); + if (subnode_name == subdetector_name) { + LoadXMLDetector(node->GetDaughter(i), subnode); + } + } + } + } } -Int_t FairEventManager::StringToColor(TString color) const { - if (color.Contains("k")) { - Int_t plus_index = color.First('+'); - Int_t minus_index = color.First('-'); - Int_t cut = plus_index; - if (cut == -1) - cut = minus_index; - if(cut==-1) cut = color.Length(); - TString col_name(color( 0, cut)); - Int_t col_val = 0; - if (col_name.EqualTo("kWhite")) { - col_val = 0; - } else if (col_name.EqualTo("kBlack")) { - col_val = 1; - } else if (col_name.EqualTo("kGray")) { - col_val = 920; - } else if (col_name.EqualTo("kRed")) { - col_val = 632; - } else if (col_name.EqualTo("kGreen")) { - col_val = 416; - } else if (col_name.EqualTo("kBlue")) { - col_val = 600; - } else if (col_name.EqualTo("kYellow")) { - col_val = 400; - } else if (col_name.EqualTo("kMagenta")) { - col_val = 616; - } else if (col_name.EqualTo("kCyan")) { - col_val = 432; - } else if (col_name.EqualTo("kOrange")) { - col_val = 800; - } else if (col_name.EqualTo("kSpring")) { - col_val = 820; - } else if (col_name.EqualTo("kTeal")) { - col_val = 840; - } else if (col_name.EqualTo("kAzure")) { - col_val = 860; - } else if (col_name.EqualTo("kViolet")) { - col_val = 880; - } else if (col_name.EqualTo("kPink")) { - col_val = 900; - } - TString col_num(color( cut + 1, color.Length())); - if(col_num.Length()>0){ - if(color.Contains("+")){ - col_val +=col_num.Atoi(); - }else{ - col_val -=col_num.Atoi(); - } - } - return col_val; - }else{ - return color.Atoi(); - } +Int_t FairEventManager::StringToColor(TString color) const +{ + if (color.Contains("k")) { + Int_t plus_index = color.First('+'); + Int_t minus_index = color.First('-'); + Int_t cut = plus_index; + if (cut == -1) + cut = minus_index; + if (cut == -1) + cut = color.Length(); + TString col_name(color(0, cut)); + Int_t col_val = 0; + if (col_name.EqualTo("kWhite")) { + col_val = 0; + } else if (col_name.EqualTo("kBlack")) { + col_val = 1; + } else if (col_name.EqualTo("kGray")) { + col_val = 920; + } else if (col_name.EqualTo("kRed")) { + col_val = 632; + } else if (col_name.EqualTo("kGreen")) { + col_val = 416; + } else if (col_name.EqualTo("kBlue")) { + col_val = 600; + } else if (col_name.EqualTo("kYellow")) { + col_val = 400; + } else if (col_name.EqualTo("kMagenta")) { + col_val = 616; + } else if (col_name.EqualTo("kCyan")) { + col_val = 432; + } else if (col_name.EqualTo("kOrange")) { + col_val = 800; + } else if (col_name.EqualTo("kSpring")) { + col_val = 820; + } else if (col_name.EqualTo("kTeal")) { + col_val = 840; + } else if (col_name.EqualTo("kAzure")) { + col_val = 860; + } else if (col_name.EqualTo("kViolet")) { + col_val = 880; + } else if (col_name.EqualTo("kPink")) { + col_val = 900; + } + TString col_num(color(cut + 1, color.Length())); + if (col_num.Length() > 0) { + if (color.Contains("+")) { + col_val += col_num.Atoi(); + } else { + col_val -= col_num.Atoi(); + } + } + return col_val; + } else { + return color.Atoi(); + } } diff --git a/eventdisplay/FairEventManager.h b/eventdisplay/FairEventManager.h index 3125517ea9..99ef14e566 100644 --- a/eventdisplay/FairEventManager.h +++ b/eventdisplay/FairEventManager.h @@ -1,27 +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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /** -* class for event management and navigation. -* 06.12.07 M.Al-Turany -*/ + * class for event management and navigation. + * 06.12.07 M.Al-Turany + */ #ifndef FairEventManager_H #define FairEventManager_H -#include "FairRunAna.h" // for FairRunAna +#include "FairRunAna.h" // for FairRunAna -#include // for Float_t, Int_t, Bool_t, etc -#include // for TEveEventManager +#include // for Float_t, Int_t, Bool_t, etc +#include // for TEveEventManager #include #include - #include -class FairRootManager; //does not work with streamer, reason unclear +class FairRootManager; // does not work with streamer, reason unclear class FairTask; class FairXMLNode; @@ -35,86 +34,88 @@ class TGListTreeItem; class FairEventManager : public TEveEventManager { public: - static FairEventManager* Instance(); + static FairEventManager *Instance(); FairEventManager(); virtual ~FairEventManager(); - virtual void SetXMLConfig(TString xml_config){fXMLConfig = xml_config;}; + virtual void SetXMLConfig(TString xml_config) { fXMLConfig = xml_config; }; virtual void Open(); - virtual void GotoEvent(Int_t event); // *MENU* - virtual void NextEvent(); // *MENU* - virtual void PrevEvent(); // *MENU* + virtual void GotoEvent(Int_t event); // *MENU* + virtual void NextEvent(); // *MENU* + virtual void PrevEvent(); // *MENU* virtual void Close(); - virtual void DisplaySettings(); // *Menu* + virtual void DisplaySettings(); // *Menu* virtual Int_t Color(Int_t pdg); - void AddTask(FairTask* t) {fRunAna->AddTask(t);} - virtual void Init( Int_t visopt = 1, Int_t vislvl = 3, Int_t maxvisnds = 10000); - virtual Int_t GetCurrentEvent() {return fEntry;} - virtual void SetPriOnly(Bool_t Pri) {fPriOnly=Pri;} - virtual Bool_t IsPriOnly() {return fPriOnly;} - virtual void SelectPDG(Int_t PDG) {fCurrentPDG= PDG;} - virtual Int_t GetCurrentPDG() {return fCurrentPDG;} - virtual void SetMaxEnergy( Float_t max) {fMaxEnergy = max;} - virtual void SetMinEnergy( Float_t min) {fMinEnergy = min;} - virtual void SetEvtMaxEnergy( Float_t max) {fEvtMaxEnergy = max;} - virtual void SetEvtMinEnergy( Float_t min) {fEvtMinEnergy = min;} - virtual Float_t GetEvtMaxEnergy() {return fEvtMaxEnergy ;} - virtual Float_t GetEvtMinEnergy() {return fEvtMinEnergy ;} - virtual Float_t GetMaxEnergy() {return fMaxEnergy;} - virtual Float_t GetMinEnergy() {return fMinEnergy;} - virtual void SetRPhiPlane(Double_t a, Double_t b, Double_t c, Double_t d,TGLViewer::ECameraType camtype); - virtual void SetRhoZPlane(Double_t a, Double_t b, Double_t c, Double_t d,TGLViewer::ECameraType camtype); + void AddTask(FairTask *t) { fRunAna->AddTask(t); } + virtual void Init(Int_t visopt = 1, Int_t vislvl = 3, Int_t maxvisnds = 10000); + virtual Int_t GetCurrentEvent() { return fEntry; } + virtual void SetPriOnly(Bool_t Pri) { fPriOnly = Pri; } + virtual Bool_t IsPriOnly() { return fPriOnly; } + virtual void SelectPDG(Int_t PDG) { fCurrentPDG = PDG; } + virtual Int_t GetCurrentPDG() { return fCurrentPDG; } + virtual void SetMaxEnergy(Float_t max) { fMaxEnergy = max; } + virtual void SetMinEnergy(Float_t min) { fMinEnergy = min; } + virtual void SetEvtMaxEnergy(Float_t max) { fEvtMaxEnergy = max; } + virtual void SetEvtMinEnergy(Float_t min) { fEvtMinEnergy = min; } + virtual Float_t GetEvtMaxEnergy() { return fEvtMaxEnergy; } + virtual Float_t GetEvtMinEnergy() { return fEvtMinEnergy; } + virtual Float_t GetMaxEnergy() { return fMaxEnergy; } + virtual Float_t GetMinEnergy() { return fMinEnergy; } + virtual void SetRPhiPlane(Double_t a, Double_t b, Double_t c, Double_t d, TGLViewer::ECameraType camtype); + virtual void SetRhoZPlane(Double_t a, Double_t b, Double_t c, Double_t d, TGLViewer::ECameraType camtype); void UpdateEditor(); - virtual void AddParticlesToPdgDataBase(Int_t pdg=0); - ClassDef(FairEventManager,1); + virtual void AddParticlesToPdgDataBase(Int_t pdg = 0); + ClassDef(FairEventManager, 1); + protected: - TEveViewer* GetRPhiView() const {return fRPhiView;}; - TEveViewer *GetRhoZView() const {return fRhoZView;}; - TEveViewer *GetMultiView() const {return fMultiView;}; - TEveViewer *GetMultiRPhiView() const { return fMultiRPhiView;}; - TEveViewer *GetMultiRhoZView() const {return fMultiRhoZView;}; - TEveScene* GetRhoZScene() const {return fRhoZScene;}; - TEveScene* GetRPhiScene() const {return fRPhiScene;}; - TEveProjectionManager* GetRhoZProjManager() const {return fRhoZProjManager;}; - TEveProjectionManager* GetRPhiProjManager() const {return fRPhiProjManager;}; - TEveProjectionAxes *GetRPhiAxes() const { return fAxesPhi;}; - TEveProjectionAxes *GetRhoZAxes() const {return fAxesRho;}; + TEveViewer *GetRPhiView() const { return fRPhiView; }; + TEveViewer *GetRhoZView() const { return fRhoZView; }; + TEveViewer *GetMultiView() const { return fMultiView; }; + TEveViewer *GetMultiRPhiView() const { return fMultiRPhiView; }; + TEveViewer *GetMultiRhoZView() const { return fMultiRhoZView; }; + TEveScene *GetRhoZScene() const { return fRhoZScene; }; + TEveScene *GetRPhiScene() const { return fRPhiScene; }; + TEveProjectionManager *GetRhoZProjManager() const { return fRhoZProjManager; }; + TEveProjectionManager *GetRPhiProjManager() const { return fRPhiProjManager; }; + TEveProjectionAxes *GetRPhiAxes() const { return fAxesPhi; }; + TEveProjectionAxes *GetRhoZAxes() const { return fAxesRho; }; virtual void LoadXMLSettings(); - void LoadXMLDetector(TGeoNode *node, FairXMLNode *xml, Int_t depth=0); - Int_t StringToColor(TString color)const; + void LoadXMLDetector(TGeoNode *node, FairXMLNode *xml, Int_t depth = 0); + Int_t StringToColor(TString color) const; + private: - FairRootManager* fRootManager; //! - Int_t fEntry; //! - FairRunAna* fRunAna; //! - TGListTreeItem* fEvent; //! - Bool_t fPriOnly; //! - Int_t fCurrentPDG; //! - Float_t fMinEnergy; //! - Float_t fMaxEnergy; //! - Float_t fEvtMinEnergy; //! - Float_t fEvtMaxEnergy; //! - Double_t fRPhiPlane[4]; //! - Double_t fRhoZPlane[4]; //! - TGLViewer::ECameraType fRphiCam; //! - TGLViewer::ECameraType fRhoCam; //! - TEveViewer *fRPhiView; //! - TEveViewer *fRhoZView; //! - TEveViewer *fMultiView; //! - TEveViewer *fMultiRPhiView; //! - TEveViewer *fMultiRhoZView; //! - TEveScene *fRPhiScene; //! - TEveScene *fRhoZScene;//! - TEveProjectionManager *fRPhiProjManager; //! - TEveProjectionManager *fRhoZProjManager; //! + FairRootManager *fRootManager; //! + Int_t fEntry; //! + FairRunAna *fRunAna; //! + TGListTreeItem *fEvent; //! + Bool_t fPriOnly; //! + Int_t fCurrentPDG; //! + Float_t fMinEnergy; //! + Float_t fMaxEnergy; //! + Float_t fEvtMinEnergy; //! + Float_t fEvtMaxEnergy; //! + Double_t fRPhiPlane[4]; //! + Double_t fRhoZPlane[4]; //! + TGLViewer::ECameraType fRphiCam; //! + TGLViewer::ECameraType fRhoCam; //! + TEveViewer *fRPhiView; //! + TEveViewer *fRhoZView; //! + TEveViewer *fMultiView; //! + TEveViewer *fMultiRPhiView; //! + TEveViewer *fMultiRhoZView; //! + TEveScene *fRPhiScene; //! + TEveScene *fRhoZScene; //! + TEveProjectionManager *fRPhiProjManager; //! + TEveProjectionManager *fRhoZProjManager; //! TEveProjectionAxes *fAxesPhi; TEveProjectionAxes *fAxesRho; TString fXMLConfig; - std::map fPDGToColor;; + std::map fPDGToColor; + ; - static FairEventManager* fgRinstance; //! - FairEventManager(const FairEventManager&); - FairEventManager& operator=(const FairEventManager&); + static FairEventManager *fgRinstance; //! + FairEventManager(const FairEventManager &); + FairEventManager &operator=(const FairEventManager &); void SetViewers(TEveViewer *RPhi, TEveViewer *RhoZ); - }; #endif diff --git a/eventdisplay/FairEventManagerEditor.cxx b/eventdisplay/FairEventManagerEditor.cxx index 8fd509fb5e..c1eca151ca 100644 --- a/eventdisplay/FairEventManagerEditor.cxx +++ b/eventdisplay/FairEventManagerEditor.cxx @@ -1,27 +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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "FairEventManagerEditor.h" -#include "FairEventManager.h" // for FairEventManager -#include "FairRootManager.h" // for FairRootManager -#include "FairRunAna.h" // for FairRunAna - -#include // for TChain -#include // for TEveGValuator -#include // for TFile -#include // for TGCheckButton, TGTextButton -#include // for TGLabel -#include // for TGLayoutHints, etc -#include // for TGNumberEntry, etc -#include // for TGeoManager, gGeoManager -#include // for TString - -#include // for NULL +#include "FairEventManager.h" // for FairEventManager +#include "FairRootManager.h" // for FairRootManager +#include "FairRunAna.h" // for FairRunAna + +#include // for TChain +#include // for TEveGValuator +#include // for TFile +#include // for TGCheckButton, TGTextButton +#include // for TGLabel +#include // for TGLayoutHints, etc +#include // for TGNumberEntry, etc +#include // for TGeoManager, gGeoManager +#include // for TString +#include // for NULL class TGWindow; class TObject; @@ -33,161 +32,156 @@ class TObject; // Specialization of TGedEditor for proper update propagation to // TEveManager. -ClassImp(FairEventManagerEditor) - -FairEventManagerEditor::FairEventManagerEditor(const TGWindow* p, Int_t width, Int_t height, - UInt_t options, Pixel_t back) - :TGedFrame(p, width, height, options | kVerticalFrame, back), - fObject(0), - fManager(FairEventManager::Instance()), - fCurrentEvent(0), - fCurrentPDG(0), - fVizPri(0), - fMinEnergy(0), - fMaxEnergy(0), - fEventTime(NULL) +ClassImp(FairEventManagerEditor); + +FairEventManagerEditor::FairEventManagerEditor(const TGWindow* p, + Int_t width, + Int_t height, + UInt_t options, + Pixel_t back) + : TGedFrame(p, width, height, options | kVerticalFrame, back) + , fObject(0) + , fManager(FairEventManager::Instance()) + , fCurrentEvent(0) + , fCurrentPDG(0) + , fVizPri(0) + , fMinEnergy(0) + , fMaxEnergy(0) + , fEventTime(NULL) { - Init(); + Init(); } void FairEventManagerEditor::Init() { - FairRootManager* fRootManager=FairRootManager::Instance(); - TChain* chain =fRootManager->GetInChain(); - Int_t Entries= chain->GetEntriesFast(); - - MakeTitle("FairEventManager Editor"); - TGVerticalFrame* fInfoFrame= CreateEditorTabSubFrame("Info"); - TGCompositeFrame* title1 = new TGCompositeFrame(fInfoFrame, 250, 10, - kVerticalFrame | kLHintsExpandX | - kFixedWidth | kOwnBackground); - - TString Infile= "Input file : "; -// TFile* file =FairRunAna::Instance()->GetInputFile(); - TFile* file =FairRootManager::Instance()->GetInChain()->GetFile(); - Infile+=file->GetName(); - TGLabel* TFName=new TGLabel(title1, Infile.Data()); - title1->AddFrame(TFName); - - UInt_t RunId= FairRunAna::Instance()->getRunId(); - TString run= "Run Id : "; - run += RunId; - TGLabel* TRunId=new TGLabel(title1, run.Data()); - title1->AddFrame( TRunId); - - TString nevent= "No of events : "; - nevent +=Entries ; - TGLabel* TEvent=new TGLabel(title1, nevent.Data()); - title1->AddFrame(TEvent); - - Int_t nodes= gGeoManager->GetNNodes(); - TString NNodes= "No. of Nodes : "; - NNodes += nodes; - TGLabel* NoNode=new TGLabel(title1, NNodes.Data()); - title1->AddFrame( NoNode); - - TGHorizontalFrame* f = new TGHorizontalFrame(title1); - TGLabel* l = new TGLabel(f, "Current Event:"); - f->AddFrame(l, new TGLayoutHints(kLHintsLeft | kLHintsCenterY, 1, 2, 1, 1)); - fCurrentEvent = new TGNumberEntry(f, 0., 6, -1, - TGNumberFormat::kNESInteger, TGNumberFormat::kNEANonNegative, - TGNumberFormat::kNELLimitMinMax, 0, Entries); - f->AddFrame(fCurrentEvent, new TGLayoutHints(kLHintsLeft, 1, 1, 1, 1)); - fCurrentEvent->Connect("ValueSet(Long_t)","FairEventManagerEditor", this, "SelectEvent()"); - title1->AddFrame(f); - - TGHorizontalFrame* f2 = new TGHorizontalFrame(title1); - TGLabel* EventTimeLabel = new TGLabel(f2, "Event Time: "); - fEventTime = new TGLabel(f2,""); - f2->AddFrame(EventTimeLabel); - f2->AddFrame(fEventTime); - title1->AddFrame(f2); - - fVizPri = new TGCheckButton(title1, "Primary Only"); - fVizPri->Connect("Toggled(Bool_t)", "FairEventManagerEditor", this, "DoVizPri()"); - title1->AddFrame(fVizPri); - - TGHorizontalFrame* f1 = new TGHorizontalFrame(title1); - TGLabel* L1 = new TGLabel(f1, "Select PDG :"); - f1->AddFrame(L1, new TGLayoutHints(kLHintsLeft | kLHintsCenterY, 1, 2, 1, 1)); - fCurrentPDG = new TGNumberEntry(f1, 0., 12, -1, - TGNumberFormat::kNESInteger, TGNumberFormat::kNEAAnyNumber, - TGNumberFormat::kNELNoLimits, 0, 1); - f1->AddFrame(fCurrentPDG, new TGLayoutHints(kLHintsLeft, 1, 1, 1, 1)); - fCurrentPDG->Connect("ValueSet(Long_t)","FairEventManagerEditor", this, "SelectPDG()"); - title1->AddFrame(f1); - - - fMinEnergy = new TEveGValuator(title1, "Min Energy:", 90, 0); - fMinEnergy->SetNELength(5); - fMinEnergy->SetLabelWidth(80); - fMinEnergy->Build(); - fMinEnergy->SetLimits(0, MAXE, 2501, TGNumberFormat::kNESRealOne); - fMinEnergy->SetToolTip("Minimum energy of displayed track."); - fMinEnergy->Connect("ValueSet(Double_t)", "FairEventManagerEditor",this, "MinEnergy()"); - title1->AddFrame(fMinEnergy, new TGLayoutHints(kLHintsTop, 1, 1, 1, 0)); - - - fMaxEnergy = new TEveGValuator(title1, "Max Energy:", 90, 0); - fMaxEnergy->SetNELength(5); - fMaxEnergy->SetLabelWidth(80); - fMaxEnergy->Build(); - fMaxEnergy->SetLimits(0, MAXE, 2501, TGNumberFormat::kNESRealOne); - fMaxEnergy->SetToolTip("Maximum energy of displayed track."); - fMaxEnergy->SetValue(MAXE); - fMaxEnergy->Connect("ValueSet(Double_t)", "FairEventManagerEditor",this, "MaxEnergy()"); - title1->AddFrame(fMaxEnergy, new TGLayoutHints(kLHintsTop, 1, 1, 1, 0)); - - TGTextButton* fUpdate = new TGTextButton(title1, "Update"); - title1->AddFrame(fUpdate, new TGLayoutHints(kLHintsRight | kLHintsExpandX, 5,5,1,1)); - fUpdate->Connect("Clicked()", "FairEventManagerEditor", this, "SelectEvent()"); - - fInfoFrame->AddFrame(title1, new TGLayoutHints(kLHintsTop, 0, 0, 2, 0)); - - fManager->SetMaxEnergy(MAXE); + FairRootManager* fRootManager = FairRootManager::Instance(); + TChain* chain = fRootManager->GetInChain(); + Int_t Entries = chain->GetEntriesFast(); + + MakeTitle("FairEventManager Editor"); + TGVerticalFrame* fInfoFrame = CreateEditorTabSubFrame("Info"); + TGCompositeFrame* title1 = + new TGCompositeFrame(fInfoFrame, 250, 10, kVerticalFrame | kLHintsExpandX | kFixedWidth | kOwnBackground); + + TString Infile = "Input file : "; + // TFile* file =FairRunAna::Instance()->GetInputFile(); + TFile* file = FairRootManager::Instance()->GetInChain()->GetFile(); + Infile += file->GetName(); + TGLabel* TFName = new TGLabel(title1, Infile.Data()); + title1->AddFrame(TFName); + + UInt_t RunId = FairRunAna::Instance()->getRunId(); + TString run = "Run Id : "; + run += RunId; + TGLabel* TRunId = new TGLabel(title1, run.Data()); + title1->AddFrame(TRunId); + + TString nevent = "No of events : "; + nevent += Entries; + TGLabel* TEvent = new TGLabel(title1, nevent.Data()); + title1->AddFrame(TEvent); + + Int_t nodes = gGeoManager->GetNNodes(); + TString NNodes = "No. of Nodes : "; + NNodes += nodes; + TGLabel* NoNode = new TGLabel(title1, NNodes.Data()); + title1->AddFrame(NoNode); + + TGHorizontalFrame* f = new TGHorizontalFrame(title1); + TGLabel* l = new TGLabel(f, "Current Event:"); + f->AddFrame(l, new TGLayoutHints(kLHintsLeft | kLHintsCenterY, 1, 2, 1, 1)); + fCurrentEvent = new TGNumberEntry(f, + 0., + 6, + -1, + TGNumberFormat::kNESInteger, + TGNumberFormat::kNEANonNegative, + TGNumberFormat::kNELLimitMinMax, + 0, + Entries); + f->AddFrame(fCurrentEvent, new TGLayoutHints(kLHintsLeft, 1, 1, 1, 1)); + fCurrentEvent->Connect("ValueSet(Long_t)", "FairEventManagerEditor", this, "SelectEvent()"); + title1->AddFrame(f); + + TGHorizontalFrame* f2 = new TGHorizontalFrame(title1); + TGLabel* EventTimeLabel = new TGLabel(f2, "Event Time: "); + fEventTime = new TGLabel(f2, ""); + f2->AddFrame(EventTimeLabel); + f2->AddFrame(fEventTime); + title1->AddFrame(f2); + + fVizPri = new TGCheckButton(title1, "Primary Only"); + fVizPri->Connect("Toggled(Bool_t)", "FairEventManagerEditor", this, "DoVizPri()"); + title1->AddFrame(fVizPri); + + TGHorizontalFrame* f1 = new TGHorizontalFrame(title1); + TGLabel* L1 = new TGLabel(f1, "Select PDG :"); + f1->AddFrame(L1, new TGLayoutHints(kLHintsLeft | kLHintsCenterY, 1, 2, 1, 1)); + fCurrentPDG = new TGNumberEntry( + f1, 0., 12, -1, TGNumberFormat::kNESInteger, TGNumberFormat::kNEAAnyNumber, TGNumberFormat::kNELNoLimits, 0, 1); + f1->AddFrame(fCurrentPDG, new TGLayoutHints(kLHintsLeft, 1, 1, 1, 1)); + fCurrentPDG->Connect("ValueSet(Long_t)", "FairEventManagerEditor", this, "SelectPDG()"); + title1->AddFrame(f1); + + fMinEnergy = new TEveGValuator(title1, "Min Energy:", 90, 0); + fMinEnergy->SetNELength(5); + fMinEnergy->SetLabelWidth(80); + fMinEnergy->Build(); + fMinEnergy->SetLimits(0, MAXE, 2501, TGNumberFormat::kNESRealOne); + fMinEnergy->SetToolTip("Minimum energy of displayed track."); + fMinEnergy->Connect("ValueSet(Double_t)", "FairEventManagerEditor", this, "MinEnergy()"); + title1->AddFrame(fMinEnergy, new TGLayoutHints(kLHintsTop, 1, 1, 1, 0)); + + fMaxEnergy = new TEveGValuator(title1, "Max Energy:", 90, 0); + fMaxEnergy->SetNELength(5); + fMaxEnergy->SetLabelWidth(80); + fMaxEnergy->Build(); + fMaxEnergy->SetLimits(0, MAXE, 2501, TGNumberFormat::kNESRealOne); + fMaxEnergy->SetToolTip("Maximum energy of displayed track."); + fMaxEnergy->SetValue(MAXE); + fMaxEnergy->Connect("ValueSet(Double_t)", "FairEventManagerEditor", this, "MaxEnergy()"); + title1->AddFrame(fMaxEnergy, new TGLayoutHints(kLHintsTop, 1, 1, 1, 0)); + + TGTextButton* fUpdate = new TGTextButton(title1, "Update"); + title1->AddFrame(fUpdate, new TGLayoutHints(kLHintsRight | kLHintsExpandX, 5, 5, 1, 1)); + fUpdate->Connect("Clicked()", "FairEventManagerEditor", this, "SelectEvent()"); + + fInfoFrame->AddFrame(title1, new TGLayoutHints(kLHintsTop, 0, 0, 2, 0)); + + fManager->SetMaxEnergy(MAXE); } -void FairEventManagerEditor::MaxEnergy() -{ - fManager->SetMaxEnergy(fMaxEnergy->GetValue()); -} +void FairEventManagerEditor::MaxEnergy() { fManager->SetMaxEnergy(fMaxEnergy->GetValue()); } -void FairEventManagerEditor::MinEnergy() -{ - fManager->SetMinEnergy(fMinEnergy->GetValue()); -} +void FairEventManagerEditor::MinEnergy() { fManager->SetMinEnergy(fMinEnergy->GetValue()); } void FairEventManagerEditor::DoVizPri() { - if (fVizPri->IsOn()) { fManager->SetPriOnly(kTRUE); } - else { fManager->SetPriOnly(kFALSE); } + if (fVizPri->IsOn()) { + fManager->SetPriOnly(kTRUE); + } else { + fManager->SetPriOnly(kFALSE); + } } -void FairEventManagerEditor::SelectPDG() -{ - fManager->SelectPDG(fCurrentPDG->GetIntNumber()); -} +void FairEventManagerEditor::SelectPDG() { fManager->SelectPDG(fCurrentPDG->GetIntNumber()); } void FairEventManagerEditor::SelectEvent() { - fManager->GotoEvent(fCurrentEvent->GetIntNumber()); - - TString time; -// time+=(FairRootManager::Instance()->GetEventTime()); - time.Form("%.2f", FairRootManager::Instance()->GetEventTime()); - time += " ns"; - fEventTime->SetText(time.Data()); - - fMinEnergy->SetLimits(fManager->GetEvtMinEnergy(), fManager->GetEvtMaxEnergy(), 100); - fMinEnergy->SetValue(fManager->GetEvtMinEnergy()); - fMaxEnergy->SetLimits(fManager->GetEvtMinEnergy(), fManager->GetEvtMaxEnergy(), 100); - fMaxEnergy->SetValue( fManager->GetEvtMaxEnergy()); - Update(); - + fManager->GotoEvent(fCurrentEvent->GetIntNumber()); + + TString time; + // time+=(FairRootManager::Instance()->GetEventTime()); + time.Form("%.2f", FairRootManager::Instance()->GetEventTime()); + time += " ns"; + fEventTime->SetText(time.Data()); + + fMinEnergy->SetLimits(fManager->GetEvtMinEnergy(), fManager->GetEvtMaxEnergy(), 100); + fMinEnergy->SetValue(fManager->GetEvtMinEnergy()); + fMaxEnergy->SetLimits(fManager->GetEvtMinEnergy(), fManager->GetEvtMaxEnergy(), 100); + fMaxEnergy->SetValue(fManager->GetEvtMaxEnergy()); + Update(); } -void FairEventManagerEditor::SetModel( TObject* obj) -{ - fObject = obj; -} +void FairEventManagerEditor::SetModel(TObject* obj) { fObject = obj; } diff --git a/eventdisplay/FairEventManagerEditor.h b/eventdisplay/FairEventManagerEditor.h index f431f901ed..5f545e15f3 100644 --- a/eventdisplay/FairEventManagerEditor.h +++ b/eventdisplay/FairEventManagerEditor.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -12,10 +12,10 @@ #ifndef ROOT_FAIREVENTMANAGEREDITOR #define ROOT_FAIREVENTMANAGEREDITOR -#include // for TGedFrame -#include // for Pixel_t -#include // for ClassDef -#include // for EFrameType::kChildFrame +#include // for Pixel_t +#include // for ClassDef +#include // for EFrameType::kChildFrame +#include // for TGedFrame class FairEventManager; class TEveGValuator; @@ -27,21 +27,25 @@ class TObject; class FairEventManagerEditor : public TGedFrame { - FairEventManagerEditor(const FairEventManagerEditor&); // Not implemented - FairEventManagerEditor& operator=(const FairEventManagerEditor&); // Not implemented + FairEventManagerEditor(const FairEventManagerEditor&); // Not implemented + FairEventManagerEditor& operator=(const FairEventManagerEditor&); // Not implemented protected: TObject* fObject; - FairEventManager* fManager; - TGNumberEntry* fCurrentEvent, *fCurrentPDG; - TGCheckButton* fVizPri; - TEveGValuator* fMinEnergy ,*fMaxEnergy; + FairEventManager* fManager; + TGNumberEntry *fCurrentEvent, *fCurrentPDG; + TGCheckButton* fVizPri; + TEveGValuator *fMinEnergy, *fMaxEnergy; TGLabel* fEventTime; + public: - FairEventManagerEditor(const TGWindow* p=0, Int_t width=170, Int_t height=30, - UInt_t options = kChildFrame, Pixel_t back=GetDefaultFrameBackground()); + FairEventManagerEditor(const TGWindow* p = 0, + Int_t width = 170, + Int_t height = 30, + UInt_t options = kChildFrame, + Pixel_t back = GetDefaultFrameBackground()); virtual ~FairEventManagerEditor() {} - void SetModel( TObject* obj); + void SetModel(TObject* obj); virtual void SelectEvent(); virtual void SelectPDG(); void DoVizPri(); @@ -49,7 +53,7 @@ class FairEventManagerEditor : public TGedFrame virtual void MinEnergy(); virtual void Init(); - ClassDef(FairEventManagerEditor, 0); // Specialization of TGedEditor for proper update propagation to TEveManager. + ClassDef(FairEventManagerEditor, 0); // Specialization of TGedEditor for proper update propagation to TEveManager. }; #endif diff --git a/eventdisplay/FairHitDraw.cxx b/eventdisplay/FairHitDraw.cxx index 30ac83e193..70afad64c2 100644 --- a/eventdisplay/FairHitDraw.cxx +++ b/eventdisplay/FairHitDraw.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* @@ -14,22 +14,20 @@ #include "FairHitDraw.h" -#include "FairHit.h" // for FairHit +#include "FairHit.h" // for FairHit class TObject; -FairHitDraw::FairHitDraw() -{ -} +FairHitDraw::FairHitDraw() {} -FairHitDraw::FairHitDraw(const char* name, Int_t iVerbose):FairBoxSetDraw(name, iVerbose) -{ -} +FairHitDraw::FairHitDraw(const char* name, Int_t iVerbose) + : FairBoxSetDraw(name, iVerbose) +{} TVector3 FairHitDraw::GetVector(TObject* obj) { - FairHit* hit =static_cast(obj); - return TVector3(hit->GetX(), hit->GetY(), hit->GetZ()); + FairHit* hit = static_cast(obj); + return TVector3(hit->GetX(), hit->GetY(), hit->GetZ()); } -ClassImp(FairHitDraw) +ClassImp(FairHitDraw); diff --git a/eventdisplay/FairHitDraw.h b/eventdisplay/FairHitDraw.h index f2f2042c57..16ae4eda93 100644 --- a/eventdisplay/FairHitDraw.h +++ b/eventdisplay/FairHitDraw.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* @@ -17,28 +17,28 @@ #ifndef FAIRHITDRAW_H_ #define FAIRHITDRAW_H_ -#include "FairBoxSetDraw.h" // for FairBoxSetDraw +#include "FairBoxSetDraw.h" // for FairBoxSetDraw -#include // for FairHitDraw::Class, etc -#include // for TVector3 +#include // for FairHitDraw::Class, etc +#include // for TVector3 class TObject; -class FairHitDraw: public FairBoxSetDraw +class FairHitDraw : public FairBoxSetDraw { public: FairHitDraw(); /** Standard constructor - *@param name Name of task - *@param iVerbose Verbosity level - **/ + *@param name Name of task + *@param iVerbose Verbosity level + **/ FairHitDraw(const char* name, Int_t iVerbose = 1); protected: TVector3 GetVector(TObject* obj); - ClassDef(FairHitDraw,1); + ClassDef(FairHitDraw, 1); }; #endif /* FAIRHITDRAW_H_ */ diff --git a/eventdisplay/FairHitPointSetDraw.cxx b/eventdisplay/FairHitPointSetDraw.cxx index 16a944cdf5..0b8464eeba 100644 --- a/eventdisplay/FairHitPointSetDraw.cxx +++ b/eventdisplay/FairHitPointSetDraw.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* @@ -14,32 +14,31 @@ #include "FairHitPointSetDraw.h" -#include "FairHit.h" // for FairHit +#include "FairHit.h" // for FairHit -#include // for TVector3 - -#include // for operator<<, basic_ostream, etc +#include // for TVector3 +#include // for operator<<, basic_ostream, etc using std::cout; using std::endl; FairHitPointSetDraw::FairHitPointSetDraw() { - // TODO Auto-generated constructor stub + // TODO Auto-generated constructor stub } FairHitPointSetDraw::~FairHitPointSetDraw() { - // TODO Auto-generated destructor stub + // TODO Auto-generated destructor stub } TVector3 FairHitPointSetDraw::GetVector(TObject* obj) { - FairHit* p = static_cast(obj); - if (fVerbose > 1) { - cout << "-I- FairHitPointSetDraw::GetVector: " << p->GetX() << " " << p->GetY() << " " << p->GetZ() << endl; - } - return TVector3(p->GetX(), p->GetY(), p->GetZ()); + FairHit* p = static_cast(obj); + if (fVerbose > 1) { + cout << "-I- FairHitPointSetDraw::GetVector: " << p->GetX() << " " << p->GetY() << " " << p->GetZ() << endl; + } + return TVector3(p->GetX(), p->GetY(), p->GetZ()); } -ClassImp(FairHitPointSetDraw) +ClassImp(FairHitPointSetDraw); diff --git a/eventdisplay/FairHitPointSetDraw.h b/eventdisplay/FairHitPointSetDraw.h index ee6826c765..cd8633d42a 100644 --- a/eventdisplay/FairHitPointSetDraw.h +++ b/eventdisplay/FairHitPointSetDraw.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* @@ -15,26 +15,26 @@ #ifndef FAIRHITPOINTSETDRAW_H_ #define FAIRHITPOINTSETDRAW_H_ -#include "FairPointSetDraw.h" // for FairPointSetDraw +#include "FairPointSetDraw.h" // for FairPointSetDraw -#include // for FairHitPointSetDraw::Class, etc +#include // for FairHitPointSetDraw::Class, etc class TObject; class TVector3; -class FairHitPointSetDraw: public FairPointSetDraw +class FairHitPointSetDraw : public FairPointSetDraw { public: FairHitPointSetDraw(); FairHitPointSetDraw(const char* name, Color_t color, Style_t mstyle, Int_t iVerbose = 1) - : FairPointSetDraw(name, color, mstyle, iVerbose) + : FairPointSetDraw(name, color, mstyle, iVerbose) {} virtual ~FairHitPointSetDraw(); protected: TVector3 GetVector(TObject* obj); - ClassDef(FairHitPointSetDraw,1); + ClassDef(FairHitPointSetDraw, 1); }; #endif /* FAIRHITPOINTSETDRAW_H_ */ diff --git a/eventdisplay/FairMCPointDraw.cxx b/eventdisplay/FairMCPointDraw.cxx index 1333bebf27..73ab115cf1 100644 --- a/eventdisplay/FairMCPointDraw.cxx +++ b/eventdisplay/FairMCPointDraw.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* @@ -14,26 +14,26 @@ #include "FairMCPointDraw.h" -#include "FairMCPoint.h" // for FairMCPoint +#include "FairMCPoint.h" // for FairMCPoint -#include // for TVector3 +#include // for TVector3 class TObject; FairMCPointDraw::FairMCPointDraw() { - // TODO Auto-generated constructor stub + // TODO Auto-generated constructor stub } FairMCPointDraw::~FairMCPointDraw() { - // TODO Auto-generated destructor stub + // TODO Auto-generated destructor stub } TVector3 FairMCPointDraw::GetVector(TObject* obj) { - FairMCPoint* p = static_cast(obj); - return TVector3(p->GetX(), p->GetY(), p->GetZ()); + FairMCPoint* p = static_cast(obj); + return TVector3(p->GetX(), p->GetY(), p->GetZ()); } -ClassImp(FairMCPointDraw) +ClassImp(FairMCPointDraw); diff --git a/eventdisplay/FairMCPointDraw.h b/eventdisplay/FairMCPointDraw.h index 697427ca22..e6d98447fc 100644 --- a/eventdisplay/FairMCPointDraw.h +++ b/eventdisplay/FairMCPointDraw.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* @@ -15,24 +15,25 @@ #ifndef FAIRMCPOINTDRAW_H_ #define FAIRMCPOINTDRAW_H_ -#include "FairPointSetDraw.h" // for FairPointSetDraw +#include "FairPointSetDraw.h" // for FairPointSetDraw -#include // for FairMCPointDraw::Class, etc +#include // for FairMCPointDraw::Class, etc class TObject; class TVector3; -class FairMCPointDraw: public FairPointSetDraw +class FairMCPointDraw : public FairPointSetDraw { public: FairMCPointDraw(); - FairMCPointDraw(const char* name, Color_t color ,Style_t mstyle, Int_t iVerbose = 1):FairPointSetDraw(name, color, mstyle, iVerbose) {}; + FairMCPointDraw(const char* name, Color_t color, Style_t mstyle, Int_t iVerbose = 1) + : FairPointSetDraw(name, color, mstyle, iVerbose){}; virtual ~FairMCPointDraw(); protected: TVector3 GetVector(TObject* obj); - ClassDef(FairMCPointDraw,1); + ClassDef(FairMCPointDraw, 1); }; #endif /* FAIRMCPOINTDRAW_H_ */ diff --git a/eventdisplay/FairMCTracks.cxx b/eventdisplay/FairMCTracks.cxx index fbd55b3191..c9c7631a5d 100644 --- a/eventdisplay/FairMCTracks.cxx +++ b/eventdisplay/FairMCTracks.cxx @@ -11,170 +11,171 @@ // ------------------------------------------------------------------------- #include "FairMCTracks.h" -#include "FairEventManager.h" // for FairEventManager -#include "FairRootManager.h" // for FairRootManager +#include "FairEventManager.h" // for FairEventManager #include "FairLogger.h" - -#include // for TClonesArray -#include // for TEveManager, gEve -#include // for TEvePathMark -#include // for TEveTrackList, TEveTrack -#include // for TEveTrackPropagator -#include // for TEveVector, TEveVectorT -#include // for TGeoTrack -#include // for Max, Min -#include // for TObjArray -#include // for TParticle - -#include // for strcmp +#include "FairRootManager.h" // for FairRootManager + +#include // for TClonesArray +#include // for TEveManager, gEve +#include // for TEvePathMark +#include // for TEveTrackList, TEveTrack +#include // for TEveTrackPropagator +#include // for TEveVector, TEveVectorT +#include // for TGeoTrack +#include // for Max, Min +#include // for TObjArray +#include // for TParticle +#include // for strcmp FairMCTracks::FairMCTracks() - : FairTask("FairMCTracks", 0), - fTrackList(nullptr), - fTrPr(nullptr), - fEventManager(nullptr), - fEveTrList(nullptr), - fEvent(""), - fTrList(nullptr), - MinEnergyLimit(-1.), - MaxEnergyLimit(-1.), - PEnergy(-1.) -{ -} + : FairTask("FairMCTracks", 0) + , fTrackList(nullptr) + , fTrPr(nullptr) + , fEventManager(nullptr) + , fEveTrList(nullptr) + , fEvent("") + , fTrList(nullptr) + , MinEnergyLimit(-1.) + , MaxEnergyLimit(-1.) + , PEnergy(-1.) +{} FairMCTracks::FairMCTracks(const char* name, Int_t iVerbose) - : FairTask(name, iVerbose), - fTrackList(nullptr), - fTrPr(nullptr), - fEventManager(nullptr), - fEveTrList(new TObjArray(16)), - fEvent(""), - fTrList(nullptr), - MinEnergyLimit(-1.), - MaxEnergyLimit(-1.), - PEnergy(-1.) -{ -} + : FairTask(name, iVerbose) + , fTrackList(nullptr) + , fTrPr(nullptr) + , fEventManager(nullptr) + , fEveTrList(new TObjArray(16)) + , fEvent("") + , fTrList(nullptr) + , MinEnergyLimit(-1.) + , MaxEnergyLimit(-1.) + , PEnergy(-1.) +{} InitStatus FairMCTracks::Init() { - LOG(debug) << "FairMCTracks::Init()"; - FairRootManager* fManager = FairRootManager::Instance(); - fTrackList = static_cast(fManager->GetObject("GeoTracks")); - if(fTrackList==0) { - LOG(error) << "FairMCTracks::Init() branch " << GetName() << " Not found! Task will be deactivated "; - SetActive(kFALSE); - } - LOG(debug1) << "FairMCTracks::Init() get track list" << fTrackList; - LOG(debug1) << "FairMCTracks::Init() create propagator"; - fEventManager =FairEventManager::Instance(); - LOG(debug1) << "FairMCTracks::Init() get instance of FairEventManager "; - fEvent = "Current Event"; - MinEnergyLimit=fEventManager->GetEvtMinEnergy(); - MaxEnergyLimit=fEventManager->GetEvtMaxEnergy(); - PEnergy=0; - if(IsActive()) { return kSUCCESS; } - else { return kERROR; } + LOG(debug) << "FairMCTracks::Init()"; + FairRootManager* fManager = FairRootManager::Instance(); + fTrackList = static_cast(fManager->GetObject("GeoTracks")); + if (fTrackList == 0) { + LOG(error) << "FairMCTracks::Init() branch " << GetName() << " Not found! Task will be deactivated "; + SetActive(kFALSE); + } + LOG(debug1) << "FairMCTracks::Init() get track list" << fTrackList; + LOG(debug1) << "FairMCTracks::Init() create propagator"; + fEventManager = FairEventManager::Instance(); + LOG(debug1) << "FairMCTracks::Init() get instance of FairEventManager "; + fEvent = "Current Event"; + MinEnergyLimit = fEventManager->GetEvtMinEnergy(); + MaxEnergyLimit = fEventManager->GetEvtMaxEnergy(); + PEnergy = 0; + if (IsActive()) { + return kSUCCESS; + } else { + return kERROR; + } } void FairMCTracks::Exec(Option_t* /*option*/) { - if (IsActive()) { - LOG(debug1) << " FairMCTracks::Exec "; - TGeoTrack* tr; - const Double_t* point; - - Reset(); - - for (Int_t i=0; iGetEntriesFast(); i++) { - LOG(debug3) << "FairMCTracks::Exec "<< i; - tr=static_cast(fTrackList->At(i)); - TParticle* P=static_cast(tr->GetParticle()); - PEnergy=P->Energy(); - MinEnergyLimit=TMath::Min(PEnergy,MinEnergyLimit) ; - MaxEnergyLimit=TMath::Max(PEnergy,MaxEnergyLimit) ; - LOG(debug3)<< "MinEnergyLimit " << MinEnergyLimit << " MaxEnergyLimit " << MaxEnergyLimit; - if (fEventManager->IsPriOnly() && P->GetMother(0)>-1) { continue; } - if(fEventManager->GetCurrentPDG()!=0 && fEventManager->GetCurrentPDG()!= tr->GetPDG()) { continue; } - LOG(debug3) << "PEnergy " << PEnergy << " Min " << fEventManager->GetMinEnergy() << " Max " << fEventManager->GetMaxEnergy(); - if( (PEnergyGetMinEnergy()) || (PEnergy >fEventManager->GetMaxEnergy())) { continue; } - - Int_t Np=tr->GetNpoints(); - fTrList= GetTrGroup(P); - TEveTrack* track= new TEveTrack(P, tr->GetPDG(), fTrPr); - track->SetLineColor(fEventManager->Color(tr->GetPDG())); - for (Int_t n=0; nGetPoint(n); - track->SetPoint(n,point[0],point[1],point[2]); - TEveVector pos= TEveVector(point[0], point[1],point[2]); - TEvePathMark* path = new TEvePathMark(); - path->fV=pos ; - path->fTime= point[3]; - if(n==0) { - TEveVector Mom= TEveVector(P->Px(), P->Py(),P->Pz()); - path->fP=Mom; + if (IsActive()) { + LOG(debug1) << " FairMCTracks::Exec "; + TGeoTrack* tr; + const Double_t* point; + + Reset(); + + for (Int_t i = 0; i < fTrackList->GetEntriesFast(); i++) { + LOG(debug3) << "FairMCTracks::Exec " << i; + tr = static_cast(fTrackList->At(i)); + TParticle* P = static_cast(tr->GetParticle()); + PEnergy = P->Energy(); + MinEnergyLimit = TMath::Min(PEnergy, MinEnergyLimit); + MaxEnergyLimit = TMath::Max(PEnergy, MaxEnergyLimit); + LOG(debug3) << "MinEnergyLimit " << MinEnergyLimit << " MaxEnergyLimit " << MaxEnergyLimit; + if (fEventManager->IsPriOnly() && P->GetMother(0) > -1) { + continue; + } + if (fEventManager->GetCurrentPDG() != 0 && fEventManager->GetCurrentPDG() != tr->GetPDG()) { + continue; + } + LOG(debug3) << "PEnergy " << PEnergy << " Min " << fEventManager->GetMinEnergy() << " Max " + << fEventManager->GetMaxEnergy(); + if ((PEnergy < fEventManager->GetMinEnergy()) || (PEnergy > fEventManager->GetMaxEnergy())) { + continue; + } + + Int_t Np = tr->GetNpoints(); + fTrList = GetTrGroup(P); + TEveTrack* track = new TEveTrack(P, tr->GetPDG(), fTrPr); + track->SetLineColor(fEventManager->Color(tr->GetPDG())); + for (Int_t n = 0; n < Np; n++) { + point = tr->GetPoint(n); + track->SetPoint(n, point[0], point[1], point[2]); + TEveVector pos = TEveVector(point[0], point[1], point[2]); + TEvePathMark* path = new TEvePathMark(); + path->fV = pos; + path->fTime = point[3]; + if (n == 0) { + TEveVector Mom = TEveVector(P->Px(), P->Py(), P->Pz()); + path->fP = Mom; + } + LOG(debug4) << "Path marker added " << path; + + track->AddPathMark(*path); + + LOG(debug4) << "Path marker added " << path; + + delete path; + } + fTrList->AddElement(track); + LOG(debug3) << "track added " << track->GetName(); } - LOG(debug4) << "Path marker added " << path; - - track->AddPathMark(*path); - - LOG(debug4) << "Path marker added " << path; - - delete path; - } - fTrList->AddElement(track); - LOG(debug3) << "track added " << track->GetName(); - } - for (Int_t i=0; iGetEntriesFast(); i++) { - // TEveTrackList *TrListIn=( TEveTrackList *) fEveTrList->At(i); - //TrListIn->FindMomentumLimits(TrListIn, kFALSE); + for (Int_t i = 0; i < fEveTrList->GetEntriesFast(); i++) { + // TEveTrackList *TrListIn=( TEveTrackList *) fEveTrList->At(i); + // TrListIn->FindMomentumLimits(TrListIn, kFALSE); + } + fEventManager->SetEvtMaxEnergy(MaxEnergyLimit); + fEventManager->SetEvtMinEnergy(MinEnergyLimit); + gEve->Redraw3D(kFALSE); } - fEventManager->SetEvtMaxEnergy(MaxEnergyLimit); - fEventManager->SetEvtMinEnergy(MinEnergyLimit); - gEve->Redraw3D(kFALSE); - } } -FairMCTracks::~FairMCTracks() -{ -} +FairMCTracks::~FairMCTracks() {} -void FairMCTracks::SetParContainers() -{ -} +void FairMCTracks::SetParContainers() {} -void FairMCTracks::Finish() -{ -} +void FairMCTracks::Finish() {} void FairMCTracks::Reset() { - for (Int_t i=0; iGetEntriesFast(); i++) { - TEveTrackList* ele=static_cast(fEveTrList->At(i)); - gEve->RemoveElement(ele,fEventManager); - } - fEveTrList->Clear(); + for (Int_t i = 0; i < fEveTrList->GetEntriesFast(); i++) { + TEveTrackList* ele = static_cast(fEveTrList->At(i)); + gEve->RemoveElement(ele, fEventManager); + } + fEveTrList->Clear(); } TEveTrackList* FairMCTracks::GetTrGroup(TParticle* P) { - fTrList=0; - for (Int_t i=0; iGetEntriesFast(); i++) { - TEveTrackList* TrListIn=static_cast(fEveTrList->At(i)); - if ( strcmp(TrListIn->GetName(),P->GetName())==0 ) { - fTrList= TrListIn; - break; + fTrList = 0; + for (Int_t i = 0; i < fEveTrList->GetEntriesFast(); i++) { + TEveTrackList* TrListIn = static_cast(fEveTrList->At(i)); + if (strcmp(TrListIn->GetName(), P->GetName()) == 0) { + fTrList = TrListIn; + break; + } + } + if (fTrList == 0) { + fTrPr = new TEveTrackPropagator(); + fTrList = new TEveTrackList(P->GetName(), fTrPr); + fTrList->SetMainColor(fEventManager->Color(P->GetPdgCode())); + fEveTrList->Add(fTrList); + gEve->AddElement(fTrList, fEventManager); + fTrList->SetRnrLine(kTRUE); } - } - if(fTrList ==0) { - fTrPr=new TEveTrackPropagator(); - fTrList= new TEveTrackList(P->GetName(),fTrPr ); - fTrList->SetMainColor(fEventManager->Color(P->GetPdgCode())); - fEveTrList->Add(fTrList); - gEve->AddElement( fTrList ,fEventManager ); - fTrList->SetRnrLine(kTRUE); - } - return fTrList; + return fTrList; } -ClassImp(FairMCTracks) +ClassImp(FairMCTracks); diff --git a/eventdisplay/FairMCTracks.h b/eventdisplay/FairMCTracks.h index 881175946b..fd0dc6c455 100644 --- a/eventdisplay/FairMCTracks.h +++ b/eventdisplay/FairMCTracks.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -20,11 +20,11 @@ #ifndef FAIRMCTRACKS_H #define FAIRMCTRACKS_H -#include "FairTask.h" // for FairTask, InitStatus +#include "FairTask.h" // for FairTask, InitStatus -#include // for Double_t, etc -#include // IWYU pragma: keep needed by cint -#include // for TString +#include // for Double_t, etc +#include // IWYU pragma: keep needed by cint +#include // for TString class FairEventManager; class TClonesArray; @@ -39,16 +39,16 @@ class FairMCTracks : public FairTask FairMCTracks(); /** Standard constructor - *@param name Name of task - *@param iVerbose Verbosity level - **/ + *@param name Name of task + *@param iVerbose Verbosity level + **/ FairMCTracks(const char* name, Int_t iVerbose = 1); /** Destructor **/ virtual ~FairMCTracks(); /** Set verbosity level. For this task and all of the subtasks. **/ - void SetVerbose(Int_t iVerbose) {fVerbose = iVerbose;} + void SetVerbose(Int_t iVerbose) { fVerbose = iVerbose; } /** Executed task **/ virtual void Exec(Option_t* option); virtual InitStatus Init(); @@ -60,13 +60,13 @@ class FairMCTracks : public FairTask TEveTrackList* GetTrGroup(TParticle* P); protected: - TClonesArray* fTrackList; //! + TClonesArray* fTrackList; //! TEveTrackPropagator* fTrPr; - FairEventManager* fEventManager; //! + FairEventManager* fEventManager; //! TObjArray* fEveTrList; - TString fEvent; //! - TEveTrackList* fTrList; //! - //TEveElementList *fTrackCont; + TString fEvent; //! + TEveTrackList* fTrList; //! + // TEveElementList *fTrackCont; Double_t MinEnergyLimit; Double_t MaxEnergyLimit; @@ -76,7 +76,7 @@ class FairMCTracks : public FairTask FairMCTracks(const FairMCTracks&); FairMCTracks& operator=(const FairMCTracks&); - ClassDef(FairMCTracks,1); + ClassDef(FairMCTracks, 1); }; #endif diff --git a/eventdisplay/FairMCTracksEditor.cxx b/eventdisplay/FairMCTracksEditor.cxx index 0e1b0c685b..2aa3927fd8 100644 --- a/eventdisplay/FairMCTracksEditor.cxx +++ b/eventdisplay/FairMCTracksEditor.cxx @@ -1,21 +1,21 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "FairMCTracksEditor.h" -#include "FairEventManager.h" // for FairEventManager -#include "FairRootManager.h" // for FairRootManager -#include "FairRunAna.h" // for FairRunAna +#include "FairEventManager.h" // for FairEventManager +#include "FairRootManager.h" // for FairRootManager +#include "FairRunAna.h" // for FairRunAna -#include // for TChain -#include // for TFile -#include // for TGLabel +#include // for TChain +#include // for TFile +#include // for TGLabel #include -#include // for TString +#include // for TString class TGWindow; class TObject; @@ -25,42 +25,35 @@ class TObject; // Specialization of TGedEditor for proper update propagation to // TEveManager. -ClassImp(FairMCTracksEditor) +ClassImp(FairMCTracksEditor); -FairMCTracksEditor::FairMCTracksEditor(const TGWindow* p, Int_t width, Int_t height, - UInt_t options, Pixel_t back) - : TGedFrame(p, width, height, options | kVerticalFrame, back), - fObject(nullptr), - fManager(FairEventManager::Instance()) +FairMCTracksEditor::FairMCTracksEditor(const TGWindow* p, Int_t width, Int_t height, UInt_t options, Pixel_t back) + : TGedFrame(p, width, height, options | kVerticalFrame, back) + , fObject(nullptr) + , fManager(FairEventManager::Instance()) { - // Resize(width, height); - // fManager= FairEventManager::Instance(); - - MakeTitle("FairEventManager Editor"); - - TGVerticalFrame* fInfoFrame= CreateEditorTabSubFrame("Info"); - TGCompositeFrame* title1 = new TGCompositeFrame(fInfoFrame, 180, 10, - kVerticalFrame | - kLHintsExpandX | - kFixedWidth | - kOwnBackground); - TString Infile= "Input File : "; -// TFile* file =FairRunAna::Instance()->GetInputFile(); - TFile* file =FairRootManager::Instance()->GetInChain()->GetFile(); - Infile+=file->GetName(); - TGLabel* TFName=new TGLabel(title1, Infile.Data()); - title1->AddFrame(TFName); - - UInt_t RunId= FairRunAna::Instance()->getRunId(); - TString run= "Run Id : "; - run += RunId; - TGLabel* TRunId=new TGLabel(title1, run.Data()); - title1->AddFrame( TRunId); - - fInfoFrame->AddFrame(title1, new TGLayoutHints(kLHintsTop, 0, 0, 2, 0)); + // Resize(width, height); + // fManager= FairEventManager::Instance(); + + MakeTitle("FairEventManager Editor"); + + TGVerticalFrame* fInfoFrame = CreateEditorTabSubFrame("Info"); + TGCompositeFrame* title1 = + new TGCompositeFrame(fInfoFrame, 180, 10, kVerticalFrame | kLHintsExpandX | kFixedWidth | kOwnBackground); + TString Infile = "Input File : "; + // TFile* file =FairRunAna::Instance()->GetInputFile(); + TFile* file = FairRootManager::Instance()->GetInChain()->GetFile(); + Infile += file->GetName(); + TGLabel* TFName = new TGLabel(title1, Infile.Data()); + title1->AddFrame(TFName); + + UInt_t RunId = FairRunAna::Instance()->getRunId(); + TString run = "Run Id : "; + run += RunId; + TGLabel* TRunId = new TGLabel(title1, run.Data()); + title1->AddFrame(TRunId); + + fInfoFrame->AddFrame(title1, new TGLayoutHints(kLHintsTop, 0, 0, 2, 0)); } -void FairMCTracksEditor::SetModel( TObject* obj) -{ - fObject = obj; -} +void FairMCTracksEditor::SetModel(TObject* obj) { fObject = obj; } diff --git a/eventdisplay/FairMCTracksEditor.h b/eventdisplay/FairMCTracksEditor.h index d2a0dd033a..6e66191ccc 100644 --- a/eventdisplay/FairMCTracksEditor.h +++ b/eventdisplay/FairMCTracksEditor.h @@ -1,18 +1,17 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef ROOT_FAIREMCTRACKSEDITOR #define ROOT_FAIREMCTRACKSEDITOR -#include // for TGedFrame - -#include // for Pixel_t -#include // for FairMCTracksEditor::Class, etc -#include // for EFrameType::kChildFrame +#include // for Pixel_t +#include // for FairMCTracksEditor::Class, etc +#include // for EFrameType::kChildFrame +#include // for TGedFrame class FairEventManager; class TGWindow; @@ -20,20 +19,24 @@ class TObject; class FairMCTracksEditor : public TGedFrame { - FairMCTracksEditor(const FairMCTracksEditor&); // Not implemented - FairMCTracksEditor& operator=(const FairMCTracksEditor&); // Not implemented + FairMCTracksEditor(const FairMCTracksEditor&); // Not implemented + FairMCTracksEditor& operator=(const FairMCTracksEditor&); // Not implemented protected: TObject* fObject; - FairEventManager* fManager; + FairEventManager* fManager; + public: - FairMCTracksEditor(const TGWindow* p=0, Int_t width=170, Int_t height=30, - UInt_t options = kChildFrame, Pixel_t back=GetDefaultFrameBackground()); + FairMCTracksEditor(const TGWindow* p = 0, + Int_t width = 170, + Int_t height = 30, + UInt_t options = kChildFrame, + Pixel_t back = GetDefaultFrameBackground()); virtual ~FairMCTracksEditor() {} - virtual void SetModel( TObject* obj); + virtual void SetModel(TObject* obj); - ClassDef(FairMCTracksEditor, 0); // Specialization of TGedEditor for proper update propagation to TEveManager. + ClassDef(FairMCTracksEditor, 0); // Specialization of TGedEditor for proper update propagation to TEveManager. }; #endif diff --git a/eventdisplay/FairPointSetDraw.cxx b/eventdisplay/FairPointSetDraw.cxx index 6ab89851cf..7e279c46b9 100644 --- a/eventdisplay/FairPointSetDraw.cxx +++ b/eventdisplay/FairPointSetDraw.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -11,18 +11,17 @@ // ------------------------------------------------------------------------- #include "FairPointSetDraw.h" -#include "FairEventManager.h" // for FairEventManager -#include "FairRootManager.h" // for FairRootManager +#include "FairEventManager.h" // for FairEventManager +#include "FairRootManager.h" // for FairRootManager -#include // for TClonesArray -#include // for TEveManager, gEve -#include // for TEvePointSet -#include // for TEvePointSelectorConsumer, etc -#include // for TNamed -#include // for Form -#include // for TVector3 - -#include // for operator<<, basic_ostream, etc +#include // for TClonesArray +#include // for TEveManager, gEve +#include // for TEvePointSet +#include // for TEvePointSelectorConsumer, etc +#include // for TNamed +#include // for Form +#include // for TVector3 +#include // for operator<<, basic_ostream, etc class TObject; @@ -30,95 +29,89 @@ using std::cout; using std::endl; FairPointSetDraw::FairPointSetDraw() - : FairTask("FairPointSetDraw", 0), - fVerbose(0), - fPointList(nullptr), - fEventManager(nullptr), - fq(nullptr), - fColor(0), - fStyle(0) -{ -} - -FairPointSetDraw::FairPointSetDraw(const char* name, Color_t color ,Style_t mstyle,Int_t iVerbose) - : FairTask(name, iVerbose), - fVerbose(iVerbose), - fPointList(nullptr), - fEventManager(nullptr), - fq(nullptr), - fColor(color), - fStyle(mstyle) -{ -} + : FairTask("FairPointSetDraw", 0) + , fVerbose(0) + , fPointList(nullptr) + , fEventManager(nullptr) + , fq(nullptr) + , fColor(0) + , fStyle(0) +{} + +FairPointSetDraw::FairPointSetDraw(const char* name, Color_t color, Style_t mstyle, Int_t iVerbose) + : FairTask(name, iVerbose) + , fVerbose(iVerbose) + , fPointList(nullptr) + , fEventManager(nullptr) + , fq(nullptr) + , fColor(color) + , fStyle(mstyle) +{} InitStatus FairPointSetDraw::Init() { - if(fVerbose>1) { cout<< "FairPointSetDraw::Init()" << endl; } - FairRootManager* fManager = FairRootManager::Instance(); - fPointList = static_cast(fManager->GetObject(GetName())); - if(fPointList==0) { - cout << "FairPointSetDraw::Init() branch " << GetName() << " Not found! Task will be deactivated "<< endl; - SetActive(kFALSE); - } - if(fVerbose>2) { cout<< "FairPointSetDraw::Init() get track list" << fPointList<< endl; } - fEventManager =FairEventManager::Instance(); - if(fVerbose>2) { cout<< "FairPointSetDraw::Init() get instance of FairEventManager " << endl; } - fq =0; + if (fVerbose > 1) { + cout << "FairPointSetDraw::Init()" << endl; + } + FairRootManager* fManager = FairRootManager::Instance(); + fPointList = static_cast(fManager->GetObject(GetName())); + if (fPointList == 0) { + cout << "FairPointSetDraw::Init() branch " << GetName() << " Not found! Task will be deactivated " << endl; + SetActive(kFALSE); + } + if (fVerbose > 2) { + cout << "FairPointSetDraw::Init() get track list" << fPointList << endl; + } + fEventManager = FairEventManager::Instance(); + if (fVerbose > 2) { + cout << "FairPointSetDraw::Init() get instance of FairEventManager " << endl; + } + fq = 0; - // gEve->AddElement(fq, fEventManager ); - return kSUCCESS; + // gEve->AddElement(fq, fEventManager ); + return kSUCCESS; } void FairPointSetDraw::Exec(Option_t* /*option*/) { - if (IsActive()) { - Int_t npoints=fPointList->GetEntriesFast(); - Reset(); - TEvePointSet* q = new TEvePointSet(GetName(),npoints, TEvePointSelectorConsumer::kTVT_XYZ); - q->SetOwnIds(kTRUE); - q->SetMarkerColor(fColor); - q->SetMarkerSize(1.5); - q->SetMarkerStyle(fStyle); - //std::cout << "fPointList: " << fPointList << " " << fPointList->GetEntries() << std::endl; - for (Int_t i=0; i(fPointList->At(i)); - if(p!=0) { - TVector3 vec(GetVector(p)); - q->SetNextPoint(vec.X(),vec.Y(), vec.Z()); - q->SetPointId(GetValue(p, i)); - } + if (IsActive()) { + Int_t npoints = fPointList->GetEntriesFast(); + Reset(); + TEvePointSet* q = new TEvePointSet(GetName(), npoints, TEvePointSelectorConsumer::kTVT_XYZ); + q->SetOwnIds(kTRUE); + q->SetMarkerColor(fColor); + q->SetMarkerSize(1.5); + q->SetMarkerStyle(fStyle); + // std::cout << "fPointList: " << fPointList << " " << fPointList->GetEntries() << std::endl; + for (Int_t i = 0; i < npoints; ++i) { + TObject* p = static_cast(fPointList->At(i)); + if (p != 0) { + TVector3 vec(GetVector(p)); + q->SetNextPoint(vec.X(), vec.Y(), vec.Z()); + q->SetPointId(GetValue(p, i)); + } + } + gEve->AddElement(q); + gEve->Redraw3D(kFALSE); + fq = q; } - gEve->AddElement(q); - gEve->Redraw3D(kFALSE); - fq=q; - } - } -TObject* FairPointSetDraw::GetValue(TObject* /*obj*/,Int_t i) -{ - return new TNamed(Form("Point %d", i),""); -} +TObject* FairPointSetDraw::GetValue(TObject* /*obj*/, Int_t i) { return new TNamed(Form("Point %d", i), ""); } -FairPointSetDraw::~FairPointSetDraw() -{ -} +FairPointSetDraw::~FairPointSetDraw() {} -void FairPointSetDraw::SetParContainers() -{ -} +void FairPointSetDraw::SetParContainers() {} /** Action after each event**/ -void FairPointSetDraw::Finish() -{ -} +void FairPointSetDraw::Finish() {} void FairPointSetDraw::Reset() { - if(fq!=0) { - fq->Reset(); - gEve->RemoveElement(fq, fEventManager ); - } + if (fq != 0) { + fq->Reset(); + gEve->RemoveElement(fq, fEventManager); + } } ClassImp(FairPointSetDraw); diff --git a/eventdisplay/FairPointSetDraw.h b/eventdisplay/FairPointSetDraw.h index 0ceedea063..a5befae89d 100644 --- a/eventdisplay/FairPointSetDraw.h +++ b/eventdisplay/FairPointSetDraw.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -10,7 +10,6 @@ // ----- Created 10/12/07 by M. Al-Turany ----- // ------------------------------------------------------------------------- - /** FairPointSetDraw * @author M. Al-Turany * @since 03.01.08 @@ -21,9 +20,9 @@ #ifndef FAIRPOINTSETDRAW_H #define FAIRPOINTSETDRAW_H -#include "FairTask.h" // for FairTask, InitStatus +#include "FairTask.h" // for FairTask, InitStatus -#include // for Int_t, Color_t, etc +#include // for Int_t, Color_t, etc class FairEventManager; class TClonesArray; @@ -38,40 +37,40 @@ class FairPointSetDraw : public FairTask FairPointSetDraw(); /** Standard constructor - *@param name Name of task - *@param iVerbose Verbosity level - **/ - FairPointSetDraw(const char* name, Color_t color ,Style_t mstyle, Int_t iVerbose = 1); + *@param name Name of task + *@param iVerbose Verbosity level + **/ + FairPointSetDraw(const char* name, Color_t color, Style_t mstyle, Int_t iVerbose = 1); /** Destructor **/ virtual ~FairPointSetDraw(); /** Set verbosity level. For this task and all of the subtasks. **/ - void SetVerbose(Int_t iVerbose) {fVerbose = iVerbose;}; + void SetVerbose(Int_t iVerbose) { fVerbose = iVerbose; }; /** Executed task **/ virtual void Exec(Option_t* option); void Reset(); protected: virtual TVector3 GetVector(TObject* obj) = 0; - virtual TObject* GetValue(TObject* obj,Int_t i); + virtual TObject* GetValue(TObject* obj, Int_t i); - Int_t fVerbose; // Verbosity level - virtual void SetParContainers() ; + Int_t fVerbose; // Verbosity level + virtual void SetParContainers(); virtual InitStatus Init(); /** Action after each event**/ - virtual void Finish() ; - TClonesArray* fPointList; //! + virtual void Finish(); + TClonesArray* fPointList; //! FairEventManager* fEventManager; //! - TEvePointSet* fq; //! - Color_t fColor; //! - Style_t fStyle; //! + TEvePointSet* fq; //! + Color_t fColor; //! + Style_t fStyle; //! private: FairPointSetDraw(const FairPointSetDraw&); FairPointSetDraw& operator=(const FairPointSetDraw&); - ClassDef(FairPointSetDraw,1); + ClassDef(FairPointSetDraw, 1); }; #endif diff --git a/eventdisplay/FairTimeStampPointDraw.cxx b/eventdisplay/FairTimeStampPointDraw.cxx index 80547b6619..f8755e8853 100644 --- a/eventdisplay/FairTimeStampPointDraw.cxx +++ b/eventdisplay/FairTimeStampPointDraw.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* @@ -14,8 +14,8 @@ #include "FairTimeStampPointDraw.h" -#include "FairMCPoint.h" // for FairMCPoint -#include "FairTimeStamp.h" // for FairTimeStamp +#include "FairMCPoint.h" // for FairMCPoint +#include "FairTimeStamp.h" // for FairTimeStamp class TObject; @@ -23,30 +23,30 @@ ClassImp(FairTimeStampPointDraw); FairTimeStampPointDraw::FairTimeStampPointDraw() { - // TODO Auto-generated constructor stub + // TODO Auto-generated constructor stub } -FairTimeStampPointDraw::FairTimeStampPointDraw(const char* name, Int_t iVerbose):FairBoxSetDraw(name, iVerbose) -{ -} +FairTimeStampPointDraw::FairTimeStampPointDraw(const char* name, Int_t iVerbose) + : FairBoxSetDraw(name, iVerbose) +{} FairTimeStampPointDraw::~FairTimeStampPointDraw() { - // TODO Auto-generated destructor stub + // TODO Auto-generated destructor stub } TVector3 FairTimeStampPointDraw::GetVector(TObject* obj) { - FairMCPoint* hit =static_cast(obj); - return TVector3(hit->GetX(), hit->GetY(), hit->GetZ()); + FairMCPoint* hit = static_cast(obj); + return TVector3(hit->GetX(), hit->GetY(), hit->GetZ()); } -Int_t FairTimeStampPointDraw::GetValue(TObject* obj,Int_t /*i*/) +Int_t FairTimeStampPointDraw::GetValue(TObject* obj, Int_t /*i*/) { - FairTimeStamp* tsdata = static_cast(obj); - if (tsdata != NULL) { - return static_cast(tsdata->GetTimeStamp()); - } else { - return 0; - } + FairTimeStamp* tsdata = static_cast(obj); + if (tsdata != NULL) { + return static_cast(tsdata->GetTimeStamp()); + } else { + return 0; + } } diff --git a/eventdisplay/FairTimeStampPointDraw.h b/eventdisplay/FairTimeStampPointDraw.h index 89e2affcf4..66b8340d6a 100644 --- a/eventdisplay/FairTimeStampPointDraw.h +++ b/eventdisplay/FairTimeStampPointDraw.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* @@ -15,10 +15,10 @@ #ifndef FAIRTIMESTAMPPOINTDRAW_H_ #define FAIRTIMESTAMPPOINTDRAW_H_ -#include "FairBoxSetDraw.h" // for FairBoxSetDraw +#include "FairBoxSetDraw.h" // for FairBoxSetDraw -#include // for Int_t, etc -#include // for TVector3 +#include // for Int_t, etc +#include // for TVector3 class TObject; @@ -31,7 +31,7 @@ class FairTimeStampPointDraw : public FairBoxSetDraw private: virtual TVector3 GetVector(TObject* obj); - virtual Int_t GetValue(TObject* obj,Int_t i); + virtual Int_t GetValue(TObject* obj, Int_t i); ClassDef(FairTimeStampPointDraw, 1); }; diff --git a/eventdisplay/FairXMLNode.cxx b/eventdisplay/FairXMLNode.cxx index ae316b9ef5..cad3ae7f36 100644 --- a/eventdisplay/FairXMLNode.cxx +++ b/eventdisplay/FairXMLNode.cxx @@ -10,173 +10,179 @@ #include "FairXMLNode.h" #include +#include // for TXMLAttr +#include // for TXMLDocument #include -#include // for TXMLAttr -#include // for TXMLDocument - #include -FairXMLNode::FairXMLNode(TString name,TString value) : TNamed(name, value){ - fChildren.SetOwner(kTRUE); - fAttrib.SetOwner(kTRUE); -} - -FairXMLNode::FairXMLNode(const FairXMLNode& other): - FairXMLNode(other.GetName(),other.GetValue()){ - for(int i=0;iGetNodeName()); - SetTitle(node->GetText()); - if(node->HasChildren()){ - TXMLNode *child = node->GetChildren(); - do{ - if(child==nullptr) break; - TString name = child->GetNodeName(); - if(name!="text"){//skip "text" nodes - FairXMLNode *tempnode = new FairXMLNode(); - tempnode->Copy(child); - fChildren.Add(tempnode); - } - if(child->HasNextNode()) - child=child->GetNextNode(); - }while(child->HasNextNode()); - } - if(node->HasAttributes()){ - TList *atr_list = node->GetAttributes(); - for(int i=0;iGetEntries();i++){ - TXMLAttr *atrib = (TXMLAttr*)atr_list->At(i); - fAttrib.Add(new FairXMLAttrib(atrib->GetName(),atrib->GetValue())); - } - } -} - -void FairXMLNode::AddAttrib(FairXMLAttrib* attrib) { - TString new_atr = attrib->GetName(); - if(GetAttrib(new_atr)!=nullptr){ - std::cout<<"FairXMLNode::AddAttrib Can't have two attributes with the same name!"<GetName(); - if(name_temp==name){ - counter++; - } - } - return counter; -} - -FairXMLNode* FairXMLNode::GetChild(TString name, Int_t count) const{ - Int_t control_index = 0; - for(int i=0;iGetName(); - if(temp==name){ - control_index++; - } - if(control_index>count) - return node; - } - return nullptr; -} - -FairXMLAttrib* FairXMLNode::GetAttrib(TString name) const{ - return static_cast(fAttrib.FindObject(name)); -} - -FairXMLNode* FairXMLNode::GetChild(Int_t index) const{ - return static_cast(fChildren.At(index)); -} - -FairXMLAttrib* FairXMLNode::GetAttrib(Int_t index) const{ - return static_cast(fAttrib.At(index)); -} - -FairXMLNode::~FairXMLNode() { -} +FairXMLNode::FairXMLNode(TString name, TString value) + : TNamed(name, value) +{ + fChildren.SetOwner(kTRUE); + fAttrib.SetOwner(kTRUE); +} + +FairXMLNode::FairXMLNode(const FairXMLNode& other) + : FairXMLNode(other.GetName(), other.GetValue()) +{ + for (int i = 0; i < other.fChildren.GetEntries(); i++) { + fChildren.Add(new FairXMLNode(*other.GetChild(i))); + } + for (int i = 0; i < other.fAttrib.GetEntries(); i++) { + fAttrib.Add(new FairXMLAttrib(*other.GetAttrib(i))); + } +} + +FairXMLNode& FairXMLNode::operator=(const FairXMLNode& other) +{ + if (&other == this) + return *this; + SetName(other.GetName()); + SetValue(other.GetValue()); + fChildren.Clear(); + fAttrib.Clear(); + for (int i = 0; i < other.fChildren.GetEntries(); i++) { + fChildren.Add(new FairXMLNode(*other.GetChild(i))); + } + for (int i = 0; i < other.fAttrib.GetEntries(); i++) { + fAttrib.Add(new FairXMLAttrib(*other.GetAttrib(i))); + } + return *this; +} + +void FairXMLNode::Copy(TXMLNode* node) +{ + fChildren.Clear(); + fAttrib.Clear(); + SetName(node->GetNodeName()); + SetTitle(node->GetText()); + if (node->HasChildren()) { + TXMLNode* child = node->GetChildren(); + do { + if (child == nullptr) + break; + TString name = child->GetNodeName(); + if (name != "text") { // skip "text" nodes + FairXMLNode* tempnode = new FairXMLNode(); + tempnode->Copy(child); + fChildren.Add(tempnode); + } + if (child->HasNextNode()) + child = child->GetNextNode(); + } while (child->HasNextNode()); + } + if (node->HasAttributes()) { + TList* atr_list = node->GetAttributes(); + for (int i = 0; i < atr_list->GetEntries(); i++) { + TXMLAttr* atrib = (TXMLAttr*)atr_list->At(i); + fAttrib.Add(new FairXMLAttrib(atrib->GetName(), atrib->GetValue())); + } + } +} + +void FairXMLNode::AddAttrib(FairXMLAttrib* attrib) +{ + TString new_atr = attrib->GetName(); + if (GetAttrib(new_atr) != nullptr) { + std::cout << "FairXMLNode::AddAttrib Can't have two attributes with the same name!" << std::endl; + return; + } + fAttrib.AddLast(attrib); +} + +Int_t FairXMLNode::GetNChildren(TString name) const +{ + Int_t counter = 0; + for (int i = 0; i < GetNChildren(); i++) { + TString name_temp = GetChild(i)->GetName(); + if (name_temp == name) { + counter++; + } + } + return counter; +} + +FairXMLNode* FairXMLNode::GetChild(TString name, Int_t count) const +{ + Int_t control_index = 0; + for (int i = 0; i < fChildren.GetEntries(); i++) { + FairXMLNode* node = GetChild(i); + TString temp = node->GetName(); + if (temp == name) { + control_index++; + } + if (control_index > count) + return node; + } + return nullptr; +} + +FairXMLAttrib* FairXMLNode::GetAttrib(TString name) const +{ + return static_cast(fAttrib.FindObject(name)); +} + +FairXMLNode* FairXMLNode::GetChild(Int_t index) const { return static_cast(fChildren.At(index)); } + +FairXMLAttrib* FairXMLNode::GetAttrib(Int_t index) const { return static_cast(fAttrib.At(index)); } + +FairXMLNode::~FairXMLNode() {} //---------- FairXMLFile ------------------------------------------------------------------------------------ -FairXMLFile::FairXMLFile(TString name, TString mode) :fName(name){ - if(mode=="read"||mode=="READ"){ - fOverwrite = kFALSE; - TDOMParser Parser; - Parser.SetValidate(kFALSE); - Parser.ParseFile(name); - TXMLNode *MainNode = Parser.GetXMLDocument()->GetRootNode(); - fRootNode.reset(new FairXMLNode()); - fRootNode->Copy(MainNode); - }else{ - fOverwrite = kTRUE; - } -} - -void FairXMLFile::CreateRootNode(TString name) { - fRootNode.reset(new FairXMLNode(name)); -} - -void FairXMLFile::SetRootNode(FairXMLNode *node) { - fRootNode.reset(node); -} - -void FairXMLFile::Close() { - if(fOverwrite){ - if(!fRootNode){ - std::cout<<"FairXMLFile::Close() No root node!"<GetName()); - ExportNode(mainnode,engine,*fRootNode.get()); - XMLDocPointer_t xmldoc = engine.NewDoc(); - engine.DocSetRootElement(xmldoc,mainnode); - engine.SaveDoc(xmldoc,fName); - engine.FreeDoc(xmldoc); - fRootNode.reset(nullptr); - } -} - -void FairXMLFile::ExportNode(XMLNodePointer_t& nodePointer, - TXMLEngine &engine,const FairXMLNode &node) const { - for(int i=0;iGetName(),node.GetChild(i)->GetValue()); - for(int j=0;jGetNAttributes();j++){ - engine.NewAttr(child,0,node.GetChild(i)->GetAttrib(j)->GetName(),node.GetChild(i)->GetAttrib(j)->GetValue()); - } - ExportNode(child,engine,*node.GetChild(i)); - } -} - -FairXMLFile::~FairXMLFile() { - if(fRootNode&&fOverwrite) - Close(); +FairXMLFile::FairXMLFile(TString name, TString mode) + : fName(name) +{ + if (mode == "read" || mode == "READ") { + fOverwrite = kFALSE; + TDOMParser Parser; + Parser.SetValidate(kFALSE); + Parser.ParseFile(name); + TXMLNode* MainNode = Parser.GetXMLDocument()->GetRootNode(); + fRootNode.reset(new FairXMLNode()); + fRootNode->Copy(MainNode); + } else { + fOverwrite = kTRUE; + } +} + +void FairXMLFile::CreateRootNode(TString name) { fRootNode.reset(new FairXMLNode(name)); } + +void FairXMLFile::SetRootNode(FairXMLNode* node) { fRootNode.reset(node); } + +void FairXMLFile::Close() +{ + if (fOverwrite) { + if (!fRootNode) { + std::cout << "FairXMLFile::Close() No root node!" << std::endl; + return; + } + TXMLEngine engine; + XMLNodePointer_t mainnode = engine.NewChild(0, 0, fRootNode->GetName()); + ExportNode(mainnode, engine, *fRootNode.get()); + XMLDocPointer_t xmldoc = engine.NewDoc(); + engine.DocSetRootElement(xmldoc, mainnode); + engine.SaveDoc(xmldoc, fName); + engine.FreeDoc(xmldoc); + fRootNode.reset(nullptr); + } +} + +void FairXMLFile::ExportNode(XMLNodePointer_t& nodePointer, TXMLEngine& engine, const FairXMLNode& node) const +{ + for (int i = 0; i < node.GetNChildren(); i++) { + XMLNodePointer_t child = + engine.NewChild(nodePointer, 0, node.GetChild(i)->GetName(), node.GetChild(i)->GetValue()); + for (int j = 0; j < node.GetChild(i)->GetNAttributes(); j++) { + engine.NewAttr( + child, 0, node.GetChild(i)->GetAttrib(j)->GetName(), node.GetChild(i)->GetAttrib(j)->GetValue()); + } + ExportNode(child, engine, *node.GetChild(i)); + } +} + +FairXMLFile::~FairXMLFile() +{ + if (fRootNode && fOverwrite) + Close(); } diff --git a/eventdisplay/FairXMLNode.h b/eventdisplay/FairXMLNode.h index b1e4a12ba4..3d613a696f 100644 --- a/eventdisplay/FairXMLNode.h +++ b/eventdisplay/FairXMLNode.h @@ -10,12 +10,11 @@ #define FAIRXLMNODE_H_ #include -#include -#include #include -#include #include - +#include +#include +#include #include class TXMLNode; @@ -23,167 +22,176 @@ class TXMLNode; /** * class for representing node attributes */ -class FairXMLAttrib: public TNamed{ +class FairXMLAttrib : public TNamed +{ public: - /** - * default constructor - */ - FairXMLAttrib():TNamed(){} - /** - * default constructor - * @param name name of attribute - * @param value value of attribute - */ - FairXMLAttrib(TString name, TString value){ - SetName(name); - SetTitle(value);} - /** - * - * @return value of node - */ - TString GetValue() const{return GetTitle();}; - /** - * - * @param val value of node to se - */ - void SetValue(TString val){SetTitle(val);}; - virtual ~FairXMLAttrib(){}; - ClassDef(FairXMLAttrib,1) + /** + * default constructor + */ + FairXMLAttrib() + : TNamed() + {} + /** + * default constructor + * @param name name of attribute + * @param value value of attribute + */ + FairXMLAttrib(TString name, TString value) + { + SetName(name); + SetTitle(value); + } + /** + * + * @return value of node + */ + TString GetValue() const { return GetTitle(); }; + /** + * + * @param val value of node to se + */ + void SetValue(TString val) { SetTitle(val); }; + virtual ~FairXMLAttrib(){}; + ClassDef(FairXMLAttrib, 1) }; /** * class for representing XML node */ -class FairXMLNode : public TNamed{ - TList fChildren; - TList fAttrib; -public: - /** - * copy constructor - * @param other - */ - FairXMLNode(const FairXMLNode &other); - /** - * default constructor - * @param name name of node - * @param value value of node - */ - FairXMLNode(TString name="",TString value=""); - /** - * assignement operator - * @param node - * @return - */ - FairXMLNode& operator=(const FairXMLNode &other); - /** - * copy data for node to this - * @param node - */ - void Copy(TXMLNode *node); - /** - * - * @param value new value - */ - void SetValue(TString value){SetTitle(value);}; - /** - * add child node to this node, node is now owned by - * parent node - * @param node node to add - */ - void AddChild(FairXMLNode *node){fChildren.AddLast(node);}; - /** - * add attribute to this class - * @param attrib - */ - void AddAttrib(FairXMLAttrib *attrib); - /** - * - * @return number of childen nodes - */ - Int_t GetNChildren() const {return fChildren.GetEntries();}; - /** - * - * @return number of attributes - */ - Int_t GetNAttributes() const{return fAttrib.GetEntries();}; - /** - * search for child with given name - * @param name name of node - * @return number of node with given name - */ - Int_t GetNChildren(TString name) const; - /** - * - * @return value of node - */ - TString GetValue() const{return GetTitle();}; - /** - * - * @param name name of atribute - * @return - */ - FairXMLAttrib *GetAttrib(TString name)const; - /** - * - * @param index index of atrribute - * @return - */ - FairXMLAttrib *GetAttrib(Int_t index)const; - /** - * search for node with given name - * @param name name of node - * @param count number of node (if more than one with given name exist) - * @return node - */ - FairXMLNode *GetChild(TString name, Int_t count =0) const; - /** - * - * @param index child number - * @return child at given position - */ - FairXMLNode *GetChild(Int_t index) const; - virtual ~FairXMLNode(); - ClassDef(FairXMLNode,1) +class FairXMLNode : public TNamed +{ + TList fChildren; + TList fAttrib; + + public: + /** + * copy constructor + * @param other + */ + FairXMLNode(const FairXMLNode &other); + /** + * default constructor + * @param name name of node + * @param value value of node + */ + FairXMLNode(TString name = "", TString value = ""); + /** + * assignement operator + * @param node + * @return + */ + FairXMLNode &operator=(const FairXMLNode &other); + /** + * copy data for node to this + * @param node + */ + void Copy(TXMLNode *node); + /** + * + * @param value new value + */ + void SetValue(TString value) { SetTitle(value); }; + /** + * add child node to this node, node is now owned by + * parent node + * @param node node to add + */ + void AddChild(FairXMLNode *node) { fChildren.AddLast(node); }; + /** + * add attribute to this class + * @param attrib + */ + void AddAttrib(FairXMLAttrib *attrib); + /** + * + * @return number of childen nodes + */ + Int_t GetNChildren() const { return fChildren.GetEntries(); }; + /** + * + * @return number of attributes + */ + Int_t GetNAttributes() const { return fAttrib.GetEntries(); }; + /** + * search for child with given name + * @param name name of node + * @return number of node with given name + */ + Int_t GetNChildren(TString name) const; + /** + * + * @return value of node + */ + TString GetValue() const { return GetTitle(); }; + /** + * + * @param name name of atribute + * @return + */ + FairXMLAttrib *GetAttrib(TString name) const; + /** + * + * @param index index of atrribute + * @return + */ + FairXMLAttrib *GetAttrib(Int_t index) const; + /** + * search for node with given name + * @param name name of node + * @param count number of node (if more than one with given name exist) + * @return node + */ + FairXMLNode *GetChild(TString name, Int_t count = 0) const; + /** + * + * @param index child number + * @return child at given position + */ + FairXMLNode *GetChild(Int_t index) const; + virtual ~FairXMLNode(); + ClassDef(FairXMLNode, 1) }; /** * class for opening XML files */ -class FairXMLFile: public TObject{ - std::unique_ptr fRootNode; - TString fName; - Bool_t fOverwrite; - void ExportNode(XMLNodePointer_t &nodePointer, TXMLEngine &engine,const FairXMLNode &node) const; -public: - /** - * - * @param name name of xml file - * @param mode if "READ" or "read" - only read file, otherwise create /overwrite file - */ - FairXMLFile(TString name="", TString mode="read"); - /** - * create new root node - * @param name name of new node - */ - void CreateRootNode(TString name); - /** - * set new root node, old node will be overwritten - * @param node root node - */ - void SetRootNode(FairXMLNode *node); - /** - * - * @return root node - */ - FairXMLNode *GetRootNode()const{return fRootNode.get();}; - /** - * close and write xml (if needed) - */ - void Close(); - /** - * destroy object (and save xml file if needed and Close was not called) - */ - virtual ~FairXMLFile(); - ClassDef(FairXMLFile,1) +class FairXMLFile : public TObject +{ + std::unique_ptr fRootNode; + TString fName; + Bool_t fOverwrite; + void ExportNode(XMLNodePointer_t &nodePointer, TXMLEngine &engine, const FairXMLNode &node) const; + + public: + /** + * + * @param name name of xml file + * @param mode if "READ" or "read" - only read file, otherwise create /overwrite file + */ + FairXMLFile(TString name = "", TString mode = "read"); + /** + * create new root node + * @param name name of new node + */ + void CreateRootNode(TString name); + /** + * set new root node, old node will be overwritten + * @param node root node + */ + void SetRootNode(FairXMLNode *node); + /** + * + * @return root node + */ + FairXMLNode *GetRootNode() const { return fRootNode.get(); }; + /** + * close and write xml (if needed) + */ + void Close(); + /** + * destroy object (and save xml file if needed and Close was not called) + */ + virtual ~FairXMLFile(); + ClassDef(FairXMLFile, 1) }; #endif /* FAIRXLMNODE_H_ */ diff --git a/examples/MQ/Lmd/FairMBSUnpacker.cxx b/examples/MQ/Lmd/FairMBSUnpacker.cxx index b68d6dca5a..1d0e54e500 100644 --- a/examples/MQ/Lmd/FairMBSUnpacker.cxx +++ b/examples/MQ/Lmd/FairMBSUnpacker.cxx @@ -22,8 +22,7 @@ FairMBSUnpacker::FairMBSUnpacker(Short_t type, Short_t subType, Short_t procId, , fRawData(new TClonesArray("FairMBSRawItem")) , fNHits(0) , fNHitsTotal(0) -{ -} +{} // Virtual FairMBSUnpacker: Public method FairMBSUnpacker::~FairMBSUnpacker() @@ -33,10 +32,7 @@ FairMBSUnpacker::~FairMBSUnpacker() } // Init: Public method -Bool_t FairMBSUnpacker::Init() -{ - return kTRUE; -} +Bool_t FairMBSUnpacker::Init() { return kTRUE; } // DoUnpack: Public method Bool_t FairMBSUnpacker::DoUnpack(Int_t* data, Int_t size) @@ -47,24 +43,23 @@ Bool_t FairMBSUnpacker::DoUnpack(Int_t* data, Int_t size) Int_t n17 = 0; - while (l_i < size) - { + while (l_i < size) { n17 = 0; UInt_t* p1 = reinterpret_cast(data + l_i); - UInt_t l_sam_id = (p1[0] & 0xf0000000) >> 28; // identifies the sam - UInt_t l_gtb_id = (p1[0] & 0x0f000000) >> 24; // 0 or 1, identifies which of the 2 cables of the sam + UInt_t l_sam_id = (p1[0] & 0xf0000000) >> 28; // identifies the sam + UInt_t l_gtb_id = (p1[0] & 0x0f000000) >> 24; // 0 or 1, identifies which of the 2 cables of the sam UInt_t l_lec = (p1[0] & 0x00f00000) >> 20; UInt_t l_da_siz = (p1[0] & 0x000001ff); - LOG(debug) << "FairMBSUnpacker: SAM: " << l_sam_id << ", GTB: " << l_gtb_id << ", lec: " << l_lec << ", size: " << l_da_siz; + LOG(debug) << "FairMBSUnpacker: SAM: " << l_sam_id << ", GTB: " << l_gtb_id << ", lec: " << l_lec + << ", size: " << l_da_siz; l_i += 1; p1 = reinterpret_cast(data + l_i); - for (UInt_t i1 = 0; i1 < l_da_siz; i1 += 2) - { + for (UInt_t i1 = 0; i1 < l_da_siz; i1 += 2) { UInt_t tac_addr; UInt_t tac_ch; UInt_t cal; @@ -79,12 +74,13 @@ Bool_t FairMBSUnpacker::DoUnpack(Int_t* data, Int_t size) qdc_data = (p1[i1 + 1] & 0x00000fff); l_i += 2; - if (16 == tac_ch) - { + if (16 == tac_ch) { n17 += 1; } - LOG(debug) << "FairMBSUnpacker: TAC ADDR: " << tac_addr << ", TAC CH: " << tac_ch << ", TAC Data: " << tac_data << ", QDC Data: " << qdc_data; - new ((*fRawData)[fNHits]) FairMBSRawItem(l_sam_id, l_gtb_id, tac_addr, tac_ch, cal, clock, tac_data, qdc_data); + LOG(debug) << "FairMBSUnpacker: TAC ADDR: " << tac_addr << ", TAC CH: " << tac_ch + << ", TAC Data: " << tac_data << ", QDC Data: " << qdc_data; + new ((*fRawData)[fNHits]) + FairMBSRawItem(l_sam_id, l_gtb_id, tac_addr, tac_ch, cal, clock, tac_data, qdc_data); fNHits++; } @@ -92,9 +88,9 @@ Bool_t FairMBSUnpacker::DoUnpack(Int_t* data, Int_t size) } LOG(debug) << "FairMBSUnpacker: Number of hits in LAND: " << fNHits; - + fNHitsTotal += fNHits; - + return kTRUE; } @@ -106,4 +102,4 @@ void FairMBSUnpacker::Reset() fNHits = 0; } -ClassImp(FairMBSUnpacker) +ClassImp(FairMBSUnpacker); diff --git a/examples/MQ/Lmd/runLmdSampler.cxx b/examples/MQ/Lmd/runLmdSampler.cxx index cac69cc26b..c658901f61 100644 --- a/examples/MQ/Lmd/runLmdSampler.cxx +++ b/examples/MQ/Lmd/runLmdSampler.cxx @@ -12,24 +12,23 @@ * Created on January 15, 2015, 1:57 PM */ -#include "runFairMQDevice.h" #include "FairMQLmdSampler.h" +#include "runFairMQDevice.h" namespace bpo = boost::program_options; void addCustomOptions(bpo::options_description& options) { + // clang-format off options.add_options() - ("input-file-name", bpo::value(), "Path to the input file") - ("lmd-type", bpo::value(), "sub-event type") - ("lmd-sub-type", bpo::value(), "sub-event subType") - ("lmd-proc-id", bpo::value(), "sub-event procId") - ("lmd-sub-crate", bpo::value(), "sub-event subCrate") - ("lmd-control", bpo::value(), "sub-event control") - ("lmd-chan-name", bpo::value(), "LMD output channel name"); + ("input-file-name", bpo::value(), "Path to the input file") + ("lmd-type", bpo::value(), "sub-event type") + ("lmd-sub-type", bpo::value(), "sub-event subType") + ("lmd-proc-id", bpo::value(), "sub-event procId") + ("lmd-sub-crate", bpo::value(), "sub-event subCrate") + ("lmd-control", bpo::value(), "sub-event control") + ("lmd-chan-name", bpo::value(), "LMD output channel name"); + // clang-format on } -FairMQDevicePtr getDevice(const FairMQProgOptions& /*config*/) -{ - return new FairMQLmdSampler(); -} +FairMQDevicePtr getDevice(const FairMQProgOptions& /*config*/) { return new FairMQLmdSampler(); } diff --git a/examples/MQ/Lmd/runMBSMQUnpacker.cxx b/examples/MQ/Lmd/runMBSMQUnpacker.cxx index b3d5bf328e..3571c81a00 100644 --- a/examples/MQ/Lmd/runMBSMQUnpacker.cxx +++ b/examples/MQ/Lmd/runMBSMQUnpacker.cxx @@ -12,14 +12,15 @@ * Created on January 15, 2015, 1:57 PM */ -#include "runFairMQDevice.h" -#include "FairMQUnpacker.h" #include "FairMBSUnpacker.h" +#include "FairMQUnpacker.h" +#include "runFairMQDevice.h" namespace bpo = boost::program_options; void addCustomOptions(bpo::options_description& options) { + // clang-format off options.add_options() ("lmd-type", bpo::value(), "sub-event type") ("lmd-sub-type", bpo::value(), "sub-event subType") @@ -28,9 +29,7 @@ void addCustomOptions(bpo::options_description& options) ("lmd-control", bpo::value(), "sub-event control") ("lmd-chan-name", bpo::value(), "LMD input channel name") ("out-chan-name", bpo::value(), "output channel name"); + // clang-format on } -FairMQDevicePtr getDevice(const FairMQProgOptions& /*config*/) -{ - return new FairMQUnpacker(); -} +FairMQDevicePtr getDevice(const FairMQProgOptions& /*config*/) { return new FairMQUnpacker(); } diff --git a/examples/MQ/Lmd/runMBSSink.cxx b/examples/MQ/Lmd/runMBSSink.cxx index f74f736d64..2918b19f77 100644 --- a/examples/MQ/Lmd/runMBSSink.cxx +++ b/examples/MQ/Lmd/runMBSSink.cxx @@ -5,28 +5,29 @@ * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ -#include "runFairMQDevice.h" #include "BaseMQFileSink.h" +#include "FairMBSRawItem.h" // data type for the OutputPolicy +#include "IOPolicy.h" // fair::mq::policy:: +#include "RootOutFileManager.h" // OutputPolicy +#include "RootSerializer.h" // RootSerializer +#include "runFairMQDevice.h" -#include "IOPolicy.h" // fair::mq::policy:: -#include "RootSerializer.h" // RootSerializer -#include "RootOutFileManager.h" // OutputPolicy -#include "FairMBSRawItem.h" // data type for the OutputPolicy - -#include // data type for the InputPolicy +#include // data type for the InputPolicy // InputPolicy - initialize input and deserialize message into it -using RootDefaultInputPolicy = fair::mq::policy::InputPolicy; // input deleter +using RootDefaultInputPolicy = + fair::mq::policy::InputPolicy; // input deleter namespace bpo = boost::program_options; void addCustomOptions(bpo::options_description& options) { + // clang-format off options.add_options() ("output-file-name", bpo::value(), "Path to the input file") ("output-file-tree", bpo::value()->default_value("mbstree"), "Name of the output tree") @@ -36,11 +37,13 @@ void addCustomOptions(bpo::options_description& options) ("use-clones-array", bpo::value()->default_value(true), "Use TClonesArray") ("flow-mode", bpo::value()->default_value(true), "Flow mode") ("in-chan-name", bpo::value()->default_value("data"), "input channel name"); + // clang-format on } FairMQDevicePtr getDevice(const FairMQProgOptions& config) { - BaseMQFileSink>* sink = new BaseMQFileSink>(); + BaseMQFileSink>* sink = + new BaseMQFileSink>(); // call function member from deserialization policy sink->InitInputData(config.GetValue("hit-classname").c_str()); diff --git a/examples/MQ/histogramServer/FairMQExHistoCanvasDrawerExample.cxx b/examples/MQ/histogramServer/FairMQExHistoCanvasDrawerExample.cxx index 649ff087c3..aced937f4f 100644 --- a/examples/MQ/histogramServer/FairMQExHistoCanvasDrawerExample.cxx +++ b/examples/MQ/histogramServer/FairMQExHistoCanvasDrawerExample.cxx @@ -8,67 +8,57 @@ #include "FairMQExHistoCanvasDrawerExample.h" #include +#include #include #include -#include -#include // for TString - +#include // for TString #include class TObject; FairMQExHistoCanvasDrawerExample::FairMQExHistoCanvasDrawerExample() : fCanvas(nullptr) -{ -} +{} FairMQExHistoCanvasDrawerExample::~FairMQExHistoCanvasDrawerExample() {} void FairMQExHistoCanvasDrawerExample::CreateCanvases(THttpServer& server) { assert(!fCanvas); - fCanvas = std::unique_ptr> - ( - new TCanvas("c1", "", 10, 10, 1000, 1000), - [&](TCanvas* p){server.Unregister(p);delete p;} - ); + fCanvas = std::unique_ptr>(new TCanvas("c1", "", 10, 10, 1000, 1000), + [&](TCanvas* p) { + server.Unregister(p); + delete p; + }); fCanvas->Divide(2, 2); server.Register("Canvases", fCanvas.get()); } void FairMQExHistoCanvasDrawerExample::DrawHistograms(TObjArray& arrayHisto) { - for (int i = 0; i < arrayHisto.GetEntriesFast(); i++) - { + for (int i = 0; i < arrayHisto.GetEntriesFast(); i++) { TObject* obj = arrayHisto.At(i); TH1* histogram = static_cast(obj); - if (TString(histogram->GetName()).EqualTo("histo1")) - { + if (TString(histogram->GetName()).EqualTo("histo1")) { fCanvas->cd(1); histogram->Draw(); fCanvas->cd(0); fCanvas->Modified(); fCanvas->Update(); - } - else if (TString(histogram->GetName()).EqualTo("histo2")) - { + } else if (TString(histogram->GetName()).EqualTo("histo2")) { fCanvas->cd(2); histogram->Draw(); fCanvas->cd(0); fCanvas->Modified(); fCanvas->Update(); - } - else if (TString(histogram->GetName()).EqualTo("histo3")) - { + } else if (TString(histogram->GetName()).EqualTo("histo3")) { fCanvas->cd(3); histogram->Draw("COL"); fCanvas->cd(0); fCanvas->Modified(); fCanvas->Update(); - } - else if (TString(histogram->GetName()).EqualTo("histo4")) - { + } else if (TString(histogram->GetName()).EqualTo("histo4")) { fCanvas->cd(4); histogram->Draw("COL"); fCanvas->cd(0); diff --git a/examples/MQ/histogramServer/FairMQExHistoCanvasDrawerExample.h b/examples/MQ/histogramServer/FairMQExHistoCanvasDrawerExample.h index 52807a39b2..2d99acf01f 100644 --- a/examples/MQ/histogramServer/FairMQExHistoCanvasDrawerExample.h +++ b/examples/MQ/histogramServer/FairMQExHistoCanvasDrawerExample.h @@ -12,8 +12,8 @@ class TCanvas; -#include #include +#include class FairMQExHistoCanvasDrawerExample : public FairMQExHistoCanvasDrawer { diff --git a/examples/MQ/histogramServer/FairMQExHistoDevice.cxx b/examples/MQ/histogramServer/FairMQExHistoDevice.cxx index f89259ba26..9b00467df8 100644 --- a/examples/MQ/histogramServer/FairMQExHistoDevice.cxx +++ b/examples/MQ/histogramServer/FairMQExHistoDevice.cxx @@ -5,20 +5,19 @@ * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ -#include -#include - #include "FairMQExHistoDevice.h" + #include "RootSerializer.h" #include +#include +#include FairMQExHistoDevice::FairMQExHistoDevice() : FairMQDevice() , fRandom(0) , fArrayHisto() -{ -} +{} FairMQExHistoDevice::~FairMQExHistoDevice() {} @@ -55,8 +54,7 @@ bool FairMQExHistoDevice::ConditionalRun() FairMQMessagePtr message(NewMessage()); Serialize(*message, &fArrayHisto); - for (auto& channel : fChannels) - { + for (auto& channel : fChannels) { Send(message, channel.first.data()); } diff --git a/examples/MQ/histogramServer/FairMQExHistoDevice.h b/examples/MQ/histogramServer/FairMQExHistoDevice.h index ff7a9fa311..9840b9a4ae 100644 --- a/examples/MQ/histogramServer/FairMQExHistoDevice.h +++ b/examples/MQ/histogramServer/FairMQExHistoDevice.h @@ -9,11 +9,10 @@ #define FAIRMQEXHISTODEVICE #include - -#include // for TH1F -#include // for TH2F -#include +#include // for TH1F +#include // for TH2F #include +#include class FairMQExHistoDevice : public FairMQDevice { diff --git a/examples/MQ/histogramServer/FairMQExHistoServer.cxx b/examples/MQ/histogramServer/FairMQExHistoServer.cxx index 04e378aef1..c756f612fc 100644 --- a/examples/MQ/histogramServer/FairMQExHistoServer.cxx +++ b/examples/MQ/histogramServer/FairMQExHistoServer.cxx @@ -7,14 +7,14 @@ ********************************************************************************/ #include "FairMQExHistoServer.h" -#include "FairMQExHistoCanvasDrawer.h" + #include "FairLogger.h" +#include "FairMQExHistoCanvasDrawer.h" #include "RootSerializer.h" #include #include #include - #include #include @@ -27,8 +27,7 @@ FairMQExHistoServer::FairMQExHistoServer() , fServer("http:8080") , fCanvasDrawer(nullptr) , fStopThread(false) -{ -} +{} FairMQExHistoServer::~FairMQExHistoServer() {} @@ -36,8 +35,7 @@ void FairMQExHistoServer::InitTask() { OnData(fInputChannelName, &FairMQExHistoServer::ReceiveData); - if (fCanvasDrawer) - { + if (fCanvasDrawer) { fCanvasDrawer->CreateCanvases(fServer); } } @@ -47,25 +45,20 @@ bool FairMQExHistoServer::ReceiveData(FairMQMessagePtr& msg, int index) TObject* tempObject = nullptr; Deserialize(*msg, tempObject); - if (TString(tempObject->ClassName()).EqualTo("TObjArray")) - { + if (TString(tempObject->ClassName()).EqualTo("TObjArray")) { std::lock_guard lk(mtx); TObjArray* arrayHisto = static_cast(tempObject); TH1* histogram_new; TH1* histogram_existing; - for (int i = 0; i < arrayHisto->GetEntriesFast(); i++) - { + for (int i = 0; i < arrayHisto->GetEntriesFast(); i++) { TObject* obj = arrayHisto->At(i); TH1* histogram = static_cast(obj); int index1 = FindHistogram(histogram->GetName()); - if (-1 == index1) - { + if (-1 == index1) { histogram_new = static_cast(histogram->Clone()); fArrayHisto.Add(histogram_new); fServer.Register("Histograms", histogram_new); - } - else - { + } else { histogram_existing = static_cast(fArrayHisto.At(index1)); histogram_existing->Add(histogram); } @@ -89,13 +82,11 @@ void FairMQExHistoServer::PreRun() void FairMQExHistoServer::UpdateHttpServer() { - while (!fStopThread) - { + while (!fStopThread) { std::this_thread::sleep_for(std::chrono::milliseconds(10)); std::lock_guard lk(mtx); - if (fCanvasDrawer) - { + if (fCanvasDrawer) { fCanvasDrawer->DrawHistograms(fArrayHisto); } @@ -111,11 +102,9 @@ void FairMQExHistoServer::PostRun() int FairMQExHistoServer::FindHistogram(const std::string& name) { - for (int i = 0; i < fArrayHisto.GetEntriesFast(); i++) - { + for (int i = 0; i < fArrayHisto.GetEntriesFast(); i++) { TObject* obj = fArrayHisto.At(i); - if (TString(obj->GetName()).EqualTo(name)) - { + if (TString(obj->GetName()).EqualTo(name)) { return i; } } diff --git a/examples/MQ/histogramServer/FairMQExHistoServer.h b/examples/MQ/histogramServer/FairMQExHistoServer.h index be4582aeb0..7389e20c65 100644 --- a/examples/MQ/histogramServer/FairMQExHistoServer.h +++ b/examples/MQ/histogramServer/FairMQExHistoServer.h @@ -8,12 +8,11 @@ #ifndef FAIRMQEXHISTOSERVER #define FAIRMQEXHISTOSERVER -#include -#include "FairMQExHistoCanvasDrawer.h" // for FairMQExHistoCanvasDrawer +#include "FairMQExHistoCanvasDrawer.h" // for FairMQExHistoCanvasDrawer +#include #include #include - #include #include #include diff --git a/examples/MQ/histogramServer/runExHistoCanvasDrawer.cxx b/examples/MQ/histogramServer/runExHistoCanvasDrawer.cxx index d9b3ea69b4..a680adfa35 100644 --- a/examples/MQ/histogramServer/runExHistoCanvasDrawer.cxx +++ b/examples/MQ/histogramServer/runExHistoCanvasDrawer.cxx @@ -5,11 +5,10 @@ * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ -#include "runExHistoServer.h" - #include "FairMQExHistoCanvasDrawerExample.h" +#include "runExHistoServer.h" std::unique_ptr getCanvasDrawer() { - return std::unique_ptr{ new FairMQExHistoCanvasDrawerExample() }; + return std::unique_ptr{new FairMQExHistoCanvasDrawerExample()}; } diff --git a/examples/MQ/histogramServer/runExHistoDevice.cxx b/examples/MQ/histogramServer/runExHistoDevice.cxx index 83337d2e13..2de490fc2b 100644 --- a/examples/MQ/histogramServer/runExHistoDevice.cxx +++ b/examples/MQ/histogramServer/runExHistoDevice.cxx @@ -5,15 +5,12 @@ * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ -#include "runFairMQDevice.h" - #include "FairMQExHistoDevice.h" +#include "runFairMQDevice.h" namespace bpo = boost::program_options; -void addCustomOptions(bpo::options_description& /*options*/) -{ -} +void addCustomOptions(bpo::options_description& /*options*/) {} FairMQDevicePtr getDevice(const FairMQProgOptions& /*config*/) { diff --git a/examples/MQ/histogramServer/runExHistoServer.h b/examples/MQ/histogramServer/runExHistoServer.h index de23c05159..cb8a9b0fcc 100644 --- a/examples/MQ/histogramServer/runExHistoServer.h +++ b/examples/MQ/histogramServer/runExHistoServer.h @@ -5,17 +5,14 @@ * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ -#include - +#include "FairMQExHistoServer.h" #include "runFairMQDevice.h" -#include "FairMQExHistoServer.h" +#include namespace bpo = boost::program_options; -void addCustomOptions(bpo::options_description& /*options*/) -{ -} +void addCustomOptions(bpo::options_description& /*options*/) {} std::unique_ptr getCanvasDrawer(); diff --git a/examples/MQ/parameters/FairMQExParamsClient.cxx b/examples/MQ/parameters/FairMQExParamsClient.cxx index 8de7ee0133..059e1a7ccc 100644 --- a/examples/MQ/parameters/FairMQExParamsClient.cxx +++ b/examples/MQ/parameters/FairMQExParamsClient.cxx @@ -12,15 +12,15 @@ * @author A. Rybalchenko */ -#include // this_thread::sleep_for -#include - -#include #include "FairMQExParamsClient.h" -#include "FairMQExParamsParOne.h" +#include "FairMQExParamsParOne.h" #include "RootSerializer.h" +#include +#include +#include // this_thread::sleep_for + using namespace std; FairMQExParamsClient::FairMQExParamsClient() @@ -28,12 +28,9 @@ FairMQExParamsClient::FairMQExParamsClient() , fParameterName() , fMaxIterations(0) , fNumIterations(0) -{ -} +{} -FairMQExParamsClient::~FairMQExParamsClient() -{ -} +FairMQExParamsClient::~FairMQExParamsClient() {} void FairMQExParamsClient::InitTask() { @@ -51,20 +48,15 @@ bool FairMQExParamsClient::ConditionalRun() FairMQMessagePtr req(NewSimpleMessage(fParameterName + "," + to_string(fRunId))); FairMQMessagePtr rep(NewMessage()); - if (Send(req, "data") > 0) - { - if (Receive(rep, "data") >= 0) - { - if (rep->GetSize() != 0) - { + if (Send(req, "data") > 0) { + if (Receive(rep, "data") >= 0) { + if (rep->GetSize() != 0) { FairMQExParamsParOne* par = nullptr; Deserialize(*rep, par); LOG(info) << "Received parameter from the server:"; par->print(); delete par; - } - else - { + } else { LOG(error) << "Received empty reply. Parameter not available"; } } @@ -72,8 +64,7 @@ bool FairMQExParamsClient::ConditionalRun() fRunId == 2099 ? fRunId = 2000 : fRunId++; - if (fMaxIterations > 0 && ++fNumIterations >= fMaxIterations) - { + if (fMaxIterations > 0 && ++fNumIterations >= fMaxIterations) { LOG(info) << "Configured maximum number of iterations reached. Leaving RUNNING state."; return false; } diff --git a/examples/MQ/parameters/FairMQExParamsClient.h b/examples/MQ/parameters/FairMQExParamsClient.h index 836ab90900..1f755c7017 100644 --- a/examples/MQ/parameters/FairMQExParamsClient.h +++ b/examples/MQ/parameters/FairMQExParamsClient.h @@ -15,10 +15,9 @@ #ifndef FAIRMQEXPARAMSCLIENT_H #define FAIRMQEXPARAMSCLIENT_H -#include -#include // uint64_t - #include +#include // uint64_t +#include class FairMQExParamsClient : public FairMQDevice { diff --git a/examples/MQ/parameters/FairMQExParamsContFact.cxx b/examples/MQ/parameters/FairMQExParamsContFact.cxx index 72bf062ddc..edc985d37b 100644 --- a/examples/MQ/parameters/FairMQExParamsContFact.cxx +++ b/examples/MQ/parameters/FairMQExParamsContFact.cxx @@ -6,12 +6,12 @@ * copied verbatim in the file "LICENSE" * ********************************************************************************/ -#include "FairRuntimeDb.h" - #include "FairMQExParamsContFact.h" + #include "FairMQExParamsParOne.h" +#include "FairRuntimeDb.h" -#include // strcmp +#include // strcmp static FairMQExParamsContFact gFairMQExParamsContFact; @@ -25,7 +25,8 @@ FairMQExParamsContFact::FairMQExParamsContFact() void FairMQExParamsContFact::setAllContainers() { - FairContainer* container = new FairContainer("FairMQExParamsParOne", "FairMQExParamsParOne Parameters", "TestDefaultContext"); + FairContainer* container = + new FairContainer("FairMQExParamsParOne", "FairMQExParamsParOne Parameters", "TestDefaultContext"); container->addContext("TestNonDefaultContext"); containers->Add(container); @@ -36,8 +37,7 @@ FairParSet* FairMQExParamsContFact::createContainer(FairContainer* container) const char* name = container->GetName(); FairParSet* p = nullptr; - if (strcmp(name, "FairMQExParamsParOne") == 0) - { + if (strcmp(name, "FairMQExParamsParOne") == 0) { p = new FairMQExParamsParOne(container->getConcatName().Data(), container->GetTitle(), container->getContext()); } diff --git a/examples/MQ/parameters/FairMQExParamsContFact.h b/examples/MQ/parameters/FairMQExParamsContFact.h index 4ea4ce2595..9a8be79646 100644 --- a/examples/MQ/parameters/FairMQExParamsContFact.h +++ b/examples/MQ/parameters/FairMQExParamsContFact.h @@ -23,7 +23,7 @@ class FairMQExParamsContFact : public FairContFact ~FairMQExParamsContFact() {} FairParSet* createContainer(FairContainer*); - ClassDef(FairMQExParamsContFact,0) + ClassDef(FairMQExParamsContFact, 0) }; -#endif /* FAIRMQEXPARAMSCONTFACT_H */ +#endif /* FAIRMQEXPARAMSCONTFACT_H */ diff --git a/examples/MQ/parameters/FairMQExParamsParOne.cxx b/examples/MQ/parameters/FairMQExParamsParOne.cxx index e9dfffe8c9..e53fe8bea4 100644 --- a/examples/MQ/parameters/FairMQExParamsParOne.cxx +++ b/examples/MQ/parameters/FairMQExParamsParOne.cxx @@ -1,28 +1,25 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "FairMQExParamsParOne.h" +#include "FairLogger.h" #include "FairParamList.h" -#include "FairLogger.h" #include -FairMQExParamsParOne::FairMQExParamsParOne(const char* name, const char* title, const char* context) : - FairParGenericSet(name, title, context), - fParameterValue(0) +FairMQExParamsParOne::FairMQExParamsParOne(const char* name, const char* title, const char* context) + : FairParGenericSet(name, title, context) + , fParameterValue(0) { detName = "TutorialDet"; } -FairMQExParamsParOne::~FairMQExParamsParOne() -{ - clear(); -} +FairMQExParamsParOne::~FairMQExParamsParOne() { clear(); } void FairMQExParamsParOne::clear() { @@ -40,8 +37,7 @@ void FairMQExParamsParOne::putParams(FairParamList* list) { LOG(info) << "FairMQExParamsParOne::putParams()"; - if (!list) - { + if (!list) { return; } @@ -52,17 +48,15 @@ Bool_t FairMQExParamsParOne::getParams(FairParamList* list) { LOG(info) << "FairMQExParamsParOne::getParams()"; - if (!list) - { + if (!list) { return kFALSE; } - if (!list->fill("Example7ParameterValue", &fParameterValue)) - { + if (!list->fill("Example7ParameterValue", &fParameterValue)) { return kFALSE; } return kTRUE; } -ClassImp(FairMQExParamsParOne) +ClassImp(FairMQExParamsParOne); diff --git a/examples/MQ/parameters/FairMQExParamsParOne.h b/examples/MQ/parameters/FairMQExParamsParOne.h index afac55f6c6..e4ddd42eef 100644 --- a/examples/MQ/parameters/FairMQExParamsParOne.h +++ b/examples/MQ/parameters/FairMQExParamsParOne.h @@ -18,8 +18,8 @@ class FairMQExParamsParOne : public FairParGenericSet { public: /** Standard constructor **/ - FairMQExParamsParOne(const char* name = "FairMQExParamsParOne", - const char* title = "FairMQ Example Parameters Parameter One", + FairMQExParamsParOne(const char* name = "FairMQExParamsParOne", + const char* title = "FairMQ Example Parameters Parameter One", const char* context = "Default"); /** Destructor **/ @@ -36,12 +36,12 @@ class FairMQExParamsParOne : public FairParGenericSet inline void SetValue(const Int_t& val) { fParameterValue = val; } private: - Int_t fParameterValue; // + Int_t fParameterValue; // FairMQExParamsParOne(const FairMQExParamsParOne&); FairMQExParamsParOne& operator=(const FairMQExParamsParOne&); - ClassDef(FairMQExParamsParOne,1); + ClassDef(FairMQExParamsParOne, 1); }; -#endif // FAIRMQEXPARAMSPARONE_H_ +#endif // FAIRMQEXPARAMSPARONE_H_ diff --git a/examples/MQ/parameters/fill_parameters.C b/examples/MQ/parameters/fill_parameters.C index 624dac2ed3..c184411e14 100644 --- a/examples/MQ/parameters/fill_parameters.C +++ b/examples/MQ/parameters/fill_parameters.C @@ -1,25 +1,24 @@ { - FairRuntimeDb* rtdb = FairRuntimeDb::instance(); + FairRuntimeDb* rtdb = FairRuntimeDb::instance(); - Bool_t kParameterMerged = kTRUE; - FairParRootFileIo* parOut = new FairParRootFileIo(kParameterMerged); - parOut->open("mq_ex_params.root"); - rtdb->setOutput(parOut); - //rtdb->saveOutput(); - //rtdb->print(); + Bool_t kParameterMerged = kTRUE; + FairParRootFileIo* parOut = new FairParRootFileIo(kParameterMerged); + parOut->open("mq_ex_params.root"); + rtdb->setOutput(parOut); + // rtdb->saveOutput(); + // rtdb->print(); - FairMQExParamsParOne* par = static_cast(rtdb->getContainer("FairMQExParamsParOne")); + FairMQExParamsParOne* par = static_cast(rtdb->getContainer("FairMQExParamsParOne")); - for(Int_t i = 0; i < 100; i++) - { - rtdb->addRun(2000 + i); + for (Int_t i = 0; i < 100; i++) { + rtdb->addRun(2000 + i); - par->SetValue(1983 + i); - par->setChanged(); - rtdb->writeContainers(); - } + par->SetValue(1983 + i); + par->setChanged(); + rtdb->writeContainers(); + } - rtdb->saveOutput(); + rtdb->saveOutput(); - rtdb->print(); + rtdb->print(); } diff --git a/examples/MQ/parameters/read_parameters.C b/examples/MQ/parameters/read_parameters.C index 45adf44b9b..a432866aeb 100644 --- a/examples/MQ/parameters/read_parameters.C +++ b/examples/MQ/parameters/read_parameters.C @@ -1,19 +1,18 @@ { - FairRuntimeDb* rtdb = FairRuntimeDb::instance(); + FairRuntimeDb* rtdb = FairRuntimeDb::instance(); - Bool_t kParameterMerged = kTRUE; - FairParRootFileIo* parOut = new FairParRootFileIo(kParameterMerged); - parOut->open("mq_ex_params.root"); - rtdb->setFirstInput(parOut); - //rtdb->saveOutput(); - //rtdb->print(); + Bool_t kParameterMerged = kTRUE; + FairParRootFileIo* parOut = new FairParRootFileIo(kParameterMerged); + parOut->open("mq_ex_params.root"); + rtdb->setFirstInput(parOut); + // rtdb->saveOutput(); + // rtdb->print(); - FairMQExParamsParOne* par = static_cast(rtdb->getContainer("FairMQExParamsParOne")); + FairMQExParamsParOne* par = static_cast(rtdb->getContainer("FairMQExParamsParOne")); - for (Int_t i = 0; i < 100; i++) - { - rtdb->initContainers(2000+i); + for (Int_t i = 0; i < 100; i++) { + rtdb->initContainers(2000 + i); - par->print(); - } + par->print(); + } } diff --git a/examples/MQ/parameters/runExParamsClient.cxx b/examples/MQ/parameters/runExParamsClient.cxx index e773a80c9e..f798bde191 100644 --- a/examples/MQ/parameters/runExParamsClient.cxx +++ b/examples/MQ/parameters/runExParamsClient.cxx @@ -6,19 +6,18 @@ * copied verbatim in the file "LICENSE" * ********************************************************************************/ -#include "runFairMQDevice.h" #include "FairMQExParamsClient.h" +#include "runFairMQDevice.h" namespace bpo = boost::program_options; void addCustomOptions(bpo::options_description& options) { + // clang-format off options.add_options() ("parameter-name", bpo::value()->default_value("FairMQExParamsParOne"), "Parameter Name") - ("max-iterations", bpo::value()->default_value(0), "Maximum number of iterations of Run/ConditionalRun/OnData (0 - infinite)"); + ("max-iterations", bpo::value()->default_value(0), "Maximum number of iterations of Run/ConditionalRun/OnData (0 - infinite)"); + // clang-format on } -FairMQDevicePtr getDevice(const FairMQProgOptions& /*config*/) -{ - return new FairMQExParamsClient(); -} +FairMQDevicePtr getDevice(const FairMQProgOptions& /*config*/) { return new FairMQExParamsClient(); } diff --git a/examples/MQ/pixelAlternative/run/runPixAltFileSinkBin.cxx b/examples/MQ/pixelAlternative/run/runPixAltFileSinkBin.cxx index 6644652072..7a21303ae9 100644 --- a/examples/MQ/pixelAlternative/run/runPixAltFileSinkBin.cxx +++ b/examples/MQ/pixelAlternative/run/runPixAltFileSinkBin.cxx @@ -15,13 +15,12 @@ namespace bpo = boost::program_options; void addCustomOptions(bpo::options_description& options) { + // clang-format off options.add_options() ("file-name", bpo::value() , "Path to the output file") ("in-channel", bpo::value()->default_value("data-in"), "input channel name") ("ack-channel", bpo::value() , "ack channel name"); + // clang-format on } -FairMQDevicePtr getDevice(const FairMQProgOptions& /*config*/) -{ - return new FairMQPixAltFileSinkBin(); -} +FairMQDevicePtr getDevice(const FairMQProgOptions& /*config*/) { return new FairMQPixAltFileSinkBin(); } diff --git a/examples/MQ/pixelAlternative/run/runPixAltSamplerBin.cxx b/examples/MQ/pixelAlternative/run/runPixAltSamplerBin.cxx index ff6d159113..7f418a511e 100644 --- a/examples/MQ/pixelAlternative/run/runPixAltSamplerBin.cxx +++ b/examples/MQ/pixelAlternative/run/runPixAltSamplerBin.cxx @@ -15,15 +15,14 @@ namespace bpo = boost::program_options; void addCustomOptions(bpo::options_description& options) { + // clang-format off options.add_options() - ("file-name", bpo::value>() , "Path to the input file") - ("max-index", bpo::value ()->default_value(-1) , "number of events to read") + ("file-name", bpo::value>(), "Path to the input file") + ("max-index", bpo::value ()->default_value(-1), "number of events to read") ("out-channel", bpo::value ()->default_value("data-out"), "output channel name") - ("ack-channel", bpo::value ()->default_value("") , "ack channel name") - ("aggregate", bpo::value ()->default_value(1) , "aggregate level"); + ("ack-channel", bpo::value ()->default_value(""), "ack channel name") + ("aggregate", bpo::value ()->default_value(1), "aggregate level"); + // clang-format on } -FairMQDevicePtr getDevice(const FairMQProgOptions& /*config*/) -{ - return new FairMQPixAltSamplerBin; -} +FairMQDevicePtr getDevice(const FairMQProgOptions& /*config*/) { return new FairMQPixAltSamplerBin; } diff --git a/examples/MQ/pixelAlternative/run/runPixAltTaskProcessorBin.cxx b/examples/MQ/pixelAlternative/run/runPixAltTaskProcessorBin.cxx index 3a0de8db73..affc929ef7 100644 --- a/examples/MQ/pixelAlternative/run/runPixAltTaskProcessorBin.cxx +++ b/examples/MQ/pixelAlternative/run/runPixAltTaskProcessorBin.cxx @@ -6,9 +6,8 @@ * copied verbatim in the file "LICENSE" * ********************************************************************************/ -#include "runFairMQDevice.h" - #include "PixelAltFindHits.h" +#include "runFairMQDevice.h" // PixelAlternative example #include "FairMQPixAltTaskProcessorBin.h" @@ -17,12 +16,14 @@ namespace bpo = boost::program_options; void addCustomOptions(bpo::options_description& options) { + // clang-format off options.add_options() - ("task-name", bpo::value()->required() , "Name of task to run") - ("keep-data", bpo::value() , "Name of data to keep in stream") - ("in-channel", bpo::value()->default_value("data-in") , "input channel name") + ("task-name", bpo::value()->required(), "Name of task to run") + ("keep-data", bpo::value(), "Name of data to keep in stream") + ("in-channel", bpo::value()->default_value("data-in"), "input channel name") ("out-channel", bpo::value()->default_value("data-out"), "output channel name") - ("par-channel", bpo::value()->default_value("param") , "param channel name"); + ("par-channel", bpo::value()->default_value("param"), "param channel name"); + // clang-format on } FairMQDevicePtr getDevice(const FairMQProgOptions& config) diff --git a/examples/MQ/pixelAlternative/src/PixelAltDigiWriteToRootVector.cxx b/examples/MQ/pixelAlternative/src/PixelAltDigiWriteToRootVector.cxx index 039ffad66e..9aa736b52c 100644 --- a/examples/MQ/pixelAlternative/src/PixelAltDigiWriteToRootVector.cxx +++ b/examples/MQ/pixelAlternative/src/PixelAltDigiWriteToRootVector.cxx @@ -15,170 +15,164 @@ #include "PixelAltDigiWriteToRootVector.h" // Includes from base -#include "FairRootManager.h" #include "FairLogger.h" +#include "FairRootManager.h" // Includes from ROOT +#include "PixelDigi.h" +#include "PixelPayload.h" + #include #include #include -#include "PixelPayload.h" - -#include "PixelDigi.h" - PixelAltDigiWriteToRootVector::PixelAltDigiWriteToRootVector() - : PixelAltDigiWriteToRootVector("Pixel DigiWriter", 0) -{ -} + : PixelAltDigiWriteToRootVector("Pixel DigiWriter", 0) +{} PixelAltDigiWriteToRootVector::PixelAltDigiWriteToRootVector(Int_t iVerbose) - : PixelAltDigiWriteToRootVector("Pixel DigiWriter", iVerbose) -{ -} + : PixelAltDigiWriteToRootVector("Pixel DigiWriter", iVerbose) +{} PixelAltDigiWriteToRootVector::PixelAltDigiWriteToRootVector(const char* name, Int_t iVerbose) - : FairTask(name, iVerbose) - , fDigis(nullptr) - , fOutputRootFile() - , fOutputRootTree() - , fPixelEventHeader(0) - , fPixelDigiVector() - , fOutputFileName("test.root") - , fNofOutputFiles(0) - , fDivideLevel(0) - , fRunId(0) - , fMCEntryNo(0) - , fPartNo(0) + : FairTask(name, iVerbose) + , fDigis(nullptr) + , fOutputRootFile() + , fOutputRootTree() + , fPixelEventHeader(0) + , fPixelDigiVector() + , fOutputFileName("test.root") + , fNofOutputFiles(0) + , fDivideLevel(0) + , fRunId(0) + , fMCEntryNo(0) + , fPartNo(0) { - Reset(); + Reset(); } -PixelAltDigiWriteToRootVector::~PixelAltDigiWriteToRootVector() -{ - Reset(); -} +PixelAltDigiWriteToRootVector::~PixelAltDigiWriteToRootVector() { Reset(); } void PixelAltDigiWriteToRootVector::Exec(Option_t* /*opt*/) { - Reset(); - - Int_t nofDigis = fDigis->GetEntriesFast(); - - for ( Int_t ifile = 0 ; ifile < fNofOutputFiles ; ifile++ ) { - fPixelDigiVector.clear(); - fPixelEventHeader->fRunId = fRunId; - fPixelEventHeader->fMCEntryNo = fMCEntryNo; - fPixelEventHeader->fPartNo = ifile; - - // std::cout << ifile << " > " << std::flush; - for ( Int_t iDigi = 0 ; iDigi < nofDigis ; iDigi++ ) { - PixelDigi* currentDigi = static_cast(fDigis->At(iDigi)); - - int detId = (int)currentDigi->GetDetectorID(); - Int_t fileToSave = 0; - if ( fDivideLevel == 1 ) { - fileToSave = detId/256 - 1; - } - else if ( fDivideLevel == 2 ) { - fileToSave = (detId/256 - 1)*4 + (detId%256 -1); - } - // std::cout << fileToSave << " " << std::flush; - if ( fileToSave != ifile ) continue; - - int feId = (int)currentDigi->GetFeID(); - int col = (int)currentDigi->GetCol(); - int row = (int)currentDigi->GetRow(); - // double charge = (double)currentDigi->GetCharge(); - - PixelPayload::Digi tempDigi;// = new PixelPayload::Digi(); - tempDigi.fDetectorID = detId; - tempDigi.fFeID = feId; - tempDigi.fCharge = 0.; - tempDigi.fCol = col; - tempDigi.fRow = row; - fPixelDigiVector.push_back(tempDigi); + Reset(); + + Int_t nofDigis = fDigis->GetEntriesFast(); + + for (Int_t ifile = 0; ifile < fNofOutputFiles; ifile++) { + fPixelDigiVector.clear(); + fPixelEventHeader->fRunId = fRunId; + fPixelEventHeader->fMCEntryNo = fMCEntryNo; + fPixelEventHeader->fPartNo = ifile; + + // std::cout << ifile << " > " << std::flush; + for (Int_t iDigi = 0; iDigi < nofDigis; iDigi++) { + PixelDigi* currentDigi = static_cast(fDigis->At(iDigi)); + + int detId = (int)currentDigi->GetDetectorID(); + Int_t fileToSave = 0; + if (fDivideLevel == 1) { + fileToSave = detId / 256 - 1; + } else if (fDivideLevel == 2) { + fileToSave = (detId / 256 - 1) * 4 + (detId % 256 - 1); + } + // std::cout << fileToSave << " " << std::flush; + if (fileToSave != ifile) + continue; + + int feId = (int)currentDigi->GetFeID(); + int col = (int)currentDigi->GetCol(); + int row = (int)currentDigi->GetRow(); + // double charge = (double)currentDigi->GetCharge(); + + PixelPayload::Digi tempDigi; // = new PixelPayload::Digi(); + tempDigi.fDetectorID = detId; + tempDigi.fFeID = feId; + tempDigi.fCharge = 0.; + tempDigi.fCol = col; + tempDigi.fRow = row; + fPixelDigiVector.push_back(tempDigi); + } + fPixelDigiVector.shrink_to_fit(); + // std::cout << std::endl; + fOutputRootTree[ifile]->Fill(); } - fPixelDigiVector.shrink_to_fit(); - // std::cout << std::endl; - fOutputRootTree[ifile]->Fill(); - } - fMCEntryNo ++; + fMCEntryNo++; } -void PixelAltDigiWriteToRootVector::SetParContainers() { -} +void PixelAltDigiWriteToRootVector::SetParContainers() {} -InitStatus PixelAltDigiWriteToRootVector::Init() { +InitStatus PixelAltDigiWriteToRootVector::Init() +{ - // Get input array - FairRootManager* ioman = FairRootManager::Instance(); + // Get input array + FairRootManager* ioman = FairRootManager::Instance(); - if ( ! ioman ) LOG(fatal) << "No FairRootManager"; - fDigis = static_cast(ioman->GetObject("PixelDigis")); + if (!ioman) + LOG(fatal) << "No FairRootManager"; + fDigis = static_cast(ioman->GetObject("PixelDigis")); - if ( !fDigis ) - LOG(warn) << "PixelAltDigiWriteToRootVector::Init() No input PixelDigis array!"; + if (!fDigis) + LOG(warn) << "PixelAltDigiWriteToRootVector::Init() No input PixelDigis array!"; - LOG(info) << "-I- " << fName.Data() << "::Init(). Initialization succesfull."; + LOG(info) << "-I- " << fName.Data() << "::Init(). Initialization succesfull."; - fRunId = ioman->GetRunId(); + fRunId = ioman->GetRunId(); - if ( fDivideLevel == 0 ) { - fNofOutputFiles = 1; - } - else { - if ( fDivideLevel == 1 ) { - fNofOutputFiles = 3; // 1 file per station (3 stations) + if (fDivideLevel == 0) { + fNofOutputFiles = 1; + } else { + if (fDivideLevel == 1) { + fNofOutputFiles = 3; // 1 file per station (3 stations) + } else if (fDivideLevel == 2) { + fNofOutputFiles = 12; // 1 file per sensor (3 stations times 4 sensors) + } else { + LOG(fatal) << "PixelAltDigiWriteToRootVector::Init(), fDivideLevel = " << fDivideLevel + << " unknown, it has to be in the range <0,2>"; + return kFATAL; + } } - else if ( fDivideLevel == 2 ) { - fNofOutputFiles = 12; // 1 file per sensor (3 stations times 4 sensors) - } - else { - LOG(fatal) << "PixelAltDigiWriteToRootVector::Init(), fDivideLevel = " << fDivideLevel << " unknown, it has to be in the range <0,2>"; - return kFATAL; - } - } - - fPixelEventHeader = new PixelPayload::EventHeader(); - for ( Int_t ifile = 0 ; ifile < fNofOutputFiles ; ifile++ ) { - TString fileName = fOutputFileName; - TString uniqFile = (fDivideLevel==0?".":(fDivideLevel==1?Form(".s%d.",ifile):Form(".c%d.",ifile))); - fileName.Replace(fileName.Last('.'),1,uniqFile.Data()); - fOutputRootFile[ifile] = new TFile(fileName.Data(),"RECREATE"); - fOutputRootTree[ifile] = new TTree("fairdata","example MQ 9 Pixel data"); - LOG(debug) << "trying to create branch in file >>" << fOutputRootFile[ifile]->GetName() << "<<"; - fOutputRootTree[ifile]->Branch("EventHeader.","PixelPayload::EventHeader",&fPixelEventHeader,0); - fOutputRootTree[ifile]->Branch("DigiVector.",&fPixelDigiVector,32000,0); - LOG(debug) << "branches created, fPixelDigiVector = >>" << &fPixelDigiVector << "<<"; - } - - return kSUCCESS; + fPixelEventHeader = new PixelPayload::EventHeader(); + for (Int_t ifile = 0; ifile < fNofOutputFiles; ifile++) { + TString fileName = fOutputFileName; + TString uniqFile = + (fDivideLevel == 0 ? "." : (fDivideLevel == 1 ? Form(".s%d.", ifile) : Form(".c%d.", ifile))); + fileName.Replace(fileName.Last('.'), 1, uniqFile.Data()); + + fOutputRootFile[ifile] = new TFile(fileName.Data(), "RECREATE"); + fOutputRootTree[ifile] = new TTree("fairdata", "example MQ 9 Pixel data"); + LOG(debug) << "trying to create branch in file >>" << fOutputRootFile[ifile]->GetName() << "<<"; + fOutputRootTree[ifile]->Branch("EventHeader.", "PixelPayload::EventHeader", &fPixelEventHeader, 0); + fOutputRootTree[ifile]->Branch("DigiVector.", &fPixelDigiVector, 32000, 0); + LOG(debug) << "branches created, fPixelDigiVector = >>" << &fPixelDigiVector << "<<"; + } + return kSUCCESS; } -InitStatus PixelAltDigiWriteToRootVector::ReInit() { - FairRootManager* ioman = FairRootManager::Instance(); - InitStatus Status=kFATAL; - if ( ! ioman ){ +InitStatus PixelAltDigiWriteToRootVector::ReInit() +{ + FairRootManager* ioman = FairRootManager::Instance(); + InitStatus Status = kFATAL; + if (!ioman) { LOG(fatal) << "No FairRootManager found."; - }else{ - fRunId = ioman->GetRunId(); - fMCEntryNo = 0; - Status=kSUCCESS; + } else { + fRunId = ioman->GetRunId(); + fMCEntryNo = 0; + Status = kSUCCESS; } return Status; } -void PixelAltDigiWriteToRootVector::Reset() { -} +void PixelAltDigiWriteToRootVector::Reset() {} -void PixelAltDigiWriteToRootVector::Finish() { - for ( Int_t ifile = 0 ; ifile < fNofOutputFiles ; ifile++ ) { - fOutputRootFile[ifile]->Write(); - fOutputRootFile[ifile]->Close(); - } +void PixelAltDigiWriteToRootVector::Finish() +{ + for (Int_t ifile = 0; ifile < fNofOutputFiles; ifile++) { + fOutputRootFile[ifile]->Write(); + fOutputRootFile[ifile]->Close(); + } } -ClassImp(PixelAltDigiWriteToRootVector) +ClassImp(PixelAltDigiWriteToRootVector); diff --git a/examples/MQ/pixelAlternative/src/PixelAltDigiWriteToRootVector.h b/examples/MQ/pixelAlternative/src/PixelAltDigiWriteToRootVector.h index e1b52e0adb..4af8508981 100644 --- a/examples/MQ/pixelAlternative/src/PixelAltDigiWriteToRootVector.h +++ b/examples/MQ/pixelAlternative/src/PixelAltDigiWriteToRootVector.h @@ -16,12 +16,10 @@ #define PIXELALTDIGIWRITETOROOTVECTOR_H 1 #include "FairTask.h" - #include "PixelPayload.h" #include #include - #include class TClonesArray; @@ -46,9 +44,9 @@ class PixelAltDigiWriteToRootVector : public FairTask /** Execution **/ virtual void Exec(Option_t* opt); - void SetOutputFileName(TString tstr) {fOutputFileName = tstr;}; + void SetOutputFileName(TString tstr) { fOutputFileName = tstr; }; - void SetDivideLevel(Int_t idiv) { fDivideLevel = idiv; } // 0 - event, 1 - station, 2 - sensor + void SetDivideLevel(Int_t idiv) { fDivideLevel = idiv; } // 0 - event, 1 - station, 2 - sensor private: TClonesArray* fDigis; /** Input array of PixelDigi **/ @@ -85,7 +83,7 @@ class PixelAltDigiWriteToRootVector : public FairTask PixelAltDigiWriteToRootVector(const PixelAltDigiWriteToRootVector&); PixelAltDigiWriteToRootVector& operator=(const PixelAltDigiWriteToRootVector&); - ClassDef(PixelAltDigiWriteToRootVector,1); + ClassDef(PixelAltDigiWriteToRootVector, 1); }; #endif diff --git a/examples/MQ/pixelAlternative/src/PixelAltFindHits.cxx b/examples/MQ/pixelAlternative/src/PixelAltFindHits.cxx index 47254702a1..4a77c5cc63 100644 --- a/examples/MQ/pixelAlternative/src/PixelAltFindHits.cxx +++ b/examples/MQ/pixelAlternative/src/PixelAltFindHits.cxx @@ -15,191 +15,210 @@ #include "PixelAltFindHits.h" // Includes from base +#include "FairLogger.h" #include "FairRootManager.h" #include "FairRun.h" #include "FairRuntimeDb.h" -#include "FairLogger.h" // Includes from ROOT +#include "PixelDigi.h" +#include "PixelDigiPar.h" +#include "PixelHit.h" + #include -#include -#include -#include -#include +#include #include #include #include -#include - -#include "PixelDigi.h" -#include "PixelHit.h" -#include "PixelDigiPar.h" +#include +#include +#include +#include PixelAltFindHits::PixelAltFindHits() - : PixelAltFindHits("Pixel Hit Finder", 0) -{ -} + : PixelAltFindHits("Pixel Hit Finder", 0) +{} PixelAltFindHits::PixelAltFindHits(Int_t iVerbose) - : PixelAltFindHits("Pixel Hit Finder", iVerbose) -{ -} + : PixelAltFindHits("Pixel Hit Finder", iVerbose) +{} PixelAltFindHits::PixelAltFindHits(const char* name, Int_t iVerbose) - : FairTask(name, iVerbose) - , fDigiPar(nullptr) - , fGeoParSet(nullptr) - , fDigis(nullptr) - , fHits(nullptr) - , fNDigis(0) - , fNHits(0) - , fTNofEvents(0) - , fTNofDigis(0) - , fTNofHits(0) - , fFeCols(0) - , fFeRows(0) - , fMaxFEperCol(0) - , fPitchX(0.) - , fPitchY(0.) + : FairTask(name, iVerbose) + , fDigiPar(nullptr) + , fGeoParSet(nullptr) + , fDigis(nullptr) + , fHits(nullptr) + , fNDigis(0) + , fNHits(0) + , fTNofEvents(0) + , fTNofDigis(0) + , fTNofHits(0) + , fFeCols(0) + , fFeRows(0) + , fMaxFEperCol(0) + , fPitchX(0.) + , fPitchY(0.) { - LOG(info) << "Created PixelAltFindHits."; - Reset(); + LOG(info) << "Created PixelAltFindHits."; + Reset(); } PixelAltFindHits::~PixelAltFindHits() { - Reset(); - delete fDigiPar; - if (fHits) { - fHits->Delete(); - delete fHits; - } + Reset(); + delete fDigiPar; + if (fHits) { + fHits->Delete(); + delete fHits; + } } void PixelAltFindHits::Exec(Option_t* /*opt*/) { - Reset(); + Reset(); - LOG(debug) << "PixelAltFindHits::Exec() EVENT " << fTNofEvents; + LOG(debug) << "PixelAltFindHits::Exec() EVENT " << fTNofEvents; - fTNofEvents++; + fTNofEvents++; - fNDigis = fDigis->GetEntriesFast(); - fTNofDigis += fNDigis; + fNDigis = fDigis->GetEntriesFast(); + fTNofDigis += fNDigis; - for (Int_t iDigi = 0 ; iDigi < fNDigis ; iDigi++) { - PixelDigi* currentDigi = static_cast(fDigis->At(iDigi)); + for (Int_t iDigi = 0; iDigi < fNDigis; iDigi++) { + PixelDigi* currentDigi = static_cast(fDigis->At(iDigi)); - Int_t detId = currentDigi->GetDetectorID(); + Int_t detId = currentDigi->GetDetectorID(); - Double_t posX, posY, posZ; - Double_t errX, errY, errZ; - Int_t hitIndex = FindHit(detId, currentDigi->GetFeID(), currentDigi->GetCol(), currentDigi->GetRow(), currentDigi->GetIndex(), - posX, posY, posZ, errX, errY, errZ); + Double_t posX, posY, posZ; + Double_t errX, errY, errZ; + Int_t hitIndex = FindHit(detId, + currentDigi->GetFeID(), + currentDigi->GetCol(), + currentDigi->GetRow(), + currentDigi->GetIndex(), + posX, + posY, + posZ, + errX, + errY, + errZ); - TVector3 pos(posX, posY, posZ); - TVector3 posErr(errX, errY, errZ); + TVector3 pos(posX, posY, posZ); + TVector3 posErr(errX, errY, errZ); - if (hitIndex == -666) continue; // hit not found + if (hitIndex == -666) + continue; // hit not found - new ((*fHits)[fNHits]) PixelHit(detId, hitIndex, pos, posErr); + new ((*fHits)[fNHits]) PixelHit(detId, hitIndex, pos, posErr); - fNHits++; - } + fNHits++; + } - fTNofHits += fNHits; + fTNofHits += fNHits; } // should return -666 if hit not found -Int_t PixelAltFindHits::FindHit(Int_t detId, Int_t feId, Int_t col, Int_t row, Int_t index, - Double_t& posX, Double_t& posY, Double_t& posZ, - Double_t& errX, Double_t& errY, Double_t& errZ) +Int_t PixelAltFindHits::FindHit(Int_t detId, + Int_t feId, + Int_t col, + Int_t row, + Int_t index, + Double_t& posX, + Double_t& posY, + Double_t& posZ, + Double_t& errX, + Double_t& errY, + Double_t& errZ) { - TString nodeName = Form("/cave/Pixel%d_%d",detId/256,detId%256); + TString nodeName = Form("/cave/Pixel%d_%d", detId / 256, detId % 256); - gGeoManager->cd(nodeName.Data()); - TGeoNode* curNode = gGeoManager->GetCurrentNode(); - TGeoVolume* actVolume = gGeoManager->GetCurrentVolume(); - TGeoBBox* actBox = static_cast(actVolume->GetShape()); + gGeoManager->cd(nodeName.Data()); + TGeoNode* curNode = gGeoManager->GetCurrentNode(); + TGeoVolume* actVolume = gGeoManager->GetCurrentVolume(); + TGeoBBox* actBox = static_cast(actVolume->GetShape()); - Double_t locPosCalc[3]; - locPosCalc[0] = (((feId-1) / fMaxFEperCol) * fFeCols + col + 0.5)*fPitchX; - locPosCalc[1] = (((feId-1) % fMaxFEperCol) * fFeRows + row + 0.5)*fPitchY; - locPosCalc[2] = 0.; + Double_t locPosCalc[3]; + locPosCalc[0] = (((feId - 1) / fMaxFEperCol) * fFeCols + col + 0.5) * fPitchX; + locPosCalc[1] = (((feId - 1) % fMaxFEperCol) * fFeRows + row + 0.5) * fPitchY; + locPosCalc[2] = 0.; - locPosCalc[0] -= actBox->GetDX(); - locPosCalc[1] -= actBox->GetDY(); + locPosCalc[0] -= actBox->GetDX(); + locPosCalc[1] -= actBox->GetDY(); - Double_t globPos[3]; + Double_t globPos[3]; - curNode->LocalToMaster(locPosCalc, globPos); + curNode->LocalToMaster(locPosCalc, globPos); - LOG(debug) << "HIT ON " << detId << " POSITION: " << locPosCalc[0] << " / " << locPosCalc[1]; - LOG(debug) << "GLOB HIT " << detId << " POSITION: " << globPos[0] << " / " << globPos[1] << " / " << globPos[2]; + LOG(debug) << "HIT ON " << detId << " POSITION: " << locPosCalc[0] << " / " << locPosCalc[1]; + LOG(debug) << "GLOB HIT " << detId << " POSITION: " << globPos[0] << " / " << globPos[1] << " / " << globPos[2]; - posX = globPos[0]; - posY = globPos[1]; - posZ = globPos[2]; - errX = fPitchX / TMath::Sqrt(12.); - errY = fPitchY / TMath::Sqrt(12.); - errZ = actBox->GetDZ(); + posX = globPos[0]; + posY = globPos[1]; + posZ = globPos[2]; + errX = fPitchX / TMath::Sqrt(12.); + errY = fPitchY / TMath::Sqrt(12.); + errZ = actBox->GetDZ(); - // should return -666 if hit not found - return index; + // should return -666 if hit not found + return index; } void PixelAltFindHits::SetParContainers() { - // Get run and runtime database - FairRun* run = FairRun::Instance(); - if (!run) LOG(fatal) << "No analysis run"; + // Get run and runtime database + FairRun* run = FairRun::Instance(); + if (!run) + LOG(fatal) << "No analysis run"; - FairRuntimeDb* db = run->GetRuntimeDb(); - if (!db) LOG(fatal) << "No runtime database"; + FairRuntimeDb* db = run->GetRuntimeDb(); + if (!db) + LOG(fatal) << "No runtime database"; - // Get GEM digitisation parameter container - fDigiPar = static_cast(db->getContainer("PixelDigiParameters")); + // Get GEM digitisation parameter container + fDigiPar = static_cast(db->getContainer("PixelDigiParameters")); } void PixelAltFindHits::GetParList(TList* tempList) { - fDigiPar = new PixelDigiPar("PixelDigiParameters"); - tempList->Add(fDigiPar); + fDigiPar = new PixelDigiPar("PixelDigiParameters"); + tempList->Add(fDigiPar); - return; + return; } -void PixelAltFindHits::InitMQ(TList* tempList) +void PixelAltFindHits::InitMQ(TList* tempList) { - LOG(info) << "********************************************** PixelAltFindHits::InitMQ()"; - fDigiPar = (PixelDigiPar*)tempList->FindObject("PixelDigiParameters"); + LOG(info) << "********************************************** PixelAltFindHits::InitMQ()"; + fDigiPar = (PixelDigiPar*)tempList->FindObject("PixelDigiParameters"); - fFeCols = fDigiPar->GetFECols(); - fFeRows = fDigiPar->GetFERows(); - fMaxFEperCol = fDigiPar->GetMaxFEperCol(); - fPitchX = fDigiPar->GetXPitch(); - fPitchY = fDigiPar->GetYPitch(); + fFeCols = fDigiPar->GetFECols(); + fFeRows = fDigiPar->GetFERows(); + fMaxFEperCol = fDigiPar->GetMaxFEperCol(); + fPitchX = fDigiPar->GetXPitch(); + fPitchY = fDigiPar->GetYPitch(); - LOG(info) << ">> fFeCols = " << fFeCols; - LOG(info) << ">> fFeRows = " << fFeRows; - LOG(info) << ">> fMaxFEperCol = " << fMaxFEperCol; - LOG(info) << ">> fPitchX = " << fPitchX; - LOG(info) << ">> fPitchY = " << fPitchY; + LOG(info) << ">> fFeCols = " << fFeCols; + LOG(info) << ">> fFeRows = " << fFeRows; + LOG(info) << ">> fMaxFEperCol = " << fMaxFEperCol; + LOG(info) << ">> fPitchX = " << fPitchX; + LOG(info) << ">> fPitchY = " << fPitchY; - fHits = new TClonesArray("PixelHit",10000); + fHits = new TClonesArray("PixelHit", 10000); - return; + return; } -void PixelAltFindHits::ExecMQ(TList* inputList,TList* outputList) +void PixelAltFindHits::ExecMQ(TList* inputList, TList* outputList) { - // LOG(info) << "********************************************** PixelAltFindHits::ExecMQ(" << inputList->GetName() << "," << outputList->GetName() << "), Event " << fTNofEvents; - // LOG(info) << "********************************************** PixelAltFindHits::ExecMQ(), Event " << fTNofEvents; - // LOG(info) << "h" << FairLogger::flush; - fDigis = (TClonesArray*) inputList->FindObject("PixelDigis"); - outputList->Add(fHits); - Exec(""); - return; + // LOG(info) << "********************************************** PixelAltFindHits::ExecMQ(" << inputList->GetName() + // << "," << outputList->GetName() << "), Event " << fTNofEvents; LOG(info) << + // "********************************************** PixelAltFindHits::ExecMQ(), Event " << fTNofEvents; LOG(info) << + // "h" << FairLogger::flush; + fDigis = (TClonesArray*)inputList->FindObject("PixelDigis"); + outputList->Add(fHits); + Exec(""); + return; } void PixelAltFindHits::ExecMQ(PixelPayload::Digi* digiPalVector, @@ -207,71 +226,75 @@ void PixelAltFindHits::ExecMQ(PixelPayload::Digi* digiPalVector, PixelPayload::Hit* hitPalVector, int& nofHits) { - for (int idigi = 0 ; idigi < nofDigis ; idigi++) { - FindHit(digiPalVector[idigi].fDetectorID, - digiPalVector[idigi].fFeID, - digiPalVector[idigi].fCol, - digiPalVector[idigi].fRow, - idigi, - hitPalVector[idigi].posX, - hitPalVector[idigi].posY, - hitPalVector[idigi].posZ, - hitPalVector[idigi].dposX, - hitPalVector[idigi].dposY, - hitPalVector[idigi].dposZ); - hitPalVector[idigi].fDetectorID = digiPalVector[idigi].fDetectorID; - nofHits++; - } - return; + for (int idigi = 0; idigi < nofDigis; idigi++) { + FindHit(digiPalVector[idigi].fDetectorID, + digiPalVector[idigi].fFeID, + digiPalVector[idigi].fCol, + digiPalVector[idigi].fRow, + idigi, + hitPalVector[idigi].posX, + hitPalVector[idigi].posY, + hitPalVector[idigi].posZ, + hitPalVector[idigi].dposX, + hitPalVector[idigi].dposY, + hitPalVector[idigi].dposZ); + hitPalVector[idigi].fDetectorID = digiPalVector[idigi].fDetectorID; + nofHits++; + } + return; } InitStatus PixelAltFindHits::Init() { - // Get input array - FairRootManager* ioman = FairRootManager::Instance(); + // Get input array + FairRootManager* ioman = FairRootManager::Instance(); - if (!ioman) LOG(fatal) << "No FairRootManager"; - fDigis = static_cast(ioman->GetObject("PixelDigis")); + if (!ioman) + LOG(fatal) << "No FairRootManager"; + fDigis = static_cast(ioman->GetObject("PixelDigis")); - if (!fDigis) - LOG(warn) << "PixelAltFindHits::Init() No input PixelDigis array!"; + if (!fDigis) + LOG(warn) << "PixelAltFindHits::Init() No input PixelDigis array!"; - // Register output array PixelHit - fHits = new TClonesArray("PixelHit",10000); - ioman->Register("PixelHits", "Pixel", fHits, kTRUE); + // Register output array PixelHit + fHits = new TClonesArray("PixelHit", 10000); + ioman->Register("PixelHits", "Pixel", fHits, kTRUE); - LOG(info) << "-I- " << fName.Data() << "::Init(). Initialization succesfull."; + LOG(info) << "-I- " << fName.Data() << "::Init(). Initialization succesfull."; - fFeCols = fDigiPar->GetFECols(); - fFeRows = fDigiPar->GetFERows(); - fMaxFEperCol = fDigiPar->GetMaxFEperCol(); - fPitchX = fDigiPar->GetXPitch(); - fPitchY = fDigiPar->GetYPitch(); + fFeCols = fDigiPar->GetFECols(); + fFeRows = fDigiPar->GetFERows(); + fMaxFEperCol = fDigiPar->GetMaxFEperCol(); + fPitchX = fDigiPar->GetXPitch(); + fPitchY = fDigiPar->GetYPitch(); - LOG(info) << "PixelAltFindHits::SetParContainers() Pixel detector with pitch size " << fPitchX << "cm x" << fPitchY << "cm"; + LOG(info) << "PixelAltFindHits::SetParContainers() Pixel detector with pitch size " << fPitchX << "cm x" << fPitchY + << "cm"; - return kSUCCESS; + return kSUCCESS; } -InitStatus PixelAltFindHits::ReInit() -{ - return kSUCCESS; -} +InitStatus PixelAltFindHits::ReInit() { return kSUCCESS; } -void PixelAltFindHits::Reset() { - fNDigis = fNHits = 0; - if (fHits) fHits->Clear(); +void PixelAltFindHits::Reset() +{ + fNDigis = fNHits = 0; + if (fHits) + fHits->Clear(); } void PixelAltFindHits::Finish() { - if (fHits) fHits->Delete(); - - LOG(info) << "-------------------- " << fName.Data() << " : Summary ------------------------"; - LOG(info) << " Events: " << fTNofEvents; - LOG(info) << " Digis: " << fTNofDigis << " (" << static_cast(fTNofDigis) /(static_cast(fTNofEvents)) << " per event)"; - LOG(info) << " Hits: " << fTNofHits << " (" << static_cast(fTNofHits )/(static_cast(fTNofEvents)) << " per event)"; - LOG(info) << "---------------------------------------------------------------------"; + if (fHits) + fHits->Delete(); + + LOG(info) << "-------------------- " << fName.Data() << " : Summary ------------------------"; + LOG(info) << " Events: " << fTNofEvents; + LOG(info) << " Digis: " << fTNofDigis << " (" + << static_cast(fTNofDigis) / (static_cast(fTNofEvents)) << " per event)"; + LOG(info) << " Hits: " << fTNofHits << " (" + << static_cast(fTNofHits) / (static_cast(fTNofEvents)) << " per event)"; + LOG(info) << "---------------------------------------------------------------------"; } -ClassImp(PixelAltFindHits) +ClassImp(PixelAltFindHits); diff --git a/examples/MQ/pixelAlternative/src/PixelAltFindHits.h b/examples/MQ/pixelAlternative/src/PixelAltFindHits.h index fb62a99996..e16d7f43d3 100644 --- a/examples/MQ/pixelAlternative/src/PixelAltFindHits.h +++ b/examples/MQ/pixelAlternative/src/PixelAltFindHits.h @@ -16,7 +16,6 @@ #define PIXELALTFINDHITS_H 1 #include "FairTask.h" - #include "PixelPayload.h" #include @@ -45,15 +44,15 @@ class PixelAltFindHits : public FairTask virtual void GetParList(TList* tempList); virtual void InitMQ(TList* tempList); - virtual void ExecMQ(TList* inputList,TList* outputList); - virtual void ExecMQ(PixelPayload::Digi *digiPalVector, int nofDigis, PixelPayload::Hit* hitPalVector, int& nofHits); + virtual void ExecMQ(TList* inputList, TList* outputList); + virtual void ExecMQ(PixelPayload::Digi* digiPalVector, int nofDigis, PixelPayload::Hit* hitPalVector, int& nofHits); private: PixelDigiPar* fDigiPar; FairGeoParSet* fGeoParSet; TClonesArray* fDigis; /** Input array of PixelDigi **/ - TClonesArray* fHits; /** Output array of PixelHit **/ + TClonesArray* fHits; /** Output array of PixelHit **/ Int_t fNDigis; Int_t fNHits; @@ -62,15 +61,23 @@ class PixelAltFindHits : public FairTask Int_t fTNofDigis; Int_t fTNofHits; - Int_t fFeCols; // Colums read per Frontend - Int_t fFeRows; // Rows read per Frontend - Int_t fMaxFEperCol; // max number of Frontend elemens per column - Double_t fPitchX; // Pixel cell size X - Double_t fPitchY; // Pixel cell size Y - - Int_t FindHit(Int_t detId, Int_t feId, Int_t col, Int_t row, Int_t index, - Double_t& posX, Double_t& posY, Double_t& posZ, - Double_t& errX, Double_t& errY, Double_t& errZ); + Int_t fFeCols; // Colums read per Frontend + Int_t fFeRows; // Rows read per Frontend + Int_t fMaxFEperCol; // max number of Frontend elemens per column + Double_t fPitchX; // Pixel cell size X + Double_t fPitchY; // Pixel cell size Y + + Int_t FindHit(Int_t detId, + Int_t feId, + Int_t col, + Int_t row, + Int_t index, + Double_t& posX, + Double_t& posY, + Double_t& posZ, + Double_t& errX, + Double_t& errY, + Double_t& errZ); /** Get parameter containers **/ virtual void SetParContainers(); @@ -90,7 +97,7 @@ class PixelAltFindHits : public FairTask PixelAltFindHits(const PixelAltFindHits&); PixelAltFindHits& operator=(const PixelAltFindHits&); - ClassDef(PixelAltFindHits,1); + ClassDef(PixelAltFindHits, 1); }; #endif diff --git a/examples/MQ/pixelAlternative/src/devices/FairMQPixAltFileSinkBin.cxx b/examples/MQ/pixelAlternative/src/devices/FairMQPixAltFileSinkBin.cxx index 422a3b826e..be4c283b4b 100644 --- a/examples/MQ/pixelAlternative/src/devices/FairMQPixAltFileSinkBin.cxx +++ b/examples/MQ/pixelAlternative/src/devices/FairMQPixAltFileSinkBin.cxx @@ -13,83 +13,82 @@ */ #include "FairMQPixAltFileSinkBin.h" -#include #include "PixelPayload.h" +#include + using namespace std; FairMQPixAltFileSinkBin::FairMQPixAltFileSinkBin() - : fInputChannelName("data-in") - , fAckChannelName("") - , fFileName() - , fOutFile(nullptr) -{ -} + : fInputChannelName("data-in") + , fAckChannelName("") + , fFileName() + , fOutFile(nullptr) +{} void FairMQPixAltFileSinkBin::Init() { - fFileName = fConfig->GetValue("file-name"); - fInputChannelName = fConfig->GetValue("in-channel"); - fAckChannelName = fConfig->GetValue("ack-channel"); + fFileName = fConfig->GetValue("file-name"); + fInputChannelName = fConfig->GetValue("in-channel"); + fAckChannelName = fConfig->GetValue("ack-channel"); - LOG(info) << "SHOULD CREATE THE FILE AND TREE"; + LOG(info) << "SHOULD CREATE THE FILE AND TREE"; - fOutFile.open(fFileName, std::fstream::out|std::fstream::binary); + fOutFile.open(fFileName, std::fstream::out | std::fstream::binary); - OnData(fInputChannelName, &FairMQPixAltFileSinkBin::StoreData); + OnData(fInputChannelName, &FairMQPixAltFileSinkBin::StoreData); } bool FairMQPixAltFileSinkBin::StoreData(FairMQParts& parts, int /*index*/) { - if (parts.Size() == 0) return true; // probably impossible, but still check - - // the first part should be the event header - PixelPayload::EventHeader* payloadE = static_cast(parts.At(0)->GetData()); - - // LOG(debug) << "GOT EVENT " << payloadE->fMCEntryNo << " OF RUN " << payloadE->fRunId << " (part " << payloadE->fPartNo << ")"; - - // the second part should be the array of PixelPayload::Hit - PixelPayload::Hit* payloadH = static_cast(parts.At(1)->GetData()); - int hitArraySize = parts.At(1)->GetSize(); - int nofHits = hitArraySize / sizeof(PixelPayload::Hit); - - fOutFile.write((char*)&(payloadE->fRunId) , sizeof(payloadE->fRunId)); - fOutFile.write((char*)&(payloadE->fMCEntryNo), sizeof(payloadE->fMCEntryNo)); - fOutFile.write((char*)&(payloadE->fPartNo) , sizeof(payloadE->fPartNo)); - fOutFile.write((char*)&nofHits , sizeof(nofHits)); - - float posX, posY, posZ, dposX, dposY, dposZ; - for (int ihit = 0 ; ihit < nofHits ; ihit++) { - posX = (float)payloadH->posX; - posY = (float)payloadH->posY; - posZ = (float)payloadH->posZ; - dposX = (float)payloadH->dposX; - dposY = (float)payloadH->dposY; - dposZ = (float)payloadH->dposZ; - fOutFile.write(reinterpret_cast(&(payloadH->fDetectorID)), sizeof(payloadH->fDetectorID)); - // fOutFile.write(reinterpret_cast(&(payloadH->posX)), sizeof(payloadH->posX)); - // fOutFile.write(reinterpret_cast(&(payloadH->posY)), sizeof(payloadH->posY)); - // fOutFile.write(reinterpret_cast(&(payloadH->posZ)), sizeof(payloadH->posZ)); - // fOutFile.write(reinterpret_cast(&(payloadH->dposX)), sizeof(payloadH->dposX)); - // fOutFile.write(reinterpret_cast(&(payloadH->dposY)), sizeof(payloadH->dposY)); - // fOutFile.write(reinterpret_cast(&(payloadH->dposZ)), sizeof(payloadH->dposZ)); - fOutFile.write(reinterpret_cast(&posX), sizeof(posX)); - fOutFile.write(reinterpret_cast(&posY), sizeof(posY)); - fOutFile.write(reinterpret_cast(&posZ), sizeof(posZ)); - fOutFile.write(reinterpret_cast(&dposX), sizeof(dposX)); - fOutFile.write(reinterpret_cast(&dposY), sizeof(dposY)); - fOutFile.write(reinterpret_cast(&dposZ), sizeof(dposZ)); - } - - if (fAckChannelName != "") { - unique_ptr msg(NewMessage()); - Send(msg, fAckChannelName); - } - return true; + if (parts.Size() == 0) + return true; // probably impossible, but still check + + // the first part should be the event header + PixelPayload::EventHeader* payloadE = static_cast(parts.At(0)->GetData()); + + // LOG(debug) << "GOT EVENT " << payloadE->fMCEntryNo << " OF RUN " << payloadE->fRunId << " (part " << + // payloadE->fPartNo << ")"; + + // the second part should be the array of PixelPayload::Hit + PixelPayload::Hit* payloadH = static_cast(parts.At(1)->GetData()); + int hitArraySize = parts.At(1)->GetSize(); + int nofHits = hitArraySize / sizeof(PixelPayload::Hit); + + fOutFile.write((char*)&(payloadE->fRunId), sizeof(payloadE->fRunId)); + fOutFile.write((char*)&(payloadE->fMCEntryNo), sizeof(payloadE->fMCEntryNo)); + fOutFile.write((char*)&(payloadE->fPartNo), sizeof(payloadE->fPartNo)); + fOutFile.write((char*)&nofHits, sizeof(nofHits)); + + float posX, posY, posZ, dposX, dposY, dposZ; + for (int ihit = 0; ihit < nofHits; ihit++) { + posX = (float)payloadH->posX; + posY = (float)payloadH->posY; + posZ = (float)payloadH->posZ; + dposX = (float)payloadH->dposX; + dposY = (float)payloadH->dposY; + dposZ = (float)payloadH->dposZ; + fOutFile.write(reinterpret_cast(&(payloadH->fDetectorID)), sizeof(payloadH->fDetectorID)); + // fOutFile.write(reinterpret_cast(&(payloadH->posX)), sizeof(payloadH->posX)); + // fOutFile.write(reinterpret_cast(&(payloadH->posY)), sizeof(payloadH->posY)); + // fOutFile.write(reinterpret_cast(&(payloadH->posZ)), sizeof(payloadH->posZ)); + // fOutFile.write(reinterpret_cast(&(payloadH->dposX)), sizeof(payloadH->dposX)); + // fOutFile.write(reinterpret_cast(&(payloadH->dposY)), sizeof(payloadH->dposY)); + // fOutFile.write(reinterpret_cast(&(payloadH->dposZ)), sizeof(payloadH->dposZ)); + fOutFile.write(reinterpret_cast(&posX), sizeof(posX)); + fOutFile.write(reinterpret_cast(&posY), sizeof(posY)); + fOutFile.write(reinterpret_cast(&posZ), sizeof(posZ)); + fOutFile.write(reinterpret_cast(&dposX), sizeof(dposX)); + fOutFile.write(reinterpret_cast(&dposY), sizeof(dposY)); + fOutFile.write(reinterpret_cast(&dposZ), sizeof(dposZ)); + } + + if (fAckChannelName != "") { + unique_ptr msg(NewMessage()); + Send(msg, fAckChannelName); + } + return true; } -FairMQPixAltFileSinkBin::~FairMQPixAltFileSinkBin() -{ - fOutFile.close(); -} +FairMQPixAltFileSinkBin::~FairMQPixAltFileSinkBin() { fOutFile.close(); } diff --git a/examples/MQ/pixelAlternative/src/devices/FairMQPixAltFileSinkBin.h b/examples/MQ/pixelAlternative/src/devices/FairMQPixAltFileSinkBin.h index 2b5677a9a6..502bd6e1ba 100644 --- a/examples/MQ/pixelAlternative/src/devices/FairMQPixAltFileSinkBin.h +++ b/examples/MQ/pixelAlternative/src/devices/FairMQPixAltFileSinkBin.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /** @@ -16,7 +16,6 @@ #define FAIRMQPIXALTFILESINKBIN_H_ #include - #include #include @@ -27,7 +26,7 @@ class FairMQPixAltFileSinkBin : public FairMQDevice virtual ~FairMQPixAltFileSinkBin(); void SetOutputFileName(const std::string& tempString) { fFileName = tempString; } - std::string GetOutputFileName() { return fFileName;} + std::string GetOutputFileName() { return fFileName; } void SetInputChannelName(const std::string& tstr) { fInputChannelName = tstr; } void SetAckChannelName(const std::string& tstr) { fAckChannelName = tstr; } diff --git a/examples/MQ/pixelAlternative/src/devices/FairMQPixAltSamplerBin.cxx b/examples/MQ/pixelAlternative/src/devices/FairMQPixAltSamplerBin.cxx index 181545e333..0a1a0f4732 100644 --- a/examples/MQ/pixelAlternative/src/devices/FairMQPixAltSamplerBin.cxx +++ b/examples/MQ/pixelAlternative/src/devices/FairMQPixAltSamplerBin.cxx @@ -14,247 +14,248 @@ #include "FairMQPixAltSamplerBin.h" -#include -#include - #include #include - +#include +#include #include #include using namespace std; FairMQPixAltSamplerBin::FairMQPixAltSamplerBin() - : FairMQDevice() - , fOutputChannelName("data-out") - , fAckChannelName("") - , fFileNames() - , fInputFile() - , fCurrentFile(0) - , fInputChain(nullptr) - , fEventHeader(nullptr) - , fDigiBranch(nullptr) - , fDigiArray(nullptr) - , fAggregateLevel(1) - , fMaxIndex(-1) - , fEventCounter(0) - , fNofRecAcks(0) - , fReadingRootFiles(false) - , fAckListener() -{ -} + : FairMQDevice() + , fOutputChannelName("data-out") + , fAckChannelName("") + , fFileNames() + , fInputFile() + , fCurrentFile(0) + , fInputChain(nullptr) + , fEventHeader(nullptr) + , fDigiBranch(nullptr) + , fDigiArray(nullptr) + , fAggregateLevel(1) + , fMaxIndex(-1) + , fEventCounter(0) + , fNofRecAcks(0) + , fReadingRootFiles(false) + , fAckListener() +{} void FairMQPixAltSamplerBin::InitTask() { - fFileNames = fConfig->GetValue>("file-name"); - fMaxIndex = fConfig->GetValue ("max-index"); //RK 2818.05.28 int64_t will print "Unknown value", but the value is still passed - fOutputChannelName = fConfig->GetValue ("out-channel"); - fAckChannelName = fConfig->GetValue ("ack-channel"); - fAggregateLevel = fConfig->GetValue ("aggregate"); + fFileNames = fConfig->GetValue>("file-name"); + fMaxIndex = fConfig->GetValue( + "max-index"); // RK 2818.05.28 int64_t will print "Unknown value", but the value is still passed + fOutputChannelName = fConfig->GetValue("out-channel"); + fAckChannelName = fConfig->GetValue("ack-channel"); + fAggregateLevel = fConfig->GetValue("aggregate"); } void FairMQPixAltSamplerBin::PreRun() { - if (fAggregateLevel < 1) fAggregateLevel = 1; + if (fAggregateLevel < 1) + fAggregateLevel = 1; - LOG(info) << "FairMQPixAltSamplerBin::PreRun() started. fAggregateLevel = " << fAggregateLevel; + LOG(info) << "FairMQPixAltSamplerBin::PreRun() started. fAggregateLevel = " << fAggregateLevel; - fReadingRootFiles = false; + fReadingRootFiles = false; - fAckListener = std::thread(&FairMQPixAltSamplerBin::ListenForAcks, this); + fAckListener = std::thread(&FairMQPixAltSamplerBin::ListenForAcks, this); - if (fFileNames.size() == 0) return; + if (fFileNames.size() == 0) + return; - if (fFileNames[0].find(".root") == std::string::npos) return; + if (fFileNames[0].find(".root") == std::string::npos) + return; - fInputChain = new TChain("fairdata"); + fInputChain = new TChain("fairdata"); - for (int ifile = 0 ; ifile < (int)fFileNames.size() ; ifile++) { - fInputChain->Add(fFileNames[ifile].c_str()); - } + for (int ifile = 0; ifile < (int)fFileNames.size(); ifile++) { + fInputChain->Add(fFileNames[ifile].c_str()); + } - fEventHeader = new PixelPayload::EventHeader(); - fInputChain->SetBranchAddress("EventHeader.",&fEventHeader); - fInputChain->SetBranchAddress("DigiVector",&fDigiArray,&fDigiBranch); + fEventHeader = new PixelPayload::EventHeader(); + fInputChain->SetBranchAddress("EventHeader.", &fEventHeader); + fInputChain->SetBranchAddress("DigiVector", &fDigiArray, &fDigiBranch); - LOG(info) << "Loaded " << fFileNames.size() << " root files. Chain has now " << fInputChain->GetEntriesFast() << " entries"; - fReadingRootFiles = true; + LOG(info) << "Loaded " << fFileNames.size() << " root files. Chain has now " << fInputChain->GetEntriesFast() + << " entries"; + fReadingRootFiles = true; } bool FairMQPixAltSamplerBin::ConditionalRun() { - if (fReadingRootFiles) { - return ReadRootFile(); - } else { - return ReadBinFile(); - } + if (fReadingRootFiles) { + return ReadRootFile(); + } else { + return ReadBinFile(); + } } bool FairMQPixAltSamplerBin::ReadBinFile() { - FairMQParts parts; + FairMQParts parts; - for (int iaggr = 0 ; iaggr < fAggregateLevel ; iaggr++) { + for (int iaggr = 0; iaggr < fAggregateLevel; iaggr++) { - if (fEventCounter == fMaxIndex) { // check if reached event limit - if (parts.Size() > 0) { - Send(parts, fOutputChannelName); - } - return false; - } + if (fEventCounter == fMaxIndex) { // check if reached event limit + if (parts.Size() > 0) { + Send(parts, fOutputChannelName); + } + return false; + } - if (!fInputFile.is_open()) { // file not there - if (fCurrentFile == (int)fFileNames.size()) { // this is last file - if (parts.Size() > 0) { - Send(parts, fOutputChannelName); + if (!fInputFile.is_open()) { // file not there + if (fCurrentFile == (int)fFileNames.size()) { // this is last file + if (parts.Size() > 0) { + Send(parts, fOutputChannelName); + } + return false; + } + fInputFile.open(fFileNames[fCurrentFile], std::fstream::in | std::fstream::binary); + fCurrentFile++; } - return false; - } - fInputFile.open(fFileNames[fCurrentFile],std::fstream::in|std::fstream::binary); - fCurrentFile++; - } - if (!fInputFile.is_open()) { // wrong file name - LOG(error) << "FairMQPixAltSamplerBin::ConditionalRun fInputFile \"" << fFileNames[fCurrentFile] << "\" could not be open!"; - if (parts.Size() > 0) { - Send(parts, fOutputChannelName); - } - return false; - } + if (!fInputFile.is_open()) { // wrong file name + LOG(error) << "FairMQPixAltSamplerBin::ConditionalRun fInputFile \"" << fFileNames[fCurrentFile] + << "\" could not be open!"; + if (parts.Size() > 0) { + Send(parts, fOutputChannelName); + } + return false; + } - std::string buffer; + std::string buffer; + + int head[4]; // runId, MCEntryNo, PartNo, NofDigis + fInputFile.read((char*)head, sizeof(head)); + + if (fInputFile.eof()) { + LOG(info) << "End of file reached!"; + fInputFile.close(); + if (fCurrentFile == (int)fFileNames.size()) { // this is the last file + if (parts.Size() > 0) { + Send(parts, fOutputChannelName); + } + return false; + } else + return true; + } - int head[4]; // runId, MCEntryNo, PartNo, NofDigis - fInputFile.read((char*)head,sizeof(head)); + int dataSize = 4; // detId, feId, col, row + const int constNofData = head[3] * dataSize; + short int dataCont[constNofData]; + fInputFile.read((char*)dataCont, sizeof(dataCont)); + + PixelPayload::EventHeader* header = new PixelPayload::EventHeader(); + header->fRunId = head[0]; + header->fMCEntryNo = head[1]; + header->fPartNo = head[2]; + FairMQMessagePtr msgHeader( + NewMessage(header, sizeof(PixelPayload::EventHeader), [](void* data, void* /*hint*/) { + delete static_cast(data); + })); + parts.AddPart(std::move(msgHeader)); + + size_t digisSize = head[3] * sizeof(PixelPayload::Digi); + + FairMQMessagePtr msgDigis(NewMessage(digisSize)); + + PixelPayload::Digi* digiPayload = static_cast(msgDigis->GetData()); + + for (int idigi = 0; idigi < head[3]; idigi++) { + new (&digiPayload[idigi]) PixelPayload::Digi(); + digiPayload[idigi].fDetectorID = (int)dataCont[idigi * dataSize + 0]; + digiPayload[idigi].fFeID = (int)dataCont[idigi * dataSize + 1]; + digiPayload[idigi].fCharge = 1.; + digiPayload[idigi].fCol = (int)dataCont[idigi * dataSize + 2]; + digiPayload[idigi].fRow = (int)dataCont[idigi * dataSize + 3]; + } + parts.AddPart(std::move(msgDigis)); + + fEventCounter++; + } + + Send(parts, fOutputChannelName); if (fInputFile.eof()) { - LOG(info) << "End of file reached!"; - fInputFile.close(); - if (fCurrentFile == (int)fFileNames.size()) { // this is the last file - if (parts.Size() > 0) { - Send(parts, fOutputChannelName); - } - return false; - } - else - return true; + LOG(info) << "End of file reached!"; + fInputFile.close(); } - int dataSize = 4; // detId, feId, col, row - const int constNofData = head[3]*dataSize; - short int dataCont[constNofData]; - fInputFile.read((char*)dataCont,sizeof(dataCont)); + return true; +} + +bool FairMQPixAltSamplerBin::ReadRootFile() +{ + if (fEventCounter == fMaxIndex) + return false; + + // fill the input data containers + fInputChain->GetEntry(fEventCounter); + fDigiBranch->GetEntry(fEventCounter); + + // create output multipart message + FairMQParts parts; PixelPayload::EventHeader* header = new PixelPayload::EventHeader(); - header->fRunId = head[0]; - header->fMCEntryNo = head[1]; - header->fPartNo = head[2]; - FairMQMessagePtr msgHeader(NewMessage(header, - sizeof(PixelPayload::EventHeader), - [](void* data, void* /*hint*/) { delete static_cast(data); } - )); + header->fRunId = fEventHeader->fRunId; + header->fMCEntryNo = fEventHeader->fMCEntryNo; + header->fPartNo = fEventHeader->fPartNo; + FairMQMessagePtr msgHeader(NewMessage(header, sizeof(PixelPayload::EventHeader), [](void* data, void* /*hint*/) { + delete static_cast(data); + })); parts.AddPart(std::move(msgHeader)); - size_t digisSize = head[3] * sizeof(PixelPayload::Digi); - - FairMQMessagePtr msgDigis(NewMessage(digisSize)); + size_t digisSize = sizeof(PixelPayload::Digi) * fDigiArray->size(); + FairMQMessagePtr msgDigis(NewMessage(digisSize)); PixelPayload::Digi* digiPayload = static_cast(msgDigis->GetData()); - for (int idigi = 0 ; idigi < head[3] ; idigi++) { - new (&digiPayload[idigi]) PixelPayload::Digi(); - digiPayload[idigi].fDetectorID = (int)dataCont[idigi*dataSize+0]; - digiPayload[idigi].fFeID = (int)dataCont[idigi*dataSize+1]; - digiPayload[idigi].fCharge = 1.; - digiPayload[idigi].fCol = (int)dataCont[idigi*dataSize+2]; - digiPayload[idigi].fRow = (int)dataCont[idigi*dataSize+3]; + for (int idigi = 0; idigi < (int)fDigiArray->size(); idigi++) { + new (&digiPayload[idigi]) PixelPayload::Digi(); + digiPayload[idigi].fDetectorID = fDigiArray->at(idigi).fDetectorID; + digiPayload[idigi].fFeID = fDigiArray->at(idigi).fFeID; + digiPayload[idigi].fCharge = fDigiArray->at(idigi).fCharge; + digiPayload[idigi].fCol = fDigiArray->at(idigi).fCol; + digiPayload[idigi].fRow = fDigiArray->at(idigi).fRow; } parts.AddPart(std::move(msgDigis)); - fEventCounter++; - } - - Send(parts, fOutputChannelName); + Send(parts, fOutputChannelName); - if (fInputFile.eof()) { - LOG(info) << "End of file reached!"; - fInputFile.close(); - } + fEventCounter++; - return true; -} + if (fInputFile.eof()) { + LOG(info) << "End of file reached!"; + fInputFile.close(); + } -bool FairMQPixAltSamplerBin::ReadRootFile() -{ - if (fEventCounter == fMaxIndex) return false; - - // fill the input data containers - fInputChain->GetEntry(fEventCounter); - fDigiBranch->GetEntry(fEventCounter); - - // create output multipart message - FairMQParts parts; - - PixelPayload::EventHeader* header = new PixelPayload::EventHeader(); - header->fRunId = fEventHeader->fRunId; - header->fMCEntryNo = fEventHeader->fMCEntryNo; - header->fPartNo = fEventHeader->fPartNo; - FairMQMessagePtr msgHeader(NewMessage(header, - sizeof(PixelPayload::EventHeader), - [](void* data, void* /*hint*/) { delete static_cast(data); } - )); - parts.AddPart(std::move(msgHeader)); - - size_t digisSize = sizeof(PixelPayload::Digi)*fDigiArray->size(); - - FairMQMessagePtr msgDigis(NewMessage(digisSize)); - PixelPayload::Digi* digiPayload = static_cast(msgDigis->GetData()); - - for (int idigi = 0 ; idigi < (int)fDigiArray->size() ; idigi++) { - new (&digiPayload[idigi]) PixelPayload::Digi(); - digiPayload[idigi].fDetectorID = fDigiArray->at(idigi).fDetectorID; - digiPayload[idigi].fFeID = fDigiArray->at(idigi).fFeID; - digiPayload[idigi].fCharge = fDigiArray->at(idigi).fCharge; - digiPayload[idigi].fCol = fDigiArray->at(idigi).fCol; - digiPayload[idigi].fRow = fDigiArray->at(idigi).fRow; - } - parts.AddPart(std::move(msgDigis)); - - Send(parts, fOutputChannelName); - - fEventCounter++; - - if (fInputFile.eof()) { - LOG(info) << "End of file reached!"; - fInputFile.close(); - } - - return true; + return true; } void FairMQPixAltSamplerBin::PostRun() { - if (fAckChannelName != "") { - fAckListener.join(); - } - LOG(info) << "PostRun() finished!"; + if (fAckChannelName != "") { + fAckListener.join(); + } + LOG(info) << "PostRun() finished!"; } void FairMQPixAltSamplerBin::ListenForAcks() { - if (fAckChannelName != "") { - do { - FairMQMessagePtr ack(NewMessage()); - if (Receive(ack, fAckChannelName) >= 0) { - fNofRecAcks++; - } - } while (fNofRecAcks < fMaxIndex/fAggregateLevel); - - LOG(info) << "Acknowledged " << fNofRecAcks << " messages (" << fAggregateLevel << " events each) out of " << fMaxIndex << " events."; - } + if (fAckChannelName != "") { + do { + FairMQMessagePtr ack(NewMessage()); + if (Receive(ack, fAckChannelName) >= 0) { + fNofRecAcks++; + } + } while (fNofRecAcks < fMaxIndex / fAggregateLevel); + + LOG(info) << "Acknowledged " << fNofRecAcks << " messages (" << fAggregateLevel << " events each) out of " + << fMaxIndex << " events."; + } } -FairMQPixAltSamplerBin::~FairMQPixAltSamplerBin() -{ -} +FairMQPixAltSamplerBin::~FairMQPixAltSamplerBin() {} diff --git a/examples/MQ/pixelAlternative/src/devices/FairMQPixAltSamplerBin.h b/examples/MQ/pixelAlternative/src/devices/FairMQPixAltSamplerBin.h index 4d64d62cae..f799004ab5 100644 --- a/examples/MQ/pixelAlternative/src/devices/FairMQPixAltSamplerBin.h +++ b/examples/MQ/pixelAlternative/src/devices/FairMQPixAltSamplerBin.h @@ -18,12 +18,11 @@ #include "PixelPayload.h" #include - +#include +#include #include #include -#include #include -#include class TBranch; class TChain; diff --git a/examples/MQ/pixelAlternative/src/devices/FairMQPixAltTaskProcessorBin.h b/examples/MQ/pixelAlternative/src/devices/FairMQPixAltTaskProcessorBin.h index 94f6248957..75b16dbeec 100644 --- a/examples/MQ/pixelAlternative/src/devices/FairMQPixAltTaskProcessorBin.h +++ b/examples/MQ/pixelAlternative/src/devices/FairMQPixAltTaskProcessorBin.h @@ -9,21 +9,18 @@ #ifndef FAIRMQPIXALTTASKPROCESSORBIN_H_ #define FAIRMQPIXALTTASKPROCESSORBIN_H_ -#include - #include "FairEventHeader.h" #include "FairGeoParSet.h" #include "FairParGenericSet.h" +#include "PixelDigi.h" +#include "PixelPayload.h" +#include "RootSerializer.h" #include #include - #include #include -#include "RootSerializer.h" - -#include "PixelPayload.h" -#include "PixelDigi.h" +#include template class FairMQPixAltTaskProcessorBin : public FairMQDevice @@ -52,11 +49,11 @@ class FairMQPixAltTaskProcessorBin : public FairMQDevice delete fFairTask; } - void SetDataToKeep(const std::string& tStr) { fDataToKeep = tStr;} + void SetDataToKeep(const std::string& tStr) { fDataToKeep = tStr; } - void SetInputChannelName(const std::string& tstr) {fInputChannelName = tstr;} - void SetOutputChannelName(const std::string& tstr) {fOutputChannelName = tstr;} - void SetParamChannelName(const std::string& tstr) {fParamChannelName = tstr;} + void SetInputChannelName(const std::string& tstr) { fInputChannelName = tstr; } + void SetOutputChannelName(const std::string& tstr) { fOutputChannelName = tstr; } + void SetParamChannelName(const std::string& tstr) { fParamChannelName = tstr; } protected: bool ProcessData(FairMQParts& parts, int) @@ -64,10 +61,11 @@ class FairMQPixAltTaskProcessorBin : public FairMQDevice // LOG(debug)<<"message received with " << parts.Size() << " parts!"; fReceivedMsgs++; - if (parts.Size() == 0) return 0; // probably impossible, but still check + if (parts.Size() == 0) + return 0; // probably impossible, but still check // expecting even number of parts in the form: header,data,header,data,header,data and so on... - int nPPE = 2; // nof parts per event + int nPPE = 2; // nof parts per event if (parts.Size() % nPPE >= 1) LOG(info) << "received " << parts.Size() << " parts, will ignore last part!!!"; @@ -75,14 +73,16 @@ class FairMQPixAltTaskProcessorBin : public FairMQDevice // creating output multipart message FairMQParts partsOut; - for (int ievent = 0 ; ievent < parts.Size()/nPPE ; ievent++) { + for (int ievent = 0; ievent < parts.Size() / nPPE; ievent++) { // the first part should be the event header - PixelPayload::EventHeader* payloadE = static_cast(parts.At(nPPE*ievent)->GetData()); - // LOG(debug) << "GOT EVENT " << payloadE->fMCEntryNo << " OF RUN " << payloadE->fRunId << " (part " << payloadE->fPartNo << ")"; + PixelPayload::EventHeader* payloadE = + static_cast(parts.At(nPPE * ievent)->GetData()); + // LOG(debug) << "GOT EVENT " << payloadE->fMCEntryNo << " OF RUN " << payloadE->fRunId << " (part " << + // payloadE->fPartNo << ")"; fNewRunId = payloadE->fRunId; if (fNewRunId != fCurrentRunId) { - fCurrentRunId=fNewRunId; + fCurrentRunId = fNewRunId; UpdateParameters(); fFairTask->InitMQ(fParCList); @@ -90,25 +90,25 @@ class FairMQPixAltTaskProcessorBin : public FairMQDevice } // the second part should the TClonesArray with necessary data... now assuming Digi - PixelPayload::Digi* payloadD = static_cast(parts.At(nPPE*ievent+1)->GetData()); - int digiArraySize = parts.At(nPPE*ievent+1)->GetSize(); - int nofDigis = digiArraySize / sizeof(PixelPayload::Digi); + PixelPayload::Digi* payloadD = static_cast(parts.At(nPPE * ievent + 1)->GetData()); + int digiArraySize = parts.At(nPPE * ievent + 1)->GetSize(); + int nofDigis = digiArraySize / sizeof(PixelPayload::Digi); // LOG(debug) << " EVENT HAS " << nofDigis << " DIGIS!!!"; // create eventHeader part PixelPayload::EventHeader* header = new PixelPayload::EventHeader(); - header->fRunId = payloadE->fRunId; + header->fRunId = payloadE->fRunId; header->fMCEntryNo = payloadE->fMCEntryNo; - header->fPartNo = payloadE->fPartNo; - FairMQMessagePtr msgHeader(NewMessage(header, - sizeof(PixelPayload::EventHeader), - [](void* data, void* /*hint*/) { delete static_cast(data); } - )); + header->fPartNo = payloadE->fPartNo; + FairMQMessagePtr msgHeader( + NewMessage(header, sizeof(PixelPayload::EventHeader), [](void* data, void* /*hint*/) { + delete static_cast(data); + })); partsOut.AddPart(std::move(msgHeader)); // create part with hits - int hitsSize = nofDigis*sizeof(PixelPayload::Hit); + int hitsSize = nofDigis * sizeof(PixelPayload::Hit); FairMQMessagePtr msgTCA = NewMessage(hitsSize); @@ -116,7 +116,7 @@ class FairMQPixAltTaskProcessorBin : public FairMQDevice // actually find hits int nofHits = 0; - fFairTask->ExecMQ(payloadD,nofDigis,hitPayload,nofHits); + fFairTask->ExecMQ(payloadD, nofDigis, hitPayload, nofHits); partsOut.AddPart(std::move(msgTCA)); } @@ -129,10 +129,10 @@ class FairMQPixAltTaskProcessorBin : public FairMQDevice virtual void Init() { - fDataToKeep = fConfig->GetValue("keep-data"); - fInputChannelName = fConfig->GetValue("in-channel"); + fDataToKeep = fConfig->GetValue("keep-data"); + fInputChannelName = fConfig->GetValue("in-channel"); fOutputChannelName = fConfig->GetValue("out-channel"); - fParamChannelName = fConfig->GetValue("par-channel"); + fParamChannelName = fConfig->GetValue("par-channel"); // fHitFinder->InitMQ(fRootParFileName,fAsciiParFileName); fFairTask = new T(); @@ -147,7 +147,8 @@ class FairMQPixAltTaskProcessorBin : public FairMQDevice virtual void PostRun() { - LOG(info) << "FairMQPixAltTaskProcessorBin::PostRun() Received " << fReceivedMsgs << " and sent " << fSentMsgs << " messages!"; + LOG(info) << "FairMQPixAltTaskProcessorBin::PostRun() Received " << fReceivedMsgs << " and sent " + << fSentMsgs << " messages!"; } private: @@ -157,10 +158,10 @@ class FairMQPixAltTaskProcessorBin : public FairMQDevice void UpdateParameters() { - for (int iparC = 0 ; iparC < fParCList->GetEntries() ; iparC++) { + for (int iparC = 0; iparC < fParCList->GetEntries(); iparC++) { FairParGenericSet* tempObj = (FairParGenericSet*)(fParCList->At(iparC)); fParCList->Remove(tempObj); - fParCList->AddAt(UpdateParameter(tempObj),iparC); + fParCList->AddAt(UpdateParameter(tempObj), iparC); } } @@ -169,18 +170,20 @@ class FairMQPixAltTaskProcessorBin : public FairMQDevice std::string paramName = thisPar->GetName(); std::string* reqStr = new std::string(paramName + "," + std::to_string(fCurrentRunId)); - LOG(warn) << "Requesting parameter \"" << paramName << "\" for Run ID " << fCurrentRunId << " (" << thisPar << ")"; - FairMQMessagePtr req(NewMessage(const_cast(reqStr->c_str()), - reqStr->length(), - [](void* /*data*/, void* obj){ delete static_cast(obj); }, - reqStr)); + LOG(warn) << "Requesting parameter \"" << paramName << "\" for Run ID " << fCurrentRunId << " (" << thisPar + << ")"; + FairMQMessagePtr req(NewMessage( + const_cast(reqStr->c_str()), + reqStr->length(), + [](void* /*data*/, void* obj) { delete static_cast(obj); }, + reqStr)); FairMQMessagePtr rep(NewMessage()); if (Send(req, fParamChannelName) > 0) { if (Receive(rep, fParamChannelName) > 0) { thisPar = nullptr; - Deserialize(*rep,thisPar); - LOG(info) << "Received parameter"<< paramName <<" from the server (" << thisPar << ")"; + Deserialize(*rep, thisPar); + LOG(info) << "Received parameter" << paramName << " from the server (" << thisPar << ")"; return thisPar; } } diff --git a/examples/MQ/pixelDetector/macros/eventDisplay.C b/examples/MQ/pixelDetector/macros/eventDisplay.C index 9b387c8f71..9ae181f700 100644 --- a/examples/MQ/pixelDetector/macros/eventDisplay.C +++ b/examples/MQ/pixelDetector/macros/eventDisplay.C @@ -5,35 +5,33 @@ * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ -eventDisplay(TString mcEngine="TGeant3") +eventDisplay(TString mcEngine = "TGeant3") { - //-----User Settings:----------------------------------------------- - TString InputFile ="pixel_" + mcEngine + ".mc.root"; - TString ParFile ="pixel_" + mcEngine + ".params.root"; - TString OutFile ="tst.root"; - //------------------------------------------------------------------ + //-----User Settings:----------------------------------------------- + TString InputFile = "pixel_" + mcEngine + ".mc.root"; + TString ParFile = "pixel_" + mcEngine + ".params.root"; + TString OutFile = "tst.root"; + //------------------------------------------------------------------ + // ----- Reconstruction run ------------------------------------------- + FairRunAna *fRun = new FairRunAna(); + FairRunAna *fRun = new FairRunAna(); + FairFileSource *fFileSource = new FairFileSource(InputFile); + fRun->SetSink(new FairRootFileSink(OutFile.Data())); - // ----- Reconstruction run ------------------------------------------- - FairRunAna *fRun= new FairRunAna(); - FairRunAna *fRun= new FairRunAna(); - FairFileSource *fFileSource = new FairFileSource(InputFile); - fRun->SetSink(new FairRootFileSink(OutFile.Data())); + FairRuntimeDb *rtdb = fRun->GetRuntimeDb(); + FairParRootFileIo *parInput1 = new FairParRootFileIo(); + parInput1->open(ParFile.Data()); + rtdb->setFirstInput(parInput1); - FairRuntimeDb* rtdb = fRun->GetRuntimeDb(); - FairParRootFileIo* parInput1 = new FairParRootFileIo(); - parInput1->open(ParFile.Data()); - rtdb->setFirstInput(parInput1); + FairEventManager *fMan = new FairEventManager(); - FairEventManager *fMan= new FairEventManager(); + //----------------------Traks and points ------------------------------------- + FairMCTracks *Track = new FairMCTracks("Monte-Carlo Tracks"); + FairMCPointDraw *TutorialDetectorPoints = new FairMCPointDraw("FairTutorialtDetPoint", kRed, kFullSquare); - //----------------------Traks and points ------------------------------------- - FairMCTracks *Track = new FairMCTracks("Monte-Carlo Tracks"); - FairMCPointDraw *TutorialDetectorPoints = new FairMCPointDraw("FairTutorialtDetPoint", kRed, kFullSquare); - - fMan->AddTask(Track); - fMan->AddTask(TutorialDetectorPoints); - - fMan->Init(); + fMan->AddTask(Track); + fMan->AddTask(TutorialDetectorPoints); + fMan->Init(); } diff --git a/examples/MQ/pixelDetector/macros/run_dAsciiSource.C b/examples/MQ/pixelDetector/macros/run_dAsciiSource.C index 0e4802dcfd..a2e113d49d 100644 --- a/examples/MQ/pixelDetector/macros/run_dAsciiSource.C +++ b/examples/MQ/pixelDetector/macros/run_dAsciiSource.C @@ -5,89 +5,87 @@ * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ -void run_dAsciiSource( TString mcEngine="TGeant3" ) +void run_dAsciiSource(TString mcEngine = "TGeant3") { - // Verbosity level (0=quiet, 1=event level, 2=track level, 3=debug) - Int_t iVerbose = 0; // just forget about it, for the moment + // Verbosity level (0=quiet, 1=event level, 2=track level, 3=debug) + Int_t iVerbose = 0; // just forget about it, for the moment - // Parameter file - TString parFile = "pixel_"; - parFile = parFile + mcEngine + ".params.root"; + // Parameter file + TString parFile = "pixel_"; + parFile = parFile + mcEngine + ".params.root"; - // Digitization parameter file - TString dir = getenv("VMCWORKDIR"); - TString tutdir = dir + "/MQ/pixelDetector"; - TString digParFile = tutdir + "/param/pixel_digi.par"; + // Digitization parameter file + TString dir = getenv("VMCWORKDIR"); + TString tutdir = dir + "/MQ/pixelDetector"; + TString digParFile = tutdir + "/param/pixel_digi.par"; - // Output file - TString outFile = "pixel_"; - outFile = outFile + mcEngine + ".viaAsciiSource.hits.root"; + // Output file + TString outFile = "pixel_"; + outFile = outFile + mcEngine + ".viaAsciiSource.hits.root"; - // ----- Timer -------------------------------------------------------- - TStopwatch timer; + // ----- Timer -------------------------------------------------------- + TStopwatch timer; - PixelEventHeader* pixelEventHeader = new PixelEventHeader(); + PixelEventHeader* pixelEventHeader = new PixelEventHeader(); - // ----- Reconstruction run ------------------------------------------- - FairRunAna *fRun= new FairRunAna(); - fRun->SetEventHeader(pixelEventHeader); - fRun->SetSink(new FairRootFileSink(outFile)); + // ----- Reconstruction run ------------------------------------------- + FairRunAna* fRun = new FairRunAna(); + fRun->SetEventHeader(pixelEventHeader); + fRun->SetSink(new FairRootFileSink(outFile)); - PixelDigiSource* digiSource = new PixelDigiSource("Pixel Digi Source"); - digiSource->SetInputFileName("digis.p0.dat"); + PixelDigiSource* digiSource = new PixelDigiSource("Pixel Digi Source"); + digiSource->SetInputFileName("digis.p0.dat"); - fRun->SetSource(digiSource); + fRun->SetSource(digiSource); - FairRuntimeDb* rtdb = fRun->GetRuntimeDb(); - FairParRootFileIo* parInput1 = new FairParRootFileIo(); - parInput1->open(parFile.Data()); + FairRuntimeDb* rtdb = fRun->GetRuntimeDb(); + FairParRootFileIo* parInput1 = new FairParRootFileIo(); + parInput1->open(parFile.Data()); - FairParAsciiFileIo* parIo1 = new FairParAsciiFileIo(); - parIo1->open(digParFile.Data(),"in"); + FairParAsciiFileIo* parIo1 = new FairParAsciiFileIo(); + parIo1->open(digParFile.Data(), "in"); - rtdb->setFirstInput(parInput1); - rtdb->setSecondInput(parIo1); + rtdb->setFirstInput(parInput1); + rtdb->setSecondInput(parIo1); - // ----- TorinoDetector hit producers --------------------------------- - // PixelDigiReadFromFile* digiRead = new PixelDigiReadFromFile(); - // fRun->AddTask(digiRead); + // ----- TorinoDetector hit producers --------------------------------- + // PixelDigiReadFromFile* digiRead = new PixelDigiReadFromFile(); + // fRun->AddTask(digiRead); - PixelFindHits* hitFinderTask = new PixelFindHits(); - fRun->AddTask(hitFinderTask); + PixelFindHits* hitFinderTask = new PixelFindHits(); + fRun->AddTask(hitFinderTask); + fRun->Init(); - fRun->Init(); + timer.Start(); + fRun->Run(); - timer.Start(); - fRun->Run(); + // ----- Finish ------------------------------------------------------- - // ----- Finish ------------------------------------------------------- + cout << endl << endl; - cout << endl << endl; + // Extract the maximal used memory an add is as Dart measurement + // This line is filtered by CTest and the value send to CDash + FairSystemInfo sysInfo; + Float_t maxMemory = sysInfo.GetMaxMemory(); + cout << ""; + cout << maxMemory; + cout << "" << endl; - // Extract the maximal used memory an add is as Dart measurement - // This line is filtered by CTest and the value send to CDash - FairSystemInfo sysInfo; - Float_t maxMemory=sysInfo.GetMaxMemory(); - cout << ""; - cout << maxMemory; - cout << "" << endl; + timer.Stop(); + Double_t rtime = timer.RealTime(); + Double_t ctime = timer.CpuTime(); - timer.Stop(); - Double_t rtime = timer.RealTime(); - Double_t ctime = timer.CpuTime(); + Float_t cpuUsage = ctime / rtime; + cout << ""; + cout << cpuUsage; + cout << "" << endl; - Float_t cpuUsage=ctime/rtime; - cout << ""; - cout << cpuUsage; - cout << "" << endl; + cout << endl << endl; + cout << "Output file is " << outFile << endl; + cout << "Parameter file is " << parFile << endl; + cout << "Real time " << rtime << " s, CPU time " << ctime << "s" << endl << endl; + cout << "Macro finished successfully." << endl; - cout << endl << endl; - cout << "Output file is " << outFile << endl; - cout << "Parameter file is " << parFile << endl; - cout << "Real time " << rtime << " s, CPU time " << ctime - << "s" << endl << endl; - cout << "Macro finished successfully." << endl; - - // ------------------------------------------------------------------------ + // ------------------------------------------------------------------------ } diff --git a/examples/MQ/pixelDetector/macros/run_dBinSource.C b/examples/MQ/pixelDetector/macros/run_dBinSource.C index f6a56a594c..ff3b52ed20 100644 --- a/examples/MQ/pixelDetector/macros/run_dBinSource.C +++ b/examples/MQ/pixelDetector/macros/run_dBinSource.C @@ -5,89 +5,87 @@ * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ -void run_dBinSource( TString mcEngine="TGeant3" ) +void run_dBinSource(TString mcEngine = "TGeant3") { - // Verbosity level (0=quiet, 1=event level, 2=track level, 3=debug) - Int_t iVerbose = 0; // just forget about it, for the moment + // Verbosity level (0=quiet, 1=event level, 2=track level, 3=debug) + Int_t iVerbose = 0; // just forget about it, for the moment - // Parameter file - TString parFile = "pixel_"; - parFile = parFile + mcEngine + ".params.root"; + // Parameter file + TString parFile = "pixel_"; + parFile = parFile + mcEngine + ".params.root"; - // Digitization parameter file - TString dir = getenv("VMCWORKDIR"); - TString tutdir = dir + "/MQ/pixelDetector"; - TString digParFile = tutdir + "/param/pixel_digi.par"; + // Digitization parameter file + TString dir = getenv("VMCWORKDIR"); + TString tutdir = dir + "/MQ/pixelDetector"; + TString digParFile = tutdir + "/param/pixel_digi.par"; - // Output file - TString outFile = "pixel_"; - outFile = outFile + mcEngine + ".viaBinSource.hits.root"; + // Output file + TString outFile = "pixel_"; + outFile = outFile + mcEngine + ".viaBinSource.hits.root"; - // ----- Timer -------------------------------------------------------- - TStopwatch timer; + // ----- Timer -------------------------------------------------------- + TStopwatch timer; - PixelEventHeader* pixelEventHeader = new PixelEventHeader(); + PixelEventHeader* pixelEventHeader = new PixelEventHeader(); - // ----- Reconstruction run ------------------------------------------- - FairRunAna *fRun= new FairRunAna(); - fRun->SetEventHeader(pixelEventHeader); - fRun->SetSink(new FairRootFileSink(outFile)); + // ----- Reconstruction run ------------------------------------------- + FairRunAna* fRun = new FairRunAna(); + fRun->SetEventHeader(pixelEventHeader); + fRun->SetSink(new FairRootFileSink(outFile)); - PixelDigiBinSource* digiSource = new PixelDigiBinSource("Pixel Digi Source"); - digiSource->SetInputFileName("digisBin.dat"); + PixelDigiBinSource* digiSource = new PixelDigiBinSource("Pixel Digi Source"); + digiSource->SetInputFileName("digisBin.dat"); - fRun->SetSource(digiSource); + fRun->SetSource(digiSource); - FairRuntimeDb* rtdb = fRun->GetRuntimeDb(); - FairParRootFileIo* parInput1 = new FairParRootFileIo(); - parInput1->open(parFile.Data()); + FairRuntimeDb* rtdb = fRun->GetRuntimeDb(); + FairParRootFileIo* parInput1 = new FairParRootFileIo(); + parInput1->open(parFile.Data()); - FairParAsciiFileIo* parIo1 = new FairParAsciiFileIo(); - parIo1->open(digParFile.Data(),"in"); + FairParAsciiFileIo* parIo1 = new FairParAsciiFileIo(); + parIo1->open(digParFile.Data(), "in"); - rtdb->setFirstInput(parInput1); - rtdb->setSecondInput(parIo1); + rtdb->setFirstInput(parInput1); + rtdb->setSecondInput(parIo1); - // ----- TorinoDetector hit producers --------------------------------- - // PixelDigiReadFromFile* digiRead = new PixelDigiReadFromFile(); - // fRun->AddTask(digiRead); + // ----- TorinoDetector hit producers --------------------------------- + // PixelDigiReadFromFile* digiRead = new PixelDigiReadFromFile(); + // fRun->AddTask(digiRead); - PixelFindHits* hitFinderTask = new PixelFindHits(); - fRun->AddTask(hitFinderTask); + PixelFindHits* hitFinderTask = new PixelFindHits(); + fRun->AddTask(hitFinderTask); + fRun->Init(); - fRun->Init(); + timer.Start(); + fRun->Run(); - timer.Start(); - fRun->Run(); + // ----- Finish ------------------------------------------------------- - // ----- Finish ------------------------------------------------------- + cout << endl << endl; - cout << endl << endl; + // Extract the maximal used memory an add is as Dart measurement + // This line is filtered by CTest and the value send to CDash + FairSystemInfo sysInfo; + Float_t maxMemory = sysInfo.GetMaxMemory(); + cout << ""; + cout << maxMemory; + cout << "" << endl; - // Extract the maximal used memory an add is as Dart measurement - // This line is filtered by CTest and the value send to CDash - FairSystemInfo sysInfo; - Float_t maxMemory=sysInfo.GetMaxMemory(); - cout << ""; - cout << maxMemory; - cout << "" << endl; + timer.Stop(); + Double_t rtime = timer.RealTime(); + Double_t ctime = timer.CpuTime(); - timer.Stop(); - Double_t rtime = timer.RealTime(); - Double_t ctime = timer.CpuTime(); + Float_t cpuUsage = ctime / rtime; + cout << ""; + cout << cpuUsage; + cout << "" << endl; - Float_t cpuUsage=ctime/rtime; - cout << ""; - cout << cpuUsage; - cout << "" << endl; + cout << endl << endl; + cout << "Output file is " << outFile << endl; + cout << "Parameter file is " << parFile << endl; + cout << "Real time " << rtime << " s, CPU time " << ctime << "s" << endl << endl; + cout << "Macro finished successfully." << endl; - cout << endl << endl; - cout << "Output file is " << outFile << endl; - cout << "Parameter file is " << parFile << endl; - cout << "Real time " << rtime << " s, CPU time " << ctime - << "s" << endl << endl; - cout << "Macro finished successfully." << endl; - - // ------------------------------------------------------------------------ + // ------------------------------------------------------------------------ } diff --git a/examples/MQ/pixelDetector/macros/run_digi.C b/examples/MQ/pixelDetector/macros/run_digi.C index 0432d0edef..b1cefdd4d1 100644 --- a/examples/MQ/pixelDetector/macros/run_digi.C +++ b/examples/MQ/pixelDetector/macros/run_digi.C @@ -5,86 +5,88 @@ * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ -void run_digi( TString mcEngine="TGeant3", Int_t fileId = 0 ) +void run_digi(TString mcEngine = "TGeant3", Int_t fileId = 0) { - // Verbosity level (0=quiet, 1=event level, 2=track level, 3=debug) - Int_t iVerbose = 0; // just forget about it, for the moment - - // Input file (MC events) - TString inFile = "pixel_"; - if ( fileId == 0 ) inFile = inFile + mcEngine + ".mc.root"; - else inFile = Form("%s%s.mc.f%d.root",inFile.Data(),mcEngine.Data(),fileId); - - // Parameter file - TString parFile = "pixel_"; - parFile = parFile + mcEngine + ".params.root"; - - // Digitization parameter file - TString dir = getenv("VMCWORKDIR"); - TString tutdir = dir + "/MQ/pixelDetector"; - TString digParFile = tutdir + "/param/pixel_digi.par"; - - // Output file - TString outFile = "pixel_"; - if ( fileId == 0 ) outFile = outFile + mcEngine + ".digi.root"; - else outFile = Form("%s%s.digi.f%d.root",outFile.Data(),mcEngine.Data(),fileId); - - - // ----- Timer -------------------------------------------------------- - TStopwatch timer; - - // ----- Reconstruction run ------------------------------------------- - FairRunAna *fRun= new FairRunAna(); - FairFileSource *fFileSource = new FairFileSource(inFile); - fRun->SetSource(fFileSource); - fRun->SetSink(new FairRootFileSink(outFile)); - - FairRuntimeDb* rtdb = fRun->GetRuntimeDb(); - FairParRootFileIo* parInput1 = new FairParRootFileIo(); - parInput1->open(parFile.Data()); - - FairParAsciiFileIo* parIo1 = new FairParAsciiFileIo(); - parIo1->open(digParFile.Data(),"in"); - - rtdb->setFirstInput(parInput1); - rtdb->setSecondInput(parIo1); - - // ----- TorinoDetector hit producers --------------------------------- - PixelDigitize* digiTask = new PixelDigitize(); - fRun->AddTask(digiTask); - - fRun->Init(); - - timer.Start(); - fRun->Run(); - - // ----- Finish ------------------------------------------------------- - - cout << endl << endl; - - // Extract the maximal used memory an add is as Dart measurement - // This line is filtered by CTest and the value send to CDash - FairSystemInfo sysInfo; - Float_t maxMemory=sysInfo.GetMaxMemory(); - cout << ""; - cout << maxMemory; - cout << "" << endl; - - timer.Stop(); - Double_t rtime = timer.RealTime(); - Double_t ctime = timer.CpuTime(); - - Float_t cpuUsage=ctime/rtime; - cout << ""; - cout << cpuUsage; - cout << "" << endl; - - cout << endl << endl; - cout << "Output file is " << outFile << endl; - cout << "Parameter file is " << parFile << endl; - cout << "Real time " << rtime << " s, CPU time " << ctime - << "s" << endl << endl; - cout << "Macro finished successfully." << endl; - - // ------------------------------------------------------------------------ + // Verbosity level (0=quiet, 1=event level, 2=track level, 3=debug) + Int_t iVerbose = 0; // just forget about it, for the moment + + // Input file (MC events) + TString inFile = "pixel_"; + if (fileId == 0) + inFile = inFile + mcEngine + ".mc.root"; + else + inFile = Form("%s%s.mc.f%d.root", inFile.Data(), mcEngine.Data(), fileId); + + // Parameter file + TString parFile = "pixel_"; + parFile = parFile + mcEngine + ".params.root"; + + // Digitization parameter file + TString dir = getenv("VMCWORKDIR"); + TString tutdir = dir + "/MQ/pixelDetector"; + TString digParFile = tutdir + "/param/pixel_digi.par"; + + // Output file + TString outFile = "pixel_"; + if (fileId == 0) + outFile = outFile + mcEngine + ".digi.root"; + else + outFile = Form("%s%s.digi.f%d.root", outFile.Data(), mcEngine.Data(), fileId); + + // ----- Timer -------------------------------------------------------- + TStopwatch timer; + + // ----- Reconstruction run ------------------------------------------- + FairRunAna* fRun = new FairRunAna(); + FairFileSource* fFileSource = new FairFileSource(inFile); + fRun->SetSource(fFileSource); + fRun->SetSink(new FairRootFileSink(outFile)); + + FairRuntimeDb* rtdb = fRun->GetRuntimeDb(); + FairParRootFileIo* parInput1 = new FairParRootFileIo(); + parInput1->open(parFile.Data()); + + FairParAsciiFileIo* parIo1 = new FairParAsciiFileIo(); + parIo1->open(digParFile.Data(), "in"); + + rtdb->setFirstInput(parInput1); + rtdb->setSecondInput(parIo1); + + // ----- TorinoDetector hit producers --------------------------------- + PixelDigitize* digiTask = new PixelDigitize(); + fRun->AddTask(digiTask); + + fRun->Init(); + + timer.Start(); + fRun->Run(); + + // ----- Finish ------------------------------------------------------- + + cout << endl << endl; + + // Extract the maximal used memory an add is as Dart measurement + // This line is filtered by CTest and the value send to CDash + FairSystemInfo sysInfo; + Float_t maxMemory = sysInfo.GetMaxMemory(); + cout << ""; + cout << maxMemory; + cout << "" << endl; + + timer.Stop(); + Double_t rtime = timer.RealTime(); + Double_t ctime = timer.CpuTime(); + + Float_t cpuUsage = ctime / rtime; + cout << ""; + cout << cpuUsage; + cout << "" << endl; + + cout << endl << endl; + cout << "Output file is " << outFile << endl; + cout << "Parameter file is " << parFile << endl; + cout << "Real time " << rtime << " s, CPU time " << ctime << "s" << endl << endl; + cout << "Macro finished successfully." << endl; + + // ------------------------------------------------------------------------ } diff --git a/examples/MQ/pixelDetector/macros/run_digiToAscii.C b/examples/MQ/pixelDetector/macros/run_digiToAscii.C index c289f5640a..c085bed8e5 100644 --- a/examples/MQ/pixelDetector/macros/run_digiToAscii.C +++ b/examples/MQ/pixelDetector/macros/run_digiToAscii.C @@ -5,88 +5,87 @@ * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ -void run_digiToAscii( TString mcEngine="TGeant3" ) +void run_digiToAscii(TString mcEngine = "TGeant3") { - // Verbosity level (0=quiet, 1=event level, 2=track level, 3=debug) - Int_t iVerbose = 0; // just forget about it, for the moment + // Verbosity level (0=quiet, 1=event level, 2=track level, 3=debug) + Int_t iVerbose = 0; // just forget about it, for the moment - // Input file (MC events) - TString inFile = "pixel_"; - inFile = inFile + mcEngine + ".mc.root"; + // Input file (MC events) + TString inFile = "pixel_"; + inFile = inFile + mcEngine + ".mc.root"; - // Parameter file - TString parFile = "pixel_"; - parFile = parFile + mcEngine + ".params.root"; + // Parameter file + TString parFile = "pixel_"; + parFile = parFile + mcEngine + ".params.root"; - // Digitization parameter file - TString dir = getenv("VMCWORKDIR"); - TString tutdir = dir + "/MQ/pixelDetector"; - TString digParFile = tutdir + "/param/pixel_digi.par"; + // Digitization parameter file + TString dir = getenv("VMCWORKDIR"); + TString tutdir = dir + "/MQ/pixelDetector"; + TString digParFile = tutdir + "/param/pixel_digi.par"; - // Output file - TString outFile = "pixel_"; - outFile = outFile + mcEngine + ".digiToAscii.root"; + // Output file + TString outFile = "pixel_"; + outFile = outFile + mcEngine + ".digiToAscii.root"; - // ----- Timer -------------------------------------------------------- - TStopwatch timer; + // ----- Timer -------------------------------------------------------- + TStopwatch timer; - // ----- Reconstruction run ------------------------------------------- - FairRunAna *fRun= new FairRunAna(); - FairFileSource *fFileSource = new FairFileSource(inFile); - fRun->SetSource(fFileSource); - fRun->SetSink(new FairRootFileSink(outFile)); + // ----- Reconstruction run ------------------------------------------- + FairRunAna* fRun = new FairRunAna(); + FairFileSource* fFileSource = new FairFileSource(inFile); + fRun->SetSource(fFileSource); + fRun->SetSink(new FairRootFileSink(outFile)); - FairRuntimeDb* rtdb = fRun->GetRuntimeDb(); - FairParRootFileIo* parInput1 = new FairParRootFileIo(); - parInput1->open(parFile.Data()); + FairRuntimeDb* rtdb = fRun->GetRuntimeDb(); + FairParRootFileIo* parInput1 = new FairParRootFileIo(); + parInput1->open(parFile.Data()); - FairParAsciiFileIo* parIo1 = new FairParAsciiFileIo(); - parIo1->open(digParFile.Data(),"in"); + FairParAsciiFileIo* parIo1 = new FairParAsciiFileIo(); + parIo1->open(digParFile.Data(), "in"); - rtdb->setFirstInput(parInput1); - rtdb->setSecondInput(parIo1); + rtdb->setFirstInput(parInput1); + rtdb->setSecondInput(parIo1); - // ----- TorinoDetector hit producers --------------------------------- - PixelDigitize* digiTask = new PixelDigitize(); - fRun->AddTask(digiTask); + // ----- TorinoDetector hit producers --------------------------------- + PixelDigitize* digiTask = new PixelDigitize(); + fRun->AddTask(digiTask); - PixelDigiWriteToFile* digiWrite = new PixelDigiWriteToFile(); - digiWrite->SetOutputFileName("digis.dat"); - digiWrite->SetDivideLevel(1); // 0 - event, 1 - station, 2 - sensor - fRun->AddTask(digiWrite); + PixelDigiWriteToFile* digiWrite = new PixelDigiWriteToFile(); + digiWrite->SetOutputFileName("digis.dat"); + digiWrite->SetDivideLevel(1); // 0 - event, 1 - station, 2 - sensor + fRun->AddTask(digiWrite); - fRun->Init(); + fRun->Init(); - timer.Start(); - fRun->Run(); + timer.Start(); + fRun->Run(); - // ----- Finish ------------------------------------------------------- + // ----- Finish ------------------------------------------------------- - cout << endl << endl; + cout << endl << endl; - // Extract the maximal used memory an add is as Dart measurement - // This line is filtered by CTest and the value send to CDash - FairSystemInfo sysInfo; - Float_t maxMemory=sysInfo.GetMaxMemory(); - cout << ""; - cout << maxMemory; - cout << "" << endl; + // Extract the maximal used memory an add is as Dart measurement + // This line is filtered by CTest and the value send to CDash + FairSystemInfo sysInfo; + Float_t maxMemory = sysInfo.GetMaxMemory(); + cout << ""; + cout << maxMemory; + cout << "" << endl; - timer.Stop(); - Double_t rtime = timer.RealTime(); - Double_t ctime = timer.CpuTime(); + timer.Stop(); + Double_t rtime = timer.RealTime(); + Double_t ctime = timer.CpuTime(); - Float_t cpuUsage=ctime/rtime; - cout << ""; - cout << cpuUsage; - cout << "" << endl; + Float_t cpuUsage = ctime / rtime; + cout << ""; + cout << cpuUsage; + cout << "" << endl; - cout << endl << endl; - cout << "Output file is " << outFile << endl; - cout << "Parameter file is " << parFile << endl; - cout << "Real time " << rtime << " s, CPU time " << ctime - << "s" << endl << endl; - cout << "Macro finished successfully." << endl; + cout << endl << endl; + cout << "Output file is " << outFile << endl; + cout << "Parameter file is " << parFile << endl; + cout << "Real time " << rtime << " s, CPU time " << ctime << "s" << endl << endl; + cout << "Macro finished successfully." << endl; - // ------------------------------------------------------------------------ + // ------------------------------------------------------------------------ } diff --git a/examples/MQ/pixelDetector/macros/run_digiToBin.C b/examples/MQ/pixelDetector/macros/run_digiToBin.C index 3a1da118c8..3d618fb051 100644 --- a/examples/MQ/pixelDetector/macros/run_digiToBin.C +++ b/examples/MQ/pixelDetector/macros/run_digiToBin.C @@ -5,98 +5,97 @@ * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ -void run_digiToBin(Int_t divideLevel = 1, TString mcEngine="TGeant3" ) +void run_digiToBin(Int_t divideLevel = 1, TString mcEngine = "TGeant3") { - if ( divideLevel < 0 || divideLevel > 2 ) { - cout << "set divideLevel to either 0 - event, 1 - station, 2 - sensor" << endl; - return; - } - - // Verbosity level (0=quiet, 1=event level, 2=track level, 3=debug) - Int_t iVerbose = 0; // just forget about it, for the moment - - // Input file (MC events) - TString inFile = "pixel_"; - inFile = inFile + mcEngine + ".mc.root"; - - // Parameter file - TString parFile = "pixel_"; - parFile = parFile + mcEngine + ".params.root"; - - // Digitization parameter file - TString dir = getenv("VMCWORKDIR"); - TString tutdir = dir + "/MQ/pixelDetector"; - TString digParFile = tutdir + "/param/pixel_digi.par"; - - // Output file - TString outFile = "pixel_"; - outFile = outFile + mcEngine + ".digiToBin.root"; - - // ----- Timer -------------------------------------------------------- - TStopwatch timer; - - // ----- Reconstruction run ------------------------------------------- - FairRunAna *fRun= new FairRunAna(); - FairFileSource *fFileSource = new FairFileSource(inFile); - fRun->SetSource(fFileSource); - fRun->SetSink(new FairRootFileSink(outFile)); - - FairRuntimeDb* rtdb = fRun->GetRuntimeDb(); - FairParRootFileIo* parInput1 = new FairParRootFileIo(); - parInput1->open(parFile.Data()); - - FairParAsciiFileIo* parIo1 = new FairParAsciiFileIo(); - parIo1->open(digParFile.Data(),"in"); - - rtdb->setFirstInput(parInput1); - rtdb->setSecondInput(parIo1); - - // ----- TorinoDetector hit producers --------------------------------- - PixelDigitize* digiTask = new PixelDigitize(); - fRun->AddTask(digiTask); - - PixelDigiWriteToBinFile* digiWrite = new PixelDigiWriteToBinFile(); - digiWrite->SetOutputFileName("digisBin.dat"); - digiWrite->SetDivideLevel(divideLevel); // 0 - event, 1 - station, 2 - sensor - fRun->AddTask(digiWrite); - - // PixelAltDigiWriteToRootVector* digiWrite = new PixelAltDigiWriteToRootVector(); - // digiWrite->SetOutputFileName("digisBin.root"); - // digiWrite->SetDivideLevel(divideLevel); // 0 - event, 1 - station, 2 - sensor - // fRun->AddTask(digiWrite); - - fRun->Init(); - - timer.Start(); - fRun->Run(); - - // ----- Finish ------------------------------------------------------- - - cout << endl << endl; - - // Extract the maximal used memory an add is as Dart measurement - // This line is filtered by CTest and the value send to CDash - FairSystemInfo sysInfo; - Float_t maxMemory=sysInfo.GetMaxMemory(); - cout << ""; - cout << maxMemory; - cout << "" << endl; - - timer.Stop(); - Double_t rtime = timer.RealTime(); - Double_t ctime = timer.CpuTime(); - - Float_t cpuUsage=ctime/rtime; - cout << ""; - cout << cpuUsage; - cout << "" << endl; - - cout << endl << endl; - cout << "Output file is " << outFile << endl; - cout << "Parameter file is " << parFile << endl; - cout << "Real time " << rtime << " s, CPU time " << ctime - << "s" << endl << endl; - cout << "Macro finished successfully." << endl; - - // ------------------------------------------------------------------------ + if (divideLevel < 0 || divideLevel > 2) { + cout << "set divideLevel to either 0 - event, 1 - station, 2 - sensor" << endl; + return; + } + + // Verbosity level (0=quiet, 1=event level, 2=track level, 3=debug) + Int_t iVerbose = 0; // just forget about it, for the moment + + // Input file (MC events) + TString inFile = "pixel_"; + inFile = inFile + mcEngine + ".mc.root"; + + // Parameter file + TString parFile = "pixel_"; + parFile = parFile + mcEngine + ".params.root"; + + // Digitization parameter file + TString dir = getenv("VMCWORKDIR"); + TString tutdir = dir + "/MQ/pixelDetector"; + TString digParFile = tutdir + "/param/pixel_digi.par"; + + // Output file + TString outFile = "pixel_"; + outFile = outFile + mcEngine + ".digiToBin.root"; + + // ----- Timer -------------------------------------------------------- + TStopwatch timer; + + // ----- Reconstruction run ------------------------------------------- + FairRunAna* fRun = new FairRunAna(); + FairFileSource* fFileSource = new FairFileSource(inFile); + fRun->SetSource(fFileSource); + fRun->SetSink(new FairRootFileSink(outFile)); + + FairRuntimeDb* rtdb = fRun->GetRuntimeDb(); + FairParRootFileIo* parInput1 = new FairParRootFileIo(); + parInput1->open(parFile.Data()); + + FairParAsciiFileIo* parIo1 = new FairParAsciiFileIo(); + parIo1->open(digParFile.Data(), "in"); + + rtdb->setFirstInput(parInput1); + rtdb->setSecondInput(parIo1); + + // ----- TorinoDetector hit producers --------------------------------- + PixelDigitize* digiTask = new PixelDigitize(); + fRun->AddTask(digiTask); + + PixelDigiWriteToBinFile* digiWrite = new PixelDigiWriteToBinFile(); + digiWrite->SetOutputFileName("digisBin.dat"); + digiWrite->SetDivideLevel(divideLevel); // 0 - event, 1 - station, 2 - sensor + fRun->AddTask(digiWrite); + + // PixelAltDigiWriteToRootVector* digiWrite = new PixelAltDigiWriteToRootVector(); + // digiWrite->SetOutputFileName("digisBin.root"); + // digiWrite->SetDivideLevel(divideLevel); // 0 - event, 1 - station, 2 - sensor + // fRun->AddTask(digiWrite); + + fRun->Init(); + + timer.Start(); + fRun->Run(); + + // ----- Finish ------------------------------------------------------- + + cout << endl << endl; + + // Extract the maximal used memory an add is as Dart measurement + // This line is filtered by CTest and the value send to CDash + FairSystemInfo sysInfo; + Float_t maxMemory = sysInfo.GetMaxMemory(); + cout << ""; + cout << maxMemory; + cout << "" << endl; + + timer.Stop(); + Double_t rtime = timer.RealTime(); + Double_t ctime = timer.CpuTime(); + + Float_t cpuUsage = ctime / rtime; + cout << ""; + cout << cpuUsage; + cout << "" << endl; + + cout << endl << endl; + cout << "Output file is " << outFile << endl; + cout << "Parameter file is " << parFile << endl; + cout << "Real time " << rtime << " s, CPU time " << ctime << "s" << endl << endl; + cout << "Macro finished successfully." << endl; + + // ------------------------------------------------------------------------ } diff --git a/examples/MQ/pixelDetector/macros/run_hits.C b/examples/MQ/pixelDetector/macros/run_hits.C index 4961098fa9..c2b4e6d1a0 100644 --- a/examples/MQ/pixelDetector/macros/run_hits.C +++ b/examples/MQ/pixelDetector/macros/run_hits.C @@ -5,94 +5,92 @@ * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ -void run_hits( TString mcEngine="TGeant3" ) +void run_hits(TString mcEngine = "TGeant3") { - // Verbosity level (0=quiet, 1=event level, 2=track level, 3=debug) - Int_t iVerbose = 0; // just forget about it, for the moment - - // Input file (MC events) - TString inFile = "pixel_"; - inFile = inFile + mcEngine + ".digi.root"; - - // Parameter file - TString parFile = "pixel_"; - parFile = parFile + mcEngine + ".params.root"; - - // Digitization parameter file - TString dir = getenv("VMCWORKDIR"); - TString tutdir = dir + "/MQ/pixelDetector"; - TString digParFile = tutdir + "/param/pixel_digi.par"; - - // Output file - TString outFile = "pixel_"; - outFile = outFile + mcEngine + ".hits.root"; - - // ----- Timer -------------------------------------------------------- - TStopwatch timer; - - // ----- Reconstruction run ------------------------------------------- - FairRunAna *fRun= new FairRunAna(); - FairFileSource *fFileSource = new FairFileSource(inFile); - fRun->SetSource(fFileSource); - fRun->SetSink(new FairRootFileSink(outFile)); - - // fRun->AddFile(inFile); - // fRun->AddFile(inFile); - // fRun->AddFile(inFile); - // fRun->AddFile(inFile); - // fRun->AddFile(inFile); - // fRun->AddFile(inFile); - // fRun->AddFile(inFile); - // fRun->AddFile(inFile); - // fRun->AddFile(inFile); - - FairRuntimeDb* rtdb = fRun->GetRuntimeDb(); - FairParRootFileIo* parInput1 = new FairParRootFileIo(); - parInput1->open(parFile.Data()); - - FairParAsciiFileIo* parIo1 = new FairParAsciiFileIo(); - parIo1->open(digParFile.Data(),"in"); - - rtdb->setFirstInput(parInput1); - rtdb->setSecondInput(parIo1); - - // ----- TorinoDetector hit producers --------------------------------- - PixelFindHits* hitFinderTask = new PixelFindHits(); - fRun->AddTask(hitFinderTask); - - - fRun->Init(); - - timer.Start(); - fRun->Run(); - - // ----- Finish ------------------------------------------------------- - - cout << endl << endl; - - // Extract the maximal used memory an add is as Dart measurement - // This line is filtered by CTest and the value send to CDash - FairSystemInfo sysInfo; - Float_t maxMemory=sysInfo.GetMaxMemory(); - cout << ""; - cout << maxMemory; - cout << "" << endl; - - timer.Stop(); - Double_t rtime = timer.RealTime(); - Double_t ctime = timer.CpuTime(); - - Float_t cpuUsage=ctime/rtime; - cout << ""; - cout << cpuUsage; - cout << "" << endl; - - cout << endl << endl; - cout << "Output file is " << outFile << endl; - cout << "Parameter file is " << parFile << endl; - cout << "Real time " << rtime << " s, CPU time " << ctime - << "s" << endl << endl; - cout << "Macro finished successfully." << endl; - - // ------------------------------------------------------------------------ + // Verbosity level (0=quiet, 1=event level, 2=track level, 3=debug) + Int_t iVerbose = 0; // just forget about it, for the moment + + // Input file (MC events) + TString inFile = "pixel_"; + inFile = inFile + mcEngine + ".digi.root"; + + // Parameter file + TString parFile = "pixel_"; + parFile = parFile + mcEngine + ".params.root"; + + // Digitization parameter file + TString dir = getenv("VMCWORKDIR"); + TString tutdir = dir + "/MQ/pixelDetector"; + TString digParFile = tutdir + "/param/pixel_digi.par"; + + // Output file + TString outFile = "pixel_"; + outFile = outFile + mcEngine + ".hits.root"; + + // ----- Timer -------------------------------------------------------- + TStopwatch timer; + + // ----- Reconstruction run ------------------------------------------- + FairRunAna* fRun = new FairRunAna(); + FairFileSource* fFileSource = new FairFileSource(inFile); + fRun->SetSource(fFileSource); + fRun->SetSink(new FairRootFileSink(outFile)); + + // fRun->AddFile(inFile); + // fRun->AddFile(inFile); + // fRun->AddFile(inFile); + // fRun->AddFile(inFile); + // fRun->AddFile(inFile); + // fRun->AddFile(inFile); + // fRun->AddFile(inFile); + // fRun->AddFile(inFile); + // fRun->AddFile(inFile); + + FairRuntimeDb* rtdb = fRun->GetRuntimeDb(); + FairParRootFileIo* parInput1 = new FairParRootFileIo(); + parInput1->open(parFile.Data()); + + FairParAsciiFileIo* parIo1 = new FairParAsciiFileIo(); + parIo1->open(digParFile.Data(), "in"); + + rtdb->setFirstInput(parInput1); + rtdb->setSecondInput(parIo1); + + // ----- TorinoDetector hit producers --------------------------------- + PixelFindHits* hitFinderTask = new PixelFindHits(); + fRun->AddTask(hitFinderTask); + + fRun->Init(); + + timer.Start(); + fRun->Run(); + + // ----- Finish ------------------------------------------------------- + + cout << endl << endl; + + // Extract the maximal used memory an add is as Dart measurement + // This line is filtered by CTest and the value send to CDash + FairSystemInfo sysInfo; + Float_t maxMemory = sysInfo.GetMaxMemory(); + cout << ""; + cout << maxMemory; + cout << "" << endl; + + timer.Stop(); + Double_t rtime = timer.RealTime(); + Double_t ctime = timer.CpuTime(); + + Float_t cpuUsage = ctime / rtime; + cout << ""; + cout << cpuUsage; + cout << "" << endl; + + cout << endl << endl; + cout << "Output file is " << outFile << endl; + cout << "Parameter file is " << parFile << endl; + cout << "Real time " << rtime << " s, CPU time " << ctime << "s" << endl << endl; + cout << "Macro finished successfully." << endl; + + // ------------------------------------------------------------------------ } diff --git a/examples/MQ/pixelDetector/macros/run_hits_sep.C b/examples/MQ/pixelDetector/macros/run_hits_sep.C index 3315453a1a..541daa3946 100644 --- a/examples/MQ/pixelDetector/macros/run_hits_sep.C +++ b/examples/MQ/pixelDetector/macros/run_hits_sep.C @@ -5,88 +5,86 @@ * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ -void run_hits_sep( Int_t ifile, TString mcEngine="TGeant3" ) +void run_hits_sep(Int_t ifile, TString mcEngine = "TGeant3") { - // Verbosity level (0=quiet, 1=event level, 2=track level, 3=debug) - Int_t iVerbose = 0; // just forget about it, for the moment + // Verbosity level (0=quiet, 1=event level, 2=track level, 3=debug) + Int_t iVerbose = 0; // just forget about it, for the moment - // Input file (MC events) - TString inFile = Form("pixel_f%d_",ifile); - inFile = inFile + mcEngine + ".digi.root"; + // Input file (MC events) + TString inFile = Form("pixel_f%d_", ifile); + inFile = inFile + mcEngine + ".digi.root"; - // Parameter file - TString parFile = "pixel_"; - parFile = parFile + mcEngine + ".params.root"; + // Parameter file + TString parFile = "pixel_"; + parFile = parFile + mcEngine + ".params.root"; - // Digitization parameter file - TString dir = getenv("VMCWORKDIR"); - TString tutdir = dir + "/MQ/pixelDetector"; - TString digParFile = tutdir + "/param/pixel_digi.par"; + // Digitization parameter file + TString dir = getenv("VMCWORKDIR"); + TString tutdir = dir + "/MQ/pixelDetector"; + TString digParFile = tutdir + "/param/pixel_digi.par"; - // Output file - TString outFile = Form("pixel_f%d_",ifile); - outFile = outFile + mcEngine + ".hits.root"; + // Output file + TString outFile = Form("pixel_f%d_", ifile); + outFile = outFile + mcEngine + ".hits.root"; - // ----- Timer -------------------------------------------------------- - TStopwatch timer; + // ----- Timer -------------------------------------------------------- + TStopwatch timer; - // ----- Reconstruction run ------------------------------------------- - FairRunAna *fRun= new FairRunAna(); - FairFileSource *fFileSource = new FairFileSource(inFile); - fRun->SetSource(fFileSource); + // ----- Reconstruction run ------------------------------------------- + FairRunAna* fRun = new FairRunAna(); + FairFileSource* fFileSource = new FairFileSource(inFile); + fRun->SetSource(fFileSource); - fRun->SetSink(new FairRootFileSink(outFile)); + fRun->SetSink(new FairRootFileSink(outFile)); - FairRuntimeDb* rtdb = fRun->GetRuntimeDb(); - FairParRootFileIo* parInput1 = new FairParRootFileIo(); - parInput1->open(parFile.Data()); + FairRuntimeDb* rtdb = fRun->GetRuntimeDb(); + FairParRootFileIo* parInput1 = new FairParRootFileIo(); + parInput1->open(parFile.Data()); - FairParAsciiFileIo* parIo1 = new FairParAsciiFileIo(); - parIo1->open(digParFile.Data(),"in"); + FairParAsciiFileIo* parIo1 = new FairParAsciiFileIo(); + parIo1->open(digParFile.Data(), "in"); - rtdb->setFirstInput(parInput1); - rtdb->setSecondInput(parIo1); + rtdb->setFirstInput(parInput1); + rtdb->setSecondInput(parIo1); - // ----- TorinoDetector hit producers --------------------------------- - PixelFindHits* hitFinderTask = new PixelFindHits(); - fRun->AddTask(hitFinderTask); + // ----- TorinoDetector hit producers --------------------------------- + PixelFindHits* hitFinderTask = new PixelFindHits(); + fRun->AddTask(hitFinderTask); + fRun->Init(); - fRun->Init(); + timer.Start(); + fRun->Run(); - timer.Start(); - fRun->Run(); + // ----- Finish ------------------------------------------------------- - // ----- Finish ------------------------------------------------------- + cout << endl << endl; - cout << endl << endl; + // Extract the maximal used memory an add is as Dart measurement + // This line is filtered by CTest and the value send to CDash + FairSystemInfo sysInfo; + Float_t maxMemory = sysInfo.GetMaxMemory(); + cout << ""; + cout << maxMemory; + cout << "" << endl; - // Extract the maximal used memory an add is as Dart measurement - // This line is filtered by CTest and the value send to CDash - FairSystemInfo sysInfo; - Float_t maxMemory=sysInfo.GetMaxMemory(); - cout << ""; - cout << maxMemory; - cout << "" << endl; + timer.Stop(); + Double_t rtime = timer.RealTime(); + Double_t ctime = timer.CpuTime(); - timer.Stop(); - Double_t rtime = timer.RealTime(); - Double_t ctime = timer.CpuTime(); + Float_t cpuUsage = ctime / rtime; + cout << ""; + cout << cpuUsage; + cout << "" << endl; - Float_t cpuUsage=ctime/rtime; - cout << ""; - cout << cpuUsage; - cout << "" << endl; + cout << endl << endl; + cout << "Output file is " << outFile << endl; + cout << "Parameter file is " << parFile << endl; + cout << "Real time " << rtime << " s, CPU time " << ctime << "s" << endl << endl; + cout << "Macro finished successfully." << endl; - cout << endl << endl; - cout << "Output file is " << outFile << endl; - cout << "Parameter file is " << parFile << endl; - cout << "Real time " << rtime << " s, CPU time " << ctime - << "s" << endl << endl; - cout << "Macro finished successfully." << endl; + cout << "DATE MARKER" << flush; + gSystem->Exec("date"); - cout << "DATE MARKER" << flush; - gSystem->Exec("date"); - - // ------------------------------------------------------------------------ + // ------------------------------------------------------------------------ } diff --git a/examples/MQ/pixelDetector/macros/run_reco.C b/examples/MQ/pixelDetector/macros/run_reco.C index 9c155e118c..b9da2c6038 100644 --- a/examples/MQ/pixelDetector/macros/run_reco.C +++ b/examples/MQ/pixelDetector/macros/run_reco.C @@ -5,92 +5,91 @@ * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ -void run_reco( TString mcEngine="TGeant3" ) +void run_reco(TString mcEngine = "TGeant3") { - // Verbosity level (0=quiet, 1=event level, 2=track level, 3=debug) - Int_t iVerbose = 0; // just forget about it, for the moment + // Verbosity level (0=quiet, 1=event level, 2=track level, 3=debug) + Int_t iVerbose = 0; // just forget about it, for the moment - // Input file (MC events) - TString inFile = "pixel_"; - inFile = inFile + mcEngine + ".mc.root"; + // Input file (MC events) + TString inFile = "pixel_"; + inFile = inFile + mcEngine + ".mc.root"; - // Parameter file - TString parFile = "pixel_"; - parFile = parFile + mcEngine + ".params.root"; + // Parameter file + TString parFile = "pixel_"; + parFile = parFile + mcEngine + ".params.root"; - // Digitization parameter file - TString dir = getenv("VMCWORKDIR"); - TString tutdir = dir + "/MQ/pixelDetector"; - TString digParFile = tutdir + "/param/pixel_digi.par"; + // Digitization parameter file + TString dir = getenv("VMCWORKDIR"); + TString tutdir = dir + "/MQ/pixelDetector"; + TString digParFile = tutdir + "/param/pixel_digi.par"; - // Output file - TString outFile = "pixel_"; - outFile = outFile + mcEngine + ".reco.root"; + // Output file + TString outFile = "pixel_"; + outFile = outFile + mcEngine + ".reco.root"; - // ----- Timer -------------------------------------------------------- - TStopwatch timer; + // ----- Timer -------------------------------------------------------- + TStopwatch timer; - // ----- Reconstruction run ------------------------------------------- - FairRunAna *fRun= new FairRunAna(); - FairFileSource *fFileSource = new FairFileSource(inFile); - fRun->SetSource(fFileSource); - fRun->SetSink(new FairRootFileSink(outFile)); + // ----- Reconstruction run ------------------------------------------- + FairRunAna* fRun = new FairRunAna(); + FairFileSource* fFileSource = new FairFileSource(inFile); + fRun->SetSource(fFileSource); + fRun->SetSink(new FairRootFileSink(outFile)); - FairRuntimeDb* rtdb = fRun->GetRuntimeDb(); - FairParRootFileIo* parInput1 = new FairParRootFileIo(); - parInput1->open(parFile.Data()); + FairRuntimeDb* rtdb = fRun->GetRuntimeDb(); + FairParRootFileIo* parInput1 = new FairParRootFileIo(); + parInput1->open(parFile.Data()); - FairParAsciiFileIo* parIo1 = new FairParAsciiFileIo(); - parIo1->open(digParFile.Data(),"in"); + FairParAsciiFileIo* parIo1 = new FairParAsciiFileIo(); + parIo1->open(digParFile.Data(), "in"); - rtdb->setFirstInput(parInput1); - rtdb->setSecondInput(parIo1); + rtdb->setFirstInput(parInput1); + rtdb->setSecondInput(parIo1); - // ----- TorinoDetector hit producers --------------------------------- - PixelDigitize* digiTask = new PixelDigitize(); - fRun->AddTask(digiTask); + // ----- TorinoDetector hit producers --------------------------------- + PixelDigitize* digiTask = new PixelDigitize(); + fRun->AddTask(digiTask); - PixelFindHits* hitFinderTask = new PixelFindHits(); - fRun->AddTask(hitFinderTask); + PixelFindHits* hitFinderTask = new PixelFindHits(); + fRun->AddTask(hitFinderTask); - PixelFindTracks* trackFinderTask = new PixelFindTracks(); - fRun->AddTask(trackFinderTask); + PixelFindTracks* trackFinderTask = new PixelFindTracks(); + fRun->AddTask(trackFinderTask); - PixelFitTracks* trackFitterTask = new PixelFitTracks(); - fRun->AddTask(trackFitterTask); + PixelFitTracks* trackFitterTask = new PixelFitTracks(); + fRun->AddTask(trackFitterTask); - fRun->Init(); + fRun->Init(); - timer.Start(); - fRun->Run(); + timer.Start(); + fRun->Run(); - // ----- Finish ------------------------------------------------------- + // ----- Finish ------------------------------------------------------- - cout << endl << endl; + cout << endl << endl; - // Extract the maximal used memory an add is as Dart measurement - // This line is filtered by CTest and the value send to CDash - FairSystemInfo sysInfo; - Float_t maxMemory=sysInfo.GetMaxMemory(); - cout << ""; - cout << maxMemory; - cout << "" << endl; + // Extract the maximal used memory an add is as Dart measurement + // This line is filtered by CTest and the value send to CDash + FairSystemInfo sysInfo; + Float_t maxMemory = sysInfo.GetMaxMemory(); + cout << ""; + cout << maxMemory; + cout << "" << endl; - timer.Stop(); - Double_t rtime = timer.RealTime(); - Double_t ctime = timer.CpuTime(); + timer.Stop(); + Double_t rtime = timer.RealTime(); + Double_t ctime = timer.CpuTime(); - Float_t cpuUsage=ctime/rtime; - cout << ""; - cout << cpuUsage; - cout << "" << endl; + Float_t cpuUsage = ctime / rtime; + cout << ""; + cout << cpuUsage; + cout << "" << endl; - cout << endl << endl; - cout << "Output file is " << outFile << endl; - cout << "Parameter file is " << parFile << endl; - cout << "Real time " << rtime << " s, CPU time " << ctime - << "s" << endl << endl; - cout << "Macro finished successfully." << endl; + cout << endl << endl; + cout << "Output file is " << outFile << endl; + cout << "Parameter file is " << parFile << endl; + cout << "Real time " << rtime << " s, CPU time " << ctime << "s" << endl << endl; + cout << "Macro finished successfully." << endl; - // ------------------------------------------------------------------------ + // ------------------------------------------------------------------------ } diff --git a/examples/MQ/pixelDetector/macros/run_sim.C b/examples/MQ/pixelDetector/macros/run_sim.C index 2924388e19..106793b803 100644 --- a/examples/MQ/pixelDetector/macros/run_sim.C +++ b/examples/MQ/pixelDetector/macros/run_sim.C @@ -8,131 +8,128 @@ void run_sim(Int_t nEvents = 10, TString mcEngine = "TGeant3", Int_t fileId = 0, Bool_t isMT = kFALSE) { - TString dir = getenv("VMCWORKDIR"); - TString tutdir = dir + "/MQ/pixelDetector"; + TString dir = getenv("VMCWORKDIR"); + TString tutdir = dir + "/MQ/pixelDetector"; - TString tut_geomdir = dir + "/common/geometry"; - gSystem->Setenv("GEOMPATH",tut_geomdir.Data()); - - TString tut_configdir = dir + "/common/gconfig"; - gSystem->Setenv("CONFIG_DIR",tut_configdir.Data()); - - TString partName[] = {"pions","eplus","proton"}; - Int_t partPdgC[] = { 211, 11, 2212}; - Int_t chosenPart = 0; - - - TString outDir = "./"; - - // Output file name - TString outFile; - if (fileId == 0) { - outFile = Form("%s/pixel_%s.mc.root", outDir.Data(), mcEngine.Data()); - } else { - outFile = Form("%s/pixel_%s.mc.f%d.root", outDir.Data(), mcEngine.Data(), fileId); - } - - // Parameter file name - TString parFile = Form("%s/pixel_%s.params.root", outDir.Data(), mcEngine.Data()); - - // In general, the following parts need not be touched - // ======================================================================== - - // ---- Debug option ------------------------------------------------- - gDebug = 0; - // ------------------------------------------------------------------------ - - // ----- Timer -------------------------------------------------------- - TStopwatch timer; - timer.Start(); - // ------------------------------------------------------------------------ - - // ----- Create simulation run ---------------------------------------- - FairRunSim* run = new FairRunSim(); - run->SetName(mcEngine); // Transport engine - run->SetIsMT(isMT); // Multi-threading mode (Geant4 only) - run->SetSink(new FairRootFileSink(outFile)); - FairRuntimeDb* rtdb = run->GetRuntimeDb(); - // ------------------------------------------------------------------------ - - // ----- Create media ------------------------------------------------- - run->SetMaterials("media.geo"); // Materials - // ------------------------------------------------------------------------ - - // ----- Create geometry ---------------------------------------------- - - FairModule* cave= new FairCave("CAVE"); - cave->SetGeometryFileName("cave_vacuum.geo"); - run->AddModule(cave); - - Pixel* det = new Pixel("PixelDetector", kTRUE); - det->SetGeometryFileName("pixel.geo"); -// det->SetMisalignDetector(kTRUE); - run->AddModule(det); - // ------------------------------------------------------------------------ - - // ----- Create PrimaryGenerator -------------------------------------- - FairPrimaryGenerator* primGen = new FairPrimaryGenerator(); - FairBoxGenerator* boxGen = new FairBoxGenerator(partPdgC[chosenPart], 5); - boxGen->SetPRange(1,2); - boxGen->SetThetaRange(0,40); - boxGen->SetPhiRange(0,360); - // boxGen->SetDebug(kTRUE); - - primGen->AddGenerator(boxGen); - - - run->SetGenerator(primGen); - // ------------------------------------------------------------------------ - - run->SetStoreTraj(kFALSE); - - // ----- Initialize simulation run ------------------------------------ - run->Init(); - // ------------------------------------------------------------------------ - - // ----- Runtime database --------------------------------------------- - - Bool_t kParameterMerged = kTRUE; - FairParRootFileIo* parOut = new FairParRootFileIo(kParameterMerged); - parOut->open(parFile.Data()); - rtdb->setOutput(parOut); - rtdb->saveOutput(); - rtdb->print(); - // ------------------------------------------------------------------------ - - // ----- Start run ---------------------------------------------------- - run->Run(nEvents); - run->CreateGeometryFile("geofile_full.root"); - // ------------------------------------------------------------------------ - - // ----- Finish ------------------------------------------------------- - - cout << endl << endl; - - // Extract the maximal used memory an add is as Dart measurement - // This line is filtered by CTest and the value send to CDash - FairSystemInfo sysInfo; - Float_t maxMemory=sysInfo.GetMaxMemory(); - cout << ""; - cout << maxMemory; - cout << "" << endl; - - timer.Stop(); - Double_t rtime = timer.RealTime(); - Double_t ctime = timer.CpuTime(); - - Float_t cpuUsage=ctime/rtime; - cout << ""; - cout << cpuUsage; - cout << "" << endl; - - cout << endl << endl; - cout << "Output file is " << outFile << endl; - cout << "Parameter file is " << parFile << endl; - cout << "Real time " << rtime << " s, CPU time " << ctime - << "s" << endl << endl; - cout << "Macro finished successfully." << endl; - - // ------------------------------------------------------------------------ + TString tut_geomdir = dir + "/common/geometry"; + gSystem->Setenv("GEOMPATH", tut_geomdir.Data()); + + TString tut_configdir = dir + "/common/gconfig"; + gSystem->Setenv("CONFIG_DIR", tut_configdir.Data()); + + TString partName[] = {"pions", "eplus", "proton"}; + Int_t partPdgC[] = {211, 11, 2212}; + Int_t chosenPart = 0; + + TString outDir = "./"; + + // Output file name + TString outFile; + if (fileId == 0) { + outFile = Form("%s/pixel_%s.mc.root", outDir.Data(), mcEngine.Data()); + } else { + outFile = Form("%s/pixel_%s.mc.f%d.root", outDir.Data(), mcEngine.Data(), fileId); + } + + // Parameter file name + TString parFile = Form("%s/pixel_%s.params.root", outDir.Data(), mcEngine.Data()); + + // In general, the following parts need not be touched + // ======================================================================== + + // ---- Debug option ------------------------------------------------- + gDebug = 0; + // ------------------------------------------------------------------------ + + // ----- Timer -------------------------------------------------------- + TStopwatch timer; + timer.Start(); + // ------------------------------------------------------------------------ + + // ----- Create simulation run ---------------------------------------- + FairRunSim* run = new FairRunSim(); + run->SetName(mcEngine); // Transport engine + run->SetIsMT(isMT); // Multi-threading mode (Geant4 only) + run->SetSink(new FairRootFileSink(outFile)); + FairRuntimeDb* rtdb = run->GetRuntimeDb(); + // ------------------------------------------------------------------------ + + // ----- Create media ------------------------------------------------- + run->SetMaterials("media.geo"); // Materials + // ------------------------------------------------------------------------ + + // ----- Create geometry ---------------------------------------------- + + FairModule* cave = new FairCave("CAVE"); + cave->SetGeometryFileName("cave_vacuum.geo"); + run->AddModule(cave); + + Pixel* det = new Pixel("PixelDetector", kTRUE); + det->SetGeometryFileName("pixel.geo"); + // det->SetMisalignDetector(kTRUE); + run->AddModule(det); + // ------------------------------------------------------------------------ + + // ----- Create PrimaryGenerator -------------------------------------- + FairPrimaryGenerator* primGen = new FairPrimaryGenerator(); + FairBoxGenerator* boxGen = new FairBoxGenerator(partPdgC[chosenPart], 5); + boxGen->SetPRange(1, 2); + boxGen->SetThetaRange(0, 40); + boxGen->SetPhiRange(0, 360); + // boxGen->SetDebug(kTRUE); + + primGen->AddGenerator(boxGen); + + run->SetGenerator(primGen); + // ------------------------------------------------------------------------ + + run->SetStoreTraj(kFALSE); + + // ----- Initialize simulation run ------------------------------------ + run->Init(); + // ------------------------------------------------------------------------ + + // ----- Runtime database --------------------------------------------- + + Bool_t kParameterMerged = kTRUE; + FairParRootFileIo* parOut = new FairParRootFileIo(kParameterMerged); + parOut->open(parFile.Data()); + rtdb->setOutput(parOut); + rtdb->saveOutput(); + rtdb->print(); + // ------------------------------------------------------------------------ + + // ----- Start run ---------------------------------------------------- + run->Run(nEvents); + run->CreateGeometryFile("geofile_full.root"); + // ------------------------------------------------------------------------ + + // ----- Finish ------------------------------------------------------- + + cout << endl << endl; + + // Extract the maximal used memory an add is as Dart measurement + // This line is filtered by CTest and the value send to CDash + FairSystemInfo sysInfo; + Float_t maxMemory = sysInfo.GetMaxMemory(); + cout << ""; + cout << maxMemory; + cout << "" << endl; + + timer.Stop(); + Double_t rtime = timer.RealTime(); + Double_t ctime = timer.CpuTime(); + + Float_t cpuUsage = ctime / rtime; + cout << ""; + cout << cpuUsage; + cout << "" << endl; + + cout << endl << endl; + cout << "Output file is " << outFile << endl; + cout << "Parameter file is " << parFile << endl; + cout << "Real time " << rtime << " s, CPU time " << ctime << "s" << endl << endl; + cout << "Macro finished successfully." << endl; + + // ------------------------------------------------------------------------ } diff --git a/examples/MQ/pixelDetector/macros/run_tracks.C b/examples/MQ/pixelDetector/macros/run_tracks.C index beae4a7335..11998d5a6d 100644 --- a/examples/MQ/pixelDetector/macros/run_tracks.C +++ b/examples/MQ/pixelDetector/macros/run_tracks.C @@ -5,84 +5,82 @@ * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ -void run_tracks( TString mcEngine="TGeant3" ) +void run_tracks(TString mcEngine = "TGeant3") { - // Verbosity level (0=quiet, 1=event level, 2=track level, 3=debug) - Int_t iVerbose = 0; // just forget about it, for the moment + // Verbosity level (0=quiet, 1=event level, 2=track level, 3=debug) + Int_t iVerbose = 0; // just forget about it, for the moment - // Input file (MC events) - TString inFile = "pixel_"; - inFile = inFile + mcEngine + ".hits.root"; + // Input file (MC events) + TString inFile = "pixel_"; + inFile = inFile + mcEngine + ".hits.root"; - // Parameter file - TString parFile = "pixel_"; - parFile = parFile + mcEngine + ".params.root"; + // Parameter file + TString parFile = "pixel_"; + parFile = parFile + mcEngine + ".params.root"; - // Digitization parameter file - TString dir = getenv("VMCWORKDIR"); - TString tutdir = dir + "/MQ/pixelDetector"; - TString digParFile = tutdir + "/param/pixel_digi.par"; + // Digitization parameter file + TString dir = getenv("VMCWORKDIR"); + TString tutdir = dir + "/MQ/pixelDetector"; + TString digParFile = tutdir + "/param/pixel_digi.par"; - // Output file - TString outFile = "pixel_"; - outFile = outFile + mcEngine + ".tracks.root"; + // Output file + TString outFile = "pixel_"; + outFile = outFile + mcEngine + ".tracks.root"; - // ----- Timer -------------------------------------------------------- - TStopwatch timer; + // ----- Timer -------------------------------------------------------- + TStopwatch timer; - // ----- Reconstruction run ------------------------------------------- - FairRunAna *fRun= new FairRunAna(); - FairFileSource *fFileSource = new FairFileSource(inFile); - fRun->SetSource(fFileSource); - fRun->SetSink(new FairRootFileSink(outFile)); + // ----- Reconstruction run ------------------------------------------- + FairRunAna* fRun = new FairRunAna(); + FairFileSource* fFileSource = new FairFileSource(inFile); + fRun->SetSource(fFileSource); + fRun->SetSink(new FairRootFileSink(outFile)); - FairRuntimeDb* rtdb = fRun->GetRuntimeDb(); - FairParRootFileIo* parInput1 = new FairParRootFileIo(); - parInput1->open(parFile.Data()); + FairRuntimeDb* rtdb = fRun->GetRuntimeDb(); + FairParRootFileIo* parInput1 = new FairParRootFileIo(); + parInput1->open(parFile.Data()); - FairParAsciiFileIo* parIo1 = new FairParAsciiFileIo(); - parIo1->open(digParFile.Data(),"in"); + FairParAsciiFileIo* parIo1 = new FairParAsciiFileIo(); + parIo1->open(digParFile.Data(), "in"); - rtdb->setFirstInput(parInput1); - rtdb->setSecondInput(parIo1); + rtdb->setFirstInput(parInput1); + rtdb->setSecondInput(parIo1); - // ----- TorinoDetector hit producers --------------------------------- - PixelFindTracks* trackFinderTask = new PixelFindTracks(); - fRun->AddTask(trackFinderTask); + // ----- TorinoDetector hit producers --------------------------------- + PixelFindTracks* trackFinderTask = new PixelFindTracks(); + fRun->AddTask(trackFinderTask); + fRun->Init(); - fRun->Init(); + timer.Start(); + fRun->Run(); - timer.Start(); - fRun->Run(); + // ----- Finish ------------------------------------------------------- - // ----- Finish ------------------------------------------------------- + cout << endl << endl; - cout << endl << endl; + // Extract the maximal used memory an add is as Dart measurement + // This line is filtered by CTest and the value send to CDash + FairSystemInfo sysInfo; + Float_t maxMemory = sysInfo.GetMaxMemory(); + cout << ""; + cout << maxMemory; + cout << "" << endl; - // Extract the maximal used memory an add is as Dart measurement - // This line is filtered by CTest and the value send to CDash - FairSystemInfo sysInfo; - Float_t maxMemory=sysInfo.GetMaxMemory(); - cout << ""; - cout << maxMemory; - cout << "" << endl; + timer.Stop(); + Double_t rtime = timer.RealTime(); + Double_t ctime = timer.CpuTime(); - timer.Stop(); - Double_t rtime = timer.RealTime(); - Double_t ctime = timer.CpuTime(); + Float_t cpuUsage = ctime / rtime; + cout << ""; + cout << cpuUsage; + cout << "" << endl; - Float_t cpuUsage=ctime/rtime; - cout << ""; - cout << cpuUsage; - cout << "" << endl; + cout << endl << endl; + cout << "Output file is " << outFile << endl; + cout << "Parameter file is " << parFile << endl; + cout << "Real time " << rtime << " s, CPU time " << ctime << "s" << endl << endl; + cout << "Macro finished successfully." << endl; - cout << endl << endl; - cout << "Output file is " << outFile << endl; - cout << "Parameter file is " << parFile << endl; - cout << "Real time " << rtime << " s, CPU time " << ctime - << "s" << endl << endl; - cout << "Macro finished successfully." << endl; - - // ------------------------------------------------------------------------ + // ------------------------------------------------------------------------ } diff --git a/examples/MQ/pixelDetector/run/runMQSim.cxx b/examples/MQ/pixelDetector/run/runMQSim.cxx index 4df580f759..a2fd095785 100644 --- a/examples/MQ/pixelDetector/run/runMQSim.cxx +++ b/examples/MQ/pixelDetector/run/runMQSim.cxx @@ -6,42 +6,41 @@ * copied verbatim in the file "LICENSE" * ********************************************************************************/ -#include "runFairMQDevice.h" - -#include "Pixel.h" -#include "PixelDigitize.h" -#include "FairOnlineSink.h" - +#include "FairBoxGenerator.h" +#include "FairCave.h" #include "FairMQSimDevice.h" #include "FairModule.h" -#include "FairCave.h" -#include "FairPrimaryGenerator.h" -#include "FairBoxGenerator.h" +#include "FairOnlineSink.h" #include "FairParAsciiFileIo.h" +#include "FairPrimaryGenerator.h" +#include "Pixel.h" +#include "PixelDigitize.h" +#include "runFairMQDevice.h" -#include -#include #include #include +#include #include - -#include -#include +#include #include #include +#include +#include namespace bpo = boost::program_options; void addCustomOptions(bpo::options_description& options) { + // clang-format off options.add_options() - ("random-seed", bpo::value ()->default_value(0) , "Random seed number") - ("transport-name", bpo::value()->default_value("TGeant3") , "Transport name") - ("nof-events", bpo::value ()->required() , "Number of events to simulate") - ("fairroot-config-dir", bpo::value()->default_value("") , "FairRoot config dir") + ("random-seed", bpo::value ()->default_value(0), "Random seed number") + ("transport-name", bpo::value()->default_value("TGeant3"), "Transport name") + ("nof-events", bpo::value ()->required(), "Number of events to simulate") + ("fairroot-config-dir", bpo::value()->default_value(""), "FairRoot config dir") ("param-channel-name", bpo::value()->default_value("updateChannel"), "Parameter update channel name") - ("run-digi-tasks", bpo::value ()->default_value(false) , "Run digi tasks") - ; + ("run-digi-tasks", bpo::value ()->default_value(false), "Run digi tasks") + // clang-format on + ; } FairMQDevicePtr getDevice(const FairMQProgOptions& config) @@ -87,8 +86,8 @@ FairMQDevicePtr getDevice(const FairMQProgOptions& config) detArray->Add(det); run->SetDetectorArray(detArray); - TString partName[] = {"pions","eplus","proton"}; - Int_t partPdgC[] = { 211, 11, 2212}; + TString partName[] = {"pions", "eplus", "proton"}; + Int_t partPdgC[] = {211, 11, 2212}; Int_t chosenPart = 0; FairPrimaryGenerator* primGen = new FairPrimaryGenerator(); @@ -105,7 +104,7 @@ FairMQDevicePtr getDevice(const FairMQProgOptions& config) // Attach tasks if needed TString digParFile = tutdir + "/param/pixel_digi.par"; FairParAsciiFileIo* parIo1 = new FairParAsciiFileIo(); - parIo1->open(digParFile.Data(),"in"); + parIo1->open(digParFile.Data(), "in"); run->SetFirstParameter(parIo1); TObjArray* taskArray = new TObjArray(); diff --git a/examples/MQ/pixelDetector/run/runPixelFileSink.cxx b/examples/MQ/pixelDetector/run/runPixelFileSink.cxx index 4acd9d759a..d416886bc6 100644 --- a/examples/MQ/pixelDetector/run/runPixelFileSink.cxx +++ b/examples/MQ/pixelDetector/run/runPixelFileSink.cxx @@ -6,9 +6,8 @@ * copied verbatim in the file "LICENSE" * ********************************************************************************/ -#include "runFairMQDevice.h" - #include "FairMQPixelFileSink.h" +#include "runFairMQDevice.h" #include @@ -16,13 +15,12 @@ namespace bpo = boost::program_options; void addCustomOptions(bpo::options_description& options) { + // clang-format off options.add_options() - ("file-name", bpo::value() , "Path to the output file") + ("file-name", bpo::value(), "Path to the output file") ("in-channel", bpo::value()->default_value("data-in"), "input channel name") - ("ack-channel", bpo::value() , "ack channel name"); + ("ack-channel", bpo::value(), "ack channel name"); + // clang-format on } -FairMQDevicePtr getDevice(const FairMQProgOptions& /*config*/) -{ - return new FairMQPixelFileSink(); -} +FairMQDevicePtr getDevice(const FairMQProgOptions& /*config*/) { return new FairMQPixelFileSink(); } diff --git a/examples/MQ/pixelDetector/run/runPixelFileSinkBin.cxx b/examples/MQ/pixelDetector/run/runPixelFileSinkBin.cxx index 58f4a4a336..a100bf6634 100644 --- a/examples/MQ/pixelDetector/run/runPixelFileSinkBin.cxx +++ b/examples/MQ/pixelDetector/run/runPixelFileSinkBin.cxx @@ -11,22 +11,21 @@ // PixelDetector example #include "FairMQPixelFileSinkBin.h" -#include #include +#include namespace bpo = boost::program_options; void addCustomOptions(bpo::options_description& options) { + // clang-format off options.add_options() - ("file-name", bpo::value () , "Path to the output file") - ("class-name", bpo::value>() , "class name") - ("branch-name", bpo::value>() , "branch name") - ("in-channel", bpo::value ()->default_value("data-in"), "input channel name") - ("ack-channel", bpo::value () , "ack channel name"); + ("file-name", bpo::value(), "Path to the output file") + ("class-name", bpo::value>(), "class name") + ("branch-name", bpo::value>(), "branch name") + ("in-channel", bpo::value()->default_value("data-in"), "input channel name") + ("ack-channel", bpo::value(), "ack channel name"); + // clang-format on } -FairMQDevicePtr getDevice(const FairMQProgOptions& /*config*/) -{ - return new FairMQPixelFileSinkBin(); -} +FairMQDevicePtr getDevice(const FairMQProgOptions& /*config*/) { return new FairMQPixelFileSinkBin(); } diff --git a/examples/MQ/pixelDetector/run/runPixelMerger.cxx b/examples/MQ/pixelDetector/run/runPixelMerger.cxx index 94575ff31f..62f3daf88a 100644 --- a/examples/MQ/pixelDetector/run/runPixelMerger.cxx +++ b/examples/MQ/pixelDetector/run/runPixelMerger.cxx @@ -13,11 +13,6 @@ namespace bpo = boost::program_options; -void addCustomOptions(bpo::options_description& /*options*/) -{ -} +void addCustomOptions(bpo::options_description& /*options*/) {} -FairMQDevicePtr getDevice(const FairMQProgOptions& /*config*/) -{ - return new FairMQPixelMerger(); -} +FairMQDevicePtr getDevice(const FairMQProgOptions& /*config*/) { return new FairMQPixelMerger(); } diff --git a/examples/MQ/pixelDetector/run/runPixelSampler.cxx b/examples/MQ/pixelDetector/run/runPixelSampler.cxx index dce57eaee5..db876ddb14 100644 --- a/examples/MQ/pixelDetector/run/runPixelSampler.cxx +++ b/examples/MQ/pixelDetector/run/runPixelSampler.cxx @@ -6,35 +6,36 @@ * copied verbatim in the file "LICENSE" * ********************************************************************************/ -#include "runFairMQDevice.h" - -#include "PixelDigiSource.h" #include "PixelDigiBinSource.h" +#include "PixelDigiSource.h" +#include "runFairMQDevice.h" // PixelDetector example #include "FairMQPixelSampler.h" +#include #include #include -#include namespace bpo = boost::program_options; void addCustomOptions(bpo::options_description& options) { + // clang-format off options.add_options() - ("file-name", bpo::value>() , "Path to the input file") - ("max-index", bpo::value ()->default_value(-1) , "number of events to read") - ("branch-name", bpo::value>()->required() , "branch name") - ("sampler-type", bpo::value ()->default_value("FairFileSource") , "FairSource type") - ("out-channel", bpo::value ()->default_value("data-out") , "output channel name") - ("ack-channel", bpo::value ()->default_value("") , "ack channel name"); + ("file-name", bpo::value>(), "Path to the input file") + ("max-index", bpo::value()->default_value(-1), "number of events to read") + ("branch-name", bpo::value>()->required(), "branch name") + ("sampler-type", bpo::value()->default_value("FairFileSource"), "FairSource type") + ("out-channel", bpo::value()->default_value("data-out"), "output channel name") + ("ack-channel", bpo::value()->default_value(""), "ack channel name"); + // clang-format on } FairMQDevicePtr getDevice(const FairMQProgOptions& config) { - std::string samplerType = config.GetValue ("sampler-type"); - std::vector filename = config.GetValue>("file-name"); + std::string samplerType = config.GetValue("sampler-type"); + std::vector filename = config.GetValue>("file-name"); FairMQPixelSampler* sampler = new FairMQPixelSampler(); @@ -50,9 +51,10 @@ FairMQDevicePtr getDevice(const FairMQProgOptions& config) sampler->SetSource(digiSource); } } else { - LOG(error) << "Sampler \"" << samplerType << "\" unknown! Set it to \"FairFileSource\" or \"PixelDigiSource\" or \"PixelDigiBinSource\""; + LOG(error) << "Sampler \"" << samplerType + << "\" unknown! Set it to \"FairFileSource\" or \"PixelDigiSource\" or \"PixelDigiBinSource\""; return nullptr; } - return sampler; + return sampler; } diff --git a/examples/MQ/pixelDetector/run/runPixelSamplerBin.cxx b/examples/MQ/pixelDetector/run/runPixelSamplerBin.cxx index 2c4d580f37..0119c559fa 100644 --- a/examples/MQ/pixelDetector/run/runPixelSamplerBin.cxx +++ b/examples/MQ/pixelDetector/run/runPixelSamplerBin.cxx @@ -11,23 +11,22 @@ // PixelDetector example #include "FairMQPixelSamplerBin.h" +#include #include #include -#include namespace bpo = boost::program_options; void addCustomOptions(bpo::options_description& options) { + // clang-format off options.add_options() - ("file-name", bpo::value>() , "Path to the input file") - ("max-index", bpo::value ()->default_value(-1) , "number of events to read") - ("branch-name", bpo::value>() , "branch name") - ("out-channel", bpo::value ()->default_value("data-out"), "output channel name") - ("ack-channel", bpo::value ()->default_value("") , "ack channel name"); + ("file-name", bpo::value>(), "Path to the input file") + ("max-index", bpo::value()->default_value(-1), "number of events to read") + ("branch-name", bpo::value>(), "branch name") + ("out-channel", bpo::value()->default_value("data-out"), "output channel name") + ("ack-channel", bpo::value()->default_value(""), "ack channel name"); + // clang-format on } -FairMQDevicePtr getDevice(const FairMQProgOptions& /*config*/) -{ - return new FairMQPixelSamplerBin; -} +FairMQDevicePtr getDevice(const FairMQProgOptions& /*config*/) { return new FairMQPixelSamplerBin; } diff --git a/examples/MQ/pixelDetector/run/runPixelTaskProcessor.cxx b/examples/MQ/pixelDetector/run/runPixelTaskProcessor.cxx index d03b39323b..76eca413b8 100644 --- a/examples/MQ/pixelDetector/run/runPixelTaskProcessor.cxx +++ b/examples/MQ/pixelDetector/run/runPixelTaskProcessor.cxx @@ -6,20 +6,19 @@ * copied verbatim in the file "LICENSE" * ********************************************************************************/ -#include "runFairMQDevice.h" - #include "PixelDigitize.h" #include "PixelFindHits.h" #include "PixelFindTracks.h" #include "PixelFitTracks.h" +#include "runFairMQDevice.h" // PixelDetector example #include "FairMQPixelTaskProcessor.h" #include -using Digitizer = FairMQPixelTaskProcessor; -using HitFinder = FairMQPixelTaskProcessor; +using Digitizer = FairMQPixelTaskProcessor; +using HitFinder = FairMQPixelTaskProcessor; using TrackFinder = FairMQPixelTaskProcessor; using TrackFitter = FairMQPixelTaskProcessor; @@ -27,13 +26,15 @@ namespace bpo = boost::program_options; void addCustomOptions(bpo::options_description& options) { + // clang-format off options.add_options() - ("task-name", bpo::value()->required() , "Name of task to run") - ("keep-data", bpo::value() , "Name of data to keep in stream") - ("in-channel", bpo::value()->default_value("data-in") , "input channel name") + ("task-name", bpo::value()->required(), "Name of task to run") + ("keep-data", bpo::value(), "Name of data to keep in stream") + ("in-channel", bpo::value()->default_value("data-in"), "input channel name") ("out-channel", bpo::value()->default_value("data-out"), "output channel name") - ("par-channel", bpo::value()->default_value("param") , "param channel name") - ("static-pars", bpo::value ()->default_value(false) , "static parameters flag"); + ("par-channel", bpo::value()->default_value("param"), "param channel name") + ("static-pars", bpo::value()->default_value(false), "static parameters flag"); + // clang-format on } FairMQDevicePtr getDevice(const FairMQProgOptions& config) diff --git a/examples/MQ/pixelDetector/run/runPixelTaskProcessorBin.cxx b/examples/MQ/pixelDetector/run/runPixelTaskProcessorBin.cxx index 61a72259d7..11acb90c11 100644 --- a/examples/MQ/pixelDetector/run/runPixelTaskProcessorBin.cxx +++ b/examples/MQ/pixelDetector/run/runPixelTaskProcessorBin.cxx @@ -6,9 +6,8 @@ * copied verbatim in the file "LICENSE" * ********************************************************************************/ -#include "runFairMQDevice.h" - #include "PixelFindHits.h" +#include "runFairMQDevice.h" // PixelDetector example #include "FairMQPixelTaskProcessorBin.h" @@ -21,13 +20,15 @@ namespace bpo = boost::program_options; void addCustomOptions(bpo::options_description& options) { + // clang-format off options.add_options() - ("task-name", bpo::value()->required() , "Name of task to run") - ("keep-data", bpo::value() , "Name of data to keep in stream") - ("in-channel", bpo::value()->default_value("data-in") , "input channel name") + ("task-name", bpo::value()->required(), "Name of task to run") + ("keep-data", bpo::value(), "Name of data to keep in stream") + ("in-channel", bpo::value()->default_value("data-in"), "input channel name") ("out-channel", bpo::value()->default_value("data-out"), "output channel name") - ("par-channel", bpo::value()->default_value("param") , "param channel name") - ("static-pars", bpo::value ()->default_value(false) , "static parameters flag"); + ("par-channel", bpo::value()->default_value("param"), "param channel name") + ("static-pars", bpo::value()->default_value(false), "static parameters flag"); + // clang-format on } FairMQDevicePtr getDevice(const FairMQProgOptions& config) diff --git a/examples/MQ/pixelDetector/src/FairOnlineSink.cxx b/examples/MQ/pixelDetector/src/FairOnlineSink.cxx index cbaaa32568..31a96be69f 100644 --- a/examples/MQ/pixelDetector/src/FairOnlineSink.cxx +++ b/examples/MQ/pixelDetector/src/FairOnlineSink.cxx @@ -15,36 +15,32 @@ #include "FairOnlineSink.h" #include "FairMQRunDevice.h" - #include "FairRootManager.h" #include FairOnlineSink::FairOnlineSink() - : FairSink() - , fMQRunDevice(nullptr) -{ -} + : FairSink() + , fMQRunDevice(nullptr) +{} FairOnlineSink::FairOnlineSink(const FairOnlineSink&) - : FairSink() - , fMQRunDevice(nullptr) -{ -} + : FairSink() + , fMQRunDevice(nullptr) +{} //_____________________________________________________________________________ -void FairOnlineSink::RegisterImpl(const char* , const char* , void* ) -{ - return; -} +void FairOnlineSink::RegisterImpl(const char*, const char*, void*) { return; } //_____________________________________________________________________________ -void FairOnlineSink::RegisterAny(const char* brname, const std::type_info &oi, const std::type_info &pi, void* obj) { - fPersistentBranchesMap[brname]=std::unique_ptr (new TypeAddressPair(oi, pi,obj)); +void FairOnlineSink::RegisterAny(const char* brname, const std::type_info& oi, const std::type_info& pi, void* obj) +{ + fPersistentBranchesMap[brname] = std::unique_ptr(new TypeAddressPair(oi, pi, obj)); } //_____________________________________________________________________________ -bool FairOnlineSink::IsPersistentBranchAny(const char *name) { +bool FairOnlineSink::IsPersistentBranchAny(const char* name) +{ if (fPersistentBranchesMap.find(name) == fPersistentBranchesMap.end()) { return false; } @@ -52,28 +48,32 @@ bool FairOnlineSink::IsPersistentBranchAny(const char *name) { } //_____________________________________________________________________________ -void FairOnlineSink::EmitPersistentBranchWrongTypeWarning(const char* brname, const char *type1, const char *type2) const { - LOG(warn) << "Trying to read from persistent branch " << brname - << " with wrong type " << type1 - << " (expexted: " << type2 << " )"; +void FairOnlineSink::EmitPersistentBranchWrongTypeWarning(const char* brname, + const char* type1, + const char* type2) const +{ + LOG(warn) << "Trying to read from persistent branch " << brname << " with wrong type " << type1 + << " (expexted: " << type2 << " )"; } //_____________________________________________________________________________ void FairOnlineSink::Fill() { - /// Fill the Root tree. - LOG(debug) << "[" << FairRootManager::Instance()->GetInstanceId() << "] called FairOnlineSink::Fill()!!!!"; + /// Fill the Root tree. + LOG(debug) << "[" << FairRootManager::Instance()->GetInstanceId() << "] called FairOnlineSink::Fill()!!!!"; - if ( fMQRunDevice ) - fMQRunDevice->SendBranches(); + if (fMQRunDevice) + fMQRunDevice->SendBranches(); } //_____________________________________________________________________________ -FairSink* FairOnlineSink::CloneSink() { +FairSink* FairOnlineSink::CloneSink() +{ FairRootManager* tempMan = FairRootManager::Instance(); FairOnlineSink* newSink = new FairOnlineSink(*this); newSink->SetMQRunDevice(this->GetMQRunDevice()); - LOG(info) << "[" << tempMan->GetInstanceId() << "] FairOnlineSink::CloneSink() setting MQRunDevice to " << this->GetMQRunDevice(); + LOG(info) << "[" << tempMan->GetInstanceId() << "] FairOnlineSink::CloneSink() setting MQRunDevice to " + << this->GetMQRunDevice(); return newSink; } diff --git a/examples/MQ/pixelDetector/src/FairOnlineSink.h b/examples/MQ/pixelDetector/src/FairOnlineSink.h index 07f8765f70..83ec9216e0 100644 --- a/examples/MQ/pixelDetector/src/FairOnlineSink.h +++ b/examples/MQ/pixelDetector/src/FairOnlineSink.h @@ -19,7 +19,6 @@ #include "FairSink.h" #include - #include #include @@ -34,48 +33,47 @@ class FairOnlineSink : public FairSink FairOnlineSink(); virtual ~FairOnlineSink() {} - virtual Bool_t InitSink() { return kTRUE; } - virtual void Close() {} - virtual void Reset() {} + virtual Bool_t InitSink() { return kTRUE; } + virtual void Close() {} + virtual void Reset() {} virtual Sink_Type GetSinkType() { return kONLINESINK; } - virtual void FillEventHeader(FairEventHeader* /* feh */) {} + virtual void FillEventHeader(FairEventHeader* /* feh */) {} - virtual void SetOutTree(TTree* /* fTree */) { return; } + virtual void SetOutTree(TTree* /* fTree */) { return; } - virtual void Fill(); + virtual void Fill(); - virtual Int_t Write(const char* /* name=0 */, Int_t /* option=0 */, Int_t /* bufsize=0 */) {return -1;} + virtual Int_t Write(const char* /* name=0 */, Int_t /* option=0 */, Int_t /* bufsize=0 */) { return -1; } - virtual void RegisterImpl(const char* , const char* , void* ); - virtual void RegisterAny(const char* brname, const std::type_info &oi, const std::type_info &pi, void* obj); + virtual void RegisterImpl(const char*, const char*, void*); + virtual void RegisterAny(const char* brname, const std::type_info& oi, const std::type_info& pi, void* obj); - virtual void WriteFolder() {} - virtual bool CreatePersistentBranchesAny() {return false;} + virtual void WriteFolder() {} + virtual bool CreatePersistentBranchesAny() { return false; } - virtual void WriteObject(TObject* /* f */, const char*, Int_t /* option = 0 */) {} - virtual void WriteGeometry() {} + virtual void WriteObject(TObject* /* f */, const char*, Int_t /* option = 0 */) {} + virtual void WriteGeometry() {} - virtual void SetMQRunDevice(FairMQRunDevice* mrs) { fMQRunDevice = mrs;} - virtual FairMQRunDevice* GetMQRunDevice() { return fMQRunDevice;} + virtual void SetMQRunDevice(FairMQRunDevice* mrs) { fMQRunDevice = mrs; } + virtual FairMQRunDevice* GetMQRunDevice() { return fMQRunDevice; } - virtual FairSink* CloneSink(); + virtual FairSink* CloneSink(); - bool IsPersistentBranchAny(const char *name); + bool IsPersistentBranchAny(const char* name); /* /// Returns a default object for a branch or looks it up when it exists already. */ /* /// Returns nullptr when the branch does not exist or looking up with wrong type. */ /* /// The returned default object will be filled with data by the framework. */ template - T GetPersistentBranchAny(const char* name) const; - + T GetPersistentBranchAny(const char* name) const; - private: + private: FairMQRunDevice* fMQRunDevice; // private helper function to emit a warning - void EmitPersistentBranchWrongTypeWarning(const char* brname, const char *typen1, const char *typen2) const; + void EmitPersistentBranchWrongTypeWarning(const char* brname, const char* typen1, const char* typen2) const; FairOnlineSink(const FairOnlineSink&); FairOnlineSink& operator=(const FairOnlineSink&); @@ -83,19 +81,20 @@ class FairOnlineSink : public FairSink // try to retrieve an object address from the registered branches/names template -T FairOnlineSink::GetPersistentBranchAny(const char* brname) const { - static_assert(std::is_pointer::value, "Return type of GetPersistentBranchAny has to be a pointer"); - using P = typename std::remove_pointer::type; - auto iter = fPersistentBranchesMap.find(brname); - if(iter != fPersistentBranchesMap.end()) { - // verify type consistency - if(typeid(P).hash_code() != iter->second->origtypeinfo.hash_code()) { - EmitPersistentBranchWrongTypeWarning(brname, typeid(P).name(), iter->second->origtypeinfo.name()); - return nullptr; +T FairOnlineSink::GetPersistentBranchAny(const char* brname) const +{ + static_assert(std::is_pointer::value, "Return type of GetPersistentBranchAny has to be a pointer"); + using P = typename std::remove_pointer::type; + auto iter = fPersistentBranchesMap.find(brname); + if (iter != fPersistentBranchesMap.end()) { + // verify type consistency + if (typeid(P).hash_code() != iter->second->origtypeinfo.hash_code()) { + EmitPersistentBranchWrongTypeWarning(brname, typeid(P).name(), iter->second->origtypeinfo.name()); + return nullptr; + } + return static_cast(iter->second->ptraddr); } - return static_cast(iter->second->ptraddr); - } - return nullptr; + return nullptr; } #endif /* FAIRONLINESIK_H_ */ diff --git a/examples/MQ/pixelDetector/src/Pixel.cxx b/examples/MQ/pixelDetector/src/Pixel.cxx index 25b8425ce0..1c2d94a68f 100644 --- a/examples/MQ/pixelDetector/src/Pixel.cxx +++ b/examples/MQ/pixelDetector/src/Pixel.cxx @@ -7,206 +7,198 @@ ********************************************************************************/ #include "Pixel.h" -#include "PixelPoint.h" +#include "FairDetectorList.h" // for DetectorId::kTutDet +#include "FairLogger.h" // for logging +#include "FairRootManager.h" // for FairRootManager +#include "FairRunSim.h" // for FairRunSim +#include "FairStack.h" // for FairStack +#include "FairVolume.h" // for FairVolume #include "PixelGeo.h" #include "PixelGeoPar.h" +#include "PixelPoint.h" -#include "FairDetectorList.h" // for DetectorId::kTutDet -#include "FairRootManager.h" // for FairRootManager -#include "FairRunSim.h" // for FairRunSim -#include "FairStack.h" // for FairStack -#include "FairVolume.h" // for FairVolume -#include "FairLogger.h" // for logging - -#include // for TClonesArray -#include // for TString -#include // for TVirtualMC -#include // for TVirtualMCStack -#include +#include // for TClonesArray #include #include - +#include +#include // for TString +#include // for TVirtualMC +#include // for TVirtualMCStack #include using std::cout; using std::endl; Pixel::Pixel() - : FairDetector("Pixel", kTRUE, kPixel), - fTrackID(-1), - fVolumeID(-1), - fPos(), - fMom(), - fTime(-1.), - fLength(-1.), - fELoss(-1), - fPixelPointCollection(new TClonesArray("PixelPoint")) -{ -} + : FairDetector("Pixel", kTRUE, kPixel) + , fTrackID(-1) + , fVolumeID(-1) + , fPos() + , fMom() + , fTime(-1.) + , fLength(-1.) + , fELoss(-1) + , fPixelPointCollection(new TClonesArray("PixelPoint")) +{} Pixel::Pixel(const char* name, Bool_t active) - : FairDetector(name, active, kPixel), - fTrackID(-1), - fVolumeID(-1), - fPos(), - fMom(), - fTime(-1.), - fLength(-1.), - fELoss(-1), - fPixelPointCollection(new TClonesArray("PixelPoint")) -{ -} + : FairDetector(name, active, kPixel) + , fTrackID(-1) + , fVolumeID(-1) + , fPos() + , fMom() + , fTime(-1.) + , fLength(-1.) + , fELoss(-1) + , fPixelPointCollection(new TClonesArray("PixelPoint")) +{} Pixel::Pixel(const Pixel& rhs) - : FairDetector(rhs), - fTrackID(-1), - fVolumeID(-1), - fPos(), - fMom(), - fTime(-1.), - fLength(-1.), - fELoss(-1), - fPixelPointCollection(new TClonesArray("PixelPoint")) -{ -} + : FairDetector(rhs) + , fTrackID(-1) + , fVolumeID(-1) + , fPos() + , fMom() + , fTime(-1.) + , fLength(-1.) + , fELoss(-1) + , fPixelPointCollection(new TClonesArray("PixelPoint")) +{} Pixel::~Pixel() { - if (fPixelPointCollection) { - fPixelPointCollection->Delete(); - delete fPixelPointCollection; - } + if (fPixelPointCollection) { + fPixelPointCollection->Delete(); + delete fPixelPointCollection; + } } -void Pixel::Initialize() -{ - FairDetector::Initialize(); -} +void Pixel::Initialize() { FairDetector::Initialize(); } -Bool_t Pixel::ProcessHits(FairVolume* vol) +Bool_t Pixel::ProcessHits(FairVolume* vol) { - /** This method is called from the MC stepping */ - //Set parameters at entrance of volume. Reset ELoss. - if (TVirtualMC::GetMC()->IsTrackEntering()) { - fELoss = 0.; - fTime = TVirtualMC::GetMC()->TrackTime() * 1.0e09; - fLength = TVirtualMC::GetMC()->TrackLength(); - TVirtualMC::GetMC()->TrackPosition(fPos); - TVirtualMC::GetMC()->TrackMomentum(fMom); - } - - // Sum energy loss for all steps in the active volume - fELoss += TVirtualMC::GetMC()->Edep(); - - // Create PixelPoint at exit of active volume - if (TVirtualMC::GetMC()->IsTrackExiting() || - TVirtualMC::GetMC()->IsTrackStop() || - TVirtualMC::GetMC()->IsTrackDisappeared()) { - fTrackID = TVirtualMC::GetMC()->GetStack()->GetCurrentTrackNumber(); - fVolumeID = vol->getMCid(); - - - if (fELoss == 0.) { return kFALSE; } - - // Taking stationNr and sectorNr from string is almost effortless. - // Simulation of 100k events with 5 pions without magnetic field takes: - // - Real time 142.366 s, CPU time 140.32s WITH USING VolPath TO GET fVolumeID - // - Real time 142.407 s, CPU time 140.64s WITHOUT THE FOLLOWING TString OPERATIONS - { - TString detPath = TVirtualMC::GetMC()->CurrentVolPath(); - detPath.Remove (0,detPath.Last('/')+1); - detPath.Remove (0,detPath.First("Pixel")+5); - Int_t stationNr = detPath.Atoi(); - detPath.Remove (0,detPath.First("_")+1); - Int_t sectorNr = detPath.Atoi(); - fVolumeID = stationNr*256+sectorNr; + /** This method is called from the MC stepping */ + // Set parameters at entrance of volume. Reset ELoss. + if (TVirtualMC::GetMC()->IsTrackEntering()) { + fELoss = 0.; + fTime = TVirtualMC::GetMC()->TrackTime() * 1.0e09; + fLength = TVirtualMC::GetMC()->TrackLength(); + TVirtualMC::GetMC()->TrackPosition(fPos); + TVirtualMC::GetMC()->TrackMomentum(fMom); } - AddHit(fTrackID, fVolumeID, TVector3(fPos.X(), fPos.Y(), fPos.Z()), - TVector3(fMom.Px(), fMom.Py(), fMom.Pz()), fTime, fLength, - fELoss); - - // Increment number of Pixel det points in TParticle - FairStack* stack = static_cast(TVirtualMC::GetMC()->GetStack()); - stack->AddPoint(kPixel); - } + // Sum energy loss for all steps in the active volume + fELoss += TVirtualMC::GetMC()->Edep(); + + // Create PixelPoint at exit of active volume + if (TVirtualMC::GetMC()->IsTrackExiting() || TVirtualMC::GetMC()->IsTrackStop() + || TVirtualMC::GetMC()->IsTrackDisappeared()) { + fTrackID = TVirtualMC::GetMC()->GetStack()->GetCurrentTrackNumber(); + fVolumeID = vol->getMCid(); + + if (fELoss == 0.) { + return kFALSE; + } + + // Taking stationNr and sectorNr from string is almost effortless. + // Simulation of 100k events with 5 pions without magnetic field takes: + // - Real time 142.366 s, CPU time 140.32s WITH USING VolPath TO GET fVolumeID + // - Real time 142.407 s, CPU time 140.64s WITHOUT THE FOLLOWING TString OPERATIONS + { + TString detPath = TVirtualMC::GetMC()->CurrentVolPath(); + detPath.Remove(0, detPath.Last('/') + 1); + detPath.Remove(0, detPath.First("Pixel") + 5); + Int_t stationNr = detPath.Atoi(); + detPath.Remove(0, detPath.First("_") + 1); + Int_t sectorNr = detPath.Atoi(); + fVolumeID = stationNr * 256 + sectorNr; + } + + AddHit(fTrackID, + fVolumeID, + TVector3(fPos.X(), fPos.Y(), fPos.Z()), + TVector3(fMom.Px(), fMom.Py(), fMom.Pz()), + fTime, + fLength, + fELoss); + + // Increment number of Pixel det points in TParticle + FairStack* stack = static_cast(TVirtualMC::GetMC()->GetStack()); + stack->AddPoint(kPixel); + } - return kTRUE; + return kTRUE; } -void Pixel::EndOfEvent() -{ - fPixelPointCollection->Clear(); -} +void Pixel::EndOfEvent() { fPixelPointCollection->Clear(); } void Pixel::Register() { - /** This will create a branch in the output tree called + /** This will create a branch in the output tree called PixelPoint, 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("PixelPoint", "Pixel", - fPixelPointCollection, kTRUE); + FairRootManager::Instance()->Register("PixelPoint", "Pixel", fPixelPointCollection, kTRUE); } TClonesArray* Pixel::GetCollection(Int_t iColl) const { - if (iColl == 0) { return fPixelPointCollection; } - else { return nullptr; } + if (iColl == 0) { + return fPixelPointCollection; + } else { + return nullptr; + } } -void Pixel::Reset() -{ - fPixelPointCollection->Clear(); -} +void Pixel::Reset() { fPixelPointCollection->Clear(); } void Pixel::ConstructGeometry() { - /** If you are using the standard ASCII input for 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. */ - PixelGeo* Geo = new PixelGeo(); + PixelGeo* Geo = new PixelGeo(); ConstructASCIIGeometry(Geo, "PixelGeoPar"); } Bool_t Pixel::IsSensitive(const std::string& name) { - if ( name.find("Pixel") != std::string::npos ) { + if (name.find("Pixel") != std::string::npos) { return kTRUE; } return kFALSE; } -PixelPoint* Pixel::AddHit(Int_t trackID, Int_t detID, - TVector3 pos, TVector3 mom, - Double_t time, Double_t length, - Double_t eLoss) +PixelPoint* Pixel::AddHit(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t time, + Double_t length, + Double_t eLoss) { - TClonesArray& clref = *fPixelPointCollection; - Int_t size = clref.GetEntriesFast(); - return new(clref[size]) PixelPoint(trackID, detID, pos, mom, - time, length, eLoss); + TClonesArray& clref = *fPixelPointCollection; + Int_t size = clref.GetEntriesFast(); + return new (clref[size]) PixelPoint(trackID, detID, pos, mom, time, length, eLoss); } -FairModule* Pixel::CloneModule() const -{ - return new Pixel(*this); -} +FairModule* Pixel::CloneModule() const { return new Pixel(*this); } -extern "C" void ExternCreateDetector() { +extern "C" void ExternCreateDetector() +{ using std::cout; using std::endl; cout << "-- ExternCreateDetector() START --" << endl; FairRunSim* run = FairRunSim::Instance(); - Pixel* det = new Pixel("PixelDetector", kTRUE); + Pixel* det = new Pixel("PixelDetector", kTRUE); det->SetGeometryFileName("pixel.geo"); run->AddModule(det); cout << "-- ExternCreateDetector(" << det->GetName() << ") DONE --" << endl; } -ClassImp(Pixel) +ClassImp(Pixel); diff --git a/examples/MQ/pixelDetector/src/Pixel.h b/examples/MQ/pixelDetector/src/Pixel.h index 5bed0f8d54..56739e2325 100644 --- a/examples/MQ/pixelDetector/src/Pixel.h +++ b/examples/MQ/pixelDetector/src/Pixel.h @@ -1,30 +1,30 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef PIXEL_H #define PIXEL_H -#include "FairDetector.h" // for FairDetector +#include "FairDetector.h" // for FairDetector -#include // for Int_t, Double32_t, Double_t, etc -#include // for TLorentzVector -#include // for TVector3 +#include // for Int_t, Double32_t, Double_t, etc +#include // for TLorentzVector +#include // for TVector3 class PixelPoint; class FairVolume; class TClonesArray; -class Pixel: public FairDetector +class Pixel : public FairDetector { public: /** Name : Detector Name * Active: kTRUE for active detectors (ProcessHits() will be called) * kFALSE for inactive detectors - */ + */ Pixel(const char* Name, Bool_t Active); /** default constructor */ @@ -34,71 +34,69 @@ class Pixel: public FairDetector virtual ~Pixel(); /** 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(); /** This method is an example of how to add your own point * of type PixelPoint to the clones array - */ - PixelPoint* AddHit(Int_t trackID, Int_t detID, - TVector3 pos, TVector3 mom, - Double_t time, Double_t length, - Double_t eLoss); + */ + PixelPoint* + AddHit(Int_t trackID, Int_t detID, TVector3 pos, TVector3 mom, Double_t time, Double_t length, Double_t eLoss); /** 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 Bool_t IsSensitive(const std::string& name); + */ + + // 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 Bool_t IsSensitive(const std::string& name); virtual FairModule* CloneModule() const; - 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 + 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* fPixelPointCollection; + TClonesArray* fPixelPointCollection; Pixel(const Pixel&); Pixel& operator=(const Pixel&); - ClassDef(Pixel,1) + ClassDef(Pixel, 1) }; -#endif //PIXEL_H +#endif // PIXEL_H diff --git a/examples/MQ/pixelDetector/src/PixelContFact.cxx b/examples/MQ/pixelDetector/src/PixelContFact.cxx index eaa7567250..cddd572b81 100644 --- a/examples/MQ/pixelDetector/src/PixelContFact.cxx +++ b/examples/MQ/pixelDetector/src/PixelContFact.cxx @@ -1,73 +1,69 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "PixelContFact.h" -#include "FairRuntimeDb.h" // for FairRuntimeDb -#include "PixelDigiPar.h" // for PixelDigiPar -#include "PixelGeoPar.h" // for PixelGeoPar -#include // for TList -#include // for TString +#include "FairRuntimeDb.h" // for FairRuntimeDb +#include "PixelDigiPar.h" // for PixelDigiPar +#include "PixelGeoPar.h" // for PixelGeoPar -#include // for strcmp +#include // for TList +#include // for TString +#include // for strcmp class FairParSet; -ClassImp(PixelContFact) +ClassImp(PixelContFact); static PixelContFact gPixelContFact; PixelContFact::PixelContFact() - : FairContFact() + : FairContFact() { - /** Constructor (called when the library is loaded) */ - fName="PixelContFact"; - fTitle="Factory for parameter containers in libPixel"; - setAllContainers(); - FairRuntimeDb::instance()->addContFactory(this); + /** Constructor (called when the library is loaded) */ + fName = "PixelContFact"; + fTitle = "Factory for parameter containers in libPixel"; + setAllContainers(); + FairRuntimeDb::instance()->addContFactory(this); } void PixelContFact::setAllContainers() { - /** Creates the Container objects with all accepted + /** Creates the Container objects with all accepted contexts and adds them to the list of containers for the Pixel library. */ - FairContainer* p= new FairContainer("PixelGeoPar", - "Pixel Geometry Parameters", - "TestDefaultContext"); - p->addContext("TestNonDefaultContext"); + FairContainer* p = new FairContainer("PixelGeoPar", "Pixel Geometry Parameters", "TestDefaultContext"); + p->addContext("TestNonDefaultContext"); - containers->Add(p); + containers->Add(p); - FairContainer* p2 = new FairContainer ("PixelDigiParameters", - "Pixel digi parameters", - "TestDefaultContext"); - p2->addContext("TestNonDefaultContext"); + FairContainer* p2 = new FairContainer("PixelDigiParameters", "Pixel digi parameters", "TestDefaultContext"); + p2->addContext("TestNonDefaultContext"); - containers->Add(p2); + containers->Add(p2); } FairParSet* PixelContFact::createContainer(FairContainer* c) { - /** Calls the constructor of the corresponding parameter container. + /** 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=nullptr; - if (strcmp(name,"PixelGeoPar") == 0) { - p = new PixelGeoPar(c->getConcatName().Data(), c->GetTitle(),c->getContext()); - } - if (strcmp(name,"PixelDigiParameters") == 0) { - p = new PixelDigiPar(c->getConcatName().Data(), c->GetTitle(),c->getContext()); - } - return p; + const char* name = c->GetName(); + FairParSet* p = nullptr; + if (strcmp(name, "PixelGeoPar") == 0) { + p = new PixelGeoPar(c->getConcatName().Data(), c->GetTitle(), c->getContext()); + } + if (strcmp(name, "PixelDigiParameters") == 0) { + p = new PixelDigiPar(c->getConcatName().Data(), c->GetTitle(), c->getContext()); + } + return p; } diff --git a/examples/MQ/pixelDetector/src/PixelContFact.h b/examples/MQ/pixelDetector/src/PixelContFact.h index ec67b4f864..1d00c34116 100644 --- a/examples/MQ/pixelDetector/src/PixelContFact.h +++ b/examples/MQ/pixelDetector/src/PixelContFact.h @@ -1,17 +1,17 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef PIXELCONTFACT_H #define PIXELCONTFACT_H #include "FairContFact.h" -#include "FairContFact.h" // for FairContFact, FairContainer (ptr only) +#include "FairContFact.h" // for FairContFact, FairContainer (ptr only) -#include // for PixelContFact::Class, ClassDef, PixelContF... +#include // for PixelContFact::Class, ClassDef, PixelContF... class FairParSet; @@ -24,7 +24,7 @@ class PixelContFact : public FairContFact PixelContFact(); ~PixelContFact() {} FairParSet* createContainer(FairContainer*); - ClassDef( PixelContFact,0) // Factory for all Pixel parameter containers + ClassDef(PixelContFact, 0) // Factory for all Pixel parameter containers }; #endif diff --git a/examples/MQ/pixelDetector/src/PixelDigi.cxx b/examples/MQ/pixelDetector/src/PixelDigi.cxx index 5f3c6d8b0b..3d4adf11d1 100644 --- a/examples/MQ/pixelDetector/src/PixelDigi.cxx +++ b/examples/MQ/pixelDetector/src/PixelDigi.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* @@ -23,8 +23,7 @@ PixelDigi::PixelDigi() , fCharge(0.) , fCol(0) , fRow(0) -{ -} +{} PixelDigi::PixelDigi(Int_t in, Int_t detid, Int_t feid, Int_t col, Int_t row, Double_t ch, Double_t tstamp) : FairTimeStamp(tstamp) @@ -34,9 +33,6 @@ PixelDigi::PixelDigi(Int_t in, Int_t detid, Int_t feid, Int_t col, Int_t row, Do , fCharge(ch) , fCol(col) , fRow(row) -{ -} +{} -PixelDigi::~PixelDigi() -{ -} +PixelDigi::~PixelDigi() {} diff --git a/examples/MQ/pixelDetector/src/PixelDigi.h b/examples/MQ/pixelDetector/src/PixelDigi.h index a3779e5ee5..a59fcd3b32 100644 --- a/examples/MQ/pixelDetector/src/PixelDigi.h +++ b/examples/MQ/pixelDetector/src/PixelDigi.h @@ -15,13 +15,13 @@ #ifndef PixelDigi_H_ #define PixelDigi_H_ -#include "FairTimeStamp.h" // for FairTimeStamp +#include "FairTimeStamp.h" // for FairTimeStamp -#include // for PixelDigi::Class, ClassDef, PixelDigi::St... +#include // for PixelDigi::Class, ClassDef, PixelDigi::St... class PixelDigi : public FairTimeStamp { - public: + public: PixelDigi(); /** *\param index position of PixelPoint in TClonesArray @@ -29,24 +29,24 @@ class PixelDigi : public FairTimeStamp *\param SensorID Sensor ID from digitization scheme *\param feID front end ID *\param charge deposited charge in electrons - **/ + **/ PixelDigi(Int_t index, Int_t detID, Int_t feID, Int_t col, Int_t row, Double_t charge, Double_t timestamp = -1); virtual ~PixelDigi(); - void SetIndex(Int_t in){fPointIndex = in;}; - void SetDetectorID(Int_t det){fDetectorID=det;}; - void SetFeID(Int_t fe){fFeID=fe;}; - void SetCharge(Double_t ch){fCharge = ch;}; - void SetCol(Int_t col){fCol = col;}; - void SetRow(Int_t row){fRow = row;}; - - Int_t GetIndex(){return fPointIndex;}; - Int_t GetDetectorID(){return fDetectorID;}; - Int_t GetFeID(){return fFeID;}; - Double_t GetCharge(){return fCharge;}; - Int_t GetCol(){return fCol;}; - Int_t GetRow(){return fRow;}; + void SetIndex(Int_t in) { fPointIndex = in; }; + void SetDetectorID(Int_t det) { fDetectorID = det; }; + void SetFeID(Int_t fe) { fFeID = fe; }; + void SetCharge(Double_t ch) { fCharge = ch; }; + void SetCol(Int_t col) { fCol = col; }; + void SetRow(Int_t row) { fRow = row; }; + + Int_t GetIndex() { return fPointIndex; }; + Int_t GetDetectorID() { return fDetectorID; }; + Int_t GetFeID() { return fFeID; }; + Double_t GetCharge() { return fCharge; }; + Int_t GetCol() { return fCol; }; + Int_t GetRow() { return fRow; }; private: Int_t fPointIndex; diff --git a/examples/MQ/pixelDetector/src/PixelDigiBinSource.cxx b/examples/MQ/pixelDetector/src/PixelDigiBinSource.cxx index d4d326cc7a..aad50b9dac 100644 --- a/examples/MQ/pixelDetector/src/PixelDigiBinSource.cxx +++ b/examples/MQ/pixelDetector/src/PixelDigiBinSource.cxx @@ -14,160 +14,150 @@ // // #include "PixelDigiBinSource.h" -#include "PixelDigi.h" -#include "PixelEventHeader.h" #include "FairLogger.h" #include "FairRootManager.h" +#include "PixelDigi.h" +#include "PixelEventHeader.h" #include -#include #include - -#include +#include #include +#include PixelDigiBinSource::PixelDigiBinSource(TString inputFileName) - : FairSource() - , fEventHeader(nullptr) - , fDigis(nullptr) - , fNDigis(0) - , fTNofEvents(0) - , fTNofDigis(0) - , fInputFileName(inputFileName) - , fInputFile() - , fCurrentEntryNo(0) - , fRunId(0) - , fMCEntryNo(0) - , fPartNo(0) + : FairSource() + , fEventHeader(nullptr) + , fDigis(nullptr) + , fNDigis(0) + , fTNofEvents(0) + , fTNofDigis(0) + , fInputFileName(inputFileName) + , fInputFile() + , fCurrentEntryNo(0) + , fRunId(0) + , fMCEntryNo(0) + , fPartNo(0) { - LOG(debug) << "PixelDigiBinSource created------------"; + LOG(debug) << "PixelDigiBinSource created------------"; } -PixelDigiBinSource::~PixelDigiBinSource() -{ -} +PixelDigiBinSource::~PixelDigiBinSource() {} Bool_t PixelDigiBinSource::Init() { - // Get input array - FairRootManager* ioman = FairRootManager::Instance(); + // Get input array + FairRootManager* ioman = FairRootManager::Instance(); - LOG(info) << "PixelDigiBinSource::Init"; - if (! ioman) LOG(fatal) << "No FairRootManager"; + LOG(info) << "PixelDigiBinSource::Init"; + if (!ioman) + LOG(fatal) << "No FairRootManager"; - // Register output array StsDigi - fDigis = new TClonesArray("PixelDigi",10000); - ioman->Register("PixelDigis", "Pixel", fDigis, kFALSE); + // Register output array StsDigi + fDigis = new TClonesArray("PixelDigi", 10000); + ioman->Register("PixelDigis", "Pixel", fDigis, kFALSE); - fEventHeader = new PixelEventHeader(); - fEventHeader->SetName("EventHeader."); - ioman->Register("EventHeader.","EvtHeader", fEventHeader, kFALSE); + fEventHeader = new PixelEventHeader(); + fEventHeader->SetName("EventHeader."); + ioman->Register("EventHeader.", "EvtHeader", fEventHeader, kFALSE); - fInputFile.open(fInputFileName.Data(),std::fstream::in|std::fstream::binary); + fInputFile.open(fInputFileName.Data(), std::fstream::in | std::fstream::binary); - if (!fInputFile.is_open()) { - LOG(fatal) << "PixelDigiBinSource::Init() fInputFile \"" << fInputFileName.Data() << "\" could not be open!"; - return kFALSE; - } + if (!fInputFile.is_open()) { + LOG(fatal) << "PixelDigiBinSource::Init() fInputFile \"" << fInputFileName.Data() << "\" could not be open!"; + return kFALSE; + } - return kTRUE; + return kTRUE; } Int_t PixelDigiBinSource::ReadEvent(UInt_t i) { - fDigis->Clear(); - fNDigis = 0; - - if (!fInputFile) { - return 1; - } - - if (i == 0) { - fInputFile.clear(); - fInputFile.seekg(0, std::ios::beg); - } - - fCurrentEntryNo = i; - - std::string buffer; - LOG(debug) << "PixelDigiBinSource::ReadEvent() Begin of (" << fDigis->GetEntries() << ")"; - - Int_t head[4]; // runId, MCEntryNo, PartNo, NofDigis - fInputFile.read((char*)head,sizeof(head)); - - if (fInputFile.eof()) { - LOG(info) << "End of file reached!"; - return 1; - } - - Int_t dataSize = 4; // detId, feId, col, row - - const Int_t constNofData = head[3]*dataSize; - short int dataCont[constNofData]; - fInputFile.read((char*)dataCont,sizeof(dataCont)); - - fRunId = head[0]; - fMCEntryNo = head[1]; - fPartNo = head[2]; - fEventHeader->SetRunId(fRunId); - fEventHeader->SetMCEntryNumber(fMCEntryNo); - fEventHeader->SetPartNo(fPartNo); - - for (Int_t idata = 0 ; idata < head[3] ; idata++) { - LOG(debug) << " --/" << idata << "/--> " - << dataCont[idata*dataSize+0] << " / " - << dataCont[idata*dataSize+1] << " / " - << dataCont[idata*dataSize+2] << " / " - << dataCont[idata*dataSize+3] << " / " - << " 0."; - new ((*fDigis)[fNDigis]) PixelDigi(-1, - (Int_t)dataCont[idata*dataSize+0], - (Int_t)dataCont[idata*dataSize+1], - (Int_t)dataCont[idata*dataSize+2], - (Int_t)dataCont[idata*dataSize+3], - 0.,0.); - fNDigis++; - } - LOG(debug) << "PixelDigiBinSource::ReadEvent() End of"; - - if (!fInputFile) { - return 1; - } - - return 0; + fDigis->Clear(); + fNDigis = 0; + + if (!fInputFile) { + return 1; + } + + if (i == 0) { + fInputFile.clear(); + fInputFile.seekg(0, std::ios::beg); + } + + fCurrentEntryNo = i; + + std::string buffer; + LOG(debug) << "PixelDigiBinSource::ReadEvent() Begin of (" << fDigis->GetEntries() << ")"; + + Int_t head[4]; // runId, MCEntryNo, PartNo, NofDigis + fInputFile.read((char*)head, sizeof(head)); + + if (fInputFile.eof()) { + LOG(info) << "End of file reached!"; + return 1; + } + + Int_t dataSize = 4; // detId, feId, col, row + + const Int_t constNofData = head[3] * dataSize; + short int dataCont[constNofData]; + fInputFile.read((char*)dataCont, sizeof(dataCont)); + + fRunId = head[0]; + fMCEntryNo = head[1]; + fPartNo = head[2]; + fEventHeader->SetRunId(fRunId); + fEventHeader->SetMCEntryNumber(fMCEntryNo); + fEventHeader->SetPartNo(fPartNo); + + for (Int_t idata = 0; idata < head[3]; idata++) { + LOG(debug) << " --/" << idata << "/--> " << dataCont[idata * dataSize + 0] << " / " + << dataCont[idata * dataSize + 1] << " / " << dataCont[idata * dataSize + 2] << " / " + << dataCont[idata * dataSize + 3] << " / " + << " 0."; + new ((*fDigis)[fNDigis]) PixelDigi(-1, + (Int_t)dataCont[idata * dataSize + 0], + (Int_t)dataCont[idata * dataSize + 1], + (Int_t)dataCont[idata * dataSize + 2], + (Int_t)dataCont[idata * dataSize + 3], + 0., + 0.); + fNDigis++; + } + LOG(debug) << "PixelDigiBinSource::ReadEvent() End of"; + + if (!fInputFile) { + return 1; + } + + return 0; } -Bool_t PixelDigiBinSource::ActivateObject(TObject** obj, const char* BrName) { - if (strcmp(BrName,"PixelDigis") == 0) - *obj = (TObject*)fDigis; - else if (strcmp(BrName,"EventHeader.") == 0) - *obj = (TObject*)fEventHeader; - else - return kFALSE; - - return kTRUE; -} - -void PixelDigiBinSource::Close() +Bool_t PixelDigiBinSource::ActivateObject(TObject** obj, const char* BrName) { - fInputFile.close(); + if (strcmp(BrName, "PixelDigis") == 0) + *obj = (TObject*)fDigis; + else if (strcmp(BrName, "EventHeader.") == 0) + *obj = (TObject*)fEventHeader; + else + return kFALSE; + + return kTRUE; } -void PixelDigiBinSource::Reset() -{ -} +void PixelDigiBinSource::Close() { fInputFile.close(); } -Int_t PixelDigiBinSource::CheckMaxEventNo(Int_t /*EvtEnd*/) -{ - return -1; -} +void PixelDigiBinSource::Reset() {} + +Int_t PixelDigiBinSource::CheckMaxEventNo(Int_t /*EvtEnd*/) { return -1; } void PixelDigiBinSource::FillEventHeader(FairEventHeader* feh) { - ((PixelEventHeader*)feh)->SetRunId(fRunId); - ((PixelEventHeader*)feh)->SetMCEntryNumber(fMCEntryNo); - ((PixelEventHeader*)feh)->SetPartNo(fPartNo); + ((PixelEventHeader*)feh)->SetRunId(fRunId); + ((PixelEventHeader*)feh)->SetMCEntryNumber(fMCEntryNo); + ((PixelEventHeader*)feh)->SetPartNo(fPartNo); } -ClassImp(PixelDigiBinSource) +ClassImp(PixelDigiBinSource); diff --git a/examples/MQ/pixelDetector/src/PixelDigiBinSource.h b/examples/MQ/pixelDetector/src/PixelDigiBinSource.h index 5e597ab1f0..2b60a611f4 100644 --- a/examples/MQ/pixelDetector/src/PixelDigiBinSource.h +++ b/examples/MQ/pixelDetector/src/PixelDigiBinSource.h @@ -18,9 +18,8 @@ #include "FairSource.h" -#include #include - +#include #include class TClonesArray; @@ -31,14 +30,14 @@ class FairEventHeader; class PixelDigiBinSource : public FairSource { public: - PixelDigiBinSource(TString inputFileName="test.dat"); + PixelDigiBinSource(TString inputFileName = "test.dat"); virtual ~PixelDigiBinSource(); - Bool_t Init(); + Bool_t Init(); - Int_t ReadEvent(UInt_t i=0); - void Close(); - void Reset(); + Int_t ReadEvent(UInt_t i = 0); + void Close(); + void Reset(); virtual Source_Type GetSourceType() { return kFILE; } @@ -49,30 +48,30 @@ class PixelDigiBinSource : public FairSource virtual Bool_t ReInitUnpackers() { return kTRUE; } /**Check the maximum event number we can run to*/ - virtual Int_t CheckMaxEventNo(Int_t EvtEnd=0); + virtual Int_t CheckMaxEventNo(Int_t EvtEnd = 0); virtual void FillEventHeader(FairEventHeader* feh); - void SetInputFileName(const TString& tstr) {fInputFileName = tstr;}; + void SetInputFileName(const TString& tstr) { fInputFileName = tstr; }; - virtual Bool_t ActivateObject(TObject** obj, const char* BrName); + virtual Bool_t ActivateObject(TObject** obj, const char* BrName); private: PixelEventHeader* fEventHeader; - TClonesArray* fDigis; /** Output array of PixelDigi **/ - Int_t fNDigis; + TClonesArray* fDigis; /** Output array of PixelDigi **/ + Int_t fNDigis; - Int_t fTNofEvents; - Int_t fTNofDigis; + Int_t fTNofEvents; + Int_t fTNofDigis; - TString fInputFileName; + TString fInputFileName; std::ifstream fInputFile; - Int_t fCurrentEntryNo; + Int_t fCurrentEntryNo; - Int_t fRunId; - Int_t fMCEntryNo; - Int_t fPartNo; + Int_t fRunId; + Int_t fMCEntryNo; + Int_t fPartNo; PixelDigiBinSource(const PixelDigiBinSource&); PixelDigiBinSource& operator=(const PixelDigiBinSource&); diff --git a/examples/MQ/pixelDetector/src/PixelDigiPar.cxx b/examples/MQ/pixelDetector/src/PixelDigiPar.cxx index 015dcf6878..cdf4e7f1ba 100644 --- a/examples/MQ/pixelDetector/src/PixelDigiPar.cxx +++ b/examples/MQ/pixelDetector/src/PixelDigiPar.cxx @@ -13,87 +13,101 @@ */ #include "PixelDigiPar.h" -#include "FairParamList.h" // for FairParamList + +#include "FairParamList.h" // for FairParamList #include PixelDigiPar::PixelDigiPar(const char* name, const char* title, const char* context) -: FairParGenericSet(name,title,context), - fFeCols(0), - fFeRows(0), - fMaxFEperCol(0), - fDimX(0.), - fDimY(0.), - fRadius(0.), - fThreshold(0.), - fNoise(0.), - fCSigma(0.), - fFeBusClock(0.), - fChargeConvMethod(0), - fPixelSorterCellWidth(0.), - fPixelSorterNumberOfCells(0) + : FairParGenericSet(name, title, context) + , fFeCols(0) + , fFeRows(0) + , fMaxFEperCol(0) + , fDimX(0.) + , fDimY(0.) + , fRadius(0.) + , fThreshold(0.) + , fNoise(0.) + , fCSigma(0.) + , fFeBusClock(0.) + , fChargeConvMethod(0) + , fPixelSorterCellWidth(0.) + , fPixelSorterNumberOfCells(0) { - clear(); + clear(); } // ----- Destructor ---------------------------------------------------- -PixelDigiPar::~PixelDigiPar(void) -{ -} +PixelDigiPar::~PixelDigiPar(void) {} void PixelDigiPar::putParams(FairParamList* list) { - if(!list) return; - list->add("dimX", fDimX); - list->add("dimY", fDimY); + if (!list) + return; + list->add("dimX", fDimX); + list->add("dimY", fDimY); - list->add("threshold", fThreshold); - list->add("noise", fNoise); - list->add("FECols", fFeCols); - list->add("FERows", fFeRows); - list->add("MaxFEperCol", fMaxFEperCol); - list->add("ClustRad",fRadius); - list->add("QCloudSigma",fCSigma); - list->add("fe_BusClock", fFeBusClock); + list->add("threshold", fThreshold); + list->add("noise", fNoise); + list->add("FECols", fFeCols); + list->add("FERows", fFeRows); + list->add("MaxFEperCol", fMaxFEperCol); + list->add("ClustRad", fRadius); + list->add("QCloudSigma", fCSigma); + list->add("fe_BusClock", fFeBusClock); - list->add("chargeconv_method", fChargeConvMethod); + list->add("chargeconv_method", fChargeConvMethod); - list->add("PixelSorterCellWidth", fPixelSorterCellWidth); - list->add("PixelSorterNumberOfCells", fPixelSorterNumberOfCells); + list->add("PixelSorterCellWidth", fPixelSorterCellWidth); + list->add("PixelSorterNumberOfCells", fPixelSorterNumberOfCells); } Bool_t PixelDigiPar::getParams(FairParamList* list) { - if (!list) return kFALSE; - if (!list->fill("dimX",&fDimX)) return kFALSE; - if (!list->fill("dimY",&fDimY)) return kFALSE; - if (!list->fill("threshold",&fThreshold)) return kFALSE; - if (!list->fill("noise",&fNoise)) return kFALSE; - if (!list->fill("FECols",&fFeCols)) return kFALSE; - if (!list->fill("FERows",&fFeRows)) return kFALSE; - if (!list->fill("MaxFEperCol",&fMaxFEperCol)) return kFALSE; - if (!list->fill("ClustRad",&fRadius)) return kFALSE; - if (!list->fill("QCloudSigma",&fCSigma)) return kFALSE; - if (!list->fill("fe_BusClock",&fFeBusClock)) return kFALSE; - if (!list->fill("chargeconv_method",&fChargeConvMethod)) return kFALSE; - if (!list->fill("PixelSorterCellWidth", &fPixelSorterCellWidth)) return kFALSE; - if (!list->fill("PixelSorterNumberOfCells", &fPixelSorterNumberOfCells)) return kFALSE; - return kTRUE; + if (!list) + return kFALSE; + if (!list->fill("dimX", &fDimX)) + return kFALSE; + if (!list->fill("dimY", &fDimY)) + return kFALSE; + if (!list->fill("threshold", &fThreshold)) + return kFALSE; + if (!list->fill("noise", &fNoise)) + return kFALSE; + if (!list->fill("FECols", &fFeCols)) + return kFALSE; + if (!list->fill("FERows", &fFeRows)) + return kFALSE; + if (!list->fill("MaxFEperCol", &fMaxFEperCol)) + return kFALSE; + if (!list->fill("ClustRad", &fRadius)) + return kFALSE; + if (!list->fill("QCloudSigma", &fCSigma)) + return kFALSE; + if (!list->fill("fe_BusClock", &fFeBusClock)) + return kFALSE; + if (!list->fill("chargeconv_method", &fChargeConvMethod)) + return kFALSE; + if (!list->fill("PixelSorterCellWidth", &fPixelSorterCellWidth)) + return kFALSE; + if (!list->fill("PixelSorterNumberOfCells", &fPixelSorterNumberOfCells)) + return kFALSE; + return kTRUE; } void PixelDigiPar::Print(Option_t*) const { - std::cout<<"SDS Pixel Digitization Parameters:"< // for PixelDigiPar::Class, ClassDef, PixelD... +#include "FairParGenericSet.h" // for FairParGenericSet + +#include // for PixelDigiPar::Class, ClassDef, PixelD... class FairParamList; //! Digitization Parameter Class for Pixel detector class PixelDigiPar : public FairParGenericSet { public: - PixelDigiPar(const char* name="PixelDigiParameters", - const char* title="Pixel digi parameters", - const char* context="TestDefaultContext"); + PixelDigiPar(const char* name = "PixelDigiParameters", + const char* title = "Pixel digi parameters", + const char* context = "TestDefaultContext"); ~PixelDigiPar(void); void clear(void){}; void putParams(FairParamList* list); @@ -33,52 +34,52 @@ class PixelDigiPar : public FairParGenericSet void Print(Option_t*) const; - Double_t GetXPitch() const {return fDimX;} - Double_t GetYPitch() const {return fDimY;} - Double_t GetThreshold() const {return fThreshold;} - Double_t GetNoise() const {return fNoise;} - Double_t GetQCloudSigma() const {return fCSigma;} - Int_t GetFECols() const {return fFeCols;} - Int_t GetFERows() const {return fFeRows;} - Int_t GetMaxFEperCol() const {return fMaxFEperCol;} - Double_t GetClustRadius() const {return fRadius;} - Double_t GetFeBusClock() const {return fFeBusClock;} - Double_t GetTimeStep() const {return (1./fFeBusClock * 1000.);} ///< Time step of one clock cycle in ns - Int_t GetChargeConvMethod() const {return fChargeConvMethod;} - Double_t GetPixelSorterCellWidth() const {return fPixelSorterCellWidth;} - Int_t GetPixelSorterNumberOfCells() const {return fPixelSorterNumberOfCells;} + Double_t GetXPitch() const { return fDimX; } + Double_t GetYPitch() const { return fDimY; } + Double_t GetThreshold() const { return fThreshold; } + Double_t GetNoise() const { return fNoise; } + Double_t GetQCloudSigma() const { return fCSigma; } + Int_t GetFECols() const { return fFeCols; } + Int_t GetFERows() const { return fFeRows; } + Int_t GetMaxFEperCol() const { return fMaxFEperCol; } + Double_t GetClustRadius() const { return fRadius; } + Double_t GetFeBusClock() const { return fFeBusClock; } + Double_t GetTimeStep() const { return (1. / fFeBusClock * 1000.); } ///< Time step of one clock cycle in ns + Int_t GetChargeConvMethod() const { return fChargeConvMethod; } + Double_t GetPixelSorterCellWidth() const { return fPixelSorterCellWidth; } + Int_t GetPixelSorterNumberOfCells() const { return fPixelSorterNumberOfCells; } - void SetXPitch(Double_t x) {fDimX = x;} - void SetYPitch(Double_t x) {fDimY = x;} - void SetThreshold(Double_t x) {fThreshold = x;} - void SetNoise(Double_t x) {fNoise = x;} - void SetQCloudSigma(Double_t x) {fCSigma = x;} - void SetFECols(Int_t x) {fFeCols = x;} - void SetFERows(Int_t x) {fFeRows = x;} - void SetMaxFEperCol(Int_t x) {fMaxFEperCol = x;} - void SetClustRadius(Double_t x) {fRadius=x;} - void SetFeBusClock(Double_t x) {fFeBusClock = x;} - void SetChargeConvMethod(Int_t x) {fChargeConvMethod = x;} - void SetPixelSorterCellWidth(Double_t x) {fPixelSorterCellWidth = x;} - void SetPixelSorterNumberOfCells(Int_t x) {fPixelSorterNumberOfCells=x;} + void SetXPitch(Double_t x) { fDimX = x; } + void SetYPitch(Double_t x) { fDimY = x; } + void SetThreshold(Double_t x) { fThreshold = x; } + void SetNoise(Double_t x) { fNoise = x; } + void SetQCloudSigma(Double_t x) { fCSigma = x; } + void SetFECols(Int_t x) { fFeCols = x; } + void SetFERows(Int_t x) { fFeRows = x; } + void SetMaxFEperCol(Int_t x) { fMaxFEperCol = x; } + void SetClustRadius(Double_t x) { fRadius = x; } + void SetFeBusClock(Double_t x) { fFeBusClock = x; } + void SetChargeConvMethod(Int_t x) { fChargeConvMethod = x; } + void SetPixelSorterCellWidth(Double_t x) { fPixelSorterCellWidth = x; } + void SetPixelSorterNumberOfCells(Int_t x) { fPixelSorterNumberOfCells = x; } private: // Pixel Parameters - Int_t fFeCols; // Colums read per Frontend - Int_t fFeRows; // Rows read per Frontend - Int_t fMaxFEperCol; // max number of Frontend elemens per column - Double_t fDimX; // Pixel cell size X - Double_t fDimY; // Pixel cell size Y - Double_t fRadius; // Clusterfinder search radius (channel numbers) - Double_t fThreshold; // Discriminator Threshold (electrons) - Double_t fNoise; // Gaussian electronics noise including threshold dispersion (electrons) - Double_t fCSigma; // Gaussian charge cloud smearing - Double_t fFeBusClock; // Frontend bus clock to determin noise rate - Int_t fChargeConvMethod; // 0: ideal conversion; 1: TOT calculation - Double_t fPixelSorterCellWidth; // Parameter for TimeStamp Sorter - Int_t fPixelSorterNumberOfCells; // Parameter for TimeStamp Sorter + Int_t fFeCols; // Colums read per Frontend + Int_t fFeRows; // Rows read per Frontend + Int_t fMaxFEperCol; // max number of Frontend elemens per column + Double_t fDimX; // Pixel cell size X + Double_t fDimY; // Pixel cell size Y + Double_t fRadius; // Clusterfinder search radius (channel numbers) + Double_t fThreshold; // Discriminator Threshold (electrons) + Double_t fNoise; // Gaussian electronics noise including threshold dispersion (electrons) + Double_t fCSigma; // Gaussian charge cloud smearing + Double_t fFeBusClock; // Frontend bus clock to determin noise rate + Int_t fChargeConvMethod; // 0: ideal conversion; 1: TOT calculation + Double_t fPixelSorterCellWidth; // Parameter for TimeStamp Sorter + Int_t fPixelSorterNumberOfCells; // Parameter for TimeStamp Sorter - ClassDef(PixelDigiPar,1); + ClassDef(PixelDigiPar, 1); }; #endif /*!PIXELDIGIPAR_H*/ diff --git a/examples/MQ/pixelDetector/src/PixelDigiSource.cxx b/examples/MQ/pixelDetector/src/PixelDigiSource.cxx index 28f304d8f1..84636bd4ba 100644 --- a/examples/MQ/pixelDetector/src/PixelDigiSource.cxx +++ b/examples/MQ/pixelDetector/src/PixelDigiSource.cxx @@ -14,154 +14,147 @@ // // #include "PixelDigiSource.h" -#include "PixelDigi.h" -#include "PixelEventHeader.h" #include "FairLogger.h" #include "FairRootManager.h" +#include "PixelDigi.h" +#include "PixelEventHeader.h" #include #include - #include #include #include PixelDigiSource::PixelDigiSource(TString inputFileName) - : FairSource() - , fEventHeader(nullptr) - , fDigis(nullptr) - , fNDigis(0) - , fTNofEvents(0) - , fTNofDigis(0) - , fInputFileName(inputFileName) - , fInputFile() - , fCurrentEntryNo(0) - , fRunId(0) - , fMCEntryNo(0) - , fPartNo(0) + : FairSource() + , fEventHeader(nullptr) + , fDigis(nullptr) + , fNDigis(0) + , fTNofEvents(0) + , fTNofDigis(0) + , fInputFileName(inputFileName) + , fInputFile() + , fCurrentEntryNo(0) + , fRunId(0) + , fMCEntryNo(0) + , fPartNo(0) { - LOG(debug) << "PixelDigiSource created------------"; + LOG(debug) << "PixelDigiSource created------------"; } -PixelDigiSource::~PixelDigiSource() -{ -} +PixelDigiSource::~PixelDigiSource() {} Bool_t PixelDigiSource::Init() { - // Get input array - FairRootManager* ioman = FairRootManager::Instance(); + // Get input array + FairRootManager* ioman = FairRootManager::Instance(); - LOG(info) << "PixelDigiSource::Init"; - if (!ioman) LOG(fatal) << "No FairRootManager"; + LOG(info) << "PixelDigiSource::Init"; + if (!ioman) + LOG(fatal) << "No FairRootManager"; - // Register output array StsDigi - fDigis = new TClonesArray("PixelDigi",10000); - ioman->Register("PixelDigis", "Pixel", fDigis, kFALSE); + // Register output array StsDigi + fDigis = new TClonesArray("PixelDigi", 10000); + ioman->Register("PixelDigis", "Pixel", fDigis, kFALSE); - fEventHeader = new PixelEventHeader(); - fEventHeader->SetName("EventHeader."); - ioman->Register("EventHeader.","EvtHeader", fEventHeader, kFALSE); + fEventHeader = new PixelEventHeader(); + fEventHeader->SetName("EventHeader."); + ioman->Register("EventHeader.", "EvtHeader", fEventHeader, kFALSE); - fInputFile.open(fInputFileName.Data(),std::fstream::in); + fInputFile.open(fInputFileName.Data(), std::fstream::in); - if (!fInputFile.is_open()) { - LOG(fatal) << "PixelDigiSource::Init() fInputFile \"" << fInputFileName.Data() << "\" could not be open!"; - return kFALSE; - } + if (!fInputFile.is_open()) { + LOG(fatal) << "PixelDigiSource::Init() fInputFile \"" << fInputFileName.Data() << "\" could not be open!"; + return kFALSE; + } - return kTRUE; + return kTRUE; } int ReadIntFromString(const std::string& wholestr, const std::string& pattern) { - std::string tempstr = wholestr; - tempstr.replace(0,tempstr.find(pattern)+pattern.length(),""); - tempstr.replace(0,tempstr.find('=')+1,""); - return atoi(tempstr.c_str()); + std::string tempstr = wholestr; + tempstr.replace(0, tempstr.find(pattern) + pattern.length(), ""); + tempstr.replace(0, tempstr.find('=') + 1, ""); + return atoi(tempstr.c_str()); } Int_t PixelDigiSource::ReadEvent(UInt_t i) { - fDigis->Delete(); - fNDigis = 0; - - if (i == 0) { - fInputFile.clear(); - fInputFile.seekg(0, std::ios::beg); - } - - fCurrentEntryNo = i; - - std::string buffer; - LOG(debug) << "PixelDigiSource::ReadEvent() Begin of (" << fDigis->GetEntries() << ")"; - do { - getline(fInputFile,buffer); - LOG(debug) << "read from file: \"" << buffer << "\""; - if (buffer.find("EVENT BEGIN") == 0) { - fRunId = ReadIntFromString(buffer,"RUNID"); - fMCEntryNo = ReadIntFromString(buffer,"MCENTRYNO"); - fPartNo = ReadIntFromString(buffer,"PARTNO"); - fEventHeader->SetRunId(fRunId); - fEventHeader->SetMCEntryNumber(fMCEntryNo); - fEventHeader->SetPartNo(fPartNo); - - LOG(debug) << "GOT NEW EVENT " << fMCEntryNo << " (part " << fPartNo << ") with run id = " << fRunId; + fDigis->Delete(); + fNDigis = 0; + + if (i == 0) { + fInputFile.clear(); + fInputFile.seekg(0, std::ios::beg); } - if (buffer.find("EVENT") == 0) continue; - Int_t detId = atoi(buffer.c_str()); - buffer.erase(0, buffer.find(' ') + 1); - Int_t feId = atoi(buffer.c_str()); - buffer.erase(0, buffer.find(' ') + 1); - Int_t col = atoi(buffer.c_str()); - buffer.erase(0, buffer.find(' ') + 1); - Int_t row = atoi(buffer.c_str()); - buffer.erase(0, buffer.find(' ') + 1); - Double_t charge = atof(buffer.c_str()); - LOG(debug) << " --/" << fNDigis << "/--> " << detId << " / " << feId << " / " << col << " / " << row << " / " << charge; - new ((*fDigis)[fNDigis]) PixelDigi(-1,detId,feId,col,row,charge,0.); - fNDigis++; - } while (fInputFile && buffer.compare("EVENT END")); - LOG(debug) << "PixelDigiSource::ReadEvent() End of"; - - if (!fInputFile) { - return 1; - } - - return 0; -} -Bool_t PixelDigiSource::ActivateObject(TObject** obj, const char* BrName) { - if (strcmp(BrName,"PixelDigis")) - *obj = (TObject*)fDigis; - else if (strcmp(BrName,"EventHeader.")) - *obj = (TObject*)fEventHeader; - else - return kFALSE; + fCurrentEntryNo = i; + + std::string buffer; + LOG(debug) << "PixelDigiSource::ReadEvent() Begin of (" << fDigis->GetEntries() << ")"; + do { + getline(fInputFile, buffer); + LOG(debug) << "read from file: \"" << buffer << "\""; + if (buffer.find("EVENT BEGIN") == 0) { + fRunId = ReadIntFromString(buffer, "RUNID"); + fMCEntryNo = ReadIntFromString(buffer, "MCENTRYNO"); + fPartNo = ReadIntFromString(buffer, "PARTNO"); + fEventHeader->SetRunId(fRunId); + fEventHeader->SetMCEntryNumber(fMCEntryNo); + fEventHeader->SetPartNo(fPartNo); + + LOG(debug) << "GOT NEW EVENT " << fMCEntryNo << " (part " << fPartNo << ") with run id = " << fRunId; + } + if (buffer.find("EVENT") == 0) + continue; + Int_t detId = atoi(buffer.c_str()); + buffer.erase(0, buffer.find(' ') + 1); + Int_t feId = atoi(buffer.c_str()); + buffer.erase(0, buffer.find(' ') + 1); + Int_t col = atoi(buffer.c_str()); + buffer.erase(0, buffer.find(' ') + 1); + Int_t row = atoi(buffer.c_str()); + buffer.erase(0, buffer.find(' ') + 1); + Double_t charge = atof(buffer.c_str()); + LOG(debug) << " --/" << fNDigis << "/--> " << detId << " / " << feId << " / " << col << " / " << row + << " / " << charge; + new ((*fDigis)[fNDigis]) PixelDigi(-1, detId, feId, col, row, charge, 0.); + fNDigis++; + } while (fInputFile && buffer.compare("EVENT END")); + LOG(debug) << "PixelDigiSource::ReadEvent() End of"; + + if (!fInputFile) { + return 1; + } - return kTRUE; + return 0; } -void PixelDigiSource::Close() +Bool_t PixelDigiSource::ActivateObject(TObject** obj, const char* BrName) { - fInputFile.close(); + if (strcmp(BrName, "PixelDigis")) + *obj = (TObject*)fDigis; + else if (strcmp(BrName, "EventHeader.")) + *obj = (TObject*)fEventHeader; + else + return kFALSE; + + return kTRUE; } -void PixelDigiSource::Reset() -{ -} +void PixelDigiSource::Close() { fInputFile.close(); } -Int_t PixelDigiSource::CheckMaxEventNo(Int_t /*EvtEnd*/) -{ - return -1; -} +void PixelDigiSource::Reset() {} + +Int_t PixelDigiSource::CheckMaxEventNo(Int_t /*EvtEnd*/) { return -1; } void PixelDigiSource::FillEventHeader(FairEventHeader* feh) { - ((PixelEventHeader*)feh)->SetRunId(fRunId); - ((PixelEventHeader*)feh)->SetMCEntryNumber(fMCEntryNo); - ((PixelEventHeader*)feh)->SetPartNo(fPartNo); + ((PixelEventHeader*)feh)->SetRunId(fRunId); + ((PixelEventHeader*)feh)->SetMCEntryNumber(fMCEntryNo); + ((PixelEventHeader*)feh)->SetPartNo(fPartNo); } -ClassImp(PixelDigiSource) +ClassImp(PixelDigiSource); diff --git a/examples/MQ/pixelDetector/src/PixelDigiSource.h b/examples/MQ/pixelDetector/src/PixelDigiSource.h index d4ce6eca7f..fe051082ca 100644 --- a/examples/MQ/pixelDetector/src/PixelDigiSource.h +++ b/examples/MQ/pixelDetector/src/PixelDigiSource.h @@ -18,9 +18,8 @@ #include "FairSource.h" -#include #include - +#include #include class TClonesArray; @@ -31,14 +30,14 @@ class FairEventHeader; class PixelDigiSource : public FairSource { public: - PixelDigiSource(TString inputFileName="test.dat"); + PixelDigiSource(TString inputFileName = "test.dat"); virtual ~PixelDigiSource(); - Bool_t Init(); + Bool_t Init(); - Int_t ReadEvent(UInt_t i=0); - void Close(); - void Reset(); + Int_t ReadEvent(UInt_t i = 0); + void Close(); + void Reset(); virtual Source_Type GetSourceType() { return kFILE; } @@ -49,30 +48,30 @@ class PixelDigiSource : public FairSource virtual Bool_t ReInitUnpackers() { return kTRUE; } /**Check the maximum event number we can run to*/ - virtual Int_t CheckMaxEventNo(Int_t EvtEnd=0); + virtual Int_t CheckMaxEventNo(Int_t EvtEnd = 0); virtual void FillEventHeader(FairEventHeader* feh); void SetInputFileName(const TString& tstr) { fInputFileName = tstr; } - virtual Bool_t ActivateObject(TObject** obj, const char* BrName); + virtual Bool_t ActivateObject(TObject** obj, const char* BrName); private: PixelEventHeader* fEventHeader; - TClonesArray* fDigis; /** Output array of PixelDigi **/ - Int_t fNDigis; + TClonesArray* fDigis; /** Output array of PixelDigi **/ + Int_t fNDigis; - Int_t fTNofEvents; - Int_t fTNofDigis; + Int_t fTNofEvents; + Int_t fTNofDigis; - TString fInputFileName; + TString fInputFileName; std::ifstream fInputFile; - Int_t fCurrentEntryNo; + Int_t fCurrentEntryNo; - Int_t fRunId; - Int_t fMCEntryNo; - Int_t fPartNo; + Int_t fRunId; + Int_t fMCEntryNo; + Int_t fPartNo; PixelDigiSource(const PixelDigiSource&); PixelDigiSource& operator=(const PixelDigiSource&); diff --git a/examples/MQ/pixelDetector/src/PixelDigiWriteToBinFile.cxx b/examples/MQ/pixelDetector/src/PixelDigiWriteToBinFile.cxx index 1ecefe0db2..b02bfbe2f4 100644 --- a/examples/MQ/pixelDetector/src/PixelDigiWriteToBinFile.cxx +++ b/examples/MQ/pixelDetector/src/PixelDigiWriteToBinFile.cxx @@ -15,158 +15,153 @@ #include "PixelDigiWriteToBinFile.h" // Includes from base -#include "FairRootManager.h" #include "FairLogger.h" +#include "FairRootManager.h" // Includes from ROOT +#include "PixelDigi.h" + #include #include -#include "PixelDigi.h" - PixelDigiWriteToBinFile::PixelDigiWriteToBinFile() - : PixelDigiWriteToBinFile("Pixel DigiWriter", 0) -{ -} + : PixelDigiWriteToBinFile("Pixel DigiWriter", 0) +{} PixelDigiWriteToBinFile::PixelDigiWriteToBinFile(Int_t iVerbose) - : PixelDigiWriteToBinFile("Pixel DigiWriter", iVerbose) -{ -} + : PixelDigiWriteToBinFile("Pixel DigiWriter", iVerbose) +{} PixelDigiWriteToBinFile::PixelDigiWriteToBinFile(const char* name, Int_t iVerbose) - : FairTask(name, iVerbose) - , fDigis(nullptr) - , fOutputFileName("test.dat") - , fNofOutputFiles(0) - , fOutputFiles() - , fDivideLevel(0) - , fRunId(0) - , fMCEntryNo(0) - , fPartNo(0) + : FairTask(name, iVerbose) + , fDigis(nullptr) + , fOutputFileName("test.dat") + , fNofOutputFiles(0) + , fOutputFiles() + , fDivideLevel(0) + , fRunId(0) + , fMCEntryNo(0) + , fPartNo(0) { - Reset(); + Reset(); } -PixelDigiWriteToBinFile::~PixelDigiWriteToBinFile() -{ - Reset(); -} +PixelDigiWriteToBinFile::~PixelDigiWriteToBinFile() { Reset(); } void PixelDigiWriteToBinFile::Exec(Option_t* /*opt*/) { - Reset(); + Reset(); - Int_t nofDigis = fDigis->GetEntriesFast(); + Int_t nofDigis = fDigis->GetEntriesFast(); - Int_t digisPerFile[12] = {0,0,0,0,0,0,0,0,0,0,0,0}; + Int_t digisPerFile[12] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; - for (Int_t iDigi = 0; iDigi < nofDigis; iDigi++) { - PixelDigi* currentDigi = static_cast(fDigis->At(iDigi)); + for (Int_t iDigi = 0; iDigi < nofDigis; iDigi++) { + PixelDigi* currentDigi = static_cast(fDigis->At(iDigi)); - short int detId = (short int)currentDigi->GetDetectorID(); + short int detId = (short int)currentDigi->GetDetectorID(); - Int_t fileToSave = 0; - if (fDivideLevel == 1) { - fileToSave = detId/256 - 1; - } - else if (fDivideLevel == 2) { - fileToSave = (detId/256 - 1)*4 + (detId%256 -1); + Int_t fileToSave = 0; + if (fDivideLevel == 1) { + fileToSave = detId / 256 - 1; + } else if (fDivideLevel == 2) { + fileToSave = (detId / 256 - 1) * 4 + (detId % 256 - 1); + } + digisPerFile[fileToSave] += 1; } - digisPerFile[fileToSave] += 1; - } - - for (Int_t ifile = 0; ifile < fNofOutputFiles; ifile++) { - fOutputFiles[ifile].write((char*)&fRunId , sizeof(fRunId)); - fOutputFiles[ifile].write((char*)&fMCEntryNo , sizeof(fMCEntryNo)); - fOutputFiles[ifile].write((char*)&ifile , sizeof(ifile)); - fOutputFiles[ifile].write((char*)&digisPerFile[ifile], sizeof(digisPerFile[ifile])); - } - - for (Int_t iDigi = 0; iDigi < nofDigis; iDigi++) { - PixelDigi* currentDigi = static_cast(fDigis->At(iDigi)); - - short int detId = (short int)currentDigi->GetDetectorID(); - short int feId = (short int)currentDigi->GetFeID(); - short int col = (short int)currentDigi->GetCol(); - short int row = (short int)currentDigi->GetRow(); - - Int_t fileToSave = 0; - if (fDivideLevel == 1) { - fileToSave = detId/256 - 1; + + for (Int_t ifile = 0; ifile < fNofOutputFiles; ifile++) { + fOutputFiles[ifile].write((char*)&fRunId, sizeof(fRunId)); + fOutputFiles[ifile].write((char*)&fMCEntryNo, sizeof(fMCEntryNo)); + fOutputFiles[ifile].write((char*)&ifile, sizeof(ifile)); + fOutputFiles[ifile].write((char*)&digisPerFile[ifile], sizeof(digisPerFile[ifile])); } - else if (fDivideLevel == 2) { - fileToSave = (detId/256 - 1)*4 + (detId%256 -1); + + for (Int_t iDigi = 0; iDigi < nofDigis; iDigi++) { + PixelDigi* currentDigi = static_cast(fDigis->At(iDigi)); + + short int detId = (short int)currentDigi->GetDetectorID(); + short int feId = (short int)currentDigi->GetFeID(); + short int col = (short int)currentDigi->GetCol(); + short int row = (short int)currentDigi->GetRow(); + + Int_t fileToSave = 0; + if (fDivideLevel == 1) { + fileToSave = detId / 256 - 1; + } else if (fDivideLevel == 2) { + fileToSave = (detId / 256 - 1) * 4 + (detId % 256 - 1); + } + fOutputFiles[fileToSave].write((char*)&detId, sizeof(detId)); + fOutputFiles[fileToSave].write((char*)&feId, sizeof(feId)); + fOutputFiles[fileToSave].write((char*)&col, sizeof(col)); + fOutputFiles[fileToSave].write((char*)&row, sizeof(row)); } - fOutputFiles[fileToSave].write((char*)&detId, sizeof(detId)); - fOutputFiles[fileToSave].write((char*)&feId , sizeof(feId)); - fOutputFiles[fileToSave].write((char*)&col , sizeof(col )); - fOutputFiles[fileToSave].write((char*)&row , sizeof(row )); - } - fMCEntryNo ++; + fMCEntryNo++; } -InitStatus PixelDigiWriteToBinFile::Init() { +InitStatus PixelDigiWriteToBinFile::Init() +{ - // Get input array - FairRootManager* ioman = FairRootManager::Instance(); + // Get input array + FairRootManager* ioman = FairRootManager::Instance(); - if (! ioman) LOG(fatal) << "No FairRootManager"; - fDigis = static_cast(ioman->GetObject("PixelDigis")); + if (!ioman) + LOG(fatal) << "No FairRootManager"; + fDigis = static_cast(ioman->GetObject("PixelDigis")); - if (!fDigis) - LOG(warn) << "PixelDigiWriteToBinFile::Init() No input PixelDigis array!"; + if (!fDigis) + LOG(warn) << "PixelDigiWriteToBinFile::Init() No input PixelDigis array!"; - LOG(info) << "-I- " << fName.Data() << "::Init(). Initialization succesfull."; + LOG(info) << "-I- " << fName.Data() << "::Init(). Initialization succesfull."; - fRunId = ioman->GetRunId(); + fRunId = ioman->GetRunId(); - if (fDivideLevel == 0) { - fNofOutputFiles = 1; - fOutputFiles[0].open(fOutputFileName.Data(),std::fstream::out|std::fstream::binary); - } else { - if (fDivideLevel == 1) { - fNofOutputFiles = 3; // 1 file per station (3 stations) - } - else if (fDivideLevel == 2) { - fNofOutputFiles = 12; // 1 file per sensor (3 stations times 4 sensors) - } - else { - LOG(fatal) << "PixelDigiWriteToBinFile::Init(), fDivideLevel = " << fDivideLevel << " unknown, it has to be in the range <0,2>"; - return kFATAL; - } - for (Int_t ifile = 0; ifile < fNofOutputFiles; ifile++) { - TString fileName = fOutputFileName; - TString uniqFile = Form(".p%d.",ifile); - fileName.Replace(fileName.Last('.'),1,uniqFile.Data()); - fOutputFiles[ifile].open(fileName.Data(),std::fstream::out); + if (fDivideLevel == 0) { + fNofOutputFiles = 1; + fOutputFiles[0].open(fOutputFileName.Data(), std::fstream::out | std::fstream::binary); + } else { + if (fDivideLevel == 1) { + fNofOutputFiles = 3; // 1 file per station (3 stations) + } else if (fDivideLevel == 2) { + fNofOutputFiles = 12; // 1 file per sensor (3 stations times 4 sensors) + } else { + LOG(fatal) << "PixelDigiWriteToBinFile::Init(), fDivideLevel = " << fDivideLevel + << " unknown, it has to be in the range <0,2>"; + return kFATAL; + } + for (Int_t ifile = 0; ifile < fNofOutputFiles; ifile++) { + TString fileName = fOutputFileName; + TString uniqFile = Form(".p%d.", ifile); + fileName.Replace(fileName.Last('.'), 1, uniqFile.Data()); + fOutputFiles[ifile].open(fileName.Data(), std::fstream::out); + } } - } - return kSUCCESS; + return kSUCCESS; } InitStatus PixelDigiWriteToBinFile::ReInit() { - FairRootManager* ioman = FairRootManager::Instance(); - - InitStatus Status = kFATAL; - if (!ioman) { - LOG(fatal) << "No FairRootManager found."; - } else { - fRunId = ioman->GetRunId(); - fMCEntryNo = 0; - Status = kSUCCESS; - } - return Status; + FairRootManager* ioman = FairRootManager::Instance(); + + InitStatus Status = kFATAL; + if (!ioman) { + LOG(fatal) << "No FairRootManager found."; + } else { + fRunId = ioman->GetRunId(); + fMCEntryNo = 0; + Status = kSUCCESS; + } + return Status; } -void PixelDigiWriteToBinFile::Finish() { - for (Int_t ifile = 0; ifile < fNofOutputFiles; ifile++) { - fOutputFiles[ifile].close(); - } +void PixelDigiWriteToBinFile::Finish() +{ + for (Int_t ifile = 0; ifile < fNofOutputFiles; ifile++) { + fOutputFiles[ifile].close(); + } } -ClassImp(PixelDigiWriteToBinFile) +ClassImp(PixelDigiWriteToBinFile); diff --git a/examples/MQ/pixelDetector/src/PixelDigiWriteToBinFile.h b/examples/MQ/pixelDetector/src/PixelDigiWriteToBinFile.h index 0da1ad61dd..d3c430249c 100644 --- a/examples/MQ/pixelDetector/src/PixelDigiWriteToBinFile.h +++ b/examples/MQ/pixelDetector/src/PixelDigiWriteToBinFile.h @@ -42,16 +42,16 @@ class PixelDigiWriteToBinFile : public FairTask /** Execution **/ virtual void Exec(Option_t* opt); - void SetOutputFileName(TString tstr) {fOutputFileName = tstr;}; + void SetOutputFileName(TString tstr) { fOutputFileName = tstr; }; - void SetDivideLevel(Int_t idiv) { fDivideLevel = idiv; } // 0 - event, 1 - station, 2 - sensor + void SetDivideLevel(Int_t idiv) { fDivideLevel = idiv; } // 0 - event, 1 - station, 2 - sensor private: TClonesArray* fDigis; /** Input array of PixelDigi **/ - TString fOutputFileName; + TString fOutputFileName; Int_t fNofOutputFiles; - std::ofstream fOutputFiles[12]; // no more than 12 output files.... + std::ofstream fOutputFiles[12]; // no more than 12 output files.... /** Get parameter containers **/ virtual void SetParContainers() {} @@ -77,7 +77,7 @@ class PixelDigiWriteToBinFile : public FairTask PixelDigiWriteToBinFile(const PixelDigiWriteToBinFile&); PixelDigiWriteToBinFile& operator=(const PixelDigiWriteToBinFile&); - ClassDef(PixelDigiWriteToBinFile,1); + ClassDef(PixelDigiWriteToBinFile, 1); }; #endif diff --git a/examples/MQ/pixelDetector/src/PixelDigiWriteToFile.cxx b/examples/MQ/pixelDetector/src/PixelDigiWriteToFile.cxx index bf3b6d6158..87f2f78575 100644 --- a/examples/MQ/pixelDetector/src/PixelDigiWriteToFile.cxx +++ b/examples/MQ/pixelDetector/src/PixelDigiWriteToFile.cxx @@ -14,138 +14,134 @@ #include "PixelDigiWriteToFile.h" -#include "PixelDigi.h" - -#include "FairRootManager.h" #include "FairLogger.h" +#include "FairRootManager.h" +#include "PixelDigi.h" #include PixelDigiWriteToFile::PixelDigiWriteToFile() - : PixelDigiWriteToFile("Pixel DigiWriter", 0) -{ -} + : PixelDigiWriteToFile("Pixel DigiWriter", 0) +{} PixelDigiWriteToFile::PixelDigiWriteToFile(Int_t iVerbose) - : PixelDigiWriteToFile("Pixel DigiWriter", iVerbose) -{ -} + : PixelDigiWriteToFile("Pixel DigiWriter", iVerbose) +{} PixelDigiWriteToFile::PixelDigiWriteToFile(const char* name, Int_t iVerbose) - : FairTask(name, iVerbose) - , fDigis(nullptr) - , fOutputFileName("test.dat") - , fNofOutputFiles(0) - , fOutputFiles() - , fDivideLevel(0) - , fRunId(0) - , fMCEntryNo(0) - , fPartNo(0) + : FairTask(name, iVerbose) + , fDigis(nullptr) + , fOutputFileName("test.dat") + , fNofOutputFiles(0) + , fOutputFiles() + , fDivideLevel(0) + , fRunId(0) + , fMCEntryNo(0) + , fPartNo(0) { - Reset(); + Reset(); } -PixelDigiWriteToFile::~PixelDigiWriteToFile() -{ - Reset(); -} +PixelDigiWriteToFile::~PixelDigiWriteToFile() { Reset(); } void PixelDigiWriteToFile::Exec(Option_t* /*opt*/) { - Reset(); - - Int_t nofDigis = fDigis->GetEntriesFast(); + Reset(); - for (Int_t ifile = 0; ifile < fNofOutputFiles; ifile++) { - fOutputFiles[ifile] << "EVENT BEGIN; RUNID = " << fRunId << "; MCENTRYNO = " << fMCEntryNo << "; PARTNO = " << ifile << ";" << std::endl; - } + Int_t nofDigis = fDigis->GetEntriesFast(); - for (Int_t iDigi = 0; iDigi < nofDigis; iDigi++) { - PixelDigi* currentDigi = static_cast(fDigis->At(iDigi)); - - Int_t detId = currentDigi->GetDetectorID(); - Int_t feId = currentDigi->GetFeID(); - Int_t col = currentDigi->GetCol(); - Int_t row = currentDigi->GetRow(); - Double_t charge = currentDigi->GetCharge(); + for (Int_t ifile = 0; ifile < fNofOutputFiles; ifile++) { + fOutputFiles[ifile] << "EVENT BEGIN; RUNID = " << fRunId << "; MCENTRYNO = " << fMCEntryNo + << "; PARTNO = " << ifile << ";" << std::endl; + } - Int_t fileToSave = 0; - if (fDivideLevel == 1) { - fileToSave = detId/256 - 1; - } else if (fDivideLevel == 2) { - fileToSave = (detId/256 - 1)*4 + (detId%256 -1); + for (Int_t iDigi = 0; iDigi < nofDigis; iDigi++) { + PixelDigi* currentDigi = static_cast(fDigis->At(iDigi)); + + Int_t detId = currentDigi->GetDetectorID(); + Int_t feId = currentDigi->GetFeID(); + Int_t col = currentDigi->GetCol(); + Int_t row = currentDigi->GetRow(); + Double_t charge = currentDigi->GetCharge(); + + Int_t fileToSave = 0; + if (fDivideLevel == 1) { + fileToSave = detId / 256 - 1; + } else if (fDivideLevel == 2) { + fileToSave = (detId / 256 - 1) * 4 + (detId % 256 - 1); + } + fOutputFiles[fileToSave] << detId << " " << feId << " " << col << " " << row << " " << charge << std::endl; } - fOutputFiles[fileToSave] << detId << " " << feId << " " << col << " " << row << " " << charge << std::endl; - } - for (Int_t ifile = 0; ifile < fNofOutputFiles; ifile++) { - fOutputFiles[ifile] << "EVENT END" << std::endl; - } + for (Int_t ifile = 0; ifile < fNofOutputFiles; ifile++) { + fOutputFiles[ifile] << "EVENT END" << std::endl; + } - fMCEntryNo ++; + fMCEntryNo++; } InitStatus PixelDigiWriteToFile::Init() { - // Get input array - FairRootManager* ioman = FairRootManager::Instance(); + // Get input array + FairRootManager* ioman = FairRootManager::Instance(); - if (!ioman) LOG(fatal) << "No FairRootManager"; - fDigis = static_cast(ioman->GetObject("PixelDigis")); + if (!ioman) + LOG(fatal) << "No FairRootManager"; + fDigis = static_cast(ioman->GetObject("PixelDigis")); - if (!fDigis) - LOG(warn) << "PixelDigiWriteToFile::Init() No input PixelDigis array!"; + if (!fDigis) + LOG(warn) << "PixelDigiWriteToFile::Init() No input PixelDigis array!"; - LOG(info) << "-I- " << fName.Data() << "::Init(). Initialization succesfull."; + LOG(info) << "-I- " << fName.Data() << "::Init(). Initialization succesfull."; - fRunId = ioman->GetRunId(); + fRunId = ioman->GetRunId(); - if (fDivideLevel == 0) { - fNofOutputFiles = 1; - fOutputFiles[0].open(fOutputFileName.Data(),std::fstream::out); - } - else { - if (fDivideLevel == 1) { - fNofOutputFiles = 3; // 1 file per station (3 stations) - } else if (fDivideLevel == 2) { - fNofOutputFiles = 12; // 1 file per sensor (3 stations times 4 sensors) + if (fDivideLevel == 0) { + fNofOutputFiles = 1; + fOutputFiles[0].open(fOutputFileName.Data(), std::fstream::out); } else { - LOG(fatal) << "PixelDigiWriteToFile::Init(), fDivideLevel = " << fDivideLevel << " unknown, it has to be in the range <0,2>"; - return kFATAL; + if (fDivideLevel == 1) { + fNofOutputFiles = 3; // 1 file per station (3 stations) + } else if (fDivideLevel == 2) { + fNofOutputFiles = 12; // 1 file per sensor (3 stations times 4 sensors) + } else { + LOG(fatal) << "PixelDigiWriteToFile::Init(), fDivideLevel = " << fDivideLevel + << " unknown, it has to be in the range <0,2>"; + return kFATAL; + } + + for (Int_t ifile = 0; ifile < fNofOutputFiles; ifile++) { + TString fileName = fOutputFileName; + TString uniqFile = Form(".p%d.", ifile); + fileName.Replace(fileName.Last('.'), 1, uniqFile.Data()); + fOutputFiles[ifile].open(fileName.Data(), std::fstream::out); + } } - for (Int_t ifile = 0; ifile < fNofOutputFiles; ifile++) { - TString fileName = fOutputFileName; - TString uniqFile = Form(".p%d.",ifile); - fileName.Replace(fileName.Last('.'),1,uniqFile.Data()); - fOutputFiles[ifile].open(fileName.Data(),std::fstream::out); - } - } - - return kSUCCESS; + return kSUCCESS; } InitStatus PixelDigiWriteToFile::ReInit() { - FairRootManager* ioman = FairRootManager::Instance(); + FairRootManager* ioman = FairRootManager::Instance(); InitStatus Status = kFATAL; - if (! ioman){ - LOG(fatal) << "No FairRootManager found."; - }else { - fRunId = ioman->GetRunId(); - fMCEntryNo = 0; - Status = kSUCCESS; + if (!ioman) { + LOG(fatal) << "No FairRootManager found."; + } else { + fRunId = ioman->GetRunId(); + fMCEntryNo = 0; + Status = kSUCCESS; } return Status; } void PixelDigiWriteToFile::Finish() { - for (Int_t ifile = 0; ifile < fNofOutputFiles; ifile++) { - fOutputFiles[ifile].close(); - } + for (Int_t ifile = 0; ifile < fNofOutputFiles; ifile++) { + fOutputFiles[ifile].close(); + } } -ClassImp(PixelDigiWriteToFile) +ClassImp(PixelDigiWriteToFile); diff --git a/examples/MQ/pixelDetector/src/PixelDigiWriteToFile.h b/examples/MQ/pixelDetector/src/PixelDigiWriteToFile.h index d24365b22d..03262b6fdb 100644 --- a/examples/MQ/pixelDetector/src/PixelDigiWriteToFile.h +++ b/examples/MQ/pixelDetector/src/PixelDigiWriteToFile.h @@ -19,7 +19,6 @@ #include #include - #include class TClonesArray; @@ -44,14 +43,14 @@ class PixelDigiWriteToFile : public FairTask void SetOutputFileName(const TString& tstr) { fOutputFileName = tstr; } - void SetDivideLevel(Int_t idiv) { fDivideLevel = idiv; } // 0 - event, 1 - station, 2 - sensor + void SetDivideLevel(Int_t idiv) { fDivideLevel = idiv; } // 0 - event, 1 - station, 2 - sensor private: - TClonesArray* fDigis; /** Input array of PixelDigi **/ + TClonesArray* fDigis; /** Input array of PixelDigi **/ - TString fOutputFileName; + TString fOutputFileName; Int_t fNofOutputFiles; - std::ofstream fOutputFiles[12]; // no more than 12 output files.... + std::ofstream fOutputFiles[12]; // no more than 12 output files.... /** Get parameter containers **/ virtual void SetParContainers() {} @@ -77,7 +76,7 @@ class PixelDigiWriteToFile : public FairTask PixelDigiWriteToFile(const PixelDigiWriteToFile&); PixelDigiWriteToFile& operator=(const PixelDigiWriteToFile&); - ClassDef(PixelDigiWriteToFile,1); + ClassDef(PixelDigiWriteToFile, 1); }; #endif diff --git a/examples/MQ/pixelDetector/src/PixelDigitize.cxx b/examples/MQ/pixelDetector/src/PixelDigitize.cxx index e4ec449316..d61bcccc4e 100644 --- a/examples/MQ/pixelDetector/src/PixelDigitize.cxx +++ b/examples/MQ/pixelDetector/src/PixelDigitize.cxx @@ -15,248 +15,254 @@ #include "PixelDigitize.h" #include "PixelDigi.h" -#include "PixelPoint.h" #include "PixelDigiPar.h" +#include "PixelPoint.h" // Includes from base +#include "FairLogger.h" #include "FairRootManager.h" #include "FairRun.h" #include "FairRuntimeDb.h" -#include "FairLogger.h" // Includes from ROOT #include +#include #include #include #include -#include #include #include PixelDigitize::PixelDigitize() - : PixelDigitize("Pixel Digitizer", 0) -{ -} + : PixelDigitize("Pixel Digitizer", 0) +{} PixelDigitize::PixelDigitize(Int_t iVerbose) - : PixelDigitize("Pixel Digitizer", iVerbose) -{ -} + : PixelDigitize("Pixel Digitizer", iVerbose) +{} PixelDigitize::PixelDigitize(const char* name, Int_t iVerbose) - : FairTask(name, iVerbose) - , fDigiPar(nullptr) - , fPoints(nullptr) - , fDigis(nullptr) - , fNPoints(0) - , fNDigis(0) - , fTNofEvents(0) - , fTNofPoints(0) - , fTNofDigis(0) - , fFeCols(0) - , fFeRows(0) - , fMaxFEperCol(0) - , fPitchX(0.) - , fPitchY(0.) + : FairTask(name, iVerbose) + , fDigiPar(nullptr) + , fPoints(nullptr) + , fDigis(nullptr) + , fNPoints(0) + , fNDigis(0) + , fTNofEvents(0) + , fTNofPoints(0) + , fTNofDigis(0) + , fFeCols(0) + , fFeRows(0) + , fMaxFEperCol(0) + , fPitchX(0.) + , fPitchY(0.) { - Reset(); + Reset(); } PixelDigitize::~PixelDigitize() { - Reset(); - delete fDigiPar; - if ( fDigis ) { - fDigis->Delete(); - delete fDigis; - } + Reset(); + delete fDigiPar; + if (fDigis) { + fDigis->Delete(); + delete fDigis; + } } void PixelDigitize::Exec(Option_t* /*opt*/) { - Reset(); + Reset(); - LOG(debug) << "PixelDigitize::Exec() EVENT " << fTNofEvents; + LOG(debug) << "PixelDigitize::Exec() EVENT " << fTNofEvents; - fTNofEvents++; + fTNofEvents++; - fNPoints = fPoints->GetEntriesFast(); - fTNofPoints+= fNPoints; + fNPoints = fPoints->GetEntriesFast(); + fTNofPoints += fNPoints; - for ( Int_t iPoint = 0 ; iPoint < fNPoints ; iPoint++ ) { - PixelPoint* currentPixelPoint = static_cast(fPoints->At(iPoint)); + for (Int_t iPoint = 0; iPoint < fNPoints; iPoint++) { + PixelPoint* currentPixelPoint = static_cast(fPoints->At(iPoint)); - Double_t posIn[3] = { currentPixelPoint->GetX(), - currentPixelPoint->GetY(), - currentPixelPoint->GetZ() }; + Double_t posIn[3] = {currentPixelPoint->GetX(), currentPixelPoint->GetY(), currentPixelPoint->GetZ()}; - Int_t detId = currentPixelPoint->GetDetectorID(); - TString nodeName = Form("/cave/Pixel%d_%d",detId/256,detId%256); + Int_t detId = currentPixelPoint->GetDetectorID(); + TString nodeName = Form("/cave/Pixel%d_%d", detId / 256, detId % 256); - gGeoManager->cd(nodeName.Data()); - TGeoNode* curNode = gGeoManager->GetCurrentNode(); + gGeoManager->cd(nodeName.Data()); + TGeoNode* curNode = gGeoManager->GetCurrentNode(); - if (!curNode) LOG(fatal) << "PixelDigitize::Exec() node \"" << nodeName.Data() << "\" unknown!"; + if (!curNode) + LOG(fatal) << "PixelDigitize::Exec() node \"" << nodeName.Data() << "\" unknown!"; - Double_t locPosIn[3]; + Double_t locPosIn[3]; - curNode->MasterToLocal(posIn,locPosIn); + curNode->MasterToLocal(posIn, locPosIn); - // The local coordinate system has the origin set to the center of the volume. - // To calculate the pixel number, it is necessary to move the origin to the bottom left corner. - TGeoVolume* actVolume = gGeoManager->GetCurrentVolume(); - TGeoBBox* actBox = static_cast(actVolume->GetShape()); - // Double_t sensorWidth = 2.*actBox->GetDX(); - // Double_t sensorHeight = 2.*actBox->GetDY(); - locPosIn[0] += actBox->GetDX(); - locPosIn[1] += actBox->GetDY(); + // The local coordinate system has the origin set to the center of the volume. + // To calculate the pixel number, it is necessary to move the origin to the bottom left corner. + TGeoVolume* actVolume = gGeoManager->GetCurrentVolume(); + TGeoBBox* actBox = static_cast(actVolume->GetShape()); + // Double_t sensorWidth = 2.*actBox->GetDX(); + // Double_t sensorHeight = 2.*actBox->GetDY(); + locPosIn[0] += actBox->GetDX(); + locPosIn[1] += actBox->GetDY(); - LOG(debug) << "GLOB PNT " << detId << " POSITION: " << posIn[0] << " / " << posIn[1] << " / " << posIn[2]; - LOG(debug) << "POINT ON " << detId << " POSITION: " << locPosIn[0] << " / " << locPosIn[1]; + LOG(debug) << "GLOB PNT " << detId << " POSITION: " << posIn[0] << " / " << posIn[1] << " / " << posIn[2]; + LOG(debug) << "POINT ON " << detId << " POSITION: " << locPosIn[0] << " / " << locPosIn[1]; - Int_t col = static_cast(locPosIn[0]/fPitchX); - Int_t ocol = col; - Int_t row = static_cast(locPosIn[1]/fPitchY); - Int_t orow = row; - Int_t feCol = col/fFeCols; - col = col % fFeCols; - Int_t feRow = row/fFeRows; - row = row % fFeRows; - Int_t feId = 1+feCol*fMaxFEperCol+feRow; + Int_t col = static_cast(locPosIn[0] / fPitchX); + Int_t ocol = col; + Int_t row = static_cast(locPosIn[1] / fPitchY); + Int_t orow = row; + Int_t feCol = col / fFeCols; + col = col % fFeCols; + Int_t feRow = row / fFeRows; + row = row % fFeRows; + Int_t feId = 1 + feCol * fMaxFEperCol + feRow; - LOG(debug) << "COL = " << feCol << " FE + " << col << " ( " << ocol << " ) /// " - << "ROW = " << feRow << " FE + " << row << " ( " << orow << " ) /// " - << " /// PIXEL = " << feId; + LOG(debug) << "COL = " << feCol << " FE + " << col << " ( " << ocol << " ) /// " + << "ROW = " << feRow << " FE + " << row << " ( " << orow << " ) /// " + << " /// PIXEL = " << feId; - ActivatePixel(iPoint,detId,feId,col,row,1.,0.); - } + ActivatePixel(iPoint, detId, feId, col, row, 1., 0.); + } - fTNofDigis += fNDigis; + fTNofDigis += fNDigis; } -void PixelDigitize::ActivatePixel(Int_t index, Int_t detId, Int_t feId, Int_t col, Int_t row, Double_t charge, Double_t timestamp) +void PixelDigitize::ActivatePixel(Int_t index, + Int_t detId, + Int_t feId, + Int_t col, + Int_t row, + Double_t charge, + Double_t timestamp) { - Bool_t pixelAlreadyFired = kFALSE; - PixelDigi* tempPixel = nullptr; - for ( Int_t ipixel = 0 ; ipixel < fNDigis ; ipixel++ ) { - tempPixel = static_cast(fDigis->At(ipixel)); - if ( tempPixel->GetDetectorID() == detId && - tempPixel->GetFeID() == feId && - tempPixel->GetCol() == col && - tempPixel->GetRow() == row ) { - pixelAlreadyFired = kTRUE; - tempPixel->SetCharge(tempPixel->GetCharge()+charge); + Bool_t pixelAlreadyFired = kFALSE; + PixelDigi* tempPixel = nullptr; + for (Int_t ipixel = 0; ipixel < fNDigis; ipixel++) { + tempPixel = static_cast(fDigis->At(ipixel)); + if (tempPixel->GetDetectorID() == detId && tempPixel->GetFeID() == feId && tempPixel->GetCol() == col + && tempPixel->GetRow() == row) { + pixelAlreadyFired = kTRUE; + tempPixel->SetCharge(tempPixel->GetCharge() + charge); + } + } + // TODO: order the PixelDigi in the output array by station, not by track... + if (!pixelAlreadyFired) { + new ((*fDigis)[fNDigis]) PixelDigi(index, detId, feId, col, row, charge, timestamp); + fNDigis++; } - } - // TODO: order the PixelDigi in the output array by station, not by track... - if ( !pixelAlreadyFired ) { - new ((*fDigis)[fNDigis]) PixelDigi(index,detId,feId,col,row,charge,timestamp); - fNDigis++; - } } void PixelDigitize::SetParContainers() { - // Get run and runtime database - FairRun* run = FairRun::Instance(); - if (!run){ LOG(fatal) << "No analysis run"; - - } else { - FairRuntimeDb* db = run->GetRuntimeDb(); - if (!db) { - LOG(fatal) << "No runtime database"; + // Get run and runtime database + FairRun* run = FairRun::Instance(); + if (!run) { + LOG(fatal) << "No analysis run"; + } else { - // Get GEM digitisation parameter container - fDigiPar = static_cast(db->getContainer("PixelDigiParameters")); + FairRuntimeDb* db = run->GetRuntimeDb(); + if (!db) { + LOG(fatal) << "No runtime database"; + } else { + // Get GEM digitisation parameter container + fDigiPar = static_cast(db->getContainer("PixelDigiParameters")); + } } - } } void PixelDigitize::GetParList(TList* tempList) { - fDigiPar = new PixelDigiPar("PixelDigiParameters"); - tempList->Add(fDigiPar); + fDigiPar = new PixelDigiPar("PixelDigiParameters"); + tempList->Add(fDigiPar); - return; + return; } -void PixelDigitize::InitMQ(TList* tempList) +void PixelDigitize::InitMQ(TList* tempList) { - LOG(info) << "********************************************** PixelDigitize::InitMQ()"; - fDigiPar = (PixelDigiPar*)tempList->FindObject("PixelDigiParameters"); + LOG(info) << "********************************************** PixelDigitize::InitMQ()"; + fDigiPar = (PixelDigiPar*)tempList->FindObject("PixelDigiParameters"); - fFeCols = fDigiPar->GetFECols(); - fFeRows = fDigiPar->GetFERows(); - fMaxFEperCol = fDigiPar->GetMaxFEperCol(); - fPitchX = fDigiPar->GetXPitch(); - fPitchY = fDigiPar->GetYPitch(); + fFeCols = fDigiPar->GetFECols(); + fFeRows = fDigiPar->GetFERows(); + fMaxFEperCol = fDigiPar->GetMaxFEperCol(); + fPitchX = fDigiPar->GetXPitch(); + fPitchY = fDigiPar->GetYPitch(); - LOG(info) << ">> fFeCols = " << fFeCols; - LOG(info) << ">> fFeRows = " << fFeRows; - LOG(info) << ">> fMaxFEperCol = " << fMaxFEperCol; - LOG(info) << ">> fPitchX = " << fPitchX; - LOG(info) << ">> fPitchY = " << fPitchY; + LOG(info) << ">> fFeCols = " << fFeCols; + LOG(info) << ">> fFeRows = " << fFeRows; + LOG(info) << ">> fMaxFEperCol = " << fMaxFEperCol; + LOG(info) << ">> fPitchX = " << fPitchX; + LOG(info) << ">> fPitchY = " << fPitchY; - fDigis = new TClonesArray("PixelDigi",10000); + fDigis = new TClonesArray("PixelDigi", 10000); - return; + return; } -void PixelDigitize::ExecMQ(TList* inputList,TList* outputList) +void PixelDigitize::ExecMQ(TList* inputList, TList* outputList) { - // LOG(info) << "********************************************** PixelDigitize::ExecMQ(" << inputList->GetName() << "," << outputList->GetName() << "), Event " << fTNofEvents; - // LOG(info) << "********************************************** PixelDigitize::ExecMQ(), Event " << fTNofEvents; - fPoints = (TClonesArray*) inputList->FindObject("PixelPoint"); - outputList->Add(fDigis); - Exec(""); - return; + // LOG(info) << "********************************************** PixelDigitize::ExecMQ(" << inputList->GetName() << + // "," << outputList->GetName() << "), Event " << fTNofEvents; LOG(info) << + // "********************************************** PixelDigitize::ExecMQ(), Event " << fTNofEvents; + fPoints = (TClonesArray*)inputList->FindObject("PixelPoint"); + outputList->Add(fDigis); + Exec(""); + return; } InitStatus PixelDigitize::Init() { - // Get input array - FairRootManager* ioman = FairRootManager::Instance(); + // Get input array + FairRootManager* ioman = FairRootManager::Instance(); - if ( ! ioman ) LOG(fatal) << "No FairRootManager"; - fPoints = static_cast(ioman->GetObject("PixelPoint")); + if (!ioman) + LOG(fatal) << "No FairRootManager"; + fPoints = static_cast(ioman->GetObject("PixelPoint")); - // Register output array StsDigi - fDigis = new TClonesArray("PixelDigi",10000); - ioman->Register("PixelDigis", "Pixel", fDigis, kTRUE); + // Register output array StsDigi + fDigis = new TClonesArray("PixelDigi", 10000); + ioman->Register("PixelDigis", "Pixel", fDigis, kTRUE); - LOG(info) << "-I- " << fName.Data() << "::Init(). Initialization succesfull."; + LOG(info) << "-I- " << fName.Data() << "::Init(). Initialization succesfull."; - fFeCols = fDigiPar->GetFECols(); - fFeRows = fDigiPar->GetFERows(); - fMaxFEperCol = fDigiPar->GetMaxFEperCol(); - fPitchX = fDigiPar->GetXPitch(); - fPitchY = fDigiPar->GetYPitch(); + fFeCols = fDigiPar->GetFECols(); + fFeRows = fDigiPar->GetFERows(); + fMaxFEperCol = fDigiPar->GetMaxFEperCol(); + fPitchX = fDigiPar->GetXPitch(); + fPitchY = fDigiPar->GetYPitch(); - LOG(info) << "PixelDigitize::SetParContainers() Pixel detector with pitch size " << fPitchX << "cm x" << fPitchY << "cm"; + LOG(info) << "PixelDigitize::SetParContainers() Pixel detector with pitch size " << fPitchX << "cm x" << fPitchY + << "cm"; - return kSUCCESS; + return kSUCCESS; } -InitStatus PixelDigitize::ReInit() -{ - return kSUCCESS; -} +InitStatus PixelDigitize::ReInit() { return kSUCCESS; } void PixelDigitize::Reset() { - fNPoints = fNDigis = 0; - if ( fDigis ) fDigis->Clear(); + fNPoints = fNDigis = 0; + if (fDigis) + fDigis->Clear(); } void PixelDigitize::Finish() { - if ( fDigis ) fDigis->Delete(); - - LOG(info) << "-------------------- " << fName.Data() << " : Summary ------------------------"; - LOG(info) << " Events: " << fTNofEvents; - LOG(info) << " MC Points: " << fTNofPoints << " ( " << static_cast(fTNofPoints)/(static_cast(fTNofEvents)) << " per event )"; - LOG(info) << " Digis: " << fTNofDigis << " ( " << static_cast(fTNofDigis )/(static_cast(fTNofEvents)) << " per event )"; - LOG(info) << "---------------------------------------------------------------------"; + if (fDigis) + fDigis->Delete(); + + LOG(info) << "-------------------- " << fName.Data() << " : Summary ------------------------"; + LOG(info) << " Events: " << fTNofEvents; + LOG(info) << " MC Points: " << fTNofPoints << " ( " + << static_cast(fTNofPoints) / (static_cast(fTNofEvents)) << " per event )"; + LOG(info) << " Digis: " << fTNofDigis << " ( " + << static_cast(fTNofDigis) / (static_cast(fTNofEvents)) << " per event )"; + LOG(info) << "---------------------------------------------------------------------"; } -ClassImp(PixelDigitize) +ClassImp(PixelDigitize); diff --git a/examples/MQ/pixelDetector/src/PixelDigitize.h b/examples/MQ/pixelDetector/src/PixelDigitize.h index 6dd36804e5..ce4156e45e 100644 --- a/examples/MQ/pixelDetector/src/PixelDigitize.h +++ b/examples/MQ/pixelDetector/src/PixelDigitize.h @@ -39,27 +39,27 @@ class PixelDigitize : public FairTask virtual void Exec(Option_t* opt); virtual void GetParList(TList* tempList); - virtual void InitMQ (TList* tempList); - virtual void ExecMQ (TList* inputList,TList* outputList); + virtual void InitMQ(TList* tempList); + virtual void ExecMQ(TList* inputList, TList* outputList); private: - PixelDigiPar* fDigiPar; + PixelDigiPar* fDigiPar; - TClonesArray* fPoints; /** Input array of PixelPoint **/ - TClonesArray* fDigis; /** Output array of PixelDigi **/ + TClonesArray* fPoints; /** Input array of PixelPoint **/ + TClonesArray* fDigis; /** Output array of PixelDigi **/ - Int_t fNPoints; - Int_t fNDigis; + Int_t fNPoints; + Int_t fNDigis; - Int_t fTNofEvents; - Int_t fTNofPoints; - Int_t fTNofDigis; + Int_t fTNofEvents; + Int_t fTNofPoints; + Int_t fTNofDigis; - Int_t fFeCols; // Colums read per Frontend - Int_t fFeRows; // Rows read per Frontend - Int_t fMaxFEperCol; // max number of Frontend elemens per column - Double_t fPitchX; // Pixel cell size X - Double_t fPitchY; // Pixel cell size Y + Int_t fFeCols; // Colums read per Frontend + Int_t fFeRows; // Rows read per Frontend + Int_t fMaxFEperCol; // max number of Frontend elemens per column + Double_t fPitchX; // Pixel cell size X + Double_t fPitchY; // Pixel cell size Y /** Activate pixel **/ void ActivatePixel(Int_t index, Int_t detId, Int_t feId, Int_t col, Int_t row, Double_t charge, Double_t timestamp); @@ -82,7 +82,7 @@ class PixelDigitize : public FairTask PixelDigitize(const PixelDigitize&); PixelDigitize& operator=(const PixelDigitize&); - ClassDef(PixelDigitize,1); + ClassDef(PixelDigitize, 1); }; #endif diff --git a/examples/MQ/pixelDetector/src/PixelEventHeader.cxx b/examples/MQ/pixelDetector/src/PixelEventHeader.cxx index ff83180322..4227164604 100644 --- a/examples/MQ/pixelDetector/src/PixelEventHeader.cxx +++ b/examples/MQ/pixelDetector/src/PixelEventHeader.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* @@ -17,11 +17,8 @@ PixelEventHeader::PixelEventHeader() : FairEventHeader() , fPartNo(0) -{ -} +{} -PixelEventHeader::~PixelEventHeader() -{ -} +PixelEventHeader::~PixelEventHeader() {} -ClassImp(PixelEventHeader) +ClassImp(PixelEventHeader); diff --git a/examples/MQ/pixelDetector/src/PixelEventHeader.h b/examples/MQ/pixelDetector/src/PixelEventHeader.h index 12dd09d7c7..029b16c77b 100644 --- a/examples/MQ/pixelDetector/src/PixelEventHeader.h +++ b/examples/MQ/pixelDetector/src/PixelEventHeader.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* @@ -15,11 +15,15 @@ #ifndef PIXELEVENTHEADER_H_ #define PIXELEVENTHEADER_H_ -#include "FairEventHeader.h" // for FairEventHeader +#include "FairEventHeader.h" // for FairEventHeader #include -namespace boost { namespace serialization { class access; } } +namespace boost { +namespace serialization { +class access; +} +} // namespace boost #include class PixelEventHeader : public FairEventHeader @@ -31,10 +35,10 @@ class PixelEventHeader : public FairEventHeader /** Destructor **/ virtual ~PixelEventHeader(); - void SetPartNo(Int_t ipart) { fPartNo = ipart;} - Int_t GetPartNo() { return fPartNo; } + void SetPartNo(Int_t ipart) { fPartNo = ipart; } + Int_t GetPartNo() { return fPartNo; } - template + template void serialize(Archive& ar, const unsigned int /*version*/) { ar& boost::serialization::base_object(*this); diff --git a/examples/MQ/pixelDetector/src/PixelFindHits.cxx b/examples/MQ/pixelDetector/src/PixelFindHits.cxx index 193c81ba05..38949a7072 100644 --- a/examples/MQ/pixelDetector/src/PixelFindHits.cxx +++ b/examples/MQ/pixelDetector/src/PixelFindHits.cxx @@ -14,224 +14,227 @@ #include "PixelFindHits.h" -#include "PixelDigi.h" -#include "PixelHit.h" -#include "PixelDigiPar.h" - +#include "FairLogger.h" #include "FairRootManager.h" #include "FairRun.h" #include "FairRuntimeDb.h" -#include "FairLogger.h" +#include "PixelDigi.h" +#include "PixelDigiPar.h" +#include "PixelHit.h" #include -#include +#include #include #include #include -#include #include +#include #include #include PixelFindHits::PixelFindHits() - : PixelFindHits("Pixel Hit Finder", 0) -{ -} + : PixelFindHits("Pixel Hit Finder", 0) +{} PixelFindHits::PixelFindHits(Int_t iVerbose) - : PixelFindHits("Pixel Hit Finder", iVerbose) -{ -} + : PixelFindHits("Pixel Hit Finder", iVerbose) +{} PixelFindHits::PixelFindHits(const char* name, Int_t iVerbose) - : FairTask(name, iVerbose) - , fDigiPar(nullptr) - , fGeoParSet(nullptr) - , fDigis(nullptr) - , fHits(nullptr) - , fNDigis(0) - , fNHits(0) - , fTNofEvents(0) - , fTNofDigis(0) - , fTNofHits(0) - , fFeCols(0) - , fFeRows(0) - , fMaxFEperCol(0) - , fPitchX(0.) - , fPitchY(0.) + : FairTask(name, iVerbose) + , fDigiPar(nullptr) + , fGeoParSet(nullptr) + , fDigis(nullptr) + , fHits(nullptr) + , fNDigis(0) + , fNHits(0) + , fTNofEvents(0) + , fTNofDigis(0) + , fTNofHits(0) + , fFeCols(0) + , fFeRows(0) + , fMaxFEperCol(0) + , fPitchX(0.) + , fPitchY(0.) { - LOG(info) << "Created PixelFindHits."; - Reset(); + LOG(info) << "Created PixelFindHits."; + Reset(); } PixelFindHits::~PixelFindHits() { - Reset(); - delete fDigiPar; - if (fHits) { - fHits->Delete(); - delete fHits; - } + Reset(); + delete fDigiPar; + if (fHits) { + fHits->Delete(); + delete fHits; + } } void PixelFindHits::Exec(Option_t* /*opt*/) { - Reset(); + Reset(); - LOG(debug) << "PixelFindHits::Exec() EVENT " << fTNofEvents; + LOG(debug) << "PixelFindHits::Exec() EVENT " << fTNofEvents; - fTNofEvents++; + fTNofEvents++; - fNDigis = fDigis->GetEntriesFast(); - fTNofDigis+= fNDigis; + fNDigis = fDigis->GetEntriesFast(); + fTNofDigis += fNDigis; - for (Int_t iDigi = 0 ; iDigi < fNDigis ; iDigi++) { - PixelDigi* currentDigi = static_cast(fDigis->At(iDigi)); + for (Int_t iDigi = 0; iDigi < fNDigis; iDigi++) { + PixelDigi* currentDigi = static_cast(fDigis->At(iDigi)); - Int_t detId = currentDigi->GetDetectorID(); - TString nodeName = Form("/cave/Pixel%d_%d",detId/256,detId%256); + Int_t detId = currentDigi->GetDetectorID(); + TString nodeName = Form("/cave/Pixel%d_%d", detId / 256, detId % 256); - gGeoManager->cd(nodeName.Data()); - TGeoNode* curNode = gGeoManager->GetCurrentNode(); + gGeoManager->cd(nodeName.Data()); + TGeoNode* curNode = gGeoManager->GetCurrentNode(); - // TGeoMatrix* matrix = curNode->GetMatrix(); + // TGeoMatrix* matrix = curNode->GetMatrix(); - TGeoVolume* actVolume = gGeoManager->GetCurrentVolume(); - TGeoBBox* actBox = static_cast(actVolume->GetShape()); + TGeoVolume* actVolume = gGeoManager->GetCurrentVolume(); + TGeoBBox* actBox = static_cast(actVolume->GetShape()); - Int_t feId = currentDigi->GetFeID(); - Int_t col = currentDigi->GetCol(); - Int_t row = currentDigi->GetRow(); + Int_t feId = currentDigi->GetFeID(); + Int_t col = currentDigi->GetCol(); + Int_t row = currentDigi->GetRow(); - Double_t locPosCalc[3]; - locPosCalc[0] = (((feId-1)/fMaxFEperCol)*fFeCols + col + 0.5)*fPitchX; - locPosCalc[1] = (((feId-1)%fMaxFEperCol)*fFeRows + row + 0.5)*fPitchY; - locPosCalc[2] = 0.; + Double_t locPosCalc[3]; + locPosCalc[0] = (((feId - 1) / fMaxFEperCol) * fFeCols + col + 0.5) * fPitchX; + locPosCalc[1] = (((feId - 1) % fMaxFEperCol) * fFeRows + row + 0.5) * fPitchY; + locPosCalc[2] = 0.; - locPosCalc[0] -= actBox->GetDX(); - locPosCalc[1] -= actBox->GetDY(); + locPosCalc[0] -= actBox->GetDX(); + locPosCalc[1] -= actBox->GetDY(); - Double_t globPos[3]; + Double_t globPos[3]; - curNode->LocalToMaster(locPosCalc,globPos); + curNode->LocalToMaster(locPosCalc, globPos); - LOG(debug) << "HIT ON " << detId << " POSITION: " << locPosCalc[0] << " / " << locPosCalc[1]; - LOG(debug) << "GLOB HIT " << detId << " POSITION: " << globPos[0] << " / " << globPos[1] << " / " << globPos[2]; + LOG(debug) << "HIT ON " << detId << " POSITION: " << locPosCalc[0] << " / " << locPosCalc[1]; + LOG(debug) << "GLOB HIT " << detId << " POSITION: " << globPos[0] << " / " << globPos[1] << " / " + << globPos[2]; - TVector3 pos (globPos[0],globPos[1],globPos[2]); - TVector3 posErr(fPitchX/TMath::Sqrt(12.),fPitchY/TMath::Sqrt(12.),actBox->GetDZ()); + TVector3 pos(globPos[0], globPos[1], globPos[2]); + TVector3 posErr(fPitchX / TMath::Sqrt(12.), fPitchY / TMath::Sqrt(12.), actBox->GetDZ()); - new ((*fHits)[fNHits]) PixelHit(detId,currentDigi->GetIndex(),pos,posErr); + new ((*fHits)[fNHits]) PixelHit(detId, currentDigi->GetIndex(), pos, posErr); - fNHits++; - } + fNHits++; + } - fTNofHits += fNHits; + fTNofHits += fNHits; } void PixelFindHits::SetParContainers() { - // Get run and runtime database - FairRun* run = FairRun::Instance(); - if (! run) LOG(fatal) << "No analysis run"; - - FairRuntimeDb* db = run->GetRuntimeDb(); - if (! db) LOG(fatal) << "No runtime database"; + // Get run and runtime database + FairRun* run = FairRun::Instance(); + if (!run) + LOG(fatal) << "No analysis run"; - // Get GEM digitisation parameter container - fDigiPar = static_cast(db->getContainer("PixelDigiParameters")); + FairRuntimeDb* db = run->GetRuntimeDb(); + if (!db) + LOG(fatal) << "No runtime database"; + // Get GEM digitisation parameter container + fDigiPar = static_cast(db->getContainer("PixelDigiParameters")); } void PixelFindHits::GetParList(TList* tempList) { - fDigiPar = new PixelDigiPar("PixelDigiParameters"); - tempList->Add(fDigiPar); + fDigiPar = new PixelDigiPar("PixelDigiParameters"); + tempList->Add(fDigiPar); - return; + return; } -void PixelFindHits::InitMQ(TList* tempList) +void PixelFindHits::InitMQ(TList* tempList) { - LOG(info) << "********************************************** PixelFindHits::InitMQ()"; - fDigiPar = (PixelDigiPar*)tempList->FindObject("PixelDigiParameters"); + LOG(info) << "********************************************** PixelFindHits::InitMQ()"; + fDigiPar = (PixelDigiPar*)tempList->FindObject("PixelDigiParameters"); - fFeCols = fDigiPar->GetFECols(); - fFeRows = fDigiPar->GetFERows(); - fMaxFEperCol = fDigiPar->GetMaxFEperCol(); - fPitchX = fDigiPar->GetXPitch(); - fPitchY = fDigiPar->GetYPitch(); + fFeCols = fDigiPar->GetFECols(); + fFeRows = fDigiPar->GetFERows(); + fMaxFEperCol = fDigiPar->GetMaxFEperCol(); + fPitchX = fDigiPar->GetXPitch(); + fPitchY = fDigiPar->GetYPitch(); - LOG(info) << ">> fFeCols = " << fFeCols; - LOG(info) << ">> fFeRows = " << fFeRows; - LOG(info) << ">> fMaxFEperCol = " << fMaxFEperCol; - LOG(info) << ">> fPitchX = " << fPitchX; - LOG(info) << ">> fPitchY = " << fPitchY; + LOG(info) << ">> fFeCols = " << fFeCols; + LOG(info) << ">> fFeRows = " << fFeRows; + LOG(info) << ">> fMaxFEperCol = " << fMaxFEperCol; + LOG(info) << ">> fPitchX = " << fPitchX; + LOG(info) << ">> fPitchY = " << fPitchY; - fHits = new TClonesArray("PixelHit",10000); + fHits = new TClonesArray("PixelHit", 10000); - return; + return; } -void PixelFindHits::ExecMQ(TList* inputList,TList* outputList) +void PixelFindHits::ExecMQ(TList* inputList, TList* outputList) { - // LOG(info) << "********************************************** PixelFindHits::ExecMQ(" << inputList->GetName() << "," << outputList->GetName() << "), Event " << fTNofEvents; - // LOG(info) << "********************************************** PixelFindHits::ExecMQ(), Event " << fTNofEvents; - // LOG(info) << "h" << FairLogger::flush; - fDigis = (TClonesArray*) inputList->FindObject("PixelDigis"); - outputList->Add(fHits); - Exec(""); - return; + // LOG(info) << "********************************************** PixelFindHits::ExecMQ(" << inputList->GetName() << + // "," << outputList->GetName() << "), Event " << fTNofEvents; LOG(info) << + // "********************************************** PixelFindHits::ExecMQ(), Event " << fTNofEvents; LOG(info) << + // "h" << FairLogger::flush; + fDigis = (TClonesArray*)inputList->FindObject("PixelDigis"); + outputList->Add(fHits); + Exec(""); + return; } InitStatus PixelFindHits::Init() { - // Get input array - FairRootManager* ioman = FairRootManager::Instance(); + // Get input array + FairRootManager* ioman = FairRootManager::Instance(); - if (! ioman) LOG(fatal) << "No FairRootManager"; - fDigis = static_cast(ioman->GetObject("PixelDigis")); + if (!ioman) + LOG(fatal) << "No FairRootManager"; + fDigis = static_cast(ioman->GetObject("PixelDigis")); - if (!fDigis) - LOG(warn) << "PixelFindHits::Init() No input PixelDigis array!"; + if (!fDigis) + LOG(warn) << "PixelFindHits::Init() No input PixelDigis array!"; - // Register output array PixelHit - fHits = new TClonesArray("PixelHit",10000); - ioman->Register("PixelHits", "Pixel", fHits, kTRUE); + // Register output array PixelHit + fHits = new TClonesArray("PixelHit", 10000); + ioman->Register("PixelHits", "Pixel", fHits, kTRUE); - LOG(info) << "-I- " << fName.Data() << "::Init(). Initialization succesfull."; + LOG(info) << "-I- " << fName.Data() << "::Init(). Initialization succesfull."; - fFeCols = fDigiPar->GetFECols(); - fFeRows = fDigiPar->GetFERows(); - fMaxFEperCol = fDigiPar->GetMaxFEperCol(); - fPitchX = fDigiPar->GetXPitch(); - fPitchY = fDigiPar->GetYPitch(); + fFeCols = fDigiPar->GetFECols(); + fFeRows = fDigiPar->GetFERows(); + fMaxFEperCol = fDigiPar->GetMaxFEperCol(); + fPitchX = fDigiPar->GetXPitch(); + fPitchY = fDigiPar->GetYPitch(); - LOG(info) << "PixelFindHits::SetParContainers() Pixel detector with pitch size " << fPitchX << "cm x" << fPitchY << "cm"; + LOG(info) << "PixelFindHits::SetParContainers() Pixel detector with pitch size " << fPitchX << "cm x" << fPitchY + << "cm"; - return kSUCCESS; + return kSUCCESS; } -InitStatus PixelFindHits::ReInit() -{ - return kSUCCESS; -} +InitStatus PixelFindHits::ReInit() { return kSUCCESS; } void PixelFindHits::Reset() { - fNDigis = fNHits = 0; - if (fHits) fHits->Clear(); + fNDigis = fNHits = 0; + if (fHits) + fHits->Clear(); } void PixelFindHits::Finish() { - if (fHits) fHits->Delete(); - - LOG(info) << "-------------------- " << fName.Data() << " : Summary ------------------------"; - LOG(info) << " Events: " << fTNofEvents; - LOG(info) << " Digis: " << fTNofDigis << " (" << static_cast(fTNofDigis) /(static_cast(fTNofEvents)) << " per event)"; - LOG(info) << " Hits: " << fTNofHits << " (" << static_cast(fTNofHits )/(static_cast(fTNofEvents)) << " per event)"; - LOG(info) << "---------------------------------------------------------------------"; + if (fHits) + fHits->Delete(); + + LOG(info) << "-------------------- " << fName.Data() << " : Summary ------------------------"; + LOG(info) << " Events: " << fTNofEvents; + LOG(info) << " Digis: " << fTNofDigis << " (" + << static_cast(fTNofDigis) / (static_cast(fTNofEvents)) << " per event)"; + LOG(info) << " Hits: " << fTNofHits << " (" + << static_cast(fTNofHits) / (static_cast(fTNofEvents)) << " per event)"; + LOG(info) << "---------------------------------------------------------------------"; } -ClassImp(PixelFindHits) +ClassImp(PixelFindHits); diff --git a/examples/MQ/pixelDetector/src/PixelFindHits.h b/examples/MQ/pixelDetector/src/PixelFindHits.h index 7bcbc2ff70..0c24a17c82 100644 --- a/examples/MQ/pixelDetector/src/PixelFindHits.h +++ b/examples/MQ/pixelDetector/src/PixelFindHits.h @@ -43,28 +43,28 @@ class PixelFindHits : public FairTask virtual void Exec(Option_t* opt); virtual void GetParList(TList* tempList); - virtual void InitMQ (TList* tempList); - virtual void ExecMQ (TList* inputList, TList* outputList); + virtual void InitMQ(TList* tempList); + virtual void ExecMQ(TList* inputList, TList* outputList); private: - PixelDigiPar* fDigiPar; + PixelDigiPar* fDigiPar; FairGeoParSet* fGeoParSet; - TClonesArray* fDigis; /** Input array of PixelDigi **/ - TClonesArray* fHits; /** Output array of PixelHit **/ + TClonesArray* fDigis; /** Input array of PixelDigi **/ + TClonesArray* fHits; /** Output array of PixelHit **/ - Int_t fNDigis; - Int_t fNHits; + Int_t fNDigis; + Int_t fNHits; - Int_t fTNofEvents; - Int_t fTNofDigis; - Int_t fTNofHits; + Int_t fTNofEvents; + Int_t fTNofDigis; + Int_t fTNofHits; - Int_t fFeCols; // Colums read per Frontend - Int_t fFeRows; // Rows read per Frontend - Int_t fMaxFEperCol; // max number of Frontend elemens per column - Double_t fPitchX; // Pixel cell size X - Double_t fPitchY; // Pixel cell size Y + Int_t fFeCols; // Colums read per Frontend + Int_t fFeRows; // Rows read per Frontend + Int_t fMaxFEperCol; // max number of Frontend elemens per column + Double_t fPitchX; // Pixel cell size X + Double_t fPitchY; // Pixel cell size Y /** Get parameter containers **/ virtual void SetParContainers(); @@ -84,7 +84,7 @@ class PixelFindHits : public FairTask PixelFindHits(const PixelFindHits&); PixelFindHits& operator=(const PixelFindHits&); - ClassDef(PixelFindHits,1); + ClassDef(PixelFindHits, 1); }; #endif diff --git a/examples/MQ/pixelDetector/src/PixelFindTracks.cxx b/examples/MQ/pixelDetector/src/PixelFindTracks.cxx index 98b7a951e7..3623136e4c 100644 --- a/examples/MQ/pixelDetector/src/PixelFindTracks.cxx +++ b/examples/MQ/pixelDetector/src/PixelFindTracks.cxx @@ -19,201 +19,209 @@ #include "PixelTrack.h" // Includes from base +#include "FairLogger.h" #include "FairRootManager.h" +#include "FairRun.h" // for FairRun #include "FairRuntimeDb.h" -#include "FairLogger.h" -#include "FairRun.h" // for FairRun // Includes from ROOT #include -#include // for TH2F -#include // for TList -#include // for Abs +#include // for TH2F +#include // for TList +#include // for Abs PixelFindTracks::PixelFindTracks() - : PixelFindTracks("Pixel Track Finder", 0) -{ -} + : PixelFindTracks("Pixel Track Finder", 0) +{} PixelFindTracks::PixelFindTracks(Int_t iVerbose) - : PixelFindTracks("Pixel Track Finder", iVerbose) -{ -} + : PixelFindTracks("Pixel Track Finder", iVerbose) +{} PixelFindTracks::PixelFindTracks(const char* name, Int_t iVerbose) - : FairTask(name, iVerbose) - , fDigiPar(nullptr) - , fHits(nullptr) - , fTracks(nullptr) - , fTNofEvents(0) - , fNHits(0) - , fTNofHits(0) - , fNTracks(0) - , fTNofTracks(0) - , fhDist2D(nullptr) + : FairTask(name, iVerbose) + , fDigiPar(nullptr) + , fHits(nullptr) + , fTracks(nullptr) + , fTNofEvents(0) + , fNHits(0) + , fTNofHits(0) + , fNTracks(0) + , fTNofTracks(0) + , fhDist2D(nullptr) { - Reset(); + Reset(); } PixelFindTracks::~PixelFindTracks() { - Reset(); - delete fDigiPar; - if ( fTracks ) { - fTracks->Delete(); - delete fTracks; - } + Reset(); + delete fDigiPar; + if (fTracks) { + fTracks->Delete(); + delete fTracks; + } } void PixelFindTracks::Exec(Option_t* /*opt*/) { - Reset(); - - fNHits = fHits->GetEntriesFast(); - - LOG(debug) << "PixelFindTracks::Exec() EVENT " << fTNofEvents << " with " << fNHits << " HITS"; - - PixelHit* curHit1; - PixelHit* curHit2; - PixelHit* curHit3; - - Double_t parX0 = 0.; - Double_t parY0 = 0.; - Double_t parAX = 0.; - Double_t parAY = 0.; - Double_t expX = 0.; - Double_t expY = 0.; - - for ( Int_t ihit1 = 0 ; ihit1 < fNHits ; ihit1++ ) { - curHit1 = static_cast(fHits->At(ihit1)); - LOG(debug) << "hit1 at " << curHit1->GetX() << " , " << curHit1->GetY() << " , " << curHit1->GetZ() << " / " << curHit1->GetDetectorID(); - if ( (curHit1->GetDetectorID())/256 != 1 ) continue; - for ( Int_t ihit2 = 0 ; ihit2 < fNHits ; ihit2++ ) { - curHit2 = static_cast(fHits->At(ihit2)); - LOG(debug) << "hit2 at " << curHit2->GetX() << " , " << curHit2->GetY() << " , " << curHit2->GetZ() << " / " << curHit2->GetDetectorID(); - if ( (curHit2->GetDetectorID())/256 != 2 ) continue; - - parAX = (curHit2->GetX()-curHit1->GetX())/(curHit2->GetZ()-curHit1->GetZ()); - parAY = (curHit2->GetY()-curHit1->GetY())/(curHit2->GetZ()-curHit1->GetZ()); - parX0 = curHit1->GetX()-parAX*curHit1->GetZ(); - parY0 = curHit1->GetY()-parAY*curHit1->GetZ(); - - for ( Int_t ihit3 = 0 ; ihit3 < fNHits ; ihit3++ ) { - curHit3 = static_cast(fHits->At(ihit3)); - LOG(debug) << "hit3 at " << curHit3->GetX() << " , " << curHit3->GetY() << " , " << curHit3->GetZ() << " / " << curHit3->GetDetectorID(); - if ( (curHit3->GetDetectorID())/256 != 3 ) continue; - expX = parX0+parAX*curHit3->GetZ(); - expY = parY0+parAY*curHit3->GetZ(); - - fhDist2D->Fill(expX-curHit3->GetX(),expY-curHit3->GetY()); - - if ( TMath::Abs(expX-curHit3->GetX()) < 0.03 && - TMath::Abs(expY-curHit3->GetY()) < 0.03 ) { - LOG(debug) << "should create track..."; - PixelTrack* tempTrack = new ((*fTracks)[fNTracks]) PixelTrack(parX0,parAX,parY0,parAY,0.,0.,0.,0.); - tempTrack->AddHitIndex(ihit1); - tempTrack->AddHitIndex(ihit2); - tempTrack->AddHitIndex(ihit3); - LOG(debug) << "--> " << fNTracks; - fNTracks++; + Reset(); + + fNHits = fHits->GetEntriesFast(); + + LOG(debug) << "PixelFindTracks::Exec() EVENT " << fTNofEvents << " with " << fNHits << " HITS"; + + PixelHit* curHit1; + PixelHit* curHit2; + PixelHit* curHit3; + + Double_t parX0 = 0.; + Double_t parY0 = 0.; + Double_t parAX = 0.; + Double_t parAY = 0.; + Double_t expX = 0.; + Double_t expY = 0.; + + for (Int_t ihit1 = 0; ihit1 < fNHits; ihit1++) { + curHit1 = static_cast(fHits->At(ihit1)); + LOG(debug) << "hit1 at " << curHit1->GetX() << " , " << curHit1->GetY() << " , " << curHit1->GetZ() << " / " + << curHit1->GetDetectorID(); + if ((curHit1->GetDetectorID()) / 256 != 1) + continue; + for (Int_t ihit2 = 0; ihit2 < fNHits; ihit2++) { + curHit2 = static_cast(fHits->At(ihit2)); + LOG(debug) << "hit2 at " << curHit2->GetX() << " , " << curHit2->GetY() << " , " << curHit2->GetZ() << " / " + << curHit2->GetDetectorID(); + if ((curHit2->GetDetectorID()) / 256 != 2) + continue; + + parAX = (curHit2->GetX() - curHit1->GetX()) / (curHit2->GetZ() - curHit1->GetZ()); + parAY = (curHit2->GetY() - curHit1->GetY()) / (curHit2->GetZ() - curHit1->GetZ()); + parX0 = curHit1->GetX() - parAX * curHit1->GetZ(); + parY0 = curHit1->GetY() - parAY * curHit1->GetZ(); + + for (Int_t ihit3 = 0; ihit3 < fNHits; ihit3++) { + curHit3 = static_cast(fHits->At(ihit3)); + LOG(debug) << "hit3 at " << curHit3->GetX() << " , " << curHit3->GetY() << " , " << curHit3->GetZ() + << " / " << curHit3->GetDetectorID(); + if ((curHit3->GetDetectorID()) / 256 != 3) + continue; + expX = parX0 + parAX * curHit3->GetZ(); + expY = parY0 + parAY * curHit3->GetZ(); + + fhDist2D->Fill(expX - curHit3->GetX(), expY - curHit3->GetY()); + + if (TMath::Abs(expX - curHit3->GetX()) < 0.03 && TMath::Abs(expY - curHit3->GetY()) < 0.03) { + LOG(debug) << "should create track..."; + PixelTrack* tempTrack = + new ((*fTracks)[fNTracks]) PixelTrack(parX0, parAX, parY0, parAY, 0., 0., 0., 0.); + tempTrack->AddHitIndex(ihit1); + tempTrack->AddHitIndex(ihit2); + tempTrack->AddHitIndex(ihit3); + LOG(debug) << "--> " << fNTracks; + fNTracks++; + } + // LOG(debug) << ">>>>>> " << curHit3->GetX() << " / " << curHit3->GetY(); + // LOG(debug) << " " << expX << " / " << expY; + } } - // LOG(debug) << ">>>>>> " << curHit3->GetX() << " / " << curHit3->GetY(); - // LOG(debug) << " " << expX << " / " << expY; - } } - } - fTNofEvents += 1; - fTNofHits += fNHits; - fTNofTracks += fNTracks; + fTNofEvents += 1; + fTNofHits += fNHits; + fTNofTracks += fNTracks; } void PixelFindTracks::SetParContainers() { - // Get run and runtime database - FairRun* run = FairRun::Instance(); - if ( ! run ) LOG(fatal) << "No analysis run"; - - FairRuntimeDb* db = run->GetRuntimeDb(); - if ( ! db ) LOG(fatal) << "No runtime database"; + // Get run and runtime database + FairRun* run = FairRun::Instance(); + if (!run) + LOG(fatal) << "No analysis run"; - // Get GEM digitisation parameter container - fDigiPar = static_cast(db->getContainer("PixelDigiParameters")); + FairRuntimeDb* db = run->GetRuntimeDb(); + if (!db) + LOG(fatal) << "No runtime database"; + // Get GEM digitisation parameter container + fDigiPar = static_cast(db->getContainer("PixelDigiParameters")); } void PixelFindTracks::GetParList(TList* tempList) { - fDigiPar = new PixelDigiPar("PixelDigiParameters"); - tempList->Add(fDigiPar); + fDigiPar = new PixelDigiPar("PixelDigiParameters"); + tempList->Add(fDigiPar); - return; + return; } -void PixelFindTracks::InitMQ(TList* tempList) +void PixelFindTracks::InitMQ(TList* tempList) { - LOG(info) << "********************************************** PixelFindTracks::InitMQ()"; - fDigiPar = (PixelDigiPar*)tempList->FindObject("PixelDigiParameters"); + LOG(info) << "********************************************** PixelFindTracks::InitMQ()"; + fDigiPar = (PixelDigiPar*)tempList->FindObject("PixelDigiParameters"); - fTracks = new TClonesArray("PixelTrack",10000); - fhDist2D = new TH2F("fhDist2D","Distance between hit and expected track",400,-1.,1.,400,-1.,1.); + fTracks = new TClonesArray("PixelTrack", 10000); + fhDist2D = new TH2F("fhDist2D", "Distance between hit and expected track", 400, -1., 1., 400, -1., 1.); - return; + return; } -void PixelFindTracks::ExecMQ(TList* inputList,TList* outputList) +void PixelFindTracks::ExecMQ(TList* inputList, TList* outputList) { - // LOG(info) << "********************************************** PixelFindTracks::ExecMQ(" << inputList->GetName() << "," << outputList->GetName() << "), Event " << fTNofEvents; - // LOG(info) << "********************************************** PixelFindTracks::ExecMQ(), Event " << fTNofEvents; - // LOG(info) << "t" << FairLogger::flush; - fHits = (TClonesArray*) inputList->FindObject("PixelHits"); - outputList->Add(fTracks); - Exec(""); - return; + // LOG(info) << "********************************************** PixelFindTracks::ExecMQ(" << inputList->GetName() + // << "," << outputList->GetName() << "), Event " << fTNofEvents; LOG(info) << + // "********************************************** PixelFindTracks::ExecMQ(), Event " << fTNofEvents; LOG(info) << + // "t" << FairLogger::flush; + fHits = (TClonesArray*)inputList->FindObject("PixelHits"); + outputList->Add(fTracks); + Exec(""); + return; } InitStatus PixelFindTracks::Init() { - // Get input array - FairRootManager* ioman = FairRootManager::Instance(); + // Get input array + FairRootManager* ioman = FairRootManager::Instance(); - if ( ! ioman ) LOG(fatal) << "No FairRootManager"; - fHits = static_cast(ioman->GetObject("PixelHits")); + if (!ioman) + LOG(fatal) << "No FairRootManager"; + fHits = static_cast(ioman->GetObject("PixelHits")); - if ( !fHits ) - LOG(warn) << "PixelFindTracks::Init() No input PixelHit array!"; + if (!fHits) + LOG(warn) << "PixelFindTracks::Init() No input PixelHit array!"; - // Register output array PixelHit - fTracks = new TClonesArray("PixelTrack",10000); - ioman->Register("PixelTracks", "Pixel", fTracks, kTRUE); + // Register output array PixelHit + fTracks = new TClonesArray("PixelTrack", 10000); + ioman->Register("PixelTracks", "Pixel", fTracks, kTRUE); - fhDist2D = new TH2F("fhDist2D","Distance between hit and expected track",400,-1.,1.,400,-1.,1.); + fhDist2D = new TH2F("fhDist2D", "Distance between hit and expected track", 400, -1., 1., 400, -1., 1.); - return kSUCCESS; + return kSUCCESS; } -InitStatus PixelFindTracks::ReInit() -{ - return kSUCCESS; -} +InitStatus PixelFindTracks::ReInit() { return kSUCCESS; } void PixelFindTracks::Reset() { - fNTracks = fNHits = 0; - if ( fTracks ) fTracks->Clear(); + fNTracks = fNHits = 0; + if (fTracks) + fTracks->Clear(); } void PixelFindTracks::Finish() { - if ( fTracks ) fTracks->Delete(); - - fhDist2D->Draw("colz"); - - LOG(info) << "-------------------- " << fName.Data() << " : Summary ------------------------"; - LOG(info) << " Events: " << fTNofEvents; - LOG(info) << " Hits: " << fTNofHits << " ( " << static_cast(fTNofHits )/(static_cast(fTNofEvents)) << " per event )"; - LOG(info) << " Tracks: " << fTNofTracks << " ( " << static_cast(fTNofTracks)/(static_cast(fTNofEvents)) << " per event )"; - LOG(info) << "---------------------------------------------------------------------"; + if (fTracks) + fTracks->Delete(); + + fhDist2D->Draw("colz"); + + LOG(info) << "-------------------- " << fName.Data() << " : Summary ------------------------"; + LOG(info) << " Events: " << fTNofEvents; + LOG(info) << " Hits: " << fTNofHits << " ( " + << static_cast(fTNofHits) / (static_cast(fTNofEvents)) << " per event )"; + LOG(info) << " Tracks: " << fTNofTracks << " ( " + << static_cast(fTNofTracks) / (static_cast(fTNofEvents)) << " per event )"; + LOG(info) << "---------------------------------------------------------------------"; } -ClassImp(PixelFindTracks) +ClassImp(PixelFindTracks); diff --git a/examples/MQ/pixelDetector/src/PixelFindTracks.h b/examples/MQ/pixelDetector/src/PixelFindTracks.h index 8a0ec7af9d..6cb307e0b5 100644 --- a/examples/MQ/pixelDetector/src/PixelFindTracks.h +++ b/examples/MQ/pixelDetector/src/PixelFindTracks.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* @@ -43,24 +43,24 @@ class PixelFindTracks : public FairTask virtual void Exec(Option_t* opt); virtual void GetParList(TList* tempList); - virtual void InitMQ (TList* tempList); - virtual void ExecMQ (TList* inputList,TList* outputList); + virtual void InitMQ(TList* tempList); + virtual void ExecMQ(TList* inputList, TList* outputList); private: PixelDigiPar* fDigiPar; - TClonesArray* fHits; /** Input array of PixelHit **/ - TClonesArray* fTracks; /** Output array of PixelTrack **/ + TClonesArray* fHits; /** Input array of PixelHit **/ + TClonesArray* fTracks; /** Output array of PixelTrack **/ - Int_t fTNofEvents; + Int_t fTNofEvents; - Int_t fNHits; - Int_t fTNofHits; + Int_t fNHits; + Int_t fTNofHits; - Int_t fNTracks; - Int_t fTNofTracks; + Int_t fNTracks; + Int_t fTNofTracks; - TH2F* fhDist2D; + TH2F* fhDist2D; /** Get parameter containers **/ virtual void SetParContainers(); @@ -80,7 +80,7 @@ class PixelFindTracks : public FairTask PixelFindTracks(const PixelFindTracks&); PixelFindTracks& operator=(const PixelFindTracks&); - ClassDef(PixelFindTracks,1); + ClassDef(PixelFindTracks, 1); }; #endif diff --git a/examples/MQ/pixelDetector/src/PixelFitTracks.cxx b/examples/MQ/pixelDetector/src/PixelFitTracks.cxx index 888472ff69..4cf55a7dde 100644 --- a/examples/MQ/pixelDetector/src/PixelFitTracks.cxx +++ b/examples/MQ/pixelDetector/src/PixelFitTracks.cxx @@ -14,232 +14,236 @@ #include "PixelFitTracks.h" +#include "FairLogger.h" +#include "FairRootManager.h" +#include "FairRun.h" +#include "FairRuntimeDb.h" #include "PixelDigiPar.h" #include "PixelHit.h" #include "PixelTrack.h" -#include "FairRootManager.h" -#include "FairRuntimeDb.h" -#include "FairLogger.h" -#include "FairRun.h" - #include -#include #include +#include PixelFitTracks::PixelFitTracks() - : PixelFitTracks("Pixel Track Fitter", 0) -{ -} + : PixelFitTracks("Pixel Track Fitter", 0) +{} PixelFitTracks::PixelFitTracks(Int_t iVerbose) - : PixelFitTracks("Pixel Track Fitter", iVerbose) -{ -} + : PixelFitTracks("Pixel Track Fitter", iVerbose) +{} PixelFitTracks::PixelFitTracks(const char* name, Int_t iVerbose) - : FairTask(name, iVerbose) - , fDigiPar(nullptr) - , fHits(nullptr) - , fTracks(nullptr) - , fFitTracks(nullptr) - , fTNofEvents(0) - , fNHits(0) - , fNTracks(0) - , fTNofTracks(0) - , fNFitTracks(0) - , fTNofFitTracks(0) + : FairTask(name, iVerbose) + , fDigiPar(nullptr) + , fHits(nullptr) + , fTracks(nullptr) + , fFitTracks(nullptr) + , fTNofEvents(0) + , fNHits(0) + , fNTracks(0) + , fTNofTracks(0) + , fNFitTracks(0) + , fTNofFitTracks(0) { - Reset(); + Reset(); } PixelFitTracks::~PixelFitTracks() { - Reset(); - delete fDigiPar; - if (fFitTracks) { - fFitTracks->Delete(); - delete fFitTracks; - } + Reset(); + delete fDigiPar; + if (fFitTracks) { + fFitTracks->Delete(); + delete fFitTracks; + } } void PixelFitTracks::Exec(Option_t* /*opt*/) { - Reset(); - - fNHits = fHits ->GetEntriesFast(); - fNTracks = fTracks->GetEntriesFast(); - - LOG(debug) << "PixelFitTracks::Exec() EVENT " << fTNofEvents << " with " << fNTracks << " TRACKS"; - - for (Int_t itrack = 0; itrack < fNTracks; itrack++) { - PixelTrack* curTrack = static_cast(fTracks->At(itrack)); - - const Int_t nofHits = curTrack->GetNofHits(); - // Default initialize the arrays - Double_t* hitXPos = new Double_t[nofHits](); - Double_t* hitYPos = new Double_t[nofHits](); - Double_t* hitZPos = new Double_t[nofHits](); - - for (Int_t ihit = 0; ihit < nofHits; ihit++) { - PixelHit* curHit = static_cast(fHits->At(curTrack->GetHitIndex(ihit))); - - // LOG(info) << " HIT[" << curTrack->GetHitIndex(ihit) << "] = (" << curHit->GetX() << " , " << curHit->GetY() << " , " << curHit->GetZ() << ")"; - hitXPos[ihit] = curHit->GetX(); - hitYPos[ihit] = curHit->GetY(); - hitZPos[ihit] = curHit->GetZ(); - } - - Double_t valX0 = 0., errX0 = 0., valAX = 0., errAX = 0.; - Double_t valY0 = 0., errY0 = 0., valAY = 0., errAY = 0.; - - LinearRegression(nofHits,hitZPos,hitXPos,valX0,errX0,valAX,errAX); - LinearRegression(nofHits,hitZPos,hitYPos,valY0,errY0,valAY,errAY); - - PixelTrack* fitTrack = new ((*fFitTracks)[fNFitTracks]) PixelTrack(valX0,valAX,valY0,valAY, - errX0,errAX,errY0,errAY); - for (Int_t ihit = 0; ihit < nofHits; ihit++) { - fitTrack->AddHitIndex(curTrack->GetHitIndex(ihit)); + Reset(); + + fNHits = fHits->GetEntriesFast(); + fNTracks = fTracks->GetEntriesFast(); + + LOG(debug) << "PixelFitTracks::Exec() EVENT " << fTNofEvents << " with " << fNTracks << " TRACKS"; + + for (Int_t itrack = 0; itrack < fNTracks; itrack++) { + PixelTrack* curTrack = static_cast(fTracks->At(itrack)); + + const Int_t nofHits = curTrack->GetNofHits(); + // Default initialize the arrays + Double_t* hitXPos = new Double_t[nofHits](); + Double_t* hitYPos = new Double_t[nofHits](); + Double_t* hitZPos = new Double_t[nofHits](); + + for (Int_t ihit = 0; ihit < nofHits; ihit++) { + PixelHit* curHit = static_cast(fHits->At(curTrack->GetHitIndex(ihit))); + + // LOG(info) << " HIT[" << curTrack->GetHitIndex(ihit) << "] = (" << curHit->GetX() << " , " << + // curHit->GetY() << " , " << curHit->GetZ() << ")"; + hitXPos[ihit] = curHit->GetX(); + hitYPos[ihit] = curHit->GetY(); + hitZPos[ihit] = curHit->GetZ(); + } + + Double_t valX0 = 0., errX0 = 0., valAX = 0., errAX = 0.; + Double_t valY0 = 0., errY0 = 0., valAY = 0., errAY = 0.; + + LinearRegression(nofHits, hitZPos, hitXPos, valX0, errX0, valAX, errAX); + LinearRegression(nofHits, hitZPos, hitYPos, valY0, errY0, valAY, errAY); + + PixelTrack* fitTrack = + new ((*fFitTracks)[fNFitTracks]) PixelTrack(valX0, valAX, valY0, valAY, errX0, errAX, errY0, errAY); + for (Int_t ihit = 0; ihit < nofHits; ihit++) { + fitTrack->AddHitIndex(curTrack->GetHitIndex(ihit)); + } + + fNFitTracks += 1; + + LOG(debug) << "Track params: " + << " AX = " << curTrack->GetAX() << " += " << curTrack->GetAXErr() << " X0 = " << curTrack->GetX0() + << " += " << curTrack->GetX0Err() << " " + << " AY = " << curTrack->GetAY() << " += " << curTrack->GetAYErr() << " Y0 = " << curTrack->GetY0() + << " += " << curTrack->GetY0Err(); + LOG(debug) << "Fitted params: " + << " AX = " << valAX << " += " << errAX << " X0 = " << valX0 << " += " << errX0 + << " " + << " AY = " << valAY << " += " << errAY << " Y0 = " << valY0 << " += " << errY0; + + delete[] hitXPos; + delete[] hitYPos; + delete[] hitZPos; } - fNFitTracks += 1; - - LOG(debug) << "Track params: " - << " AX = " << curTrack->GetAX() << " += " << curTrack->GetAXErr() - << " X0 = " << curTrack->GetX0() << " += " << curTrack->GetX0Err() - << " " - << " AY = " << curTrack->GetAY() << " += " << curTrack->GetAYErr() - << " Y0 = " << curTrack->GetY0() << " += " << curTrack->GetY0Err(); - LOG(debug) << "Fitted params: " - << " AX = " << valAX << " += " << errAX - << " X0 = " << valX0 << " += " << errX0 - << " " - << " AY = " << valAY << " += " << errAY - << " Y0 = " << valY0 << " += " << errY0; - - delete [] hitXPos; - delete [] hitYPos; - delete [] hitZPos; - } - - fTNofEvents += 1; - fTNofTracks += fNTracks; - fTNofFitTracks += fNFitTracks; + fTNofEvents += 1; + fTNofTracks += fNTracks; + fTNofFitTracks += fNFitTracks; } -Double_t PixelFitTracks::LinearRegression(Int_t nval, Double_t xval[], Double_t yval[], - Double_t& valA0, Double_t& errA0, - Double_t& valA1, Double_t& errA1) +Double_t PixelFitTracks::LinearRegression(Int_t nval, + Double_t xval[], + Double_t yval[], + Double_t& valA0, + Double_t& errA0, + Double_t& valA1, + Double_t& errA1) { - Double_t valN = static_cast(nval); - Double_t sumXY = 0.; - Double_t sumX = 0.; - Double_t sumY = 0.; - Double_t sumXX = 0.; - - for (Int_t ival = 0; ival < nval; ival++) { - sumXY += xval[ival] * yval[ival]; - sumX += xval[ival]; - sumY += yval[ival]; - sumXX += xval[ival] * xval[ival]; - } - valA1 = (valN*sumXY-sumX*sumY)/(valN*sumXX-sumX*sumX); - valA0 = (sumY-valA1*sumX)/valN; - Double_t sumEE = 0.; - for (Int_t ival = 0; ival < nval; ival++) { - sumEE += (yval[ival]-valA0-valA1*xval[ival])*(yval[ival]-valA0-valA1*xval[ival]); - } - Double_t valS = TMath::Sqrt(sumEE/(valN-2.)); - errA1 = valS*TMath::Sqrt(valN/(valN*sumXX-sumX*sumX)); - errA0 = valS*TMath::Sqrt(sumXX/(valN*sumXX-sumX*sumX)); - // cout << "A0 = " << valA0 << " +- " << errA0 << " / A1 = " << valA1 << " +- " << errA1 << " / S = " << valS << endl; - return valS; + Double_t valN = static_cast(nval); + Double_t sumXY = 0.; + Double_t sumX = 0.; + Double_t sumY = 0.; + Double_t sumXX = 0.; + + for (Int_t ival = 0; ival < nval; ival++) { + sumXY += xval[ival] * yval[ival]; + sumX += xval[ival]; + sumY += yval[ival]; + sumXX += xval[ival] * xval[ival]; + } + valA1 = (valN * sumXY - sumX * sumY) / (valN * sumXX - sumX * sumX); + valA0 = (sumY - valA1 * sumX) / valN; + Double_t sumEE = 0.; + for (Int_t ival = 0; ival < nval; ival++) { + sumEE += (yval[ival] - valA0 - valA1 * xval[ival]) * (yval[ival] - valA0 - valA1 * xval[ival]); + } + Double_t valS = TMath::Sqrt(sumEE / (valN - 2.)); + errA1 = valS * TMath::Sqrt(valN / (valN * sumXX - sumX * sumX)); + errA0 = valS * TMath::Sqrt(sumXX / (valN * sumXX - sumX * sumX)); + // cout << "A0 = " << valA0 << " +- " << errA0 << " / A1 = " << valA1 << " +- " << errA1 << " / S = " << valS << + // endl; + return valS; } void PixelFitTracks::SetParContainers() { - // Get run and runtime database - FairRun* run = FairRun::Instance(); - if (! run) LOG(fatal) << "No analysis run"; + // Get run and runtime database + FairRun* run = FairRun::Instance(); + if (!run) + LOG(fatal) << "No analysis run"; - FairRuntimeDb* db = run->GetRuntimeDb(); - if (! db) LOG(fatal) << "No runtime database"; - - // Get GEM digitisation parameter container - fDigiPar = static_cast(db->getContainer("PixelDigiParameters")); + FairRuntimeDb* db = run->GetRuntimeDb(); + if (!db) + LOG(fatal) << "No runtime database"; + // Get GEM digitisation parameter container + fDigiPar = static_cast(db->getContainer("PixelDigiParameters")); } void PixelFitTracks::GetParList(TList* tempList) { - fDigiPar = new PixelDigiPar("PixelDigiParameters"); - tempList->Add(fDigiPar); + fDigiPar = new PixelDigiPar("PixelDigiParameters"); + tempList->Add(fDigiPar); - return; + return; } void PixelFitTracks::InitMQ(TList* tempList) { - LOG(info) << "********************************************** PixelFitTracks::InitMQ()"; - fDigiPar = (PixelDigiPar*)tempList->FindObject("PixelDigiParameters"); + LOG(info) << "********************************************** PixelFitTracks::InitMQ()"; + fDigiPar = (PixelDigiPar*)tempList->FindObject("PixelDigiParameters"); - fFitTracks = new TClonesArray("PixelTrack",10000); - fFitTracks->SetName("PixelFitTracks"); - return; + fFitTracks = new TClonesArray("PixelTrack", 10000); + fFitTracks->SetName("PixelFitTracks"); + return; } -void PixelFitTracks::ExecMQ(TList* inputList,TList* outputList) +void PixelFitTracks::ExecMQ(TList* inputList, TList* outputList) { - // LOG(info) << "********************************************** PixelFitTracks::ExecMQ(" << inputList->GetName() << "," << outputList->GetName() << "), Event " << fTNofEvents; - // LOG(info) << "********************************************** PixelFitTracks::ExecMQ(), Event " << fTNofEvents; - // LOG(info) << "f" << FairLogger::flush; - fHits = (TClonesArray*) inputList->FindObject("PixelHits"); - fTracks = (TClonesArray*) inputList->FindObject("PixelTracks"); - outputList->Add(fFitTracks); - Exec(""); - return; + // LOG(info) << "********************************************** PixelFitTracks::ExecMQ(" << inputList->GetName() << + // "," << outputList->GetName() << "), Event " << fTNofEvents; LOG(info) << + // "********************************************** PixelFitTracks::ExecMQ(), Event " << fTNofEvents; LOG(info) << + // "f" << FairLogger::flush; + fHits = (TClonesArray*)inputList->FindObject("PixelHits"); + fTracks = (TClonesArray*)inputList->FindObject("PixelTracks"); + outputList->Add(fFitTracks); + Exec(""); + return; } InitStatus PixelFitTracks::Init() { - // Get input array - FairRootManager* ioman = FairRootManager::Instance(); - if (! ioman) LOG(fatal) << "No FairRootManager"; - - fHits = static_cast(ioman->GetObject("PixelHits")); - if (!fHits) - LOG(warn) << "PixelFitTracks::Init() No input PixelHit array!"; - fTracks = static_cast(ioman->GetObject("PixelTracks")); - if (!fTracks) - LOG(warn) << "PixelFitTracks::Init() No input PixelTrack array!"; - - // Register output array PixelHit - fFitTracks = new TClonesArray("PixelTrack", 10000); - ioman->Register("PixelFitTracks", "Pixel", fFitTracks, kTRUE); - - return kSUCCESS; + // Get input array + FairRootManager* ioman = FairRootManager::Instance(); + if (!ioman) + LOG(fatal) << "No FairRootManager"; + + fHits = static_cast(ioman->GetObject("PixelHits")); + if (!fHits) + LOG(warn) << "PixelFitTracks::Init() No input PixelHit array!"; + fTracks = static_cast(ioman->GetObject("PixelTracks")); + if (!fTracks) + LOG(warn) << "PixelFitTracks::Init() No input PixelTrack array!"; + + // Register output array PixelHit + fFitTracks = new TClonesArray("PixelTrack", 10000); + ioman->Register("PixelFitTracks", "Pixel", fFitTracks, kTRUE); + + return kSUCCESS; } -InitStatus PixelFitTracks::ReInit() -{ - return kSUCCESS; -} +InitStatus PixelFitTracks::ReInit() { return kSUCCESS; } void PixelFitTracks::Reset() { - fNFitTracks = fNTracks = fNHits = 0; - if (fFitTracks) fFitTracks->Clear(); + fNFitTracks = fNTracks = fNHits = 0; + if (fFitTracks) + fFitTracks->Clear(); } void PixelFitTracks::Finish() { - if (fFitTracks) fFitTracks->Delete(); - - LOG(info) << "-------------------- " << fName.Data() << " : Summary ------------------------"; - LOG(info) << " Events: " << fTNofEvents; - LOG(info) << " Tracks: " << fTNofTracks << " (" << static_cast(fTNofTracks )/(static_cast(fTNofEvents)) << " per event)"; - LOG(info) << " Fitted Tracks: " << fTNofFitTracks << " (" << static_cast(fTNofFitTracks)/(static_cast(fTNofEvents)) << " per event)"; - LOG(info) << "---------------------------------------------------------------------"; + if (fFitTracks) + fFitTracks->Delete(); + + LOG(info) << "-------------------- " << fName.Data() << " : Summary ------------------------"; + LOG(info) << " Events: " << fTNofEvents; + LOG(info) << " Tracks: " << fTNofTracks << " (" + << static_cast(fTNofTracks) / (static_cast(fTNofEvents)) << " per event)"; + LOG(info) << " Fitted Tracks: " << fTNofFitTracks << " (" + << static_cast(fTNofFitTracks) / (static_cast(fTNofEvents)) << " per event)"; + LOG(info) << "---------------------------------------------------------------------"; } -ClassImp(PixelFitTracks) +ClassImp(PixelFitTracks); diff --git a/examples/MQ/pixelDetector/src/PixelFitTracks.h b/examples/MQ/pixelDetector/src/PixelFitTracks.h index 0a648dde26..6a6042ee4e 100644 --- a/examples/MQ/pixelDetector/src/PixelFitTracks.h +++ b/examples/MQ/pixelDetector/src/PixelFitTracks.h @@ -42,29 +42,33 @@ class PixelFitTracks : public FairTask virtual void Exec(Option_t* opt); virtual void GetParList(TList* tempList); - virtual void InitMQ (TList* tempList); - virtual void ExecMQ (TList* inputList,TList* outputList); + virtual void InitMQ(TList* tempList); + virtual void ExecMQ(TList* inputList, TList* outputList); private: PixelDigiPar* fDigiPar; - TClonesArray* fHits; /** Input array of PixelHit **/ + TClonesArray* fHits; /** Input array of PixelHit **/ TClonesArray* fTracks; /** Input array of PixelTrack **/ TClonesArray* fFitTracks; /** Output array of PixelTrack **/ - Int_t fTNofEvents; + Int_t fTNofEvents; - Int_t fNHits; + Int_t fNHits; - Int_t fNTracks; - Int_t fTNofTracks; + Int_t fNTracks; + Int_t fTNofTracks; - Int_t fNFitTracks; - Int_t fTNofFitTracks; + Int_t fNFitTracks; + Int_t fTNofFitTracks; - Double_t LinearRegression(Int_t nval, Double_t xval[], Double_t yval[], - Double_t& valA0, Double_t& errA0, - Double_t& valA1, Double_t& errA1 ); + Double_t LinearRegression(Int_t nval, + Double_t xval[], + Double_t yval[], + Double_t& valA0, + Double_t& errA0, + Double_t& valA1, + Double_t& errA1); /** Get parameter containers **/ virtual void SetParContainers(); @@ -84,7 +88,7 @@ class PixelFitTracks : public FairTask PixelFitTracks(const PixelFitTracks&); PixelFitTracks& operator=(const PixelFitTracks&); - ClassDef(PixelFitTracks,1); + ClassDef(PixelFitTracks, 1); }; #endif diff --git a/examples/MQ/pixelDetector/src/PixelGeo.cxx b/examples/MQ/pixelDetector/src/PixelGeo.cxx index bc4ea99d9a..9033227fa9 100644 --- a/examples/MQ/pixelDetector/src/PixelGeo.cxx +++ b/examples/MQ/pixelDetector/src/PixelGeo.cxx @@ -1,41 +1,41 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "PixelGeo.h" -#include // for sprintf +#include // for sprintf -ClassImp(PixelGeo) +ClassImp(PixelGeo); PixelGeo::PixelGeo() - : FairGeoSet() + : FairGeoSet() { - // Constructor - // fName has to be the name used in the geometry for all volumes. - // If there is a mismatch the geometry cannot be build. - fName="Pixel"; - maxSectors=0; - maxModules=10; + // Constructor + // fName has to be the name used in the geometry for all volumes. + // If there is a mismatch the geometry cannot be build. + fName = "Pixel"; + maxSectors = 0; + maxModules = 10; } const char* PixelGeo::getModuleName(Int_t m) { - /** Returns the module name of Pixel number m + /** Returns the module name of Pixel number m Setting Pixel here means that all modules names in the ASCII file should start with Pixel otherwise they will not be constructed */ - sprintf(modName,"Pixel%i",m+1); - return modName; + sprintf(modName, "Pixel%i", m + 1); + return modName; } const char* PixelGeo::getEleName(Int_t m) { - /** Returns the element name of Det number m */ - sprintf(eleName,"Pixel%i",m+1); - return eleName; + /** Returns the element name of Det number m */ + sprintf(eleName, "Pixel%i", m + 1); + return eleName; } diff --git a/examples/MQ/pixelDetector/src/PixelGeo.h b/examples/MQ/pixelDetector/src/PixelGeo.h index 77763c7a85..adcce9566d 100644 --- a/examples/MQ/pixelDetector/src/PixelGeo.h +++ b/examples/MQ/pixelDetector/src/PixelGeo.h @@ -1,23 +1,23 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef PIXELGEO_H #define PIXELGEO_H -#include "FairGeoSet.h" // for FairGeoSet +#include "FairGeoSet.h" // for FairGeoSet -#include // for PixelGeo::Class, ClassDef, PixelGeo::Streamer -#include // for TString +#include // for PixelGeo::Class, ClassDef, PixelGeo::Streamer +#include // for TString class PixelGeo : public FairGeoSet { protected: - char modName[20]; // name of module - char eleName[20]; // substring for elements in module + char modName[20]; // name of module + char eleName[20]; // substring for elements in module public: PixelGeo(); @@ -26,17 +26,17 @@ class PixelGeo : public FairGeoSet const char* getEleName(Int_t); inline Int_t getModNumInMod(const TString&); - ClassDef(PixelGeo,1) + ClassDef(PixelGeo, 1) }; inline Int_t PixelGeo::getModNumInMod(const TString& name) { - /** returns the module index from module name + /** returns the module index from module name ?? in name[??] has to be the length of the detector name in the .geo file. For example if all nodes in this file starts with newdetector ?? has to be 11. */ - return static_cast((name[5]-'0')-1); // + return static_cast((name[5] - '0') - 1); // } #endif diff --git a/examples/MQ/pixelDetector/src/PixelGeoPar.cxx b/examples/MQ/pixelDetector/src/PixelGeoPar.cxx index 5ade0c5735..d37903da6c 100644 --- a/examples/MQ/pixelDetector/src/PixelGeoPar.cxx +++ b/examples/MQ/pixelDetector/src/PixelGeoPar.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "PixelGeoPar.h" @@ -11,38 +11,41 @@ #include -ClassImp(PixelGeoPar) +ClassImp(PixelGeoPar); -PixelGeoPar ::PixelGeoPar(const char* name, - const char* title, - const char* context) - : FairParGenericSet(name,title,context), - fGeoSensNodes(new TObjArray()), - fGeoPassNodes(new TObjArray()) -{ -} +PixelGeoPar ::PixelGeoPar(const char* name, const char* title, const char* context) + : FairParGenericSet(name, title, context) + , fGeoSensNodes(new TObjArray()) + , fGeoPassNodes(new TObjArray()) +{} -PixelGeoPar::~PixelGeoPar(void) -{ -} +PixelGeoPar::~PixelGeoPar(void) {} void PixelGeoPar::clear(void) { - delete fGeoSensNodes; - delete fGeoPassNodes; + delete fGeoSensNodes; + delete fGeoPassNodes; } void PixelGeoPar::putParams(FairParamList* l) { - if (!l) { return; } - l->addObject("FairGeoNodes Sensitive List", fGeoSensNodes); - l->addObject("FairGeoNodes Passive List", fGeoPassNodes); + if (!l) { + return; + } + l->addObject("FairGeoNodes Sensitive List", fGeoSensNodes); + l->addObject("FairGeoNodes Passive List", fGeoPassNodes); } Bool_t PixelGeoPar::getParams(FairParamList* l) { - if (!l) { return kFALSE; } - if (!l->fillObject("FairGeoNodes Sensitive List", fGeoSensNodes)) { return kFALSE; } - if (!l->fillObject("FairGeoNodes Passive List", fGeoPassNodes)) { return kFALSE; } - return kTRUE; + if (!l) { + return kFALSE; + } + if (!l->fillObject("FairGeoNodes Sensitive List", fGeoSensNodes)) { + return kFALSE; + } + if (!l->fillObject("FairGeoNodes Passive List", fGeoPassNodes)) { + return kFALSE; + } + return kTRUE; } diff --git a/examples/MQ/pixelDetector/src/PixelGeoPar.h b/examples/MQ/pixelDetector/src/PixelGeoPar.h index 26e8e8a909..396ec2c323 100644 --- a/examples/MQ/pixelDetector/src/PixelGeoPar.h +++ b/examples/MQ/pixelDetector/src/PixelGeoPar.h @@ -1,15 +1,16 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef PIXELGEOPAR_H #define PIXELGEOPAR_H -#include "FairParGenericSet.h" // for FairParGenericSet -#include // for PixelGeoPar::Class, ClassDef, PixelGe... +#include "FairParGenericSet.h" // for FairParGenericSet + +#include // for PixelGeoPar::Class, ClassDef, PixelGe... class FairParamList; class TObjArray; @@ -23,21 +24,21 @@ class PixelGeoPar : public FairParGenericSet /** List of FairGeoNodes for sensitive volumes */ TObjArray* fGeoPassNodes; - PixelGeoPar(const char* name="PixelGeoPar", - const char* title="Pixel Geometry Parameters", - const char* context="TestDefaultContext"); + PixelGeoPar(const char* name = "PixelGeoPar", + const char* title = "Pixel Geometry Parameters", + const char* context = "TestDefaultContext"); ~PixelGeoPar(void); void clear(void); void putParams(FairParamList*); Bool_t getParams(FairParamList*); - TObjArray* GetGeoSensitiveNodes() {return fGeoSensNodes;} - TObjArray* GetGeoPassiveNodes() {return fGeoPassNodes;} + TObjArray* GetGeoSensitiveNodes() { return fGeoSensNodes; } + TObjArray* GetGeoPassiveNodes() { return fGeoPassNodes; } private: PixelGeoPar(const PixelGeoPar&); PixelGeoPar& operator=(const PixelGeoPar&); - ClassDef(PixelGeoPar,1) + ClassDef(PixelGeoPar, 1) }; #endif diff --git a/examples/MQ/pixelDetector/src/PixelHit.cxx b/examples/MQ/pixelDetector/src/PixelHit.cxx index 3ec4e565a2..dc7b5eeebd 100644 --- a/examples/MQ/pixelDetector/src/PixelHit.cxx +++ b/examples/MQ/pixelDetector/src/PixelHit.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* @@ -16,16 +16,12 @@ PixelHit::PixelHit() : FairHit() -{ -} +{} PixelHit::PixelHit(Int_t detID, Int_t mcindex, const TVector3& pos, const TVector3& dpos) : FairHit(detID, pos, dpos, mcindex) -{ -} +{} -PixelHit::~PixelHit() -{ -} +PixelHit::~PixelHit() {} -ClassImp(PixelHit) +ClassImp(PixelHit); diff --git a/examples/MQ/pixelDetector/src/PixelHit.h b/examples/MQ/pixelDetector/src/PixelHit.h index 65a6a8da64..abd3690392 100644 --- a/examples/MQ/pixelDetector/src/PixelHit.h +++ b/examples/MQ/pixelDetector/src/PixelHit.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* @@ -15,12 +15,17 @@ #ifndef PIXELHIT_H_ #define PIXELHIT_H_ -#include "FairHit.h" // for FairHit -#include // for PixelHit::Class, ClassDef, PixelHit::Streamer +#include "FairHit.h" // for FairHit + +#include // for PixelHit::Class, ClassDef, PixelHit::Streamer class TVector3; -namespace boost { namespace serialization { class access; } } +namespace boost { +namespace serialization { +class access; +} +} // namespace boost #include class PixelHit : public FairHit @@ -35,7 +40,7 @@ class PixelHit : public FairHit /** Destructor **/ virtual ~PixelHit(); - template + template void serialize(Archive& ar, const unsigned int /*version*/) { ar& boost::serialization::base_object(*this); diff --git a/examples/MQ/pixelDetector/src/PixelPayload.h b/examples/MQ/pixelDetector/src/PixelPayload.h index 294b3e080d..83e047f172 100644 --- a/examples/MQ/pixelDetector/src/PixelPayload.h +++ b/examples/MQ/pixelDetector/src/PixelPayload.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /** @@ -17,51 +17,50 @@ #include -namespace PixelPayload +namespace PixelPayload { +class EventHeader { - class EventHeader - { - public: - int fRunId; - int fMCEntryNo; - int fPartNo; - }; + public: + int fRunId; + int fMCEntryNo; + int fPartNo; +}; - class Digi - { - public: - int fDetectorID; - int fFeID; - double fCharge; - int fCol; - int fRow; - }; +class Digi +{ + public: + int fDetectorID; + int fFeID; + double fCharge; + int fCol; + int fRow; +}; - class Hit - { - public: - int fDetectorID; - double posX; - double posY; - double posZ; - double dposX; - double dposY; - double dposZ; - }; +class Hit +{ + public: + int fDetectorID; + double posX; + double posY; + double posZ; + double dposX; + double dposY; + double dposZ; +}; - class Track - { - public: - double fX0; - double fAX; - double fY0; - double fAY; - double fX0Err; - double fAXErr; - double fY0Err; - double fAYErr; - }; -} +class Track +{ + public: + double fX0; + double fAX; + double fY0; + double fAY; + double fX0Err; + double fAXErr; + double fY0Err; + double fAYErr; +}; +} // namespace PixelPayload #define BIGBUFFERSIZE 1000000 diff --git a/examples/MQ/pixelDetector/src/PixelPoint.cxx b/examples/MQ/pixelDetector/src/PixelPoint.cxx index fe09fd72bd..9ba67eb30f 100644 --- a/examples/MQ/pixelDetector/src/PixelPoint.cxx +++ b/examples/MQ/pixelDetector/src/PixelPoint.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "PixelPoint.h" @@ -12,26 +12,28 @@ using std::cout; using std::endl; PixelPoint::PixelPoint() - : FairMCPoint() -{ -} + : FairMCPoint() +{} -PixelPoint::PixelPoint(Int_t trackID, Int_t detID, - TVector3 pos, TVector3 mom, - Double_t tof, Double_t length, - Double_t eLoss) - : FairMCPoint(trackID, detID, pos, mom, tof, length, eLoss) -{ -} +PixelPoint::PixelPoint(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t tof, + Double_t length, + Double_t eLoss) + : FairMCPoint(trackID, detID, pos, mom, tof, length, eLoss) +{} -PixelPoint::~PixelPoint() { } +PixelPoint::~PixelPoint() {} void PixelPoint::Print(const Option_t* /*opt*/) const { - cout << "-I- PixelPoint: Pixel 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- PixelPoint: Pixel 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; } -ClassImp(PixelPoint) +ClassImp(PixelPoint); diff --git a/examples/MQ/pixelDetector/src/PixelPoint.h b/examples/MQ/pixelDetector/src/PixelPoint.h index cd29e55eaa..5d9861f248 100644 --- a/examples/MQ/pixelDetector/src/PixelPoint.h +++ b/examples/MQ/pixelDetector/src/PixelPoint.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef PIXELPOINT_H @@ -10,8 +10,8 @@ #include "FairMCPoint.h" -#include #include +#include class PixelPoint : public FairMCPoint { @@ -28,8 +28,7 @@ class PixelPoint : public FairMCPoint *@param length Track length since creation [cm] *@param eLoss Energy deposit [GeV] **/ - PixelPoint(Int_t trackID, Int_t detID, TVector3 pos, TVector3 mom, - Double_t tof, Double_t length, Double_t eLoss); + PixelPoint(Int_t trackID, Int_t detID, TVector3 pos, TVector3 mom, Double_t tof, Double_t length, Double_t eLoss); /** Destructor **/ virtual ~PixelPoint(); @@ -42,7 +41,7 @@ class PixelPoint : public FairMCPoint PixelPoint(const PixelPoint& point); PixelPoint operator=(const PixelPoint& point); - ClassDef(PixelPoint,1) + ClassDef(PixelPoint, 1) }; #endif diff --git a/examples/MQ/pixelDetector/src/PixelTrack.cxx b/examples/MQ/pixelDetector/src/PixelTrack.cxx index 7651233280..9c74828ec9 100644 --- a/examples/MQ/pixelDetector/src/PixelTrack.cxx +++ b/examples/MQ/pixelDetector/src/PixelTrack.cxx @@ -17,36 +17,38 @@ #include "FairTimeStamp.h" PixelTrack::PixelTrack() - : FairTimeStamp() - , fX0(0.) - , fAX(0.) - , fY0(0.) - , fAY(0.) - , fX0Err(0.) - , fAXErr(0.) - , fY0Err(0.) - , fAYErr(0.) - , fHitIndices() -{ -} + : FairTimeStamp() + , fX0(0.) + , fAX(0.) + , fY0(0.) + , fAY(0.) + , fX0Err(0.) + , fAXErr(0.) + , fY0Err(0.) + , fAYErr(0.) + , fHitIndices() +{} -PixelTrack::PixelTrack(Double_t x0 , Double_t ax , Double_t y0 , Double_t ay , - Double_t x0e, Double_t axe, Double_t y0e, Double_t aye) - : FairTimeStamp() - , fX0(x0) - , fAX(ax) - , fY0(y0) - , fAY(ay) - , fX0Err(x0e) - , fAXErr(axe) - , fY0Err(y0e) - , fAYErr(aye) - , fHitIndices() -{ -} +PixelTrack::PixelTrack(Double_t x0, + Double_t ax, + Double_t y0, + Double_t ay, + Double_t x0e, + Double_t axe, + Double_t y0e, + Double_t aye) + : FairTimeStamp() + , fX0(x0) + , fAX(ax) + , fY0(y0) + , fAY(ay) + , fX0Err(x0e) + , fAXErr(axe) + , fY0Err(y0e) + , fAYErr(aye) + , fHitIndices() +{} -PixelTrack::~PixelTrack() -{ -} +PixelTrack::~PixelTrack() {} -ClassImp(PixelTrack) +ClassImp(PixelTrack); diff --git a/examples/MQ/pixelDetector/src/PixelTrack.h b/examples/MQ/pixelDetector/src/PixelTrack.h index ef44bcec31..a3e483d56c 100644 --- a/examples/MQ/pixelDetector/src/PixelTrack.h +++ b/examples/MQ/pixelDetector/src/PixelTrack.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* @@ -15,12 +15,16 @@ #ifndef PIXELTRACK_H_ #define PIXELTRACK_H_ -#include "FairTimeStamp.h" // for FairTimeStamp -#include // for PixelTrack::Class, ClassDef, PixelTrack::... +#include "FairTimeStamp.h" // for FairTimeStamp -namespace boost { namespace serialization { class access; } } -#include +#include // for PixelTrack::Class, ClassDef, PixelTrack::... +namespace boost { +namespace serialization { +class access; +} +} // namespace boost +#include #include class PixelTrack : public FairTimeStamp @@ -30,35 +34,41 @@ class PixelTrack : public FairTimeStamp PixelTrack(); /** Constructor **/ - PixelTrack(Double_t x0 , Double_t ax , Double_t y0 , Double_t ay , - Double_t x0e, Double_t axe, Double_t y0e, Double_t aye); - - void SetX0 (Double_t x0) {fX0 = x0;}; - void SetAX (Double_t ax) {fAX = ax;}; - void SetY0 (Double_t y0) {fY0 = y0;}; - void SetAY (Double_t ay) {fAY = ay;}; - void SetX0Err(Double_t x0e) {fX0Err = x0e;}; - void SetAXErr(Double_t axe) {fAXErr = axe;}; - void SetY0Err(Double_t y0e) {fY0Err = y0e;}; - void SetAYERr(Double_t aye) {fAYErr = aye;}; - - Double_t GetX0 () {return fX0;}; - Double_t GetAX () {return fAX;}; - Double_t GetY0 () {return fY0;}; - Double_t GetAY () {return fAY;}; - Double_t GetX0Err() {return fX0Err;}; - Double_t GetAXErr() {return fAXErr;}; - Double_t GetY0Err() {return fY0Err;}; - Double_t GetAYErr() {return fAYErr;}; - - void AddHitIndex(Int_t hitIndex) {fHitIndices.push_back(hitIndex);}; - Int_t GetNofHits () {return fHitIndices.size();}; - Int_t GetHitIndex(Int_t ihit) {return fHitIndices.at(ihit);}; + PixelTrack(Double_t x0, + Double_t ax, + Double_t y0, + Double_t ay, + Double_t x0e, + Double_t axe, + Double_t y0e, + Double_t aye); + + void SetX0(Double_t x0) { fX0 = x0; }; + void SetAX(Double_t ax) { fAX = ax; }; + void SetY0(Double_t y0) { fY0 = y0; }; + void SetAY(Double_t ay) { fAY = ay; }; + void SetX0Err(Double_t x0e) { fX0Err = x0e; }; + void SetAXErr(Double_t axe) { fAXErr = axe; }; + void SetY0Err(Double_t y0e) { fY0Err = y0e; }; + void SetAYERr(Double_t aye) { fAYErr = aye; }; + + Double_t GetX0() { return fX0; }; + Double_t GetAX() { return fAX; }; + Double_t GetY0() { return fY0; }; + Double_t GetAY() { return fAY; }; + Double_t GetX0Err() { return fX0Err; }; + Double_t GetAXErr() { return fAXErr; }; + Double_t GetY0Err() { return fY0Err; }; + Double_t GetAYErr() { return fAYErr; }; + + void AddHitIndex(Int_t hitIndex) { fHitIndices.push_back(hitIndex); }; + Int_t GetNofHits() { return fHitIndices.size(); }; + Int_t GetHitIndex(Int_t ihit) { return fHitIndices.at(ihit); }; /** Destructor **/ virtual ~PixelTrack(); - template + template void serialize(Archive& ar, const unsigned int /*version*/) { ar& boost::serialization::base_object(*this); diff --git a/examples/MQ/pixelDetector/src/devices/FairMQPixelFileSink.cxx b/examples/MQ/pixelDetector/src/devices/FairMQPixelFileSink.cxx index d06bc708d6..35fb12d358 100644 --- a/examples/MQ/pixelDetector/src/devices/FairMQPixelFileSink.cxx +++ b/examples/MQ/pixelDetector/src/devices/FairMQPixelFileSink.cxx @@ -12,15 +12,14 @@ * @author R. Karabowicz */ +#include "FairMQPixelFileSink.h" + #include "RootSerializer.h" -#include "FairMQPixelFileSink.h" #include - #include #include #include - #include #include #include @@ -28,42 +27,41 @@ using namespace std; FairMQPixelFileSink::FairMQPixelFileSink() - : FairMQDevice() - , fInputChannelName("data-in") - , fAckChannelName("") - , fFileName() - , fTreeName() - , fFileOption() - , fFlowMode(false) - , fWrite(false) - , fOutFile(nullptr) - , fTree(nullptr) - , fNObjects(0) - , fOutputObjects(new TObject*[1000]) -{ -} + : FairMQDevice() + , fInputChannelName("data-in") + , fAckChannelName("") + , fFileName() + , fTreeName() + , fFileOption() + , fFlowMode(false) + , fWrite(false) + , fOutFile(nullptr) + , fTree(nullptr) + , fNObjects(0) + , fOutputObjects(new TObject*[1000]) +{} void FairMQPixelFileSink::Init() { - fFileName = fConfig->GetValue("file-name"); - fInputChannelName = fConfig->GetValue("in-channel"); - fAckChannelName = fConfig->GetValue("ack-channel"); - - LOG(info) << "SHOULD CREATE THE FILE AND TREE"; - fFileOption = "RECREATE"; - fTreeName = "cbmsim"; - - if (::getenv("DDS_SESSION_ID")) { - std::string DDS_SESSION_ID = ::getenv("DDS_SESSION_ID"); - if (fFileName.length() > 5) { - DDS_SESSION_ID = "." + DDS_SESSION_ID + ".root"; - fFileName.replace(fFileName.length()-5,5,DDS_SESSION_ID.c_str()); + fFileName = fConfig->GetValue("file-name"); + fInputChannelName = fConfig->GetValue("in-channel"); + fAckChannelName = fConfig->GetValue("ack-channel"); + + LOG(info) << "SHOULD CREATE THE FILE AND TREE"; + fFileOption = "RECREATE"; + fTreeName = "cbmsim"; + + if (::getenv("DDS_SESSION_ID")) { + std::string DDS_SESSION_ID = ::getenv("DDS_SESSION_ID"); + if (fFileName.length() > 5) { + DDS_SESSION_ID = "." + DDS_SESSION_ID + ".root"; + fFileName.replace(fFileName.length() - 5, 5, DDS_SESSION_ID.c_str()); + } } - } - fOutFile = TFile::Open(fFileName.c_str(),fFileOption.c_str()); + fOutFile = TFile::Open(fFileName.c_str(), fFileOption.c_str()); - OnData(fInputChannelName, &FairMQPixelFileSink::StoreData); + OnData(fInputChannelName, &FairMQPixelFileSink::StoreData); } bool FairMQPixelFileSink::StoreData(FairMQParts& parts, int /*index*/) @@ -77,11 +75,11 @@ bool FairMQPixelFileSink::StoreData(FairMQParts& parts, int /*index*/) for (int ipart = 0; ipart < parts.Size(); ipart++) { fOutputObjects[ipart] = nullptr; - Deserialize (*parts.At(ipart),fOutputObjects[ipart]); + Deserialize(*parts.At(ipart), fOutputObjects[ipart]); tempObjects.push_back(fOutputObjects[ipart]); if (creatingTree) - fTree->Branch(tempObjects.back()->GetName(),tempObjects.back()->ClassName(),&fOutputObjects[ipart]); - fTree->SetBranchAddress(tempObjects.back()->GetName(),&fOutputObjects[ipart]); + fTree->Branch(tempObjects.back()->GetName(), tempObjects.back()->ClassName(), &fOutputObjects[ipart]); + fTree->SetBranchAddress(tempObjects.back()->GetName(), &fOutputObjects[ipart]); } // LOG(INFO) << "Finished branches"; fTree->Fill(); diff --git a/examples/MQ/pixelDetector/src/devices/FairMQPixelFileSink.h b/examples/MQ/pixelDetector/src/devices/FairMQPixelFileSink.h index 551b510224..ec7ebc7344 100644 --- a/examples/MQ/pixelDetector/src/devices/FairMQPixelFileSink.h +++ b/examples/MQ/pixelDetector/src/devices/FairMQPixelFileSink.h @@ -16,7 +16,6 @@ #define FAIRMQPIXELFILESINK_H_ #include - #include class TFile; @@ -30,10 +29,10 @@ class FairMQPixelFileSink : public FairMQDevice virtual ~FairMQPixelFileSink(); void SetOutputFileName(const std::string& tempString) { fFileName = tempString; } - std::string GetOutputFileName () { return fFileName;} + std::string GetOutputFileName() { return fFileName; } - void SetInputChannelName (const std::string& tstr) {fInputChannelName = tstr;} - void SetAckChannelName(const std::string& tstr) {fAckChannelName = tstr;} + void SetInputChannelName(const std::string& tstr) { fInputChannelName = tstr; } + void SetAckChannelName(const std::string& tstr) { fAckChannelName = tstr; } protected: bool StoreData(FairMQParts&, int); diff --git a/examples/MQ/pixelDetector/src/devices/FairMQPixelFileSinkBin.cxx b/examples/MQ/pixelDetector/src/devices/FairMQPixelFileSinkBin.cxx index 86d5129d7b..d90597b23c 100644 --- a/examples/MQ/pixelDetector/src/devices/FairMQPixelFileSinkBin.cxx +++ b/examples/MQ/pixelDetector/src/devices/FairMQPixelFileSinkBin.cxx @@ -13,152 +13,153 @@ */ #include "FairMQPixelFileSinkBin.h" -#include - #include "FairEventHeader.h" -#include "PixelPayload.h" #include "PixelHit.h" +#include "PixelPayload.h" +#include #include #include #include #include -#include #include +#include #include #include using namespace std; FairMQPixelFileSinkBin::FairMQPixelFileSinkBin() - : FairMQDevice() - , fInputChannelName("data-in") - , fAckChannelName("") - , fFileName() - , fTreeName() - - , fBranchNames() - , fClassNames() - , fFileOption() - , fFlowMode(false) - , fWrite(false) - - , fOutFile(nullptr) - , fTree(nullptr) - , fNObjects(0) - , fOutputObjects(new TObject*[1000]) - , fFolder(nullptr) -{ -} + : FairMQDevice() + , fInputChannelName("data-in") + , fAckChannelName("") + , fFileName() + , fTreeName() + + , fBranchNames() + , fClassNames() + , fFileOption() + , fFlowMode(false) + , fWrite(false) + + , fOutFile(nullptr) + , fTree(nullptr) + , fNObjects(0) + , fOutputObjects(new TObject*[1000]) + , fFolder(nullptr) +{} void FairMQPixelFileSinkBin::Init() { - fFileName = fConfig->GetValue ("file-name"); - fClassNames = fConfig->GetValue>("class-name"); - fBranchNames = fConfig->GetValue>("branch-name"); - fInputChannelName = fConfig->GetValue ("in-channel"); - fAckChannelName = fConfig->GetValue ("ack-channel"); - - LOG(info) << "SHOULD CREATE THE FILE AND TREE"; - fFileOption = "RECREATE"; - fTreeName = "cbmsim"; - - fOutFile = TFile::Open(fFileName.c_str(),fFileOption.c_str()); - - fTree = new TTree(fTreeName.c_str(), "/cbmout"); - - fFolder = new TFolder("cbmout", "Main Output Folder"); - TFolder* foldEventHeader = fFolder->AddFolder("EvtHeader","EvtHeader"); - TFolder* foldPixel = fFolder->AddFolder("Pixel","Pixel"); - - TList branchNameList; - - for (fNObjects = 0; fNObjects < fBranchNames.size(); fNObjects++) { - if (fClassNames[fNObjects].find("TClonesArray(") == 0) { - fClassNames[fNObjects] = fClassNames[fNObjects].substr(13, fClassNames[fNObjects].length() - 12 - 2); - fOutputObjects[fNObjects] = new TClonesArray(fClassNames[fNObjects].c_str()); - fTree->Branch(fBranchNames[fNObjects].c_str(), "TClonesArray", &fOutputObjects[fNObjects]); - foldPixel->Add(fOutputObjects[fNObjects]); - branchNameList.AddLast(new TObjString(fBranchNames[fNObjects].c_str())); - } else if (fClassNames[fNObjects].find("FairEventHeader") == 0) { - fOutputObjects[fNObjects] = new FairEventHeader(); - fTree->Branch(fBranchNames[fNObjects].c_str(), "FairEventHeader", &fOutputObjects[fNObjects]); - foldEventHeader->Add(fOutputObjects[fNObjects]); - branchNameList.AddLast(new TObjString(fBranchNames[fNObjects].c_str())); - } else { - LOG(error) << "!!! Unknown output object \"" << fClassNames[fNObjects] << "\" !!!"; + fFileName = fConfig->GetValue("file-name"); + fClassNames = fConfig->GetValue>("class-name"); + fBranchNames = fConfig->GetValue>("branch-name"); + fInputChannelName = fConfig->GetValue("in-channel"); + fAckChannelName = fConfig->GetValue("ack-channel"); + + LOG(info) << "SHOULD CREATE THE FILE AND TREE"; + fFileOption = "RECREATE"; + fTreeName = "cbmsim"; + + fOutFile = TFile::Open(fFileName.c_str(), fFileOption.c_str()); + + fTree = new TTree(fTreeName.c_str(), "/cbmout"); + + fFolder = new TFolder("cbmout", "Main Output Folder"); + TFolder* foldEventHeader = fFolder->AddFolder("EvtHeader", "EvtHeader"); + TFolder* foldPixel = fFolder->AddFolder("Pixel", "Pixel"); + + TList branchNameList; + + for (fNObjects = 0; fNObjects < fBranchNames.size(); fNObjects++) { + if (fClassNames[fNObjects].find("TClonesArray(") == 0) { + fClassNames[fNObjects] = fClassNames[fNObjects].substr(13, fClassNames[fNObjects].length() - 12 - 2); + fOutputObjects[fNObjects] = new TClonesArray(fClassNames[fNObjects].c_str()); + fTree->Branch(fBranchNames[fNObjects].c_str(), "TClonesArray", &fOutputObjects[fNObjects]); + foldPixel->Add(fOutputObjects[fNObjects]); + branchNameList.AddLast(new TObjString(fBranchNames[fNObjects].c_str())); + } else if (fClassNames[fNObjects].find("FairEventHeader") == 0) { + fOutputObjects[fNObjects] = new FairEventHeader(); + fTree->Branch(fBranchNames[fNObjects].c_str(), "FairEventHeader", &fOutputObjects[fNObjects]); + foldEventHeader->Add(fOutputObjects[fNObjects]); + branchNameList.AddLast(new TObjString(fBranchNames[fNObjects].c_str())); + } else { + LOG(error) << "!!! Unknown output object \"" << fClassNames[fNObjects] << "\" !!!"; + } } - } - fFolder->Write(); - branchNameList.Write("BranchList", TObject::kSingleKey); - branchNameList.Delete(); + fFolder->Write(); + branchNameList.Write("BranchList", TObject::kSingleKey); + branchNameList.Delete(); - OnData(fInputChannelName, &FairMQPixelFileSinkBin::StoreData); + OnData(fInputChannelName, &FairMQPixelFileSinkBin::StoreData); } bool FairMQPixelFileSinkBin::StoreData(FairMQParts& parts, int /*index*/) { - if (parts.Size() == 0) return true; // probably impossible, but still check - - // expecting even number of parts in the form: header,data,header,data,header,data and so on... - int nPPE = 2; // nof parts per event - - if (parts.Size() % nPPE >= 1) - LOG(info) << "received " << parts.Size() << " parts, will ignore last part!!!"; - + if (parts.Size() == 0) + return true; // probably impossible, but still check + + // expecting even number of parts in the form: header,data,header,data,header,data and so on... + int nPPE = 2; // nof parts per event + + if (parts.Size() % nPPE >= 1) + LOG(info) << "received " << parts.Size() << " parts, will ignore last part!!!"; + + for (int ievent = 0; ievent < parts.Size() / nPPE; ievent++) { + // the first part should be the event header + PixelPayload::EventHeader* payloadE = + static_cast(parts.At(nPPE * ievent)->GetData()); + // LOG(debug) << "GOT EVENT " << payloadE->fMCEntryNo << " OF RUN " << payloadE->fRunId << " (part " << + // payloadE->fPartNo << ")"; + + for (unsigned int ibr = 0; ibr < fBranchNames.size(); ibr++) { + if ("EventHeader." == fBranchNames[ibr]) { + ((FairEventHeader*)fOutputObjects[ibr])->SetRunId(payloadE->fRunId); + ((FairEventHeader*)fOutputObjects[ibr])->SetMCEntryNumber(payloadE->fMCEntryNo); + } + } - for (int ievent = 0; ievent < parts.Size() / nPPE; ievent++) { - // the first part should be the event header - PixelPayload::EventHeader* payloadE = static_cast(parts.At(nPPE * ievent)->GetData()); - // LOG(debug) << "GOT EVENT " << payloadE->fMCEntryNo << " OF RUN " << payloadE->fRunId << " (part " << payloadE->fPartNo << ")"; + // the second part should the TClonesArray with necessary data... now assuming Digi + PixelPayload::Hit* payloadH = static_cast(parts.At(nPPE * ievent + 1)->GetData()); + int hitArraySize = parts.At(nPPE * ievent + 1)->GetSize(); + int nofHits = hitArraySize / sizeof(PixelPayload::Hit); + + for (unsigned int ibr = 0; ibr < fBranchNames.size(); ibr++) { + if ("PixelHits" == fBranchNames[ibr]) { + ((TClonesArray*)fOutputObjects[ibr])->Clear(); + for (int ihit = 0; ihit < nofHits; ihit++) { + TVector3 pos(payloadH[ihit].posX, payloadH[ihit].posY, payloadH[ihit].posZ); + TVector3 posErr(payloadH[ihit].dposX, payloadH[ihit].dposY, payloadH[ihit].dposZ); + new ((*((TClonesArray*)fOutputObjects[ibr]))[ihit]) + PixelHit(payloadH[ihit].fDetectorID, -1, pos, posErr); + // new ((*fHits)[fNHits]) PixelHit(detId,currentDigi->GetIndex(),pos,posErr); + } + } + } - for (unsigned int ibr = 0; ibr < fBranchNames.size(); ibr++) { - if ("EventHeader." == fBranchNames[ibr]) { - ((FairEventHeader*)fOutputObjects[ibr])->SetRunId(payloadE->fRunId); - ((FairEventHeader*)fOutputObjects[ibr])->SetMCEntryNumber(payloadE->fMCEntryNo); - } + fTree->Fill(); } - // the second part should the TClonesArray with necessary data... now assuming Digi - PixelPayload::Hit* payloadH = static_cast(parts.At(nPPE * ievent + 1)->GetData()); - int hitArraySize = parts.At(nPPE * ievent + 1)->GetSize(); - int nofHits = hitArraySize / sizeof(PixelPayload::Hit); - - for (unsigned int ibr = 0; ibr < fBranchNames.size(); ibr++) { - if ("PixelHits" == fBranchNames[ibr]) { - ((TClonesArray*)fOutputObjects[ibr])->Clear(); - for (int ihit = 0; ihit < nofHits; ihit++) { - TVector3 pos(payloadH[ihit].posX, payloadH[ihit].posY, payloadH[ihit].posZ); - TVector3 posErr(payloadH[ihit].dposX, payloadH[ihit].dposY, payloadH[ihit].dposZ); - new ((*((TClonesArray*)fOutputObjects[ibr]))[ihit]) PixelHit(payloadH[ihit].fDetectorID, -1, pos, posErr); - // new ((*fHits)[fNHits]) PixelHit(detId,currentDigi->GetIndex(),pos,posErr); - } - } + if (fAckChannelName != "") { + FairMQMessagePtr msg(NewMessage()); + Send(msg, fAckChannelName); } - - fTree->Fill(); - } - - if (fAckChannelName != "") { - FairMQMessagePtr msg(NewMessage()); - Send(msg, fAckChannelName); - } - return true; + return true; } FairMQPixelFileSinkBin::~FairMQPixelFileSinkBin() { - if (fTree) { - fTree->Write(); - delete fTree; - } - - if (fOutFile) { - if (fOutFile->IsOpen()) { - fOutFile->Close(); + if (fTree) { + fTree->Write(); + delete fTree; + } + + if (fOutFile) { + if (fOutFile->IsOpen()) { + fOutFile->Close(); + } + delete fOutFile; } - delete fOutFile; - } } diff --git a/examples/MQ/pixelDetector/src/devices/FairMQPixelFileSinkBin.h b/examples/MQ/pixelDetector/src/devices/FairMQPixelFileSinkBin.h index 9f516eb4dc..cdb9cd03e9 100644 --- a/examples/MQ/pixelDetector/src/devices/FairMQPixelFileSinkBin.h +++ b/examples/MQ/pixelDetector/src/devices/FairMQPixelFileSinkBin.h @@ -16,7 +16,6 @@ #define FAIRMQPIXELFILESINKBIN_H_ #include - #include #include @@ -34,10 +33,10 @@ class FairMQPixelFileSinkBin : public FairMQDevice void SetOutputFileName(const std::string& tempString) { fFileName = tempString; } void AddOutputBranch(const std::string& classString, const std::string& branchString) { - fClassNames .push_back(classString); - fBranchNames.push_back(branchString); + fClassNames.push_back(classString); + fBranchNames.push_back(branchString); } - std::string GetOutputFileName () { return fFileName; } + std::string GetOutputFileName() { return fFileName; } void SetInputChannelName(const std::string& tstr) { fInputChannelName = tstr; } void SetAckChannelName(const std::string& tstr) { fAckChannelName = tstr; } @@ -46,7 +45,7 @@ class FairMQPixelFileSinkBin : public FairMQDevice bool StoreData(FairMQParts&, int); virtual void Init(); - private: + private: std::string fInputChannelName; std::string fAckChannelName; diff --git a/examples/MQ/pixelDetector/src/devices/FairMQPixelMerger.cxx b/examples/MQ/pixelDetector/src/devices/FairMQPixelMerger.cxx index 2af540182c..d664958b33 100644 --- a/examples/MQ/pixelDetector/src/devices/FairMQPixelMerger.cxx +++ b/examples/MQ/pixelDetector/src/devices/FairMQPixelMerger.cxx @@ -14,144 +14,152 @@ #include "FairMQPixelMerger.h" -#include #include "PixelEventHeader.h" #include "RootSerializer.h" +#include #include #include - -#include // strcmp +#include // strcmp using namespace std; FairMQPixelMerger::FairMQPixelMerger() - : fInputChannelName("data-in") - , fOutputChannelName("data-out") - , fNofPartsPerEventMap() - , fObjectMap() - , fEvRIPair() - , fEvRIPartTrio() - , fRet() - , fNofReceivedMessages(0) - , fNofSentMessages(0) - , fNofParts(3) - , fEventHeader(nullptr) -{ -} - -void FairMQPixelMerger::Init() -{ - OnData(fInputChannelName, &FairMQPixelMerger::MergeData); -} + : fInputChannelName("data-in") + , fOutputChannelName("data-out") + , fNofPartsPerEventMap() + , fObjectMap() + , fEvRIPair() + , fEvRIPartTrio() + , fRet() + , fNofReceivedMessages(0) + , fNofSentMessages(0) + , fNofParts(3) + , fEventHeader(nullptr) +{} + +void FairMQPixelMerger::Init() { OnData(fInputChannelName, &FairMQPixelMerger::MergeData); } bool FairMQPixelMerger::MergeData(FairMQParts& parts, int /*index*/) { - bool printInfo = false; - int nofReceivedParts = 0; // if set to -1, the data seems to be duplicated - - fNofReceivedMessages++; - // dataDuplicationFlag = false; - TObject* tempObject; - TClonesArray* tempArrays[10]; - int nofArrays = 0; - // LOG(debug) << "******************************************************************************************************"; - for (int ipart = 0 ; ipart < parts.Size() ; ipart++) { - tempObject = nullptr; - Deserialize(*parts.At(ipart),tempObject); - if (strcmp(tempObject->GetName(),"EventHeader.") == 0) { - fEventHeader = (PixelEventHeader*)tempObject; - // LOG(debug) << "GOT PART [" << fEventHeader->GetRunId() << "][" << fEventHeader->GetMCEntryNumber() << "][" << fEventHeader->GetPartNo() << "]"; - - // setting how many parts were received... - fEvRIPair.first = fEventHeader->GetMCEntryNumber(); - fEvRIPair.second = fEventHeader->GetRunId(); - fEvRIPartTrio.first = fEvRIPair; - fEvRIPartTrio.second = fEventHeader->GetPartNo(); - - if (fObjectMap.find(fEvRIPartTrio) != fObjectMap.end()) { - LOG(info) << "FairMQPixelMerger::Run(), shouldn't happen, already got objects for part " << fEvRIPartTrio.second - << ", event " << fEvRIPair.first << ", run " << fEvRIPair.second << ". Skipping this message!!!"; - nofReceivedParts = -1; - break; // break the for(ipart) loop, as nothing else is left to do - } - - auto it2 = fNofPartsPerEventMap.find(fEvRIPair); - if (it2 == fNofPartsPerEventMap.end()) { - // LOG(debug) << "FIRST PART OF event " << fEvRIPair.first; - fNofPartsPerEventMap[fEvRIPair] = 1; - nofReceivedParts = 1; - } else { - it2->second += 1; - nofReceivedParts = it2->second; - } - // LOG(debug) << " got " << nofReceivedParts << " parts of event " << fEvRIPair.first; - } else { - tempArrays[nofArrays] = (TClonesArray*)tempObject; - nofArrays++; - } - } // end the for(ipart) loop, should have received TCAs in tempArrays and PixelEventHeader - if (nofReceivedParts == -1) return true; - - // not all parts are there yet, have to put them in buffer - if (nofReceivedParts != fNofParts) { - // LOG(debug) << "not all parts are yet here... adding to (size = " << fObjectMap.size() << ")"; - // LOG(debug) << "+" << fEventHeader->GetName() << "[" << fEvRIPartTrio.first.second << "][" << fEvRIPartTrio.first.first << "][" << fEvRIPartTrio.second << "]"; - fObjectMap.insert(std::pair,int>,TObject*>(fEvRIPartTrio,(TObject*)fEventHeader)); - for (int iarray = 0 ; iarray < nofArrays ; iarray++) { - // LOG(debug) << "+" << tempArrays[iarray]->GetName() << "[" << fEvRIPartTrio.first.second << "][" << fEvRIPartTrio.first.first << "][" << fEvRIPartTrio.second << "]"; - fObjectMap.insert(std::pair,int>,TObject*>(fEvRIPartTrio,(TObject*)tempArrays[iarray])); - } - // LOG(debug) << " now we have fObjectMap (size = " << fObjectMap.size() << ")"; - if (printInfo) - LOG(info) << ">> [" << fEventHeader->GetRunId() << "][" << fEventHeader->GetMCEntryNumber() << "][" << fEventHeader->GetPartNo() << "] Received: " << fNofReceivedMessages << " // Buffered: " << fObjectMap.size() << " // Sent: " << fNofSentMessages << " <<"; - } else { // got all the parts of the event, have to combine and send message, consisting of objects from tempArrays - int currentEventPart = fEventHeader->GetPartNo(); - for (int iarray = 0 ; iarray < nofArrays ; iarray++) { - // LOG(debug) << "BEFORE ADDING, TCA \"" << tempArrays[iarray]->GetName() << "\" has " << tempArrays[iarray]->GetEntries() << " entries."; - TClonesArray* arrayToAdd; - - for (int ieventpart = 0 ; ieventpart < fNofParts ; ieventpart++) { - if (ieventpart == currentEventPart) - continue; - fEvRIPartTrio.second = ieventpart; - fRet = fObjectMap.equal_range(fEvRIPartTrio); - for (auto& it = fRet.first ; it != fRet.second ; ++it) { - if (tempArrays[iarray]->GetName() == it->second->GetName()) { - arrayToAdd = (TClonesArray*)it->second; - tempArrays[iarray]->AbsorbObjects(arrayToAdd); - // LOG(debug) << "FOUND ONE!, TCA has now " << tempArrays[iarray]->GetEntries() << " entries."; - } + bool printInfo = false; + int nofReceivedParts = 0; // if set to -1, the data seems to be duplicated + + fNofReceivedMessages++; + // dataDuplicationFlag = false; + TObject* tempObject; + TClonesArray* tempArrays[10]; + int nofArrays = 0; + // LOG(debug) << + // "******************************************************************************************************"; + for (int ipart = 0; ipart < parts.Size(); ipart++) { + tempObject = nullptr; + Deserialize(*parts.At(ipart), tempObject); + if (strcmp(tempObject->GetName(), "EventHeader.") == 0) { + fEventHeader = (PixelEventHeader*)tempObject; + // LOG(debug) << "GOT PART [" << fEventHeader->GetRunId() << "][" << fEventHeader->GetMCEntryNumber() << + // "][" << fEventHeader->GetPartNo() << "]"; + + // setting how many parts were received... + fEvRIPair.first = fEventHeader->GetMCEntryNumber(); + fEvRIPair.second = fEventHeader->GetRunId(); + fEvRIPartTrio.first = fEvRIPair; + fEvRIPartTrio.second = fEventHeader->GetPartNo(); + + if (fObjectMap.find(fEvRIPartTrio) != fObjectMap.end()) { + LOG(info) << "FairMQPixelMerger::Run(), shouldn't happen, already got objects for part " + << fEvRIPartTrio.second << ", event " << fEvRIPair.first << ", run " << fEvRIPair.second + << ". Skipping this message!!!"; + nofReceivedParts = -1; + break; // break the for(ipart) loop, as nothing else is left to do + } + + auto it2 = fNofPartsPerEventMap.find(fEvRIPair); + if (it2 == fNofPartsPerEventMap.end()) { + // LOG(debug) << "FIRST PART OF event " << fEvRIPair.first; + fNofPartsPerEventMap[fEvRIPair] = 1; + nofReceivedParts = 1; + } else { + it2->second += 1; + nofReceivedParts = it2->second; + } + // LOG(debug) << " got " << nofReceivedParts << " parts of event " << fEvRIPair.first; + } else { + tempArrays[nofArrays] = (TClonesArray*)tempObject; + nofArrays++; + } + } // end the for(ipart) loop, should have received TCAs in tempArrays and PixelEventHeader + if (nofReceivedParts == -1) + return true; + + // not all parts are there yet, have to put them in buffer + if (nofReceivedParts != fNofParts) { + // LOG(debug) << "not all parts are yet here... adding to (size = " << fObjectMap.size() << ")"; + // LOG(debug) << "+" << fEventHeader->GetName() << "[" << fEvRIPartTrio.first.second << "][" << + // fEvRIPartTrio.first.first << "][" << fEvRIPartTrio.second << "]"; + fObjectMap.insert( + pair, int>, TObject*>(fEvRIPartTrio, static_cast(fEventHeader))); + for (int iarray = 0; iarray < nofArrays; iarray++) { + // LOG(debug) << "+" << tempArrays[iarray]->GetName() << "[" << fEvRIPartTrio.first.second << "][" << + // fEvRIPartTrio.first.first << "][" << fEvRIPartTrio.second << "]"; + fObjectMap.insert( + pair, int>, TObject*>(fEvRIPartTrio, static_cast(tempArrays[iarray]))); + } + // LOG(debug) << " now we have fObjectMap (size = " << fObjectMap.size() << ")"; + if (printInfo) + LOG(info) << ">> [" << fEventHeader->GetRunId() << "][" << fEventHeader->GetMCEntryNumber() << "][" + << fEventHeader->GetPartNo() << "] Received: " << fNofReceivedMessages + << " // Buffered: " << fObjectMap.size() << " // Sent: " << fNofSentMessages << " <<"; + } else { // got all the parts of the event, have to combine and send message, consisting of objects from + // tempArrays + int currentEventPart = fEventHeader->GetPartNo(); + for (int iarray = 0; iarray < nofArrays; iarray++) { + // LOG(debug) << "BEFORE ADDING, TCA \"" << tempArrays[iarray]->GetName() << "\" has " << + // tempArrays[iarray]->GetEntries() << " entries."; + TClonesArray* arrayToAdd; + + for (int ieventpart = 0; ieventpart < fNofParts; ieventpart++) { + if (ieventpart == currentEventPart) + continue; + fEvRIPartTrio.second = ieventpart; + fRet = fObjectMap.equal_range(fEvRIPartTrio); + for (auto& it = fRet.first; it != fRet.second; ++it) { + if (tempArrays[iarray]->GetName() == it->second->GetName()) { + arrayToAdd = (TClonesArray*)it->second; + tempArrays[iarray]->AbsorbObjects(arrayToAdd); + // LOG(debug) << "FOUND ONE!, TCA has now " << tempArrays[iarray]->GetEntries() << " entries."; + } + } + } + } + for (int ieventpart = 0; ieventpart < fNofParts; ieventpart++) { + if (ieventpart == currentEventPart) + continue; + fEvRIPartTrio.second = ieventpart; + fRet = fObjectMap.equal_range(fEvRIPartTrio); + fObjectMap.erase(fRet.first, fRet.second); } - } - } - for (int ieventpart = 0 ; ieventpart < fNofParts ; ieventpart++) { - if (ieventpart == currentEventPart) continue; - fEvRIPartTrio.second = ieventpart; - fRet = fObjectMap.equal_range(fEvRIPartTrio); - fObjectMap.erase(fRet.first,fRet.second); - } - FairMQMessagePtr messageTCA[10]; - FairMQParts partsOut; + FairMQMessagePtr messageTCA[10]; + FairMQParts partsOut; - FairMQMessagePtr messFEH(NewMessage()); - Serialize(*messFEH,fEventHeader); - partsOut.AddPart(std::move(messFEH)); - for (int iarray = 0 ; iarray < nofArrays ; iarray++) { - messageTCA[iarray] = NewMessage(); - Serialize(*messageTCA[iarray],tempArrays[iarray]); - partsOut.AddPart(std::move(messageTCA[iarray])); + FairMQMessagePtr messFEH(NewMessage()); + Serialize(*messFEH, fEventHeader); + partsOut.AddPart(std::move(messFEH)); + for (int iarray = 0; iarray < nofArrays; iarray++) { + messageTCA[iarray] = NewMessage(); + Serialize(*messageTCA[iarray], tempArrays[iarray]); + partsOut.AddPart(std::move(messageTCA[iarray])); + } + Send(partsOut, fOutputChannelName); + fNofSentMessages++; + if (printInfo) + LOG(info) << ">> [" << fEventHeader->GetRunId() << "][" << fEventHeader->GetMCEntryNumber() << "][" + << fEventHeader->GetPartNo() << "] Received: " << fNofReceivedMessages + << " // Buffered: " << fObjectMap.size() << " // Sent: " << fNofSentMessages << " <<"; } - Send(partsOut, fOutputChannelName); - fNofSentMessages++; - if (printInfo) - LOG(info) << ">> [" << fEventHeader->GetRunId() << "][" << fEventHeader->GetMCEntryNumber() << "][" << fEventHeader->GetPartNo() << "] Received: " << fNofReceivedMessages << " // Buffered: " << fObjectMap.size() << " // Sent: " << fNofSentMessages << " <<"; - } - return true; + return true; } -FairMQPixelMerger::~FairMQPixelMerger() -{ -} +FairMQPixelMerger::~FairMQPixelMerger() {} diff --git a/examples/MQ/pixelDetector/src/devices/FairMQPixelMerger.h b/examples/MQ/pixelDetector/src/devices/FairMQPixelMerger.h index e82da2d018..031512a724 100644 --- a/examples/MQ/pixelDetector/src/devices/FairMQPixelMerger.h +++ b/examples/MQ/pixelDetector/src/devices/FairMQPixelMerger.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /** @@ -16,10 +16,9 @@ #define FAIRMQPIXELMERGER_H_ #include - #include #include -#include // pair +#include // pair class PixelEventHeader; class TObject; @@ -42,11 +41,11 @@ class FairMQPixelMerger : public FairMQDevice std::string fInputChannelName; std::string fOutputChannelName; - std::map, int> fNofPartsPerEventMap; // number of parts for pair - MultiMapDef fObjectMap; // TObjects for given pairpart> + std::map, int> fNofPartsPerEventMap; // number of parts for pair + MultiMapDef fObjectMap; // TObjects for given pairpart> std::pair fEvRIPair; - std::pair,int> fEvRIPartTrio; + std::pair, int> fEvRIPartTrio; std::pair fRet; int fNofReceivedMessages; diff --git a/examples/MQ/pixelDetector/src/devices/FairMQPixelSampler.cxx b/examples/MQ/pixelDetector/src/devices/FairMQPixelSampler.cxx index 5d09cb65a7..870c6bc369 100644 --- a/examples/MQ/pixelDetector/src/devices/FairMQPixelSampler.cxx +++ b/examples/MQ/pixelDetector/src/devices/FairMQPixelSampler.cxx @@ -14,131 +14,130 @@ #include "FairMQPixelSampler.h" +#include "FairFileSource.h" #include "FairRunAna.h" -#include "RootSerializer.h" #include "FairSource.h" -#include "FairFileSource.h" +#include "RootSerializer.h" #include #include - #include #include #include - #include -#include // move +#include // move using namespace std; FairMQPixelSampler::FairMQPixelSampler() - : FairMQDevice() - , fOutputChannelName("data-out") - , fAckChannelName("") - , fRunAna(nullptr) - , fSource(nullptr) - , fInputObjects() - , fNObjects(0) - , fMaxIndex(-1) - , fEventCounter(0) - , fBranchNames() - , fFileNames() - , fAckListener() -{ -} + : FairMQDevice() + , fOutputChannelName("data-out") + , fAckChannelName("") + , fRunAna(nullptr) + , fSource(nullptr) + , fInputObjects() + , fNObjects(0) + , fMaxIndex(-1) + , fEventCounter(0) + , fBranchNames() + , fFileNames() + , fAckListener() +{} void FairMQPixelSampler::InitTask() { - fFileNames = fConfig->GetValue>("file-name"); - fMaxIndex = fConfig->GetValue ("max-index"); - fBranchNames = fConfig->GetValue>("branch-name"); - fOutputChannelName = fConfig->GetValue ("out-channel"); - fAckChannelName = fConfig->GetValue ("ack-channel"); - - fRunAna = new FairRunAna(); - - if (fSource == nullptr) { - fSource = new FairFileSource(fFileNames.at(0).c_str()); - for (unsigned int ifile = 1 ; ifile < fFileNames.size() ; ifile++) { - ((FairFileSource*)fSource)->AddFile(fFileNames.at(ifile)); + fFileNames = fConfig->GetValue>("file-name"); + fMaxIndex = fConfig->GetValue("max-index"); + fBranchNames = fConfig->GetValue>("branch-name"); + fOutputChannelName = fConfig->GetValue("out-channel"); + fAckChannelName = fConfig->GetValue("ack-channel"); + + fRunAna = new FairRunAna(); + + if (fSource == nullptr) { + fSource = new FairFileSource(fFileNames.at(0).c_str()); + for (unsigned int ifile = 1; ifile < fFileNames.size(); ifile++) { + ((FairFileSource*)fSource)->AddFile(fFileNames.at(ifile)); + } } - } - - fSource->Init(); - LOG(info) << "Going to request " << fBranchNames.size() << " branches:"; - for (unsigned int ibrn = 0 ; ibrn < fBranchNames.size() ; ibrn++) { - LOG(info) << " requesting branch \"" << fBranchNames[ibrn] << "\""; - int branchStat = fSource->ActivateObject((TObject**)&fInputObjects[fNObjects],fBranchNames[ibrn].c_str()); // should check the status... - if (fInputObjects[fNObjects]) { - LOG(info) << "Activated object \"" << fInputObjects[fNObjects] << "\" with name \"" << fBranchNames[ibrn] << "\" (" << branchStat << "), it got name: \"" << fInputObjects[fNObjects]->GetName() << "\""; - if (strcmp(fInputObjects[fNObjects]->GetName(),fBranchNames[ibrn].c_str())) - if (strcmp(fInputObjects[fNObjects]->ClassName(),"TClonesArray") == 0) - ((TClonesArray*)fInputObjects[fNObjects])->SetName(fBranchNames[ibrn].c_str()); - fNObjects++; + + fSource->Init(); + LOG(info) << "Going to request " << fBranchNames.size() << " branches:"; + for (unsigned int ibrn = 0; ibrn < fBranchNames.size(); ibrn++) { + LOG(info) << " requesting branch \"" << fBranchNames[ibrn] << "\""; + int branchStat = fSource->ActivateObject((TObject**)&fInputObjects[fNObjects], + fBranchNames[ibrn].c_str()); // should check the status... + if (fInputObjects[fNObjects]) { + LOG(info) << "Activated object \"" << fInputObjects[fNObjects] << "\" with name \"" << fBranchNames[ibrn] + << "\" (" << branchStat << "), it got name: \"" << fInputObjects[fNObjects]->GetName() << "\""; + if (strcmp(fInputObjects[fNObjects]->GetName(), fBranchNames[ibrn].c_str())) + if (strcmp(fInputObjects[fNObjects]->ClassName(), "TClonesArray") == 0) + ((TClonesArray*)fInputObjects[fNObjects])->SetName(fBranchNames[ibrn].c_str()); + fNObjects++; + } } - } - if (fMaxIndex < 0) - fMaxIndex = fSource->CheckMaxEventNo(); - LOG(info) << "Input source has " << fMaxIndex << " events."; + if (fMaxIndex < 0) + fMaxIndex = fSource->CheckMaxEventNo(); + LOG(info) << "Input source has " << fMaxIndex << " events."; } void FairMQPixelSampler::PreRun() { - if (fAckChannelName != "") { - fAckListener = thread(&FairMQPixelSampler::ListenForAcks, this); - } + if (fAckChannelName != "") { + fAckListener = thread(&FairMQPixelSampler::ListenForAcks, this); + } - LOG(info) << "FairMQPixelSampler::PreRun() finished!"; + LOG(info) << "FairMQPixelSampler::PreRun() finished!"; } bool FairMQPixelSampler::ConditionalRun() { - if (fEventCounter == fMaxIndex) return false; + if (fEventCounter == fMaxIndex) + return false; - Int_t readEventReturn = fSource->ReadEvent(fEventCounter); + Int_t readEventReturn = fSource->ReadEvent(fEventCounter); - if (readEventReturn != 0) return false; + if (readEventReturn != 0) + return false; - FairMQParts parts; + FairMQParts parts; - for (int iobj = 0 ; iobj < fNObjects ; iobj++) { - FairMQMessagePtr mess(NewMessage()); - Serialize(*mess, fInputObjects[iobj]); - parts.AddPart(std::move(mess)); - } + for (int iobj = 0; iobj < fNObjects; iobj++) { + FairMQMessagePtr mess(NewMessage()); + Serialize(*mess, fInputObjects[iobj]); + parts.AddPart(std::move(mess)); + } - Send(parts, fOutputChannelName); + Send(parts, fOutputChannelName); - fEventCounter++; + fEventCounter++; - return true; + return true; } void FairMQPixelSampler::PostRun() { - if (fAckChannelName != "") { - fAckListener.join(); - } + if (fAckChannelName != "") { + fAckListener.join(); + } - LOG(info) << "PostRun() finished!"; + LOG(info) << "PostRun() finished!"; } void FairMQPixelSampler::ListenForAcks() { - if (fAckChannelName != "") { - Long64_t numAcks = 0; - do { - unique_ptr ack(NewMessage()); - if (Receive(ack, fAckChannelName) >= 0) { - numAcks++; - } - } while (numAcks < fMaxIndex); - - LOG(info) << "Acknowledged " << numAcks << " messages."; - } + if (fAckChannelName != "") { + Long64_t numAcks = 0; + do { + unique_ptr ack(NewMessage()); + if (Receive(ack, fAckChannelName) >= 0) { + numAcks++; + } + } while (numAcks < fMaxIndex); + + LOG(info) << "Acknowledged " << numAcks << " messages."; + } } -FairMQPixelSampler::~FairMQPixelSampler() -{ -} +FairMQPixelSampler::~FairMQPixelSampler() {} diff --git a/examples/MQ/pixelDetector/src/devices/FairMQPixelSampler.h b/examples/MQ/pixelDetector/src/devices/FairMQPixelSampler.h index 361ef267e4..3380fe1453 100644 --- a/examples/MQ/pixelDetector/src/devices/FairMQPixelSampler.h +++ b/examples/MQ/pixelDetector/src/devices/FairMQPixelSampler.h @@ -16,10 +16,9 @@ #define FAIRMQPIXELSAMPLER_H_ #include - +#include #include #include -#include #include class FairSource; @@ -35,14 +34,14 @@ class FairMQPixelSampler : public FairMQDevice void AddInputFileName(const std::string& tempString) { fFileNames.push_back(tempString); } void AddInputBranchName(const std::string& tempString) { fBranchNames.push_back(tempString); } - void SetMaxIndex(int64_t tempInt) { fMaxIndex=tempInt; } + void SetMaxIndex(int64_t tempInt) { fMaxIndex = tempInt; } void SetSource(FairSource* tempSource) { fSource = tempSource; } void ListenForAcks(); - void SetOutputChannelName(const std::string& tstr) {fOutputChannelName = tstr;} - void SetAckChannelName(const std::string& tstr) {fAckChannelName = tstr;} + void SetOutputChannelName(const std::string& tstr) { fOutputChannelName = tstr; } + void SetAckChannelName(const std::string& tstr) { fAckChannelName = tstr; } protected: virtual bool ConditionalRun(); @@ -54,13 +53,13 @@ class FairMQPixelSampler : public FairMQDevice std::string fOutputChannelName; std::string fAckChannelName; - FairRunAna* fRunAna; - FairSource* fSource; - TObject* fInputObjects[100]; - int fNObjects; - int64_t fMaxIndex; + FairRunAna* fRunAna; + FairSource* fSource; + TObject* fInputObjects[100]; + int fNObjects; + int64_t fMaxIndex; - int fEventCounter; + int fEventCounter; std::vector fBranchNames; std::vector fFileNames; diff --git a/examples/MQ/pixelDetector/src/devices/FairMQPixelSamplerBin.cxx b/examples/MQ/pixelDetector/src/devices/FairMQPixelSamplerBin.cxx index 673e3932ee..322c0b7a7b 100644 --- a/examples/MQ/pixelDetector/src/devices/FairMQPixelSamplerBin.cxx +++ b/examples/MQ/pixelDetector/src/devices/FairMQPixelSamplerBin.cxx @@ -13,157 +13,156 @@ */ #include "FairMQPixelSamplerBin.h" -#include "PixelDigi.h" -#include "PixelPayload.h" #include "FairEventHeader.h" #include "FairFileSource.h" #include "FairRunAna.h" +#include "PixelDigi.h" +#include "PixelPayload.h" #include - -#include -#include // for Int_t, Long64_t +#include // for Int_t, Long64_t #include - +#include #include -#include // move +#include // move using namespace std; FairMQPixelSamplerBin::FairMQPixelSamplerBin() - : FairMQDevice() - , fOutputChannelName("data-out") - , fAckChannelName("") - , fRunAna(nullptr) - , fSource(nullptr) - , fInputObjects() - , fNObjects(0) - , fMaxIndex(-1) - , fEventCounter(0) - , fBranchNames() - , fFileNames() - , fAckListener() -{ -} + : FairMQDevice() + , fOutputChannelName("data-out") + , fAckChannelName("") + , fRunAna(nullptr) + , fSource(nullptr) + , fInputObjects() + , fNObjects(0) + , fMaxIndex(-1) + , fEventCounter(0) + , fBranchNames() + , fFileNames() + , fAckListener() +{} void FairMQPixelSamplerBin::InitTask() { - fFileNames = fConfig->GetValue>("file-name"); - fMaxIndex = fConfig->GetValue ("max-index"); - fBranchNames = fConfig->GetValue>("branch-name"); - fOutputChannelName = fConfig->GetValue ("out-channel"); - fAckChannelName = fConfig->GetValue ("ack-channel"); - - fRunAna = new FairRunAna(); - if (fFileNames.size() > 0) { - fSource = new FairFileSource(fFileNames.at(0).c_str()); - for (unsigned int ifile = 1 ; ifile < fFileNames.size() ; ifile++) - fSource->AddFile(fFileNames.at(ifile)); - } - fSource->Init(); - LOG(info) << "Going to request " << fBranchNames.size() << " branches:"; - for (unsigned int ibrn = 0 ; ibrn < fBranchNames.size() ; ibrn++) { - LOG(info) << " requesting branch \"" << fBranchNames[ibrn] << "\""; - int branchStat = fSource->ActivateObject((TObject**)&fInputObjects[fNObjects],fBranchNames[ibrn].c_str()); // should check the status... - if (fInputObjects[fNObjects]) { - LOG(info) << "Activated object \"" << fInputObjects[fNObjects] << "\" with name \"" << fBranchNames[ibrn] << "\" (" << branchStat << ")"; - fNObjects++; + fFileNames = fConfig->GetValue>("file-name"); + fMaxIndex = fConfig->GetValue("max-index"); + fBranchNames = fConfig->GetValue>("branch-name"); + fOutputChannelName = fConfig->GetValue("out-channel"); + fAckChannelName = fConfig->GetValue("ack-channel"); + + fRunAna = new FairRunAna(); + if (fFileNames.size() > 0) { + fSource = new FairFileSource(fFileNames.at(0).c_str()); + for (unsigned int ifile = 1; ifile < fFileNames.size(); ifile++) + fSource->AddFile(fFileNames.at(ifile)); + } + fSource->Init(); + LOG(info) << "Going to request " << fBranchNames.size() << " branches:"; + for (unsigned int ibrn = 0; ibrn < fBranchNames.size(); ibrn++) { + LOG(info) << " requesting branch \"" << fBranchNames[ibrn] << "\""; + int branchStat = fSource->ActivateObject((TObject**)&fInputObjects[fNObjects], + fBranchNames[ibrn].c_str()); // should check the status... + if (fInputObjects[fNObjects]) { + LOG(info) << "Activated object \"" << fInputObjects[fNObjects] << "\" with name \"" << fBranchNames[ibrn] + << "\" (" << branchStat << ")"; + fNObjects++; + } } - } - if (fMaxIndex < 0) - fMaxIndex = fSource->CheckMaxEventNo(); - LOG(info) << "Input source has " << fMaxIndex << " events."; + if (fMaxIndex < 0) + fMaxIndex = fSource->CheckMaxEventNo(); + LOG(info) << "Input source has " << fMaxIndex << " events."; } void FairMQPixelSamplerBin::PreRun() { - LOG(info) << "FairMQPixelSampler::PreRun() started!"; + LOG(info) << "FairMQPixelSampler::PreRun() started!"; - fAckListener = thread(&FairMQPixelSamplerBin::ListenForAcks, this); + fAckListener = thread(&FairMQPixelSamplerBin::ListenForAcks, this); } bool FairMQPixelSamplerBin::ConditionalRun() { - if (fEventCounter == fMaxIndex) return false; - - int readEventReturn = 0; - readEventReturn = fSource->ReadEvent(fEventCounter); - - if (readEventReturn != 0) return false; - - FairMQParts parts; - - for (int iobj = 0 ; iobj < fNObjects ; iobj++) { - if (strcmp(fInputObjects[iobj]->GetName(),"EventHeader.") == 0) { - PixelPayload::EventHeader* header = new PixelPayload::EventHeader(); - header->fRunId = ((FairEventHeader*)fInputObjects[iobj])->GetRunId(); - header->fMCEntryNo = ((FairEventHeader*)fInputObjects[iobj])->GetMCEntryNumber(); - header->fPartNo = 0; - FairMQMessagePtr msgHeader(NewMessage(header, - sizeof(PixelPayload::EventHeader), - [](void* data, void* /*hint*/) { delete static_cast(data); } - )); - parts.AddPart(std::move(msgHeader)); - // LOG(debug) << "-----------------------------"; - // LOG(debug) << "first part has size = " << sizeof(PixelPayload::EventHeader); - } else { - Int_t nofEntries = ((TClonesArray*)fInputObjects[iobj])->GetEntries(); - size_t digisSize = nofEntries * sizeof(PixelPayload::Digi); - - FairMQMessagePtr msgTCA(NewMessage(digisSize)); - - PixelPayload::Digi* digiPayload = static_cast(msgTCA->GetData()); - - for (int idigi = 0 ; idigi < nofEntries ; idigi++) { - PixelDigi* digi = static_cast(((TClonesArray*)fInputObjects[iobj])->At(idigi)); - if (!digi) { - continue; + if (fEventCounter == fMaxIndex) + return false; + + int readEventReturn = 0; + readEventReturn = fSource->ReadEvent(fEventCounter); + + if (readEventReturn != 0) + return false; + + FairMQParts parts; + + for (int iobj = 0; iobj < fNObjects; iobj++) { + if (strcmp(fInputObjects[iobj]->GetName(), "EventHeader.") == 0) { + PixelPayload::EventHeader* header = new PixelPayload::EventHeader(); + header->fRunId = ((FairEventHeader*)fInputObjects[iobj])->GetRunId(); + header->fMCEntryNo = ((FairEventHeader*)fInputObjects[iobj])->GetMCEntryNumber(); + header->fPartNo = 0; + FairMQMessagePtr msgHeader( + NewMessage(header, sizeof(PixelPayload::EventHeader), [](void* data, void* /*hint*/) { + delete static_cast(data); + })); + parts.AddPart(std::move(msgHeader)); + // LOG(debug) << "-----------------------------"; + // LOG(debug) << "first part has size = " << sizeof(PixelPayload::EventHeader); + } else { + Int_t nofEntries = ((TClonesArray*)fInputObjects[iobj])->GetEntries(); + size_t digisSize = nofEntries * sizeof(PixelPayload::Digi); + + FairMQMessagePtr msgTCA(NewMessage(digisSize)); + + PixelPayload::Digi* digiPayload = static_cast(msgTCA->GetData()); + + for (int idigi = 0; idigi < nofEntries; idigi++) { + PixelDigi* digi = static_cast(((TClonesArray*)fInputObjects[iobj])->At(idigi)); + if (!digi) { + continue; + } + new (&digiPayload[idigi]) PixelPayload::Digi(); + digiPayload[idigi].fDetectorID = digi->GetDetectorID(); + digiPayload[idigi].fFeID = digi->GetFeID(); + digiPayload[idigi].fCharge = digi->GetCharge(); + digiPayload[idigi].fCol = digi->GetCol(); + digiPayload[idigi].fRow = digi->GetRow(); + } + // LOG(debug) << "second part has size = " << digisSize; + parts.AddPart(std::move(msgTCA)); } - new (&digiPayload[idigi]) PixelPayload::Digi(); - digiPayload[idigi].fDetectorID = digi->GetDetectorID(); - digiPayload[idigi].fFeID = digi->GetFeID(); - digiPayload[idigi].fCharge = digi->GetCharge(); - digiPayload[idigi].fCol = digi->GetCol(); - digiPayload[idigi].fRow = digi->GetRow(); - } - // LOG(debug) << "second part has size = " << digisSize; - parts.AddPart(std::move(msgTCA)); } - } - // LOG(debug) << "sending data with " << parts.Size() << " parts"; - Send(parts, fOutputChannelName); + // LOG(debug) << "sending data with " << parts.Size() << " parts"; + Send(parts, fOutputChannelName); - fEventCounter++; + fEventCounter++; - return true; + return true; } void FairMQPixelSamplerBin::PostRun() { - if (fAckChannelName != "") { - fAckListener.join(); - } + if (fAckChannelName != "") { + fAckListener.join(); + } - LOG(info) << "PostRun() finished!"; + LOG(info) << "PostRun() finished!"; } void FairMQPixelSamplerBin::ListenForAcks() { - if (fAckChannelName != "") { - Long64_t numAcks = 0; - do { - FairMQMessagePtr ack(NewMessage()); - if (Receive(ack, fAckChannelName) >= 0) { - numAcks++; - } - } while (numAcks < fMaxIndex); - - LOG(info) << "Acknowledged " << numAcks << " messages."; - } + if (fAckChannelName != "") { + Long64_t numAcks = 0; + do { + FairMQMessagePtr ack(NewMessage()); + if (Receive(ack, fAckChannelName) >= 0) { + numAcks++; + } + } while (numAcks < fMaxIndex); + + LOG(info) << "Acknowledged " << numAcks << " messages."; + } } -FairMQPixelSamplerBin::~FairMQPixelSamplerBin() -{ -} +FairMQPixelSamplerBin::~FairMQPixelSamplerBin() {} diff --git a/examples/MQ/pixelDetector/src/devices/FairMQPixelSamplerBin.h b/examples/MQ/pixelDetector/src/devices/FairMQPixelSamplerBin.h index 891c7f9534..e7360ccd22 100644 --- a/examples/MQ/pixelDetector/src/devices/FairMQPixelSamplerBin.h +++ b/examples/MQ/pixelDetector/src/devices/FairMQPixelSamplerBin.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /** @@ -16,10 +16,9 @@ #define FAIRMQPIXELSAMPLERBIN_H_ #include - +#include #include #include -#include #include class FairFileSource; @@ -49,16 +48,16 @@ class FairMQPixelSamplerBin : public FairMQDevice virtual void InitTask(); private: - std::string fOutputChannelName; - std::string fAckChannelName; + std::string fOutputChannelName; + std::string fAckChannelName; - FairRunAna* fRunAna; + FairRunAna* fRunAna; FairFileSource* fSource; - TObject* fInputObjects[100]; - int fNObjects; - int64_t fMaxIndex; + TObject* fInputObjects[100]; + int fNObjects; + int64_t fMaxIndex; - int fEventCounter; + int fEventCounter; std::vector fBranchNames; std::vector fFileNames; diff --git a/examples/MQ/pixelDetector/src/devices/FairMQPixelTaskProcessor.h b/examples/MQ/pixelDetector/src/devices/FairMQPixelTaskProcessor.h index 046aff597e..72562badea 100644 --- a/examples/MQ/pixelDetector/src/devices/FairMQPixelTaskProcessor.h +++ b/examples/MQ/pixelDetector/src/devices/FairMQPixelTaskProcessor.h @@ -9,20 +9,17 @@ #ifndef FAIRMQPIXELTASKPROCESSOR_H_ #define FAIRMQPIXELTASKPROCESSOR_H_ -#include -#include - #include "FairEventHeader.h" -#include "FairMCEventHeader.h" #include "FairGeoParSet.h" +#include "FairMCEventHeader.h" #include "FairParGenericSet.h" +#include "RootSerializer.h" #include #include - -#include "RootSerializer.h" - #include +#include +#include template class FairMQPixelTaskProcessor : public FairMQDevice @@ -60,11 +57,11 @@ class FairMQPixelTaskProcessor : public FairMQDevice void SetDataToKeep(const std::string& tStr) { fDataToKeep = tStr; } - void SetInputChannelName (const std::string& tstr) { fInputChannelName = tstr; } + void SetInputChannelName(const std::string& tstr) { fInputChannelName = tstr; } void SetOutputChannelName(const std::string& tstr) { fOutputChannelName = tstr; } - void SetParamChannelName (const std::string& tstr) { fParamChannelName = tstr; } + void SetParamChannelName(const std::string& tstr) { fParamChannelName = tstr; } - void SetStaticParameters (bool tbool) { fStaticParameters = tbool; } + void SetStaticParameters(bool tbool) { fStaticParameters = tbool; } protected: bool ProcessData(FairMQParts& parts, int) @@ -80,10 +77,10 @@ class FairMQPixelTaskProcessor : public FairMQDevice Deserialize(*parts.At(ipart), obj); tempObjects.push_back(obj); // LOG(trace) << "got TObject with name \"" << tempObjects[ipart]->GetName() << "\"."; - if (strcmp(tempObjects.back()->GetName(),"EventHeader.") == 0) { + if (strcmp(tempObjects.back()->GetName(), "EventHeader.") == 0) { fEventHeader = (FairEventHeader*)(tempObjects.back()); } - if (strcmp(tempObjects.back()->GetName(),"MCEventHeader.") == 0) { + if (strcmp(tempObjects.back()->GetName(), "MCEventHeader.") == 0) { fMCEventHeader = (FairMCEventHeader*)(tempObjects.back()); } else { fInput->Add(tempObjects.back()); @@ -116,24 +113,25 @@ class FairMQPixelTaskProcessor : public FairMQDevice if (!fDataToKeep.empty()) { objectToKeep = (fInput->FindObject(fDataToKeep.c_str()))->Clone(); - if (objectToKeep) fOutput->Add(objectToKeep); + if (objectToKeep) + fOutput->Add(objectToKeep); } FairMQParts partsOut; if (fEventHeader) { FairMQMessagePtr mess(NewMessage()); - Serialize(*mess,fEventHeader); + Serialize(*mess, fEventHeader); partsOut.AddPart(std::move(mess)); } else if (fMCEventHeader) { FairMQMessagePtr mess(NewMessage()); - Serialize(*mess,fMCEventHeader); + Serialize(*mess, fMCEventHeader); partsOut.AddPart(std::move(mess)); } for (int iobj = 0; iobj < fOutput->GetEntries(); iobj++) { FairMQMessagePtr mess(NewMessage()); - Serialize(*mess,fOutput->At(iobj)); + Serialize(*mess, fOutput->At(iobj)); partsOut.AddPart(std::move(mess)); } @@ -155,11 +153,11 @@ class FairMQPixelTaskProcessor : public FairMQDevice virtual void Init() { - fDataToKeep = fConfig->GetValue("keep-data"); - fInputChannelName = fConfig->GetValue("in-channel"); + fDataToKeep = fConfig->GetValue("keep-data"); + fInputChannelName = fConfig->GetValue("in-channel"); fOutputChannelName = fConfig->GetValue("out-channel"); - fParamChannelName = fConfig->GetValue("par-channel"); - fStaticParameters = fConfig->GetValue ("static-pars"); + fParamChannelName = fConfig->GetValue("par-channel"); + fStaticParameters = fConfig->GetValue("static-pars"); fFairTask = new T(); fFairTask->SetStreamProcessing(kTRUE); @@ -176,7 +174,8 @@ class FairMQPixelTaskProcessor : public FairMQDevice virtual void PostRun() { - LOG(info) << "FairMQPixelTaskProcessor::PostRun() Received " << fReceivedMsgs << " and sent " << fSentMsgs << " messages!"; + LOG(info) << "FairMQPixelTaskProcessor::PostRun() Received " << fReceivedMsgs << " and sent " << fSentMsgs + << " messages!"; } private: @@ -198,19 +197,21 @@ class FairMQPixelTaskProcessor : public FairMQDevice std::string paramName = thisPar->GetName(); std::string* reqStr = new std::string(paramName + "," + std::to_string(fCurrentRunId)); - LOG(debug) << "Requesting parameter \"" << paramName << "\" for Run ID " << fCurrentRunId << " (" << thisPar << ")"; - - FairMQMessagePtr req(NewMessage(const_cast(reqStr->c_str()), - reqStr->length(), - [](void* /* data */, void* hint){ delete static_cast(hint); }, - reqStr)); + LOG(debug) << "Requesting parameter \"" << paramName << "\" for Run ID " << fCurrentRunId << " (" << thisPar + << ")"; + + FairMQMessagePtr req(NewMessage( + const_cast(reqStr->c_str()), + reqStr->length(), + [](void* /* data */, void* hint) { delete static_cast(hint); }, + reqStr)); FairMQMessagePtr rep(NewMessage()); if (Send(req, fParamChannelName) > 0) { if (Receive(rep, fParamChannelName) > 0) { thisPar = nullptr; Deserialize(*rep, thisPar); - LOG(info) << "Received parameter"<< paramName <<" from the server (" << thisPar << ")"; + LOG(info) << "Received parameter" << paramName << " from the server (" << thisPar << ")"; return thisPar; } } @@ -218,10 +219,10 @@ class FairMQPixelTaskProcessor : public FairMQDevice return nullptr; } - FairEventHeader* fEventHeader; + FairEventHeader* fEventHeader; FairMCEventHeader* fMCEventHeader; - TList* fInput; - TList* fOutput; + TList* fInput; + TList* fOutput; bool fStaticParameters; int fNewRunId; diff --git a/examples/MQ/pixelDetector/src/devices/FairMQPixelTaskProcessorBin.h b/examples/MQ/pixelDetector/src/devices/FairMQPixelTaskProcessorBin.h index fbb1bca734..e83bb40fd9 100644 --- a/examples/MQ/pixelDetector/src/devices/FairMQPixelTaskProcessorBin.h +++ b/examples/MQ/pixelDetector/src/devices/FairMQPixelTaskProcessorBin.h @@ -9,22 +9,19 @@ #ifndef FAIRMQPIXELTASKPROCESSORBIN_H_ #define FAIRMQPIXELTASKPROCESSORBIN_H_ -#include - #include "FairEventHeader.h" #include "FairGeoParSet.h" #include "FairParGenericSet.h" +#include "PixelDigi.h" +#include "PixelHit.h" +#include "PixelPayload.h" +#include "RootSerializer.h" #include #include - #include #include -#include "RootSerializer.h" - -#include "PixelPayload.h" -#include "PixelDigi.h" -#include "PixelHit.h" +#include template class FairMQPixelTaskProcessorBin : public FairMQDevice @@ -67,11 +64,11 @@ class FairMQPixelTaskProcessorBin : public FairMQDevice void SetDataToKeep(const std::string& str) { fDataToKeep = str; } - void SetInputChannelName (const std::string& str) { fInputChannelName = str; } + void SetInputChannelName(const std::string& str) { fInputChannelName = str; } void SetOutputChannelName(const std::string& str) { fOutputChannelName = str; } - void SetParamChannelName (const std::string& str) { fParamChannelName = str; } + void SetParamChannelName(const std::string& str) { fParamChannelName = str; } - void SetStaticParameters (bool tbool) {fStaticParameters = tbool;} + void SetStaticParameters(bool tbool) { fStaticParameters = tbool; } protected: bool ProcessData(FairMQParts& parts, int) @@ -79,13 +76,15 @@ class FairMQPixelTaskProcessorBin : public FairMQDevice // LOG(debug) << "message received with " << parts.Size() << " parts!"; fReceivedMsgs++; - if (parts.Size() == 0) return 0; // probably impossible, but still check + if (parts.Size() == 0) + return 0; // probably impossible, but still check // the first part should be the event header PixelPayload::EventHeader* payloadE = static_cast(parts.At(0)->GetData()); - // LOG(debug) << "GOT EVENT " << payloadE->fMCEntryNo << " OF RUN " << payloadE->fRunId << " (part " << payloadE->fPartNo << ")"; + // LOG(debug) << "GOT EVENT " << payloadE->fMCEntryNo << " OF RUN " << payloadE->fRunId << " (part " << + // payloadE->fPartNo << ")"; - if ( fStaticParameters == false || fCurrentRunId == -1 ) { + if (fStaticParameters == false || fCurrentRunId == -1) { fNewRunId = payloadE->fRunId; if (fNewRunId != fCurrentRunId) { fCurrentRunId = fNewRunId; @@ -99,16 +98,16 @@ class FairMQPixelTaskProcessorBin : public FairMQDevice // the second part should the TClonesArray with necessary data... now assuming Digi PixelPayload::Digi* payloadD = static_cast(parts.At(1)->GetData()); int digiArraySize = parts.At(1)->GetSize(); - int nofDigis = digiArraySize / sizeof(PixelPayload::Digi); + int nofDigis = digiArraySize / sizeof(PixelPayload::Digi); fInputArray->Clear(); for (int idigi = 0; idigi < nofDigis; idigi++) { new ((*fInputArray)[idigi]) PixelDigi(-1, - payloadD[idigi].fDetectorID, - payloadD[idigi].fFeID, - payloadD[idigi].fCol, - payloadD[idigi].fRow, - payloadD[idigi].fCharge); + payloadD[idigi].fDetectorID, + payloadD[idigi].fFeID, + payloadD[idigi].fCol, + payloadD[idigi].fRow, + payloadD[idigi].fCharge); } // LOG(debug) << " EVENT HAS " << nofDigis << " DIGIS!!!"; @@ -121,18 +120,19 @@ class FairMQPixelTaskProcessorBin : public FairMQDevice FairMQParts partsOut; PixelPayload::EventHeader* header = new PixelPayload::EventHeader(); - header->fRunId = payloadE->fRunId; + header->fRunId = payloadE->fRunId; header->fMCEntryNo = payloadE->fMCEntryNo; - header->fPartNo = payloadE->fPartNo; + header->fPartNo = payloadE->fPartNo; - FairMQMessagePtr msgHeader(NewMessage(header, - sizeof(PixelPayload::EventHeader), - [](void* data, void* /*hint*/) { delete static_cast(data); }, - nullptr)); + FairMQMessagePtr msgHeader(NewMessage( + header, + sizeof(PixelPayload::EventHeader), + [](void* data, void* /*hint*/) { delete static_cast(data); }, + nullptr)); partsOut.AddPart(std::move(msgHeader)); for (int iobj = 0; iobj < fOutput->GetEntries(); iobj++) { - if (strcmp(fOutput->At(iobj)->GetName(),"PixelHits") == 0) { + if (strcmp(fOutput->At(iobj)->GetName(), "PixelHits") == 0) { Int_t nofEntries = ((TClonesArray*)fOutput->At(iobj))->GetEntries(); size_t hitsSize = nofEntries * sizeof(PixelPayload::Hit); @@ -147,12 +147,12 @@ class FairMQPixelTaskProcessorBin : public FairMQDevice } new (&hitPayload[ihit]) PixelPayload::Hit(); hitPayload[ihit].fDetectorID = hit->GetDetectorID(); - hitPayload[ihit].posX = hit->GetX(); - hitPayload[ihit].posY = hit->GetY(); - hitPayload[ihit].posZ = hit->GetZ(); - hitPayload[ihit].dposX = hit->GetDx(); - hitPayload[ihit].dposY = hit->GetDy(); - hitPayload[ihit].dposZ = hit->GetDz(); + hitPayload[ihit].posX = hit->GetX(); + hitPayload[ihit].posY = hit->GetY(); + hitPayload[ihit].posZ = hit->GetZ(); + hitPayload[ihit].dposX = hit->GetDx(); + hitPayload[ihit].dposY = hit->GetDy(); + hitPayload[ihit].dposZ = hit->GetDz(); } // LOG(debug) << "second part has size = " << hitsSize; partsOut.AddPart(std::move(msgTCA)); @@ -169,11 +169,11 @@ class FairMQPixelTaskProcessorBin : public FairMQDevice virtual void Init() { - fDataToKeep = fConfig->GetValue("keep-data"); - fInputChannelName = fConfig->GetValue("in-channel"); + fDataToKeep = fConfig->GetValue("keep-data"); + fInputChannelName = fConfig->GetValue("in-channel"); fOutputChannelName = fConfig->GetValue("out-channel"); - fParamChannelName = fConfig->GetValue("par-channel"); - fStaticParameters = fConfig->GetValue ("static-pars"); + fParamChannelName = fConfig->GetValue("par-channel"); + fStaticParameters = fConfig->GetValue("static-pars"); // fHitFinder->InitMQ(fRootParFileName,fAsciiParFileName); fFairTask = new T(); @@ -197,7 +197,8 @@ class FairMQPixelTaskProcessorBin : public FairMQDevice virtual void PostRun() { - LOG(info) << "FairMQPixelTaskProcessorBin::PostRun() Received " << fReceivedMsgs << " and sent " << fSentMsgs << " messages!"; + LOG(info) << "FairMQPixelTaskProcessorBin::PostRun() Received " << fReceivedMsgs << " and sent " << fSentMsgs + << " messages!"; } private: @@ -219,18 +220,20 @@ class FairMQPixelTaskProcessorBin : public FairMQDevice std::string paramName = thisPar->GetName(); std::string* reqStr = new std::string(paramName + "," + std::to_string(fCurrentRunId)); - LOG(warn) << "Requesting parameter \"" << paramName << "\" for Run ID " << fCurrentRunId << " (" << thisPar << ")"; - FairMQMessagePtr req(NewMessage(const_cast(reqStr->c_str()), - reqStr->length(), - [](void* /* data */, void* hint){ delete static_cast(hint); }, - reqStr)); + LOG(warn) << "Requesting parameter \"" << paramName << "\" for Run ID " << fCurrentRunId << " (" << thisPar + << ")"; + FairMQMessagePtr req(NewMessage( + const_cast(reqStr->c_str()), + reqStr->length(), + [](void* /* data */, void* hint) { delete static_cast(hint); }, + reqStr)); FairMQMessagePtr rep(NewMessage()); - if (Send(req,fParamChannelName) > 0) { - if (Receive(rep,fParamChannelName) > 0) { + if (Send(req, fParamChannelName) > 0) { + if (Receive(rep, fParamChannelName) > 0) { thisPar = nullptr; - Deserialize(*rep,thisPar); - LOG(info) << "Received parameter"<< paramName <<" from the server (" << thisPar << ")"; + Deserialize(*rep, thisPar); + LOG(info) << "Received parameter" << paramName << " from the server (" << thisPar << ")"; return thisPar; } } @@ -239,8 +242,8 @@ class FairMQPixelTaskProcessorBin : public FairMQDevice } FairEventHeader* fEventHeader; - TList* fInput; - TList* fOutput; + TList* fInput; + TList* fOutput; TClonesArray* fInputArray; TClonesArray* fOutputArray; diff --git a/examples/MQ/pixelDetector/src/devices/FairMQRunDevice.cxx b/examples/MQ/pixelDetector/src/devices/FairMQRunDevice.cxx index 8cb7c8f082..a985468ebe 100644 --- a/examples/MQ/pixelDetector/src/devices/FairMQRunDevice.cxx +++ b/examples/MQ/pixelDetector/src/devices/FairMQRunDevice.cxx @@ -20,31 +20,30 @@ #include #include - +#include #include #include -#include - -#include // printf +#include // printf using namespace std; -#include // std::mutex -std::mutex mtx; // mutex for critical section +#include // std::mutex +std::mutex mtx; // mutex for critical section -void FairMQRunDevice::SendObject(TObject* obj, const std::string& chan) { - FairMQMessagePtr mess(NewMessage()); - Serialize(*mess, obj); +void FairMQRunDevice::SendObject(TObject* obj, const std::string& chan) +{ + FairMQMessagePtr mess(NewMessage()); + Serialize(*mess, obj); - FairMQMessagePtr rep(NewMessage()); + FairMQMessagePtr rep(NewMessage()); - printf("sending %s",obj->GetName()); - if (Send(mess, chan) > 0) { - if (Receive(rep, chan) > 0) { - std::string repString = string(static_cast(rep->GetData()), rep->GetSize()); - LOG(info) << " -> " << repString.data(); + printf("sending %s", obj->GetName()); + if (Send(mess, chan) > 0) { + if (Receive(rep, chan) > 0) { + std::string repString = string(static_cast(rep->GetData()), rep->GetSize()); + LOG(info) << " -> " << repString.data(); + } } - } } void FairMQRunDevice::SendBranches() @@ -60,49 +59,54 @@ void FairMQRunDevice::SendBranches() FairMQParts parts; - for(Int_t t=0; tGetEntries(); t++) { - ObjStr= static_cast(branchNameList->TList::At(t)); + for (Int_t t = 0; t < branchNameList->GetEntries(); t++) { + ObjStr = static_cast(branchNameList->TList::At(t)); LOG(debug) << " branch >" << ObjStr->GetString().Data() << "<"; std::string modifiedBranchName = std::string("#") + ObjStr->GetString().Data() + "#"; - if ( mi.first.find(modifiedBranchName) != std::string::npos || mi.first.find("#all#") != std::string::npos ) { - if ( (static_cast(FairRootManager::Instance()->GetSink()))->IsPersistentBranchAny(ObjStr->GetString()) ) { + if (mi.first.find(modifiedBranchName) != std::string::npos || mi.first.find("#all#") != std::string::npos) { + if ((static_cast(FairRootManager::Instance()->GetSink())) + ->IsPersistentBranchAny(ObjStr->GetString())) { LOG(debug) << "Branch \"" << ObjStr->GetString() << "\" is persistent ANY"; - if ( ObjStr->GetString().CompareTo("MCTrack") == 0 ) { - TClonesArray** mcTrackArray = (static_cast(FairRootManager::Instance()->GetSink()))->GetPersistentBranchAny(ObjStr->GetString()); - if ( mcTrackArray ) { + if (ObjStr->GetString().CompareTo("MCTrack") == 0) { + TClonesArray** mcTrackArray = + (static_cast(FairRootManager::Instance()->GetSink())) + ->GetPersistentBranchAny(ObjStr->GetString()); + if (mcTrackArray) { (*mcTrackArray)->SetName("MCTrack"); - LOG(debug) << "[" << FairRootManager::Instance()->GetInstanceId() << "] mcTrack " << mcTrackArray << " /// *mcTrackArray " << *mcTrackArray << " /// *mcTrackArray->GetName() " << (*mcTrackArray)->GetName(); + LOG(debug) << "[" << FairRootManager::Instance()->GetInstanceId() << "] mcTrack " + << mcTrackArray << " /// *mcTrackArray " << *mcTrackArray + << " /// *mcTrackArray->GetName() " << (*mcTrackArray)->GetName(); TObject* objClone = (*mcTrackArray)->Clone(); - LOG(debug) << "FairMQRunDevice::SendBranches() the track array has " << ((TClonesArray*)(objClone))->GetEntries() << " entries."; + LOG(debug) << "FairMQRunDevice::SendBranches() the track array has " + << ((TClonesArray*)(objClone))->GetEntries() << " entries."; FairMQMessagePtr mess(NewMessage()); - Serialize(*mess,objClone); + Serialize(*mess, objClone); parts.AddPart(std::move(mess)); - LOG(debug) << "channel >" << mi.first.data() << "< --> >" << ObjStr->GetString().Data() << "<"; + LOG(debug) << "channel >" << mi.first.data() << "< --> >" << ObjStr->GetString().Data() + << "<"; } - } - else { - LOG(warning) << "FairMQRunDevice::SendBranches() hasn't got knowledge how to send any branch \"" << ObjStr->GetString().Data() << "\""; + } else { + LOG(warning) << "FairMQRunDevice::SendBranches() hasn't got knowledge how to send any branch \"" + << ObjStr->GetString().Data() << "\""; continue; } - } - else { - TObject* object = FairRootManager::Instance()->GetObject(ObjStr->GetString()); - if ( object ) { + } else { + TObject* object = FairRootManager::Instance()->GetObject(ObjStr->GetString()); + if (object) { TObject* objClone = object->Clone(); FairMQMessagePtr mess(NewMessage()); - Serialize(*mess,objClone); + Serialize(*mess, objClone); parts.AddPart(std::move(mess)); LOG(debug) << "channel >" << mi.first.data() << "< --> >" << ObjStr->GetString().Data() << "<"; - } - else { + } else { LOG(fatal) << "Object " << ObjStr->GetString() << " NOT FOUND!!!"; } } } } - if ( parts.Size() > 0 ) { + if (parts.Size() > 0) { std::unique_lock lock(mtx); - Send(parts,mi.first.data()); + Send(parts, mi.first.data()); } } } diff --git a/examples/MQ/pixelDetector/src/devices/FairMQRunDevice.h b/examples/MQ/pixelDetector/src/devices/FairMQRunDevice.h index 0d52ef1550..e137178617 100644 --- a/examples/MQ/pixelDetector/src/devices/FairMQRunDevice.h +++ b/examples/MQ/pixelDetector/src/devices/FairMQRunDevice.h @@ -16,26 +16,25 @@ #ifndef FAIRMQRUNDEVICE_H_ #define FAIRMQRUNDEVICE_H_ -#include - #include +#include class TObject; class FairMQRunDevice : public FairMQDevice { public: - FairMQRunDevice() {} - virtual ~FairMQRunDevice() {} + FairMQRunDevice() {} + virtual ~FairMQRunDevice() {} - virtual void SendBranches(); + virtual void SendBranches(); - protected: - void SendObject(TObject* obj, const std::string& chan); + protected: + void SendObject(TObject* obj, const std::string& chan); - private: - FairMQRunDevice(const FairMQRunDevice&); - FairMQRunDevice& operator=(const FairMQRunDevice&); + private: + FairMQRunDevice(const FairMQRunDevice&); + FairMQRunDevice& operator=(const FairMQRunDevice&); }; #endif /* FAIRMQRUNDEVICE_H_ */ diff --git a/examples/MQ/pixelDetector/src/devices/FairMQSimDevice.cxx b/examples/MQ/pixelDetector/src/devices/FairMQSimDevice.cxx index eb2507d33a..e227740e9e 100644 --- a/examples/MQ/pixelDetector/src/devices/FairMQSimDevice.cxx +++ b/examples/MQ/pixelDetector/src/devices/FairMQSimDevice.cxx @@ -14,148 +14,148 @@ #include "FairMQSimDevice.h" -#include "FairRunSim.h" -#include "FairRuntimeDb.h" #include "FairModule.h" -#include "FairPrimaryGenerator.h" #include "FairParSet.h" +#include "FairPrimaryGenerator.h" +#include "FairRunSim.h" +#include "FairRuntimeDb.h" -#include #include - +#include +#include #include #include -#include - -#include // printf +#include // printf using namespace std; FairMQSimDevice::FairMQSimDevice() - : FairMQRunDevice() - , fSimDeviceId(0) - , fUpdateChannelName("updateChannel") - , fRunSim(nullptr) - , fNofEvents(1) - , fTransportName("TGeant3") - , fMaterialsFile("") - , fMagneticField(nullptr) - , fDetectorArray(nullptr) - , fPrimaryGenerator(nullptr) - , fStoreTrajFlag(false) - , fTaskArray(nullptr) - , fFirstParameter(nullptr) - , fSecondParameter(nullptr) - , fSink(nullptr) -{ -} + : FairMQRunDevice() + , fSimDeviceId(0) + , fUpdateChannelName("updateChannel") + , fRunSim(nullptr) + , fNofEvents(1) + , fTransportName("TGeant3") + , fMaterialsFile("") + , fMagneticField(nullptr) + , fDetectorArray(nullptr) + , fPrimaryGenerator(nullptr) + , fStoreTrajFlag(false) + , fTaskArray(nullptr) + , fFirstParameter(nullptr) + , fSecondParameter(nullptr) + , fSink(nullptr) +{} void FairMQSimDevice::InitTask() { - fRunSim = new FairRunSim(); - - fRunSim->SetSink(fSink); - - if (fFirstParameter || fSecondParameter) { - FairRuntimeDb *rtdb=fRunSim->GetRuntimeDb(); - if (fFirstParameter) - rtdb->setFirstInput(fFirstParameter); - if (fSecondParameter) - rtdb->setSecondInput(fSecondParameter); - } - - fRunSim->SetName(fTransportName.data()); - // fRunSim->SetSimulationConfig(new FairVMCConfig()); - fRunSim->SetIsMT(kFALSE); - - if (fUserConfig.Length() > 0) - fRunSim->SetUserConfig(fUserConfig); - if (fUserCuts.Length() > 0) - fRunSim->SetUserCuts(fUserCuts); - - // ----- Create media ------------------------------------------------- - fRunSim->SetMaterials(fMaterialsFile.data()); - - // ----- Magnetic field ------------------------------------------- - if (fMagneticField) - fRunSim->SetField(fMagneticField); - - // ----- Create geometry ---------------------------------------------- - for (int idet = 0 ; idet < fDetectorArray->GetEntries() ; idet++) { - fRunSim->AddModule((FairModule*)(fDetectorArray->At(idet))); - } - - // ----- Negotiate the run number ------------------------------------- - // ----- via the fUpdateChannelName -------------------------------- - // ----- ask the fParamMQServer ------------------------------------ - // ----- receive the run number and sampler id --------------------- - std::string* askForRunNumber = new string("ReportSimDevice"); - FairMQMessagePtr req(NewMessage(const_cast(askForRunNumber->c_str()), - askForRunNumber->length(), - [](void* /*data*/, void* object) { delete static_cast(object); }, - askForRunNumber)); - FairMQMessagePtr rep(NewMessage()); - - unsigned int runId = 0; - if (Send(req, fUpdateChannelName) > 0) { - if (Receive(rep, fUpdateChannelName) > 0) { - std::string repString = string(static_cast(rep->GetData()), rep->GetSize()); - LOG(info) << " -> " << repString.data(); - runId = stoi(repString); - repString = repString.substr(repString.find_first_of('_')+1,repString.length()); - fSimDeviceId = stoi(repString); - LOG(info) << "runId = " << runId << " /// fSimDeviceId = " << fSimDeviceId; + fRunSim = new FairRunSim(); + + fRunSim->SetSink(fSink); + + if (fFirstParameter || fSecondParameter) { + FairRuntimeDb* rtdb = fRunSim->GetRuntimeDb(); + if (fFirstParameter) + rtdb->setFirstInput(fFirstParameter); + if (fSecondParameter) + rtdb->setSecondInput(fSecondParameter); + } + + fRunSim->SetName(fTransportName.data()); + // fRunSim->SetSimulationConfig(new FairVMCConfig()); + fRunSim->SetIsMT(kFALSE); + + if (fUserConfig.Length() > 0) + fRunSim->SetUserConfig(fUserConfig); + if (fUserCuts.Length() > 0) + fRunSim->SetUserCuts(fUserCuts); + + // ----- Create media ------------------------------------------------- + fRunSim->SetMaterials(fMaterialsFile.data()); + + // ----- Magnetic field ------------------------------------------- + if (fMagneticField) + fRunSim->SetField(fMagneticField); + + // ----- Create geometry ---------------------------------------------- + for (int idet = 0; idet < fDetectorArray->GetEntries(); idet++) { + fRunSim->AddModule((FairModule*)(fDetectorArray->At(idet))); + } + + // ----- Negotiate the run number ------------------------------------- + // ----- via the fUpdateChannelName -------------------------------- + // ----- ask the fParamMQServer ------------------------------------ + // ----- receive the run number and sampler id --------------------- + std::string* askForRunNumber = new string("ReportSimDevice"); + FairMQMessagePtr req(NewMessage( + const_cast(askForRunNumber->c_str()), + askForRunNumber->length(), + [](void* /*data*/, void* object) { delete static_cast(object); }, + askForRunNumber)); + FairMQMessagePtr rep(NewMessage()); + + unsigned int runId = 0; + if (Send(req, fUpdateChannelName) > 0) { + if (Receive(rep, fUpdateChannelName) > 0) { + std::string repString = string(static_cast(rep->GetData()), rep->GetSize()); + LOG(info) << " -> " << repString.data(); + runId = stoi(repString); + repString = repString.substr(repString.find_first_of('_') + 1, repString.length()); + fSimDeviceId = stoi(repString); + LOG(info) << "runId = " << runId << " /// fSimDeviceId = " << fSimDeviceId; + } } - } - if (fPrimaryGenerator) { - fPrimaryGenerator->SetEventNr(fSimDeviceId*fNofEvents); // run n simulations with same run id - offset the event number - fRunSim->SetGenerator(fPrimaryGenerator); - } + if (fPrimaryGenerator) { + fPrimaryGenerator->SetEventNr(fSimDeviceId + * fNofEvents); // run n simulations with same run id - offset the event number + fRunSim->SetGenerator(fPrimaryGenerator); + } - fRunSim->SetStoreTraj(fStoreTrajFlag); + fRunSim->SetStoreTraj(fStoreTrajFlag); - // ----- Set tasks ---------------------------------------------------- - if (fTaskArray) { - for (int itask = 0 ; itask < fTaskArray->GetEntries() ; itask++) { - fRunSim->AddTask((FairTask*)(fTaskArray->At(itask))); + // ----- Set tasks ---------------------------------------------------- + if (fTaskArray) { + for (int itask = 0; itask < fTaskArray->GetEntries(); itask++) { + fRunSim->AddTask((FairTask*)(fTaskArray->At(itask))); + } } - } - // ----- Initialize simulation run ------------------------------------ - fRunSim->SetRunId(runId); // run n simulations with same run id - offset the event number - fRunSim->Init(); + // ----- Initialize simulation run ------------------------------------ + fRunSim->SetRunId(runId); // run n simulations with same run id - offset the event number + fRunSim->Init(); } bool FairMQSimDevice::ConditionalRun() { - if (fSimDeviceId == 0) - UpdateParameterServer(); - fRunSim->Run(fNofEvents); - return false; + if (fSimDeviceId == 0) + UpdateParameterServer(); + fRunSim->Run(fNofEvents); + return false; } void FairMQSimDevice::UpdateParameterServer() { - FairRuntimeDb* rtdb = fRunSim->GetRuntimeDb(); - - printf("FairMQSimDevice::UpdateParameterServer() (%d containers)\n",rtdb->getListOfContainers()->GetEntries()); - - // send the parameters to be saved - TIter next(rtdb->getListOfContainers()); - FairParSet* cont; - while ((cont = static_cast(next()))) { - std::string ridString = std::string("RUNID") + std::to_string(fRunSim->GetRunId()) + std::string("RUNID") + std::string(cont->getDescription()); - cont->setDescription(ridString.data()); - FairMQRunDevice::SendObject(cont, fUpdateChannelName); - } + FairRuntimeDb* rtdb = fRunSim->GetRuntimeDb(); + + printf("FairMQSimDevice::UpdateParameterServer() (%d containers)\n", rtdb->getListOfContainers()->GetEntries()); + + // send the parameters to be saved + TIter next(rtdb->getListOfContainers()); + FairParSet* cont; + while ((cont = static_cast(next()))) { + std::string ridString = std::string("RUNID") + std::to_string(fRunSim->GetRunId()) + std::string("RUNID") + + std::string(cont->getDescription()); + cont->setDescription(ridString.data()); + FairMQRunDevice::SendObject(cont, fUpdateChannelName); + } - printf("FairMQSimDevice::UpdateParameterServer() finished\n"); + printf("FairMQSimDevice::UpdateParameterServer() finished\n"); } void FairMQSimDevice::SendBranches() { - if ( NewStatePending() ) { + if (NewStatePending()) { fRunSim->StopMCRun(); } FairMQRunDevice::SendBranches(); diff --git a/examples/MQ/pixelDetector/src/devices/FairMQSimDevice.h b/examples/MQ/pixelDetector/src/devices/FairMQSimDevice.h index 16d859c930..49d935c589 100644 --- a/examples/MQ/pixelDetector/src/devices/FairMQSimDevice.h +++ b/examples/MQ/pixelDetector/src/devices/FairMQSimDevice.h @@ -1,8 +1,8 @@ /******************************************************************************** * Copyright (C) 2017 GSI Helmholtzzentrum fuer Schwerionenforschung GmbH * * * - * This software is distributed under the terms of the * - * GNU Lesser General Public Licence version 3 (LGPL) version 3, * + * 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" * ********************************************************************************/ @@ -18,11 +18,10 @@ #include "FairMQRunDevice.h" -#include #include - -#include +#include #include +#include class FairRunSim; class FairField; @@ -40,19 +39,19 @@ class FairMQSimDevice : public FairMQRunDevice virtual void SetParamUpdateChannelName(const TString& tString) { fUpdateChannelName = tString; } // ------ FairRunSim setters ------ - void SetNofEvents (int64_t nofev) { fNofEvents = nofev; } - void SetTransportName (const std::string& str) { fTransportName = str; } - void SetMaterials (const std::string& str) { fMaterialsFile = str; } - void SetMagneticField (FairField* field) { fMagneticField = field; } - void SetDetectorArray (TObjArray* array) { fDetectorArray = array; } - void SetGenerator (FairPrimaryGenerator* primGen) { fPrimaryGenerator = primGen; } - void SetStoreTraj (bool flag=true) { fStoreTrajFlag = flag; } - void SetTaskArray (TObjArray* array) { fTaskArray = array; } - void SetFirstParameter (FairParIo* par) { fFirstParameter = par; } - void SetSecondParameter (FairParIo* par) { fSecondParameter = par; } - void SetUserConfig (const TString& Config) { fUserConfig = Config; } - void SetUserCuts (const TString& Cuts) { fUserCuts = Cuts; } - void SetSink (FairSink* sink) { fSink = sink; } + void SetNofEvents(int64_t nofev) { fNofEvents = nofev; } + void SetTransportName(const std::string& str) { fTransportName = str; } + void SetMaterials(const std::string& str) { fMaterialsFile = str; } + void SetMagneticField(FairField* field) { fMagneticField = field; } + void SetDetectorArray(TObjArray* array) { fDetectorArray = array; } + void SetGenerator(FairPrimaryGenerator* primGen) { fPrimaryGenerator = primGen; } + void SetStoreTraj(bool flag = true) { fStoreTrajFlag = flag; } + void SetTaskArray(TObjArray* array) { fTaskArray = array; } + void SetFirstParameter(FairParIo* par) { fFirstParameter = par; } + void SetSecondParameter(FairParIo* par) { fSecondParameter = par; } + void SetUserConfig(const TString& Config) { fUserConfig = Config; } + void SetUserCuts(const TString& Cuts) { fUserCuts = Cuts; } + void SetSink(FairSink* sink) { fSink = sink; } // ------ ---------- -------- ------ virtual void SendBranches(); @@ -67,21 +66,21 @@ class FairMQSimDevice : public FairMQRunDevice UInt_t fSimDeviceId; std::string fUpdateChannelName; - FairRunSim* fRunSim; + FairRunSim* fRunSim; // ------ FairRunSim settings ------ - int64_t fNofEvents; - std::string fTransportName; - std::string fMaterialsFile; - FairField* fMagneticField; - TObjArray* fDetectorArray; + int64_t fNofEvents; + std::string fTransportName; + std::string fMaterialsFile; + FairField* fMagneticField; + TObjArray* fDetectorArray; FairPrimaryGenerator* fPrimaryGenerator; - bool fStoreTrajFlag; - TObjArray* fTaskArray; - FairParIo* fFirstParameter; // first (prefered) input for parameters - FairParIo* fSecondParameter; // second input (used if not found in first input) - TString fUserConfig; //! /** Macro for geant configuration*/ - TString fUserCuts; //! /** Macro for geant cuts*/ - FairSink* fSink; + bool fStoreTrajFlag; + TObjArray* fTaskArray; + FairParIo* fFirstParameter; // first (prefered) input for parameters + FairParIo* fSecondParameter; // second input (used if not found in first input) + TString fUserConfig; //! /** Macro for geant configuration*/ + TString fUserCuts; //! /** Macro for geant cuts*/ + FairSink* fSink; // ------ ---------- -------- ------ void UpdateParameterServer(); diff --git a/examples/MQ/pixelDetector/src/devices/PixelFindHitsTask.cxx b/examples/MQ/pixelDetector/src/devices/PixelFindHitsTask.cxx index 329e347732..33a1a476da 100644 --- a/examples/MQ/pixelDetector/src/devices/PixelFindHitsTask.cxx +++ b/examples/MQ/pixelDetector/src/devices/PixelFindHitsTask.cxx @@ -14,201 +14,200 @@ #include "PixelFindHitsTask.h" +#include "FairGeoParSet.h" #include "PixelDigi.h" -#include "PixelHit.h" #include "PixelDigiPar.h" - -#include "FairGeoParSet.h" +#include "PixelHit.h" #include - -#include -#include #include -#include -#include +#include #include #include #include -#include +#include +#include +#include +#include PixelFindHitsTask::PixelFindHitsTask() - : fGeoParSet(nullptr) - , fNDigis(0) - , fNHits(0) - , fTNofEvents(0) - , fTNofDigis(0) - , fTNofHits(0) - , fFeCols(0) - , fFeRows(0) - , fMaxFEperCol(0) - , fPitchX(0.) - , fPitchY(0.) + : fGeoParSet(nullptr) + , fNDigis(0) + , fNHits(0) + , fTNofEvents(0) + , fTNofDigis(0) + , fTNofHits(0) + , fFeCols(0) + , fFeRows(0) + , fMaxFEperCol(0) + , fPitchX(0.) + , fPitchY(0.) { - // Reset(); + // Reset(); } -PixelFindHitsTask::~PixelFindHitsTask() { - // Reset(); - +PixelFindHitsTask::~PixelFindHitsTask() +{ + // Reset(); } void PixelFindHitsTask::Reset(TClonesArray* hits) { - fNDigis = fNHits = 0; - if (hits) hits->Delete(); + fNDigis = fNHits = 0; + if (hits) + hits->Delete(); } void PixelFindHitsTask::Finish() { - // if (fDigis) fDigis->Delete(); - - LOG(info) << "-------------------- PixelFindHitsTask : Summary ------------------------"; - LOG(info) << " Events: " << fTNofEvents; - LOG(info) << " Digis: " << fTNofDigis << " (" << static_cast(fTNofDigis) /(static_cast(fTNofEvents)) << " per event)"; - LOG(info) << " Hits: " << fTNofHits << " (" << static_cast(fTNofHits) /(static_cast(fTNofEvents)) << " per event)"; - LOG(info) << "---------------------------------------------------------------------"; + // if (fDigis) fDigis->Delete(); + + LOG(info) << "-------------------- PixelFindHitsTask : Summary ------------------------"; + LOG(info) << " Events: " << fTNofEvents; + LOG(info) << " Digis: " << fTNofDigis << " (" + << static_cast(fTNofDigis) / (static_cast(fTNofEvents)) << " per event)"; + LOG(info) << " Hits: " << fTNofHits << " (" + << static_cast(fTNofHits) / (static_cast(fTNofEvents)) << " per event)"; + LOG(info) << "---------------------------------------------------------------------"; } void PixelFindHitsTask::Init(PixelDigiPar* digipar, FairGeoParSet* geopar) { - fFeCols = digipar->GetFECols(); - fFeRows = digipar->GetFERows(); - fMaxFEperCol = digipar->GetMaxFEperCol(); - fPitchX = digipar->GetXPitch(); - fPitchY = digipar->GetYPitch(); - fGeoParSet = geopar; - LOG(info) << "PixelFindHitsTask::Init" - << " fFeCols=" << fFeCols - << " fFeRows=" << fFeRows - << " fMaxFEperCol=" << fMaxFEperCol - << " fPitchX=" << fPitchX - << " fPitchY=" << fPitchX; - LOG(info) << "geopar->printParams()"; - geopar->printParams(); - LOG(info)<<"fGeoParSet->printParams()"; - fGeoParSet->printParams(); + fFeCols = digipar->GetFECols(); + fFeRows = digipar->GetFERows(); + fMaxFEperCol = digipar->GetMaxFEperCol(); + fPitchX = digipar->GetXPitch(); + fPitchY = digipar->GetYPitch(); + fGeoParSet = geopar; + LOG(info) << "PixelFindHitsTask::Init" + << " fFeCols=" << fFeCols << " fFeRows=" << fFeRows << " fMaxFEperCol=" << fMaxFEperCol + << " fPitchX=" << fPitchX << " fPitchY=" << fPitchX; + LOG(info) << "geopar->printParams()"; + geopar->printParams(); + LOG(info) << "fGeoParSet->printParams()"; + fGeoParSet->printParams(); } void PixelFindHitsTask::Exec(TClonesArray* digis, TClonesArray* hits) { - Reset(hits); + Reset(hits); - LOG(info) << "PixelFindHits::Exec(TCA) EVENT " << fTNofEvents; + LOG(info) << "PixelFindHits::Exec(TCA) EVENT " << fTNofEvents; - fTNofEvents++; - LOG(debug)<<"PixelFindHits::Exec() ok 0 "; - fNDigis = digis->GetEntriesFast(); - LOG(debug)<<"PixelFindHits::Exec() fNDigis = "<At(iDigi); + fTNofEvents++; + LOG(debug) << "PixelFindHits::Exec() ok 0 "; + fNDigis = digis->GetEntriesFast(); + LOG(debug) << "PixelFindHits::Exec() fNDigis = " << fNDigis; + fTNofDigis += fNDigis; + //* + for (Int_t iDigi = 0; iDigi < fNDigis; iDigi++) { + PixelDigi* currentDigi = (PixelDigi*)digis->At(iDigi); - Int_t detId = currentDigi->GetDetectorID(); - TString nodeName = Form("/cave/Pixel%d_%d",detId/256,detId%256); - LOG(debug)<<"PixelFindHits::Exec() ok 1 node name = "<GetGeometry()->cd(nodeName.Data()); - LOG(debug)<<"PixelFindHits::Exec() ok 2 "; - TGeoNode* curNode = fGeoParSet->GetGeometry()->GetCurrentNode(); - LOG(debug)<<"PixelFindHits::Exec() ok 3 "; - //TGeoMatrix* matrix = curNode->GetMatrix(); + Int_t detId = currentDigi->GetDetectorID(); + TString nodeName = Form("/cave/Pixel%d_%d", detId / 256, detId % 256); + LOG(debug) << "PixelFindHits::Exec() ok 1 node name = " << nodeName.Data(); + fGeoParSet->GetGeometry()->cd(nodeName.Data()); + LOG(debug) << "PixelFindHits::Exec() ok 2 "; + TGeoNode* curNode = fGeoParSet->GetGeometry()->GetCurrentNode(); + LOG(debug) << "PixelFindHits::Exec() ok 3 "; + // TGeoMatrix* matrix = curNode->GetMatrix(); - TGeoVolume* actVolume = fGeoParSet->GetGeometry()->GetCurrentVolume(); - TGeoBBox* actBox = (TGeoBBox*)(actVolume->GetShape()); + TGeoVolume* actVolume = fGeoParSet->GetGeometry()->GetCurrentVolume(); + TGeoBBox* actBox = (TGeoBBox*)(actVolume->GetShape()); - Int_t feId = currentDigi->GetFeID(); - Int_t col = currentDigi->GetCol(); - Int_t row = currentDigi->GetRow(); + Int_t feId = currentDigi->GetFeID(); + Int_t col = currentDigi->GetCol(); + Int_t row = currentDigi->GetRow(); - Double_t locPosCalc[3]; - locPosCalc[0] = (((feId-1)/fMaxFEperCol)*fFeCols + col + 0.5)*fPitchX; - locPosCalc[1] = (((feId-1)%fMaxFEperCol)*fFeRows + row + 0.5)*fPitchY; - locPosCalc[2] = 0.; + Double_t locPosCalc[3]; + locPosCalc[0] = (((feId - 1) / fMaxFEperCol) * fFeCols + col + 0.5) * fPitchX; + locPosCalc[1] = (((feId - 1) % fMaxFEperCol) * fFeRows + row + 0.5) * fPitchY; + locPosCalc[2] = 0.; - locPosCalc[0] -= actBox->GetDX(); - locPosCalc[1] -= actBox->GetDY(); + locPosCalc[0] -= actBox->GetDX(); + locPosCalc[1] -= actBox->GetDY(); - Double_t globPos[3]; + Double_t globPos[3]; - curNode->LocalToMaster(locPosCalc,globPos); + curNode->LocalToMaster(locPosCalc, globPos); - LOG(debug) << "HIT ON " << detId << " POSITION: " << locPosCalc[0] << " / " << locPosCalc[1]; - LOG(debug) << "GLOB HIT " << detId << " POSITION: " << globPos[0] << " / " << globPos[1] << " / " << globPos[2]; + LOG(debug) << "HIT ON " << detId << " POSITION: " << locPosCalc[0] << " / " << locPosCalc[1]; + LOG(debug) << "GLOB HIT " << detId << " POSITION: " << globPos[0] << " / " << globPos[1] << " / " + << globPos[2]; - TVector3 pos(globPos[0],globPos[1],globPos[2]); - TVector3 posErr(fPitchX/TMath::Sqrt(12.),fPitchY/TMath::Sqrt(12.),actBox->GetDZ()); + TVector3 pos(globPos[0], globPos[1], globPos[2]); + TVector3 posErr(fPitchX / TMath::Sqrt(12.), fPitchY / TMath::Sqrt(12.), actBox->GetDZ()); - new ((*hits)[fNHits]) PixelHit(detId,currentDigi->GetIndex(),pos,posErr); + new ((*hits)[fNHits]) PixelHit(detId, currentDigi->GetIndex(), pos, posErr); - fNHits++; - } + fNHits++; + } - fTNofHits += fNHits; - //return fHits; + fTNofHits += fNHits; + // return fHits; } void PixelFindHitsTask::Exec(TList* list, TClonesArray* hits) { - Reset(hits); + Reset(hits); - LOG(info) << "PixelFindHits::Exec(TList) EVENT " << fTNofEvents; + LOG(info) << "PixelFindHits::Exec(TList) EVENT " << fTNofEvents; - TClonesArray* digis = (TClonesArray*)list->FindObject("PixelDigis"); - if (!digis) { - LOG(error) << "OOOPS!!! no digis array"; - return; - } + TClonesArray* digis = (TClonesArray*)list->FindObject("PixelDigis"); + if (!digis) { + LOG(error) << "OOOPS!!! no digis array"; + return; + } - fTNofEvents++; - LOG(debug)<<"PixelFindHits::Exec() ok 0 "; - fNDigis = digis->GetEntriesFast(); - LOG(debug)<<"PixelFindHits::Exec() fNDigis = "<(digis->At(iDigi)); + fTNofEvents++; + LOG(debug) << "PixelFindHits::Exec() ok 0 "; + fNDigis = digis->GetEntriesFast(); + LOG(debug) << "PixelFindHits::Exec() fNDigis = " << fNDigis; + fTNofDigis += fNDigis; + //* + for (Int_t iDigi = 0; iDigi < fNDigis; iDigi++) { + PixelDigi* currentDigi = static_cast(digis->At(iDigi)); - Int_t detId = currentDigi->GetDetectorID(); - TString nodeName = Form("/cave/Pixel%d_%d",detId/256,detId%256); - LOG(debug)<<"PixelFindHits::Exec() ok 1 node name = "<GetGeometry()->cd(nodeName.Data()); - LOG(debug)<<"PixelFindHits::Exec() ok 2 "; - TGeoNode* curNode = fGeoParSet->GetGeometry()->GetCurrentNode(); - LOG(debug)<<"PixelFindHits::Exec() ok 3 "; -// TGeoMatrix* matrix = curNode->GetMatrix(); + Int_t detId = currentDigi->GetDetectorID(); + TString nodeName = Form("/cave/Pixel%d_%d", detId / 256, detId % 256); + LOG(debug) << "PixelFindHits::Exec() ok 1 node name = " << nodeName.Data(); + fGeoParSet->GetGeometry()->cd(nodeName.Data()); + LOG(debug) << "PixelFindHits::Exec() ok 2 "; + TGeoNode* curNode = fGeoParSet->GetGeometry()->GetCurrentNode(); + LOG(debug) << "PixelFindHits::Exec() ok 3 "; + // TGeoMatrix* matrix = curNode->GetMatrix(); - TGeoVolume* actVolume = fGeoParSet->GetGeometry()->GetCurrentVolume(); - TGeoBBox* actBox = static_cast(actVolume->GetShape()); + TGeoVolume* actVolume = fGeoParSet->GetGeometry()->GetCurrentVolume(); + TGeoBBox* actBox = static_cast(actVolume->GetShape()); - Int_t feId = currentDigi->GetFeID(); - Int_t col = currentDigi->GetCol(); - Int_t row = currentDigi->GetRow(); + Int_t feId = currentDigi->GetFeID(); + Int_t col = currentDigi->GetCol(); + Int_t row = currentDigi->GetRow(); - Double_t locPosCalc[3]; - locPosCalc[0] = (((feId-1)/fMaxFEperCol)*fFeCols + col + 0.5)*fPitchX; - locPosCalc[1] = (((feId-1)%fMaxFEperCol)*fFeRows + row + 0.5)*fPitchY; - locPosCalc[2] = 0.; + Double_t locPosCalc[3]; + locPosCalc[0] = (((feId - 1) / fMaxFEperCol) * fFeCols + col + 0.5) * fPitchX; + locPosCalc[1] = (((feId - 1) % fMaxFEperCol) * fFeRows + row + 0.5) * fPitchY; + locPosCalc[2] = 0.; - locPosCalc[0] -= actBox->GetDX(); - locPosCalc[1] -= actBox->GetDY(); + locPosCalc[0] -= actBox->GetDX(); + locPosCalc[1] -= actBox->GetDY(); - Double_t globPos[3]; + Double_t globPos[3]; - curNode->LocalToMaster(locPosCalc,globPos); + curNode->LocalToMaster(locPosCalc, globPos); - LOG(debug) << "HIT ON " << detId << " POSITION: " << locPosCalc[0] << " / " << locPosCalc[1]; - LOG(debug) << "GLOB HIT " << detId << " POSITION: " << globPos[0] << " / " << globPos[1] << " / " << globPos[2]; + LOG(debug) << "HIT ON " << detId << " POSITION: " << locPosCalc[0] << " / " << locPosCalc[1]; + LOG(debug) << "GLOB HIT " << detId << " POSITION: " << globPos[0] << " / " << globPos[1] << " / " + << globPos[2]; - TVector3 pos (globPos[0],globPos[1],globPos[2]); - TVector3 posErr(fPitchX/TMath::Sqrt(12.),fPitchY/TMath::Sqrt(12.),actBox->GetDZ()); + TVector3 pos(globPos[0], globPos[1], globPos[2]); + TVector3 posErr(fPitchX / TMath::Sqrt(12.), fPitchY / TMath::Sqrt(12.), actBox->GetDZ()); - new ((*hits)[fNHits]) PixelHit(detId,currentDigi->GetIndex(),pos,posErr); + new ((*hits)[fNHits]) PixelHit(detId, currentDigi->GetIndex(), pos, posErr); - fNHits++; - } + fNHits++; + } - fTNofHits += fNHits; - //return fHits; + fTNofHits += fNHits; + // return fHits; } diff --git a/examples/MQ/pixelDetector/src/devices/PixelFindHitsTask.h b/examples/MQ/pixelDetector/src/devices/PixelFindHitsTask.h index 759dbd9ed9..ef1238d692 100644 --- a/examples/MQ/pixelDetector/src/devices/PixelFindHitsTask.h +++ b/examples/MQ/pixelDetector/src/devices/PixelFindHitsTask.h @@ -46,11 +46,11 @@ class PixelFindHitsTask Int_t fTNofDigis; Int_t fTNofHits; - Int_t fFeCols; // Colums read per Frontend - Int_t fFeRows; // Rows read per Frontend - Int_t fMaxFEperCol; // max number of Frontend elemens per column - Double_t fPitchX; // Pixel cell size X - Double_t fPitchY; // Pixel cell size Y + Int_t fFeCols; // Colums read per Frontend + Int_t fFeRows; // Rows read per Frontend + Int_t fMaxFEperCol; // max number of Frontend elemens per column + Double_t fPitchX; // Pixel cell size X + Double_t fPitchY; // Pixel cell size Y /** Reset eventwise counters **/ void Reset(TClonesArray* hits); diff --git a/examples/MQ/pixelSimSplit/run/runMQChunkMerger.cxx b/examples/MQ/pixelSimSplit/run/runMQChunkMerger.cxx index 1b32beabec..b438454471 100644 --- a/examples/MQ/pixelSimSplit/run/runMQChunkMerger.cxx +++ b/examples/MQ/pixelSimSplit/run/runMQChunkMerger.cxx @@ -7,12 +7,11 @@ namespace bpo = boost::program_options; void addCustomOptions(bpo::options_description& options) { + // clang-format off options.add_options() - ("in-channel", bpo::value()->default_value("data-in") , "input channel name") + ("in-channel", bpo::value()->default_value("data-in"), "input channel name") ("out-channel", bpo::value()->default_value("data-out"), "output channel name"); + // clang-format on } -FairMQDevicePtr getDevice(const FairMQProgOptions& config) -{ - return new FairMQChunkMerger(); -} +FairMQDevicePtr getDevice(const FairMQProgOptions& config) { return new FairMQChunkMerger(); } diff --git a/examples/MQ/pixelSimSplit/run/runMQGen.cxx b/examples/MQ/pixelSimSplit/run/runMQGen.cxx index 097b84f711..1303ec8733 100644 --- a/examples/MQ/pixelSimSplit/run/runMQGen.cxx +++ b/examples/MQ/pixelSimSplit/run/runMQGen.cxx @@ -1,35 +1,35 @@ #include "runFairMQDevice.h" // MQRunSim -#include "FairPrimaryGenerator.h" #include "FairBoxGenerator.h" #include "FairMQPrimaryGeneratorDevice.h" +#include "FairPrimaryGenerator.h" #include #include -#include #include - -#include +#include #include +#include namespace bpo = boost::program_options; void addCustomOptions(bpo::options_description& options) { + // clang-format off options.add_options() - ("random-seed", bpo::value ()->default_value(0) , "Random seed number") - ("nof-events", bpo::value ()->required() , "Number of events to simulate") - ("running-mode", bpo::value()->default_value("pp") , "pp to push, rr to reply") - ("fairroot-config-dir", bpo::value()->default_value("") , "FairRoot config dir") - ("chunk-size", bpo::value ()->default_value(0) , "Max nof primaries in chunk") - ("ack-channel", bpo::value()->default_value("") , "Ack channel name"); - ; + ("random-seed", bpo::value()->default_value(0), "Random seed number") + ("nof-events", bpo::value()->required(), "Number of events to simulate") + ("running-mode", bpo::value()->default_value("pp"), "pp to push, rr to reply") + ("fairroot-config-dir", bpo::value()->default_value(""), "FairRoot config dir") + ("chunk-size", bpo::value()->default_value(0), "Max nof primaries in chunk") + ("ack-channel", bpo::value()->default_value(""), "Ack channel name"); + // clang-format on } FairMQDevicePtr getDevice(const FairMQProgOptions& config) { - gRandom->SetSeed(config.GetValue ("random-seed")); + gRandom->SetSeed(config.GetValue("random-seed")); TString dir = getenv("VMCWORKDIR"); TString tutdir = dir + "/MQ/pixelDetector"; @@ -37,23 +37,23 @@ FairMQDevicePtr getDevice(const FairMQProgOptions& config) TString tut_configdir = config.GetValue("fairroot-config-dir"); if (tut_configdir.Length() < 1) tut_configdir = dir + "/common/gconfig"; - gSystem->Setenv("CONFIG_DIR",tut_configdir.Data()); + gSystem->Setenv("CONFIG_DIR", tut_configdir.Data()); - Int_t partPdgC[] = { 211, 11, 2212 }; //{"pions","eplus","proton"} - Int_t chosenPart = 0; + Int_t partPdgC[] = {211, 11, 2212}; //{"pions","eplus","proton"} + Int_t chosenPart = 0; FairPrimaryGenerator* primGen = new FairPrimaryGenerator(); FairBoxGenerator* boxGen = new FairBoxGenerator(partPdgC[chosenPart], 100); - boxGen->SetPRange(1,2); - boxGen->SetThetaRange(0,180); - boxGen->SetPhiRange(0,360); + boxGen->SetPRange(1, 2); + boxGen->SetThetaRange(0, 180); + boxGen->SetPhiRange(0, 360); primGen->AddGenerator(boxGen); FairMQPrimaryGeneratorDevice* mqDevice = new FairMQPrimaryGeneratorDevice(); - LOG(INFO) << "Going to generate " << config.GetValue ("nof-events") << " events."; + LOG(INFO) << "Going to generate " << config.GetValue("nof-events") << " events."; mqDevice->SetChunkSize(config.GetValue("chunk-size")); mqDevice->RunInPushMode(true); - if (config.GetValue ("running-mode") == "rr") { + if (config.GetValue("running-mode") == "rr") { LOG(INFO) << "Going to reply with data."; mqDevice->RunInPushMode(false); } else { diff --git a/examples/MQ/pixelSimSplit/run/runMQTrans.cxx b/examples/MQ/pixelSimSplit/run/runMQTrans.cxx index ce6ca4e908..84fb2ccb5b 100644 --- a/examples/MQ/pixelSimSplit/run/runMQTrans.cxx +++ b/examples/MQ/pixelSimSplit/run/runMQTrans.cxx @@ -1,37 +1,35 @@ #include "runFairMQDevice.h" // MQRunSim +#include "FairCave.h" #include "FairMQTransportDevice.h" #include "FairModule.h" -#include "FairCave.h" +#include "FairOnlineSink.h" #include "FairParAsciiFileIo.h" - #include "PixelDigitize.h" -#include "FairOnlineSink.h" - -#include -#include #include +#include #include - -#include -#include +#include #include +#include +#include namespace bpo = boost::program_options; void addCustomOptions(bpo::options_description& options) { + // clang-format off options.add_options() - ("random-seed", bpo::value ()->default_value(0) , "Random seed number") - ("transport-name", bpo::value()->default_value("TGeant3") , "Transport name") - ("fairroot-config-dir", bpo::value()->default_value("") , "FairRoot config dir") - ("param-channel-name", bpo::value()->default_value("updateChannel"), "Parameter update channel name") - ("running-mode", bpo::value()->default_value("pp") , "pp to pull, rr to request") - ("detector-library", bpo::value>() , "detector library") - ("run-digi-tasks", bpo::value ()->default_value(false) , "Run digi tasks") - ; + ("random-seed", bpo::value()->default_value(0), "Random seed number") + ("transport-name", bpo::value()->default_value("TGeant3"), "Transport name") + ("fairroot-config-dir", bpo::value()->default_value(""), "FairRoot config dir") + ("param-channel-name", bpo::value()->default_value("updateChannel"), "Parameter update channel name") + ("running-mode", bpo::value()->default_value("pp"), "pp to pull, rr to request") + ("detector-library", bpo::value>(), "detector library") + ("run-digi-tasks", bpo::value()->default_value(false), "Run digi tasks"); + // clang-format on } FairMQDevicePtr getDevice(const FairMQProgOptions& config) @@ -42,16 +40,16 @@ FairMQDevicePtr getDevice(const FairMQProgOptions& config) TString tutdir = dir + "/MQ/pixelDetector"; TString tut_geomdir = dir + "/common/geometry"; - gSystem->Setenv("GEOMPATH",tut_geomdir.Data()); + gSystem->Setenv("GEOMPATH", tut_geomdir.Data()); TString tut_configdir = config.GetValue("fairroot-config-dir"); - if ( tut_configdir.Length() < 1 ) + if (tut_configdir.Length() < 1) tut_configdir = dir + "/common/gconfig"; - gSystem->Setenv("CONFIG_DIR",tut_configdir.Data()); + gSystem->Setenv("CONFIG_DIR", tut_configdir.Data()); FairMQTransportDevice* run = new FairMQTransportDevice(); run->RunInPullMode(true); - if ( config.GetValue ("running-mode") == "rr" ) { + if (config.GetValue("running-mode") == "rr") { LOG(INFO) << "Going to request data."; run->RunInPullMode(false); } else { @@ -66,25 +64,25 @@ FairMQDevicePtr getDevice(const FairMQProgOptions& config) run->SetParamUpdateChannelName(config.GetValue("param-channel-name")); - run->SetTransportName (config.GetValue("transport-name")); - run->SetMaterials ("media.geo"); + run->SetTransportName(config.GetValue("transport-name")); + run->SetMaterials("media.geo"); TObjArray* detArray = new TObjArray(); - FairModule* cave= new FairCave("CAVE"); + FairModule* cave = new FairCave("CAVE"); cave->SetGeometryFileName("cave_vacuum.geo"); detArray->Add(cave); // Pixel* det = new Pixel("PixelDetector", kTRUE); // det->SetGeometryFileName("pixel.geo"); // detArray->Add(det); - run->SetDetectorArray (detArray); + run->SetDetectorArray(detArray); - run->SetStoreTraj (false); + run->SetStoreTraj(false); - if ( (config.GetValue("run-digi-tasks")) == true ) { + if ((config.GetValue("run-digi-tasks")) == true) { // Attach tasks if needed TString digParFile = tutdir + "/param/pixel_digi.par"; FairParAsciiFileIo* parIo1 = new FairParAsciiFileIo(); - parIo1->open(digParFile.Data(),"in"); + parIo1->open(digParFile.Data(), "in"); run->SetFirstParameter(parIo1); TObjArray* taskArray = new TObjArray(); diff --git a/examples/MQ/pixelSimSplit/src/FairMCSplitEventHeader.cxx b/examples/MQ/pixelSimSplit/src/FairMCSplitEventHeader.cxx index 1fe834609a..0ba46e3fbd 100644 --- a/examples/MQ/pixelSimSplit/src/FairMCSplitEventHeader.cxx +++ b/examples/MQ/pixelSimSplit/src/FairMCSplitEventHeader.cxx @@ -14,8 +14,7 @@ FairMCSplitEventHeader::FairMCSplitEventHeader() : FairMCEventHeader() , fNofChunks(1) , fChunkStart(0) -{ -} +{} FairMCSplitEventHeader::FairMCSplitEventHeader(UInt_t runID, UInt_t eventID, UInt_t nofChunks, UInt_t chunkStart) : FairMCEventHeader(runID) @@ -25,14 +24,12 @@ FairMCSplitEventHeader::FairMCSplitEventHeader(UInt_t runID, UInt_t eventID, UIn SetEventID(eventID); } -FairMCSplitEventHeader::~FairMCSplitEventHeader() -{ -} +FairMCSplitEventHeader::~FairMCSplitEventHeader() {} void FairMCSplitEventHeader::Register() { - // Dot at the end of the name is needed for splitting!! - FairRootManager::Instance()->Register("MCEventHeader.", "Event", this, kTRUE); + // Dot at the end of the name is needed for splitting!! + FairRootManager::Instance()->Register("MCEventHeader.", "Event", this, kTRUE); } -ClassImp(FairMCSplitEventHeader) +ClassImp(FairMCSplitEventHeader); diff --git a/examples/MQ/pixelSimSplit/src/FairMCSplitEventHeader.h b/examples/MQ/pixelSimSplit/src/FairMCSplitEventHeader.h index 05fd1fb845..283a89d4b7 100644 --- a/examples/MQ/pixelSimSplit/src/FairMCSplitEventHeader.h +++ b/examples/MQ/pixelSimSplit/src/FairMCSplitEventHeader.h @@ -7,7 +7,6 @@ ********************************************************************************/ /** FairMCSplitEventHeader.h **/ - #ifndef FAIRMCSPLITEVENTHEADER_H #define FAIRMCSPLITEVENTHEADER_H 1 @@ -23,20 +22,26 @@ class FairMCSplitEventHeader : public FairMCEventHeader virtual ~FairMCSplitEventHeader(); - void SetRECC(UInt_t i1, UInt_t i2, UInt_t i3, UInt_t i4) { SetRunID(i1); SetEventID(i2); SetNofChunks(i3); SetChunkStart(i4); } - void SetNofChunks (UInt_t ti) { fNofChunks = ti; } + void SetRECC(UInt_t i1, UInt_t i2, UInt_t i3, UInt_t i4) + { + SetRunID(i1); + SetEventID(i2); + SetNofChunks(i3); + SetChunkStart(i4); + } + void SetNofChunks(UInt_t ti) { fNofChunks = ti; } void SetChunkStart(UInt_t ti) { fChunkStart = ti; } - UInt_t GetNofChunks () { return fNofChunks; } + UInt_t GetNofChunks() { return fNofChunks; } UInt_t GetChunkStart() { return fChunkStart; } virtual void Register(); protected: - UInt_t fNofChunks; - UInt_t fChunkStart; + UInt_t fNofChunks; + UInt_t fChunkStart; - ClassDef(FairMCSplitEventHeader,1); + ClassDef(FairMCSplitEventHeader, 1); }; #endif /* FAIRMCSPLITEVENTHEADER_H_ */ diff --git a/examples/MQ/pixelSimSplit/src/devices/FairMQChunkMerger.cxx b/examples/MQ/pixelSimSplit/src/devices/FairMQChunkMerger.cxx index 97116a0198..2989c99b73 100644 --- a/examples/MQ/pixelSimSplit/src/devices/FairMQChunkMerger.cxx +++ b/examples/MQ/pixelSimSplit/src/devices/FairMQChunkMerger.cxx @@ -13,42 +13,39 @@ */ #include "FairMQChunkMerger.h" -#include "FairMCSplitEventHeader.h" -#include "RootSerializer.h" -#include "FairMCTrack.h" #include "FairMCPoint.h" +#include "FairMCSplitEventHeader.h" +#include "FairMCTrack.h" +#include "RootSerializer.h" #include - #include #include - #include -#include #include +#include using namespace std; FairMQChunkMerger::FairMQChunkMerger() - : FairMQDevice() - , fInputChannelName("data-in") - , fOutputChannelName("data-out") - , fNofPartsPerEventMap() - , fObjectMap() - , fEvRIPair() - , fEvCOPair() - , fRet() - , fNofReceivedMessages(0) - , fNofSentMessages(0) - , fNofParts(3) - , fMCSplitEventHeader(nullptr) -{ -} + : FairMQDevice() + , fInputChannelName("data-in") + , fOutputChannelName("data-out") + , fNofPartsPerEventMap() + , fObjectMap() + , fEvRIPair() + , fEvCOPair() + , fRet() + , fNofReceivedMessages(0) + , fNofSentMessages(0) + , fNofParts(3) + , fMCSplitEventHeader(nullptr) +{} void FairMQChunkMerger::Init() { - fInputChannelName = fConfig->GetValue("in-channel"); + fInputChannelName = fConfig->GetValue("in-channel"); fOutputChannelName = fConfig->GetValue("out-channel"); OnData(fInputChannelName, &FairMQChunkMerger::MergeData); @@ -57,7 +54,7 @@ void FairMQChunkMerger::Init() bool FairMQChunkMerger::MergeData(FairMQParts& parts, int /*index*/) { bool printInfo = false; - int nofReceivedParts = 0; // if set to -1, the data seems to be duplicated + int nofReceivedParts = 0; // if set to -1, the data seems to be duplicated int nofExpectedParts = 1; fNofReceivedMessages++; @@ -66,15 +63,16 @@ bool FairMQChunkMerger::MergeData(FairMQParts& parts, int /*index*/) std::vector tcaVector; for (int ipart = 0; ipart < parts.Size(); ++ipart) { TObject* tempObject = nullptr; - Deserialize(*parts.At(ipart),tempObject); + Deserialize(*parts.At(ipart), tempObject); // LOG(INFO) << "Got object " << tempObject->ClassName() << " named " << tempObject->GetName(); - if (strcmp(tempObject->GetName(),"MCEventHeader.") == 0) { + if (strcmp(tempObject->GetName(), "MCEventHeader.") == 0) { fMCSplitEventHeader = dynamic_cast(tempObject); - // LOG(info) << "GOT PART [" << fMCSplitEventHeader->GetRunID() << "][" << fMCSplitEventHeader->GetEventID() << "][" << fMCSplitEventHeader->GetChunkStart() << "]"; - fEvRIPair.first = fMCSplitEventHeader->GetEventID(); + // LOG(info) << "GOT PART [" << fMCSplitEventHeader->GetRunID() << "][" << + // fMCSplitEventHeader->GetEventID() << "][" << fMCSplitEventHeader->GetChunkStart() << "]"; + fEvRIPair.first = fMCSplitEventHeader->GetEventID(); fEvRIPair.second = fMCSplitEventHeader->GetRunID(); - fEvCOPair.first = fMCSplitEventHeader->GetChunkStart(); + fEvCOPair.first = fMCSplitEventHeader->GetChunkStart(); nofExpectedParts = fMCSplitEventHeader->GetNofChunks(); fRet = fObjectMap.equal_range(fEvRIPair); @@ -89,7 +87,7 @@ bool FairMQChunkMerger::MergeData(FairMQParts& parts, int /*index*/) fNofPartsPerEventMap[fEvRIPair] = 1; nofReceivedParts = 1; } else { - it2->second+=1; + it2->second += 1; nofReceivedParts = it2->second; } } else { @@ -99,16 +97,20 @@ bool FairMQChunkMerger::MergeData(FairMQParts& parts, int /*index*/) // not all parts are there yet, have to put them in buffer if (nofReceivedParts != nofExpectedParts) { - // LOG(info) << "not all parts are yet here (got " << nofReceivedParts << " out of " << nofExpectedParts << ")... adding to (size = " << fObjectMap.size() << ")"; - // LOG(info) << "+" << fMCSplitEventHeader->GetName() << "[" << fEvRIPair.second << "][" << fEvRIPair.first << "][" << fEvCOPair.first << "]"; + // LOG(info) << "not all parts are yet here (got " << nofReceivedParts << " out of " << nofExpectedParts << + // ")... adding to (size = " << fObjectMap.size() << ")"; LOG(info) << "+" << fMCSplitEventHeader->GetName() << + // "[" << fEvRIPair.second << "][" << fEvRIPair.first << "][" << fEvCOPair.first << "]"; for (int iarray = 0; iarray < tcaVector.size(); ++iarray) { - LOG(debug) << "+ [" << fEvRIPair.second << "][" << fEvRIPair.first << "][" << fEvCOPair.first << "] " << tcaVector[iarray]->GetName(); + LOG(debug) << "+ [" << fEvRIPair.second << "][" << fEvRIPair.first << "][" << fEvCOPair.first << "] " + << tcaVector[iarray]->GetName(); fEvCOPair.second = (dynamic_cast(tcaVector[iarray])); - fObjectMap.insert(std::pair,std::pair>(fEvRIPair,fEvCOPair)); + fObjectMap.insert(std::pair, std::pair>(fEvRIPair, fEvCOPair)); } // LOG(info) << " now we have fObjectMap (size = " << fObjectMap.size() << ")"; if (printInfo) - LOG(info) << ">> [" << fMCSplitEventHeader->GetRunID() << "][" << fMCSplitEventHeader->GetEventID() << "][" << fMCSplitEventHeader->GetChunkStart() << "] Received: " << fNofReceivedMessages << " // Buffered: " << fObjectMap.size() << " // Sent: " << fNofSentMessages << " <<"; + LOG(info) << ">> [" << fMCSplitEventHeader->GetRunID() << "][" << fMCSplitEventHeader->GetEventID() << "][" + << fMCSplitEventHeader->GetChunkStart() << "] Received: " << fNofReceivedMessages + << " // Buffered: " << fObjectMap.size() << " // Sent: " << fNofSentMessages << " <<"; } else { // got all the parts of the event, have to combine and send message, consisting of objects from fObjectMap int currentEventPart = fMCSplitEventHeader->GetChunkStart(); @@ -116,18 +118,21 @@ bool FairMQChunkMerger::MergeData(FairMQParts& parts, int /*index*/) std::vector trackShift; LOG(debug) << "- [" << fEvRIPair.second << "][" << fEvRIPair.first << "][ALL]"; for (int iarray = 0; iarray < tcaVector.size(); ++iarray) { - if (strcmp(tcaVector[iarray]->GetName(),"MCTrack") != 0) continue; // want only MCTrack array to renumber tracks and get track shifts... - // LOG(info) << "BEFORE ADDING, TCA \"" << tcaVector[iarray]->GetName() << "\" has " << tcaVector[iarray]->GetEntries() << " entries."; + if (strcmp(tcaVector[iarray]->GetName(), "MCTrack") != 0) + continue; // want only MCTrack array to renumber tracks and get track shifts... + // LOG(info) << "BEFORE ADDING, TCA \"" << tcaVector[iarray]->GetName() << "\" has " << + // tcaVector[iarray]->GetEntries() << " entries."; TClonesArray* arrayToAdd; for (auto& it = fRet.first; it != fRet.second; ++it) { - if (it->second.first == fMCSplitEventHeader->GetChunkStart()) continue; - if (strcmp(tcaVector[iarray]->GetName(),it->second.second->GetName()) == 0) { + if (it->second.first == fMCSplitEventHeader->GetChunkStart()) + continue; + if (strcmp(tcaVector[iarray]->GetName(), it->second.second->GetName()) == 0) { trackShift.push_back(tcaVector[iarray]->GetEntries()); arrayToAdd = dynamic_cast(it->second.second); for (int iobj = 0; iobj < arrayToAdd->GetEntries(); ++iobj) { FairMCTrack* temp = dynamic_cast(arrayToAdd->At(iobj)); if (temp->GetMotherId() >= 0) { - temp->SetMotherId(temp->GetMotherId()+trackShift.back()); + temp->SetMotherId(temp->GetMotherId() + trackShift.back()); } } tcaVector[iarray]->AbsorbObjects(arrayToAdd); @@ -137,27 +142,32 @@ bool FairMQChunkMerger::MergeData(FairMQParts& parts, int /*index*/) } for (int iarray = 0; iarray < tcaVector.size(); ++iarray) { - if (strcmp(tcaVector[iarray]->GetName(),"MCTrack") == 0) continue; // MCTrack already done, renumber all _other_ arrays... - // LOG(info) << "BEFORE ADDING, TCA \"" << tcaVector[iarray]->GetName() << "\" has " << tcaVector[iarray]->GetEntries() << " entries."; + if (strcmp(tcaVector[iarray]->GetName(), "MCTrack") == 0) + continue; // MCTrack already done, renumber all _other_ arrays... + // LOG(info) << "BEFORE ADDING, TCA \"" << tcaVector[iarray]->GetName() << "\" has " << + // tcaVector[iarray]->GetEntries() << " entries."; int addedArray = 0; TClonesArray* arrayToAdd; for (auto& it = fRet.first; it != fRet.second; ++it) { - if (it->second.first == fMCSplitEventHeader->GetChunkStart()) continue; - if (strcmp(tcaVector[iarray]->GetName(),it->second.second->GetName()) == 0) { + if (it->second.first == fMCSplitEventHeader->GetChunkStart()) + continue; + if (strcmp(tcaVector[iarray]->GetName(), it->second.second->GetName()) == 0) { int objShift = trackShift[addedArray++]; - // LOG(INFO) << "trying to add " << tcaVector[iarray]->GetName() << " and " << it->second.second->GetName() << "(shift = " << objShift << ")"; + // LOG(INFO) << "trying to add " << tcaVector[iarray]->GetName() << " and " << + // it->second.second->GetName() << "(shift = " << objShift << ")"; arrayToAdd = dynamic_cast(it->second.second); for (int iobj = 0; iobj < arrayToAdd->GetEntries(); ++iobj) { FairMCPoint* temp = dynamic_cast(arrayToAdd->At(iobj)); - temp->SetTrackID(temp->GetTrackID()+objShift); + temp->SetTrackID(temp->GetTrackID() + objShift); } } tcaVector[iarray]->AbsorbObjects(arrayToAdd); - // LOG(info) << "FOUND ONE!, TCA has now " << tcaVector[iarray]->GetEntries() << " entries."; + // LOG(info) << "FOUND ONE!, TCA has now " << tcaVector[iarray]->GetEntries() << " + // entries."; } } - fObjectMap.erase(fRet.first,fRet.second); + fObjectMap.erase(fRet.first, fRet.second); FairMQParts partsOut; @@ -165,27 +175,28 @@ bool FairMQChunkMerger::MergeData(FairMQParts& parts, int /*index*/) fMCSplitEventHeader->SetChunkStart(0); FairMQMessagePtr messEH(NewMessage()); - Serialize(*messEH,fMCSplitEventHeader); + Serialize(*messEH, fMCSplitEventHeader); partsOut.AddPart(std::move(messEH)); for (int iarray = 0; iarray < tcaVector.size(); ++iarray) { FairMQMessagePtr mess(NewMessage()); - Serialize(*mess,tcaVector[iarray]); + Serialize(*mess, tcaVector[iarray]); partsOut.AddPart(std::move(mess)); } // LOG(info) << "created output message with " << partsOut.Size() << " parts."; Send(partsOut, fOutputChannelName); fNofSentMessages++; if (printInfo) - LOG(info) << ">> [" << fMCSplitEventHeader->GetRunID() << "][" << fMCSplitEventHeader->GetEventID() << "][" << fMCSplitEventHeader->GetChunkStart() << "] Received: " << fNofReceivedMessages << " // Buffered: " << fObjectMap.size() << " // Sent: " << fNofSentMessages << " <<"; + LOG(info) << ">> [" << fMCSplitEventHeader->GetRunID() << "][" << fMCSplitEventHeader->GetEventID() << "][" + << fMCSplitEventHeader->GetChunkStart() << "] Received: " << fNofReceivedMessages + << " // Buffered: " << fObjectMap.size() << " // Sent: " << fNofSentMessages << " <<"; } for (auto it = fObjectMap.begin(); it != fObjectMap.end(); ++it) { - LOG(debug) << "= [" << it->first.second << "][" << it->first.first << "][" << it->second.first << "] " << it->second.second->GetName(); + LOG(debug) << "= [" << it->first.second << "][" << it->first.first << "][" << it->second.first << "] " + << it->second.second->GetName(); } return true; } -FairMQChunkMerger::~FairMQChunkMerger() -{ -} +FairMQChunkMerger::~FairMQChunkMerger() {} diff --git a/examples/MQ/pixelSimSplit/src/devices/FairMQChunkMerger.h b/examples/MQ/pixelSimSplit/src/devices/FairMQChunkMerger.h index 96d8f49b1b..4312021be3 100644 --- a/examples/MQ/pixelSimSplit/src/devices/FairMQChunkMerger.h +++ b/examples/MQ/pixelSimSplit/src/devices/FairMQChunkMerger.h @@ -16,15 +16,14 @@ #define FAIRMQCHUNKMERGER_H_ #include - -#include // pair #include #include +#include // pair class TObject; class FairMCSplitEventHeader; -typedef std::multimap,std::pair> MultiMapDef; +typedef std::multimap, std::pair> MultiMapDef; class FairMQChunkMerger : public FairMQDevice { @@ -38,15 +37,15 @@ class FairMQChunkMerger : public FairMQDevice bool MergeData(FairMQParts&, int); virtual void Init(); - private: + private: std::string fInputChannelName; std::string fOutputChannelName; - std::map, int> fNofPartsPerEventMap; // number of parts for pair - MultiMapDef fObjectMap; // TObjects for given pairpart> + std::map, int> fNofPartsPerEventMap; // number of parts for pair + MultiMapDef fObjectMap; // TObjects for given pairpart> - std::pair fEvRIPair; - std::pair fEvCOPair; + std::pair fEvRIPair; + std::pair fEvCOPair; std::pair fRet; int fNofReceivedMessages; diff --git a/examples/MQ/pixelSimSplit/src/devices/FairMQPrimaryGeneratorDevice.cxx b/examples/MQ/pixelSimSplit/src/devices/FairMQPrimaryGeneratorDevice.cxx index 0930d09571..8555ef60f9 100644 --- a/examples/MQ/pixelSimSplit/src/devices/FairMQPrimaryGeneratorDevice.cxx +++ b/examples/MQ/pixelSimSplit/src/devices/FairMQPrimaryGeneratorDevice.cxx @@ -14,40 +14,37 @@ #include "FairMQPrimaryGeneratorDevice.h" -#include "FairMCSplitEventHeader.h" #include "FairMCEventHeader.h" +#include "FairMCSplitEventHeader.h" #include "FairPrimaryGenerator.h" #include "FairStack.h" #include "RootSerializer.h" #include #include - #include #include - -#include // move +#include // move using namespace std; FairMQPrimaryGeneratorDevice::FairMQPrimaryGeneratorDevice() - : fRunConditional(true) - , fAckChannelName("") - , fGeneratorChannelName("primariesChannel") - , fEventCounter(0) - , fNofEvents(10) - , fPrimaryGenerator(nullptr) - , fMCEventHeader(nullptr) - , fStack(nullptr) - , fChunkSize(0) - , fChunkPointer(0) - , fAckListener() -{ -} + : fRunConditional(true) + , fAckChannelName("") + , fGeneratorChannelName("primariesChannel") + , fEventCounter(0) + , fNofEvents(10) + , fPrimaryGenerator(nullptr) + , fMCEventHeader(nullptr) + , fStack(nullptr) + , fChunkSize(0) + , fChunkPointer(0) + , fAckListener() +{} void FairMQPrimaryGeneratorDevice::InitTask() { - fAckChannelName = fConfig->GetValue ("ack-channel"); + fAckChannelName = fConfig->GetValue("ack-channel"); fStack = new FairStack(); fMCEventHeader = new FairMCEventHeader(); @@ -69,16 +66,15 @@ void FairMQPrimaryGeneratorDevice::PreRun() bool FairMQPrimaryGeneratorDevice::ConditionalRun() { - if (!fRunConditional) return false; + if (!fRunConditional) + return false; return GenerateAndSendData(); } -bool FairMQPrimaryGeneratorDevice::Reply(FairMQMessagePtr& mPtr, int /*index*/) -{ - return GenerateAndSendData(); -} +bool FairMQPrimaryGeneratorDevice::Reply(FairMQMessagePtr& mPtr, int /*index*/) { return GenerateAndSendData(); } -bool FairMQPrimaryGeneratorDevice::GenerateAndSendData() { +bool FairMQPrimaryGeneratorDevice::GenerateAndSendData() +{ if (fChunkPointer == 0) { // LOG(INFO) << "Reseting fStack and generating new event!!!"; fStack->Reset(); @@ -90,39 +86,39 @@ bool FairMQPrimaryGeneratorDevice::GenerateAndSendData() { FairMQParts parts; - // even if sending in chunks is set, send all of the primaries anyway, the transporter takes care of transporting needed primaries - // create FairMCEventHeader, misuse not-yet-set fRunID to store begin + // even if sending in chunks is set, send all of the primaries anyway, the transporter takes care of transporting + // needed primaries create FairMCEventHeader, misuse not-yet-set fRunID to store begin TClonesArray* prims = fStack->GetListOfParticles(); - FairMCSplitEventHeader* meh = new FairMCSplitEventHeader(0,fEventCounter,1,0); // RunId will be provided in the Transport from ParameterServer + FairMCSplitEventHeader* meh = new FairMCSplitEventHeader( + 0, fEventCounter, 1, 0); // RunId will be provided in the Transport from ParameterServer meh->SetNPrim(prims->GetEntries()); if (fChunkSize != 0) { - meh->SetNofChunks ((UInt_t)(prims->GetEntries()/fChunkSize)); + meh->SetNofChunks((UInt_t)(prims->GetEntries() / fChunkSize)); meh->SetChunkStart(fChunkPointer); - meh->SetNPrim(fChunkPointer+fChunkSize); - if (fChunkPointer+fChunkSize > prims->GetEntries()) - meh->SetNPrim(prims->GetEntries()-fChunkPointer); + meh->SetNPrim(fChunkPointer + fChunkSize); + if (fChunkPointer + fChunkSize > prims->GetEntries()) + meh->SetNPrim(prims->GetEntries() - fChunkPointer); } FairMQMessagePtr messEH(NewMessage()); - Serialize(*messEH,meh); + Serialize(*messEH, meh); parts.AddPart(std::move(messEH)); FairMQMessagePtr mess(NewMessage()); - Serialize(*mess,prims); + Serialize(*mess, prims); parts.AddPart(std::move(mess)); // LOG(INFO) << "sending event " << fEventCounter << ", chunk starts at " << fChunkPointer; - if (Send(parts, fGeneratorChannelName) > 0) { - } + if (Send(parts, fGeneratorChannelName) > 0) {} int numberofparticles = (int)prims->GetEntries(); - if (fChunkSize != 0) { // should send events in chunks with maximum size of fChunkSize + if (fChunkSize != 0) { // should send events in chunks with maximum size of fChunkSize // the whole work should be done after fChunkPointer += fChunkSize; - if (fChunkPointer >= numberofparticles) { // it means that already sent all primaries from this event - fChunkPointer = 0; // this will cause the reset of the stack and generating new event + if (fChunkPointer >= numberofparticles) { // it means that already sent all primaries from this event + fChunkPointer = 0; // this will cause the reset of the stack and generating new event } } @@ -152,10 +148,6 @@ void FairMQPrimaryGeneratorDevice::ListenForAcks() } } -FairMQPrimaryGeneratorDevice::~FairMQPrimaryGeneratorDevice() -{ -} +FairMQPrimaryGeneratorDevice::~FairMQPrimaryGeneratorDevice() {} -void FairMQPrimaryGeneratorDevice::SendPrimaries() -{ -} +void FairMQPrimaryGeneratorDevice::SendPrimaries() {} diff --git a/examples/MQ/pixelSimSplit/src/devices/FairMQPrimaryGeneratorDevice.h b/examples/MQ/pixelSimSplit/src/devices/FairMQPrimaryGeneratorDevice.h index 6ce1a703fa..21a939d1d6 100644 --- a/examples/MQ/pixelSimSplit/src/devices/FairMQPrimaryGeneratorDevice.h +++ b/examples/MQ/pixelSimSplit/src/devices/FairMQPrimaryGeneratorDevice.h @@ -17,10 +17,9 @@ #define FAIRMQPRIMARYGENERATORDEVICE_H_ #include - +#include #include #include -#include class FairMCEventHeader; class FairPrimaryGenerator; @@ -35,18 +34,18 @@ class FairMQPrimaryGeneratorDevice : public FairMQDevice virtual void SendPrimaries(); - void SetNofEvents (int64_t nofev) { fNofEvents = nofev;}; - void SetGenerator (FairPrimaryGenerator* primGen) { fPrimaryGenerator = primGen;}; + void SetNofEvents(int64_t nofev) { fNofEvents = nofev; }; + void SetGenerator(FairPrimaryGenerator* primGen) { fPrimaryGenerator = primGen; }; - void SetChunkSize(int64_t ti) { fChunkSize = ti;}; + void SetChunkSize(int64_t ti) { fChunkSize = ti; }; - void RunInPushMode(bool tb=true) { fRunConditional = tb; }; - void RunInRepMode (bool tb=true) { fRunConditional = !tb; }; + void RunInPushMode(bool tb = true) { fRunConditional = tb; }; + void RunInRepMode(bool tb = true) { fRunConditional = !tb; }; void ListenForAcks(); - void SetGeneratorChannelName(std::string tstr) {fGeneratorChannelName = tstr;} - void SetAckChannelName(std::string tstr) {fAckChannelName = tstr;} + void SetGeneratorChannelName(std::string tstr) { fGeneratorChannelName = tstr; } + void SetAckChannelName(std::string tstr) { fAckChannelName = tstr; } protected: bool Reply(FairMQMessagePtr&, int); @@ -59,16 +58,16 @@ class FairMQPrimaryGeneratorDevice : public FairMQDevice std::string fGeneratorChannelName; std::string fAckChannelName; - bool fRunConditional; // if true run ConditionalRun, if false run Reply + bool fRunConditional; // if true run ConditionalRun, if false run Reply - FairPrimaryGenerator* fPrimaryGenerator; - FairMCEventHeader* fMCEventHeader; - FairStack* fStack; - int64_t fNofEvents; - int64_t fEventCounter; + FairPrimaryGenerator* fPrimaryGenerator; + FairMCEventHeader* fMCEventHeader; + FairStack* fStack; + int64_t fNofEvents; + int64_t fEventCounter; - int64_t fChunkSize; // to set the maximal number of primaries sent in one bunch - int64_t fChunkPointer; // to set the first primary to be sent + int64_t fChunkSize; // to set the maximal number of primaries sent in one bunch + int64_t fChunkPointer; // to set the first primary to be sent bool GenerateAndSendData(); void SendObject(TObject* obj, std::string chan); diff --git a/examples/MQ/pixelSimSplit/src/devices/FairMQTransportDevice.cxx b/examples/MQ/pixelSimSplit/src/devices/FairMQTransportDevice.cxx index d3733fca9c..8871550e3a 100644 --- a/examples/MQ/pixelSimSplit/src/devices/FairMQTransportDevice.cxx +++ b/examples/MQ/pixelSimSplit/src/devices/FairMQTransportDevice.cxx @@ -13,10 +13,10 @@ */ #include "FairMQTransportDevice.h" -#include "FairMCSplitEventHeader.h" #include "FairGenericStack.h" #include "FairMCApplication.h" +#include "FairMCSplitEventHeader.h" #include "FairModule.h" #include "FairParSet.h" #include "FairRunSim.h" @@ -26,44 +26,41 @@ #include #include - #include #include #include #include #include #include - -#include // for strcmp +#include // for strcmp +#include // dlopen #include #include -#include // dlopen using namespace std; FairMQTransportDevice::FairMQTransportDevice() - : FairMQRunDevice() - , fRunConditional(false) - , fRunId(0) - , fTransportDeviceId(0) - , fGeneratorChannelName("primariesChannel") - , fRunSim(nullptr) - , fNofEvents(1) - , fTransportName("TGeant3") - , fMaterialsFile("") - , fMagneticField(nullptr) - , fDetectorArray(nullptr) - , fStoreTrajFlag(false) - , fTaskArray(nullptr) - , fFirstParameter(nullptr) - , fSecondParameter(nullptr) - , fSink(nullptr) - , fVMC(nullptr) - , fStack(nullptr) - , fMCApplication(nullptr) - , fMCSplitEventHeader(nullptr) -{ -} + : FairMQRunDevice() + , fRunConditional(false) + , fRunId(0) + , fTransportDeviceId(0) + , fGeneratorChannelName("primariesChannel") + , fRunSim(nullptr) + , fNofEvents(1) + , fTransportName("TGeant3") + , fMaterialsFile("") + , fMagneticField(nullptr) + , fDetectorArray(nullptr) + , fStoreTrajFlag(false) + , fTaskArray(nullptr) + , fFirstParameter(nullptr) + , fSecondParameter(nullptr) + , fSink(nullptr) + , fVMC(nullptr) + , fStack(nullptr) + , fMCApplication(nullptr) + , fMCSplitEventHeader(nullptr) +{} void FairMQTransportDevice::Init() { @@ -75,14 +72,14 @@ void FairMQTransportDevice::InitTask() { fRunSim = new FairRunSim(); - fMCSplitEventHeader = new FairMCSplitEventHeader(fRunId,0,0,0); + fMCSplitEventHeader = new FairMCSplitEventHeader(fRunId, 0, 0, 0); fRunSim->SetMCEventHeader(fMCSplitEventHeader); fRunSim->SetRunId(fRunSim->GetMCEventHeader()->GetRunID()); fRunSim->SetSink(fSink); if (fFirstParameter || fSecondParameter) { - FairRuntimeDb *rtdb=fRunSim->GetRuntimeDb(); + FairRuntimeDb* rtdb = fRunSim->GetRuntimeDb(); if (fFirstParameter) rtdb->setFirstInput(fFirstParameter); if (fSecondParameter) @@ -104,13 +101,13 @@ void FairMQTransportDevice::InitTask() fRunSim->SetField(fMagneticField); // ----- Create geometry ---------------------------------------------- - for (int idet = 0 ; idet < fDetectorArray->GetEntries() ; idet++) { + for (int idet = 0; idet < fDetectorArray->GetEntries(); idet++) { fRunSim->AddModule(dynamic_cast(fDetectorArray->At(idet))); } std::vector detectorLibraries = fConfig->GetValue>("detector-library"); - for (unsigned int ilib = 0 ; ilib < detectorLibraries.size() ; ilib++) { + for (unsigned int ilib = 0; ilib < detectorLibraries.size(); ilib++) { LOG(info) << " -----> library \"" << detectorLibraries.at(ilib) << "\""; void* handle = dlopen(detectorLibraries.at(ilib).c_str(), RTLD_LAZY); @@ -126,8 +123,8 @@ void FairMQTransportDevice::InitTask() // reset errors dlerror(); - det_t ExternCreateDetector = (det_t) dlsym(handle, "ExternCreateDetector"); - const char *dlsym_error = dlerror(); + det_t ExternCreateDetector = (det_t)dlsym(handle, "ExternCreateDetector"); + const char* dlsym_error = dlerror(); if (dlsym_error) { LOG(fatal) << "Cannot load symbol 'ExternCreateDetector': " << dlsym_error; dlclose(handle); @@ -147,10 +144,11 @@ void FairMQTransportDevice::InitTask() // ----- ask the fParamMQServer ------------------------------------ // ----- receive the run number and sampler id --------------------- std::string* askForRunNumber = new string("ReportSimDevice"); - FairMQMessagePtr req(NewMessage(const_cast(askForRunNumber->c_str()), - askForRunNumber->length(), - [](void* /*data*/, void* object) { delete static_cast(object); }, - askForRunNumber)); + FairMQMessagePtr req(NewMessage( + const_cast(askForRunNumber->c_str()), + askForRunNumber->length(), + [](void* /*data*/, void* object) { delete static_cast(object); }, + askForRunNumber)); FairMQMessagePtr rep(NewMessage()); if (Send(req, fUpdateChannelName) > 0) { @@ -159,7 +157,7 @@ void FairMQTransportDevice::InitTask() LOG(INFO) << " -> " << repString.data(); fRunId = stoi(repString); fMCSplitEventHeader->SetRunID(fRunId); - repString = repString.substr(repString.find_first_of('_')+1,repString.length()); + repString = repString.substr(repString.find_first_of('_') + 1, repString.length()); fTransportDeviceId = stoi(repString); LOG(INFO) << "runId = " << fRunId << " /// fTransportDeviceId = " << fTransportDeviceId; } @@ -169,7 +167,7 @@ void FairMQTransportDevice::InitTask() // ----- Set tasks ---------------------------------------------------- if (fTaskArray) { - for (int itask = 0 ; itask < fTaskArray->GetEntries() ; itask++) { + for (int itask = 0; itask < fTaskArray->GetEntries(); itask++) { fRunSim->AddTask(dynamic_cast(fTaskArray->At(itask))); } } @@ -178,36 +176,36 @@ void FairMQTransportDevice::InitTask() // fRunSim->SetRunId(fRunId); // run n simulations with same run id - offset the event number fRunSim->Init(); - fVMC = TVirtualMC::GetMC(); + fVMC = TVirtualMC::GetMC(); fMCApplication = FairMCApplication::Instance(); - fStack = fMCApplication->GetStack(); + fStack = fMCApplication->GetStack(); fStack->Register(); // fRunSim->Run(0); UpdateParameterServer(); LOG(INFO) << "end of FairMQTransportDevice::InitTask() run id = " << fRunSim->GetMCEventHeader()->GetRunID(); - LOG(INFO) << " name/title/classname = " << fRunSim->GetMCEventHeader()->GetName() << "/" << fRunSim->GetMCEventHeader()->GetTitle() << "/" << fRunSim->GetMCEventHeader()->ClassName(); - + LOG(INFO) << " name/title/classname = " << fRunSim->GetMCEventHeader()->GetName() << "/" + << fRunSim->GetMCEventHeader()->GetTitle() << "/" << fRunSim->GetMCEventHeader()->ClassName(); } -void FairMQTransportDevice::PreRun() -{ -} +void FairMQTransportDevice::PreRun() {} bool FairMQTransportDevice::ConditionalRun() { - if (!fRunConditional) return false; + if (!fRunConditional) + return false; std::string* requestString = new string("RequestData"); - FairMQMessagePtr req(NewMessage(const_cast(requestString->c_str()), - requestString->length(), - [](void* /*data*/, void* object) { delete static_cast(object); }, - requestString)); + FairMQMessagePtr req(NewMessage( + const_cast(requestString->c_str()), + requestString->length(), + [](void* /*data*/, void* object) { delete static_cast(object); }, + requestString)); FairMQParts parts; // FairMQMessagePtr rep(NewMessage()); if (Send(req, fGeneratorChannelName) > 0) { if (Receive(parts, fGeneratorChannelName) > 0) { - return TransportData(parts,0); + return TransportData(parts, 0); } } return false; @@ -225,19 +223,19 @@ bool FairMQTransportDevice::ConditionalRun() bool FairMQTransportDevice::TransportData(FairMQParts& mParts, int /*index*/) { - TClonesArray* chunk = nullptr; + TClonesArray* chunk = nullptr; FairMCSplitEventHeader* meh = nullptr; - for (int ipart = 0 ; ipart < mParts.Size() ; ipart++) { + for (int ipart = 0; ipart < mParts.Size(); ipart++) { TObject* obj = nullptr; - Deserialize(*mParts.At(ipart),obj); - if (strcmp(obj->GetName(),"MCEvent") == 0) + Deserialize(*mParts.At(ipart), obj); + if (strcmp(obj->GetName(), "MCEvent") == 0) meh = dynamic_cast(obj); - else if (strcmp(obj->GetName(),"TParticles") == 0) + else if (strcmp(obj->GetName(), "TParticles") == 0) chunk = dynamic_cast(obj); } if (chunk != nullptr) { - fStack->SetParticleArray(chunk,meh->GetChunkStart(),meh->GetNPrim()); - fMCSplitEventHeader->SetRECC(fRunId,meh->GetEventID(),meh->GetNofChunks(),meh->GetChunkStart()); + fStack->SetParticleArray(chunk, meh->GetChunkStart(), meh->GetNPrim()); + fMCSplitEventHeader->SetRECC(fRunId, meh->GetEventID(), meh->GetNofChunks(), meh->GetChunkStart()); fVMC->ProcessRun(1); } @@ -248,24 +246,22 @@ void FairMQTransportDevice::UpdateParameterServer() { FairRuntimeDb* rtdb = fRunSim->GetRuntimeDb(); - LOG(info) << "FairMQTransportDevice::UpdateParameterServer() (" << rtdb->getListOfContainers()->GetEntries() << " containers)"; + LOG(info) << "FairMQTransportDevice::UpdateParameterServer() (" << rtdb->getListOfContainers()->GetEntries() + << " containers)"; // send the parameters to be saved TIter next(rtdb->getListOfContainers()); FairParSet* cont; - while ((cont=static_cast(next()))) { - std::string ridString = std::string("RUNID") + std::to_string(fRunSim->GetRunId()) + std::string("RUNID") + std::string(cont->getDescription()); + while ((cont = static_cast(next()))) { + std::string ridString = std::string("RUNID") + std::to_string(fRunSim->GetRunId()) + std::string("RUNID") + + std::string(cont->getDescription()); cont->setDescription(ridString.data()); - SendObject(cont,fUpdateChannelName); + SendObject(cont, fUpdateChannelName); } LOG(info) << "FairMQTransportDevice::UpdateParameterServer() finished"; } -void FairMQTransportDevice::PostRun() -{ -} +void FairMQTransportDevice::PostRun() {} -FairMQTransportDevice::~FairMQTransportDevice() -{ -} +FairMQTransportDevice::~FairMQTransportDevice() {} diff --git a/examples/MQ/pixelSimSplit/src/devices/FairMQTransportDevice.h b/examples/MQ/pixelSimSplit/src/devices/FairMQTransportDevice.h index edf35535a2..07897a12fc 100644 --- a/examples/MQ/pixelSimSplit/src/devices/FairMQTransportDevice.h +++ b/examples/MQ/pixelSimSplit/src/devices/FairMQTransportDevice.h @@ -18,11 +18,10 @@ #include "FairMQRunDevice.h" -#include #include - -#include +#include #include +#include class FairMCSplitEventHeader; class FairRunSim; @@ -41,24 +40,24 @@ class FairMQTransportDevice : public FairMQRunDevice virtual ~FairMQTransportDevice(); // ------ FairRunSim setters ------ - void SetNofEvents (int64_t nofev) { fNofEvents = nofev;}; - void SetTransportName (const std::string& str) { fTransportName = str;}; - void SetMaterials (const std::string& str) { fMaterialsFile = str;}; - void SetMagneticField (FairField* field) { fMagneticField = field;}; - void SetDetectorArray (TObjArray* array) { fDetectorArray = array;}; - void SetStoreTraj (bool flag=true) { fStoreTrajFlag = flag;}; - void SetTaskArray (TObjArray* array) { fTaskArray = array;}; - void SetFirstParameter (FairParIo* par) { fFirstParameter = par;}; - void SetSecondParameter (FairParIo* par) { fSecondParameter = par;}; - void SetUserConfig (const TString& Config) { fUserConfig = Config;} - void SetUserCuts (const TString& Cuts) { fUserCuts = Cuts;} - void SetSink (FairSink* sink) { fSink = sink;} + void SetNofEvents(int64_t nofev) { fNofEvents = nofev; }; + void SetTransportName(const std::string& str) { fTransportName = str; }; + void SetMaterials(const std::string& str) { fMaterialsFile = str; }; + void SetMagneticField(FairField* field) { fMagneticField = field; }; + void SetDetectorArray(TObjArray* array) { fDetectorArray = array; }; + void SetStoreTraj(bool flag = true) { fStoreTrajFlag = flag; }; + void SetTaskArray(TObjArray* array) { fTaskArray = array; }; + void SetFirstParameter(FairParIo* par) { fFirstParameter = par; }; + void SetSecondParameter(FairParIo* par) { fSecondParameter = par; }; + void SetUserConfig(const TString& Config) { fUserConfig = Config; } + void SetUserCuts(const TString& Cuts) { fUserCuts = Cuts; } + void SetSink(FairSink* sink) { fSink = sink; } // ------ ---------- -------- ------ void SetParamUpdateChannelName(TString tString) { fUpdateChannelName = tString; } - void RunInPullMode(bool tb=true) { fRunConditional = !tb; }; - void RunInReqMode (bool tb=true) { fRunConditional = tb; }; + void RunInPullMode(bool tb = true) { fRunConditional = !tb; }; + void RunInReqMode(bool tb = true) { fRunConditional = tb; }; protected: bool TransportData(FairMQParts&, int); @@ -75,25 +74,25 @@ class FairMQTransportDevice : public FairMQRunDevice std::string fGeneratorChannelName; std::string fUpdateChannelName; - bool fRunConditional; // if true run ConditionalRun, if false run TransportData + bool fRunConditional; // if true run ConditionalRun, if false run TransportData - TVirtualMC* fVMC; - FairGenericStack* fStack; - FairMCApplication* fMCApplication; - FairRunSim* fRunSim; + TVirtualMC* fVMC; + FairGenericStack* fStack; + FairMCApplication* fMCApplication; + FairRunSim* fRunSim; // ------ FairRunSim settings ------ - int64_t fNofEvents; - std::string fTransportName; - std::string fMaterialsFile; - FairField* fMagneticField; - TObjArray* fDetectorArray; - bool fStoreTrajFlag; - TObjArray* fTaskArray; - FairParIo* fFirstParameter; // first (prefered) input for parameters - FairParIo* fSecondParameter; // second input (used if not found in first input) - TString fUserConfig; //! /** Macro for geant configuration*/ - TString fUserCuts; //! /** Macro for geant cuts*/ - FairSink* fSink; + int64_t fNofEvents; + std::string fTransportName; + std::string fMaterialsFile; + FairField* fMagneticField; + TObjArray* fDetectorArray; + bool fStoreTrajFlag; + TObjArray* fTaskArray; + FairParIo* fFirstParameter; // first (prefered) input for parameters + FairParIo* fSecondParameter; // second input (used if not found in first input) + TString fUserConfig; //! /** Macro for geant configuration*/ + TString fUserCuts; //! /** Macro for geant cuts*/ + FairSink* fSink; // ------ ---------- -------- ------ FairMCSplitEventHeader* fMCSplitEventHeader; diff --git a/examples/MQ/serialization/1-simple/Ex1Processor.h b/examples/MQ/serialization/1-simple/Ex1Processor.h index b35e9f83e3..6945723cde 100644 --- a/examples/MQ/serialization/1-simple/Ex1Processor.h +++ b/examples/MQ/serialization/1-simple/Ex1Processor.h @@ -3,14 +3,11 @@ #include "MyDigi.h" #include "MyHit.h" - #include "RootSerializer.h" #include - #include #include - #include class Ex1Processor : public FairMQDevice @@ -23,27 +20,20 @@ class Ex1Processor : public FairMQDevice Ex1Processor(const Ex1Processor&); Ex1Processor& operator=(const Ex1Processor&); - virtual ~Ex1Processor() - { - } + virtual ~Ex1Processor() {} protected: - virtual void Init() - { - fNumMsgs = fConfig->GetValue("num-msgs"); - } + virtual void Init() { fNumMsgs = fConfig->GetValue("num-msgs"); } virtual void Run() { int receivedMsgs = 0; int sentMsgs = 0; - while (!NewStatePending()) - { + while (!NewStatePending()) { /// RECEIVE /// FairMQMessagePtr msgIn(NewMessageFor("data1", 0)); - if (Receive(msgIn, "data1") > 0) - { + if (Receive(msgIn, "data1") > 0) { receivedMsgs++; /// DESERIALIZE /// @@ -61,10 +51,8 @@ class Ex1Processor : public FairMQDevice Send(msgOut, "data2"); sentMsgs++; - if (fNumMsgs != 0) - { - if (receivedMsgs == fNumMsgs) - { + if (fNumMsgs != 0) { + if (receivedMsgs == fNumMsgs) { break; } } @@ -78,8 +66,7 @@ class Ex1Processor : public FairMQDevice { TClonesArray hits("MyHit"); - for (int i = 0; i < digis.GetEntriesFast(); i++) - { + for (int i = 0; i < digis.GetEntriesFast(); i++) { TVector3 pos; TVector3 dpos; // Double_t timestamp = 0; @@ -101,4 +88,4 @@ class Ex1Processor : public FairMQDevice int fNumMsgs; }; -#endif // EX1PROCESSOR_H +#endif // EX1PROCESSOR_H diff --git a/examples/MQ/serialization/1-simple/Ex1Sampler.h b/examples/MQ/serialization/1-simple/Ex1Sampler.h index f8083d7f1c..3a1499460a 100644 --- a/examples/MQ/serialization/1-simple/Ex1Sampler.h +++ b/examples/MQ/serialization/1-simple/Ex1Sampler.h @@ -2,13 +2,11 @@ #define EX1SAMPLER_H #include "MyDigi.h" - #include "RootSerializer.h" #include - -#include #include +#include #include #include @@ -27,8 +25,7 @@ class Ex1Sampler : public FairMQDevice virtual ~Ex1Sampler() { - if (fInputFile) - { + if (fInputFile) { fInputFile->Close(); delete fInputFile; } @@ -39,20 +36,14 @@ class Ex1Sampler : public FairMQDevice { fFileName = fConfig->GetValue("input-file"); fInputFile = TFile::Open(fFileName.c_str(), "READ"); - if (fInputFile) - { + if (fInputFile) { fTree = static_cast(fInputFile->Get("cbmsim")); - if (fTree) - { + if (fTree) { fTree->SetBranchAddress("MyDigi", &fInput); - } - else - { + } else { LOG(error) << "Could not find tree 'MyDigi'"; } - } - else - { + } else { LOG(error) << "Could not open file " << fFileName << " in SimpleTreeReader::InitSource()"; } } @@ -63,15 +54,13 @@ class Ex1Sampler : public FairMQDevice const uint64_t numEvents = fTree->GetEntries(); LOG(info) << "Number of events to process: " << numEvents; - for (uint64_t i = 0; i < numEvents; i++) - { + for (uint64_t i = 0; i < numEvents; i++) { FairMQMessagePtr msg(NewMessage()); fTree->GetEntry(i); Serialize(*msg, fInput); Send(msg, "data1"); sentMsgs++; - if (NewStatePending()) - { + if (NewStatePending()) { break; } } @@ -86,4 +75,4 @@ class Ex1Sampler : public FairMQDevice TFile* fInputFile; }; -#endif // EX1SAMPLER_H +#endif // EX1SAMPLER_H diff --git a/examples/MQ/serialization/1-simple/Ex1Sink.h b/examples/MQ/serialization/1-simple/Ex1Sink.h index a8a0b94075..85e899fbb5 100644 --- a/examples/MQ/serialization/1-simple/Ex1Sink.h +++ b/examples/MQ/serialization/1-simple/Ex1Sink.h @@ -1,15 +1,14 @@ #ifndef EX1SINK_H #define EX1SINK_H -#include +#include "MyHit.h" #include "RootSerializer.h" +#include #include #include #include -#include "MyHit.h" - class Ex1Sink : public FairMQDevice { public: @@ -26,16 +25,13 @@ class Ex1Sink : public FairMQDevice virtual ~Ex1Sink() { - if (fTree) - { + if (fTree) { fTree->Write("", TObject::kOverwrite); delete fTree; } - if (fOutFile) - { - if (fOutFile->IsOpen()) - { + if (fOutFile) { + if (fOutFile->IsOpen()) { fOutFile->Close(); } delete fOutFile; @@ -47,29 +43,25 @@ class Ex1Sink : public FairMQDevice { fNumMsgs = fConfig->GetValue("num-msgs"); fFileName = fConfig->GetValue("output-file"); - fOutFile = TFile::Open(fFileName.c_str(),"RECREATE"); + fOutFile = TFile::Open(fFileName.c_str(), "RECREATE"); fInput = new TClonesArray("MyHit"); fTree = new TTree("SerializationEx1", "Test output"); - fTree->Branch("MyHit","TClonesArray", &fInput); + fTree->Branch("MyHit", "TClonesArray", &fInput); } virtual void Run() { int receivedMsgs = 0; - while (!NewStatePending()) - { + while (!NewStatePending()) { FairMQMessagePtr msg(NewMessage()); - if (Receive(msg, "data2") > 0) - { + if (Receive(msg, "data2") > 0) { Deserialize(*msg, fInput); receivedMsgs++; fTree->SetBranchAddress("MyHit", &fInput); fTree->Fill(); - if (fNumMsgs != 0) - { - if (receivedMsgs == fNumMsgs) - { + if (fNumMsgs != 0) { + if (receivedMsgs == fNumMsgs) { break; } } @@ -86,4 +78,4 @@ class Ex1Sink : public FairMQDevice int fNumMsgs; }; -#endif // EX1SINK_H +#endif // EX1SINK_H diff --git a/examples/MQ/serialization/1-simple/runEx1Processor.cxx b/examples/MQ/serialization/1-simple/runEx1Processor.cxx index b8808403f8..aae9a381ce 100644 --- a/examples/MQ/serialization/1-simple/runEx1Processor.cxx +++ b/examples/MQ/serialization/1-simple/runEx1Processor.cxx @@ -6,18 +6,17 @@ * copied verbatim in the file "LICENSE" * ********************************************************************************/ -#include "runFairMQDevice.h" #include "Ex1Processor.h" +#include "runFairMQDevice.h" namespace bpo = boost::program_options; void addCustomOptions(bpo::options_description& options) { + // clang-format off options.add_options() ("num-msgs", bpo::value()->default_value(0), "Stop after msgs (0 - no limit)."); + // clang-format on } -FairMQDevicePtr getDevice(const FairMQProgOptions& /*config*/) -{ - return new Ex1Processor(); -} +FairMQDevicePtr getDevice(const FairMQProgOptions& /*config*/) { return new Ex1Processor(); } diff --git a/examples/MQ/serialization/1-simple/runEx1Sampler.cxx b/examples/MQ/serialization/1-simple/runEx1Sampler.cxx index a078a45749..2385721f12 100644 --- a/examples/MQ/serialization/1-simple/runEx1Sampler.cxx +++ b/examples/MQ/serialization/1-simple/runEx1Sampler.cxx @@ -12,18 +12,17 @@ * Created on January 15, 2015, 1:57 PM */ -#include "runFairMQDevice.h" #include "Ex1Sampler.h" +#include "runFairMQDevice.h" namespace bpo = boost::program_options; void addCustomOptions(bpo::options_description& options) { + // clang-format off options.add_options() ("input-file", bpo::value(), "Path to the input file"); + // clang-format on } -FairMQDevicePtr getDevice(const FairMQProgOptions& /*config*/) -{ - return new Ex1Sampler(); -} +FairMQDevicePtr getDevice(const FairMQProgOptions& /*config*/) { return new Ex1Sampler(); } diff --git a/examples/MQ/serialization/1-simple/runEx1Sink.cxx b/examples/MQ/serialization/1-simple/runEx1Sink.cxx index d36001dd87..02d970d07b 100644 --- a/examples/MQ/serialization/1-simple/runEx1Sink.cxx +++ b/examples/MQ/serialization/1-simple/runEx1Sink.cxx @@ -6,19 +6,18 @@ * copied verbatim in the file "LICENSE" * ********************************************************************************/ -#include "runFairMQDevice.h" #include "Ex1Sink.h" +#include "runFairMQDevice.h" namespace bpo = boost::program_options; void addCustomOptions(bpo::options_description& options) { + // clang-format off options.add_options() - ("output-file", bpo::value(), "Path to the output file") - ("num-msgs", bpo::value()->default_value(0), "Stop after msgs (0 - no limit)."); + ("output-file", bpo::value(), "Path to the output file") + ("num-msgs", bpo::value()->default_value(0), "Stop after msgs (0 - no limit)."); + // clang-format on } -FairMQDevicePtr getDevice(const FairMQProgOptions& /*config*/) -{ - return new Ex1Sink(); -} +FairMQDevicePtr getDevice(const FairMQProgOptions& /*config*/) { return new Ex1Sink(); } diff --git a/examples/MQ/serialization/2-multipart/Ex2Processor.h b/examples/MQ/serialization/2-multipart/Ex2Processor.h index 731227b886..cd97877fab 100644 --- a/examples/MQ/serialization/2-multipart/Ex2Processor.h +++ b/examples/MQ/serialization/2-multipart/Ex2Processor.h @@ -1,16 +1,14 @@ #ifndef EX2PROCESSOR_H #define EX2PROCESSOR_H -#include "SerializerExample2.h" +#include "BoostSerializer.h" #include "MyDigi.h" #include "MyHit.h" - #include "RootSerializer.h" -#include "BoostSerializer.h" +#include "SerializerExample2.h" #include #include - #include class Ex2Processor : public FairMQDevice @@ -39,12 +37,10 @@ class Ex2Processor : public FairMQDevice int receivedMsgs = 0; int sentMsgs = 0; - while (!NewStatePending()) - { + while (!NewStatePending()) { FairMQParts partsIn; - if (Receive(partsIn, "data1") > 0) - { + if (Receive(partsIn, "data1") > 0) { Ex2Header* header = nullptr; Deserialize(*(partsIn.At(0)), header); Deserialize(*(partsIn.At(1)), fInput); @@ -62,10 +58,8 @@ class Ex2Processor : public FairMQDevice Send(partsOut, "data2"); sentMsgs++; - if (fNumMsgs != 0) - { - if (receivedMsgs == fNumMsgs) - { + if (fNumMsgs != 0) { + if (receivedMsgs == fNumMsgs) { break; } } @@ -78,8 +72,7 @@ class Ex2Processor : public FairMQDevice void Exec(TClonesArray* digis, TClonesArray* hits) { hits->Delete(); - for (int idigi(0); idigiGetEntriesFast(); idigi++) - { + for (int idigi(0); idigi < digis->GetEntriesFast(); idigi++) { TVector3 pos; TVector3 dpos; // Double_t timestamp = 0; diff --git a/examples/MQ/serialization/2-multipart/Ex2Sampler.h b/examples/MQ/serialization/2-multipart/Ex2Sampler.h index f743f465bb..ff3de85077 100644 --- a/examples/MQ/serialization/2-multipart/Ex2Sampler.h +++ b/examples/MQ/serialization/2-multipart/Ex2Sampler.h @@ -2,27 +2,24 @@ #define EX2SAMPLER_H #include "MyDigi.h" -#include "SerializerExample2.h" - #include "RootSerializer.h" +#include "SerializerExample2.h" #include - #include #include #include - #include class Ex2Sampler : public FairMQDevice { public: - Ex2Sampler() : - FairMQDevice(), - fInput(nullptr), - fTree(nullptr), - fFileName(), - fInputFile(nullptr) + Ex2Sampler() + : FairMQDevice() + , fInput(nullptr) + , fTree(nullptr) + , fFileName() + , fInputFile(nullptr) {} Ex2Sampler(const Ex2Sampler&); @@ -30,8 +27,7 @@ class Ex2Sampler : public FairMQDevice virtual ~Ex2Sampler() { - if (fInputFile) - { + if (fInputFile) { fInputFile->Close(); delete fInputFile; } @@ -42,20 +38,14 @@ class Ex2Sampler : public FairMQDevice { fFileName = fConfig->GetValue("input-file"); fInputFile = TFile::Open(fFileName.c_str(), "READ"); - if (fInputFile) - { + if (fInputFile) { fTree = static_cast(fInputFile->Get("cbmsim")); - if (fTree) - { + if (fTree) { fTree->SetBranchAddress("MyDigi", &fInput); - } - else - { + } else { LOG(error) << "Could not find tree 'MyDigi'"; } - } - else - { + } else { LOG(error) << "Could not open file " << fFileName << " in SimpleTreeReader::InitSource()"; } } @@ -68,8 +58,7 @@ class Ex2Sampler : public FairMQDevice auto tStart = std::chrono::high_resolution_clock::now(); - for (int64_t idx = 0; idx < numEvents; idx++) - { + for (int64_t idx = 0; idx < numEvents; idx++) { fTree->GetEntry(idx); Ex2Header* header = new Ex2Header(); header->EventNumber = idx; @@ -84,19 +73,18 @@ class Ex2Sampler : public FairMQDevice parts.AddPart(std::move(msgHeader)); parts.AddPart(std::move(msg)); - if (Send(parts,"data1") > 0) - { + if (Send(parts, "data1") > 0) { sentMsgs++; } - if (NewStatePending()) - { + if (NewStatePending()) { break; } } auto tEnd = std::chrono::high_resolution_clock::now(); - LOG(info) << "Sent " << sentMsgs << " messages in: " << std::chrono::duration(tEnd - tStart).count() << " ms"; + LOG(info) << "Sent " << sentMsgs + << " messages in: " << std::chrono::duration(tEnd - tStart).count() << " ms"; } private: diff --git a/examples/MQ/serialization/2-multipart/Ex2Sink.h b/examples/MQ/serialization/2-multipart/Ex2Sink.h index d024847a94..31200d7911 100644 --- a/examples/MQ/serialization/2-multipart/Ex2Sink.h +++ b/examples/MQ/serialization/2-multipart/Ex2Sink.h @@ -1,26 +1,24 @@ #ifndef EX2SINK_H #define EX2SINK_H +#include "BoostSerializer.h" #include "MyHit.h" #include "SerializerExample2.h" -#include "BoostSerializer.h" - #include - #include #include class Ex2Sink : public FairMQDevice { public: - Ex2Sink() : - FairMQDevice(), - fInput(nullptr), - fFileName(), - fOutFile(nullptr), - fTree(nullptr), - fNumMsgs(0) + Ex2Sink() + : FairMQDevice() + , fInput(nullptr) + , fFileName() + , fOutFile(nullptr) + , fTree(nullptr) + , fNumMsgs(0) {} Ex2Sink(const Ex2Sink&); @@ -28,17 +26,14 @@ class Ex2Sink : public FairMQDevice virtual ~Ex2Sink() { - if (fTree) - { + if (fTree) { fTree->Write("", TObject::kOverwrite); delete fTree; } - if (fOutFile) - { - if (fOutFile->IsOpen()) - { + if (fOutFile) { + if (fOutFile->IsOpen()) { fOutFile->Close(); } delete fOutFile; @@ -59,11 +54,9 @@ class Ex2Sink : public FairMQDevice virtual void Run() { int receivedMsgs = 0; - while (!NewStatePending()) - { + while (!NewStatePending()) { FairMQParts parts; - if (Receive(parts, "data2") > 0) - { + if (Receive(parts, "data2") > 0) { Ex2Header header; Deserialize>(*(parts.At(0)), header); Deserialize>(*(parts.At(1)), fInput); @@ -72,10 +65,8 @@ class Ex2Sink : public FairMQDevice fTree->SetBranchAddress("MyHit", &fInput); fTree->Fill(); - if (fNumMsgs != 0) - { - if (receivedMsgs == fNumMsgs) - { + if (fNumMsgs != 0) { + if (receivedMsgs == fNumMsgs) { break; } } diff --git a/examples/MQ/serialization/2-multipart/SerializerExample2.h b/examples/MQ/serialization/2-multipart/SerializerExample2.h index 06feb8e0fe..db70fd5589 100644 --- a/examples/MQ/serialization/2-multipart/SerializerExample2.h +++ b/examples/MQ/serialization/2-multipart/SerializerExample2.h @@ -3,7 +3,11 @@ #include -namespace boost { namespace serialization { class access; } } +namespace boost { +namespace serialization { +class access; +} +} // namespace boost struct Ex2Header { @@ -21,23 +25,17 @@ void serialize(Archive& ar, Ex2Header& header, const unsigned int /*version*/) ar& header.DetectorId; } -} // namespace serialization -} // namespace boost +} // namespace serialization +} // namespace boost struct SerializerEx2 { void Serialize(FairMQMessage& msg, Ex2Header* header) { - msg.Rebuild(header, - sizeof(header), - [](void* ptr, void* /*hint*/) { delete static_cast(ptr); } - ); + msg.Rebuild(header, sizeof(header), [](void* ptr, void* /*hint*/) { delete static_cast(ptr); }); } - void Deserialize(FairMQMessage& msg, Ex2Header*& header) - { - header = static_cast(msg.GetData()); - } + void Deserialize(FairMQMessage& msg, Ex2Header*& header) { header = static_cast(msg.GetData()); } }; #endif diff --git a/examples/MQ/serialization/2-multipart/runEx2Processor.cxx b/examples/MQ/serialization/2-multipart/runEx2Processor.cxx index feaab9dd7e..481467282c 100644 --- a/examples/MQ/serialization/2-multipart/runEx2Processor.cxx +++ b/examples/MQ/serialization/2-multipart/runEx2Processor.cxx @@ -6,18 +6,17 @@ * copied verbatim in the file "LICENSE" * ********************************************************************************/ -#include "runFairMQDevice.h" #include "Ex2Processor.h" +#include "runFairMQDevice.h" namespace bpo = boost::program_options; void addCustomOptions(bpo::options_description& options) { + // clang-format off options.add_options() ("num-msgs", bpo::value()->default_value(0), "Stop after msgs (0 - no limit)."); + // clang-format on } -FairMQDevicePtr getDevice(const FairMQProgOptions& /*config*/) -{ - return new Ex2Processor(); -} +FairMQDevicePtr getDevice(const FairMQProgOptions& /*config*/) { return new Ex2Processor(); } diff --git a/examples/MQ/serialization/2-multipart/runEx2Sampler.cxx b/examples/MQ/serialization/2-multipart/runEx2Sampler.cxx index 373795dd56..af84f30d17 100644 --- a/examples/MQ/serialization/2-multipart/runEx2Sampler.cxx +++ b/examples/MQ/serialization/2-multipart/runEx2Sampler.cxx @@ -12,18 +12,17 @@ * Created on January 15, 2015, 1:57 PM */ -#include "runFairMQDevice.h" #include "Ex2Sampler.h" +#include "runFairMQDevice.h" namespace bpo = boost::program_options; void addCustomOptions(bpo::options_description& options) { + // clang-format off options.add_options() ("input-file", bpo::value(), "Path to the input file"); + // clang-format on } -FairMQDevicePtr getDevice(const FairMQProgOptions& /*config*/) -{ - return new Ex2Sampler(); -} +FairMQDevicePtr getDevice(const FairMQProgOptions& /*config*/) { return new Ex2Sampler(); } diff --git a/examples/MQ/serialization/2-multipart/runEx2Sink.cxx b/examples/MQ/serialization/2-multipart/runEx2Sink.cxx index 762ab7312c..b3cd10aea3 100644 --- a/examples/MQ/serialization/2-multipart/runEx2Sink.cxx +++ b/examples/MQ/serialization/2-multipart/runEx2Sink.cxx @@ -6,19 +6,18 @@ * copied verbatim in the file "LICENSE" * ********************************************************************************/ -#include "runFairMQDevice.h" #include "Ex2Sink.h" +#include "runFairMQDevice.h" namespace bpo = boost::program_options; void addCustomOptions(bpo::options_description& options) { + // clang-format off options.add_options() - ("output-file", bpo::value(), "Path to the output file") - ("num-msgs", bpo::value()->default_value(0), "Stop after msgs (0 - no limit)."); + ("output-file", bpo::value(), "Path to the output file") + ("num-msgs", bpo::value()->default_value(0), "Stop after msgs (0 - no limit)."); + // clang-format on } -FairMQDevicePtr getDevice(const FairMQProgOptions& /*config*/) -{ - return new Ex2Sink(); -} +FairMQDevicePtr getDevice(const FairMQProgOptions& /*config*/) { return new Ex2Sink(); } diff --git a/examples/MQ/serialization/data/MyDigi.cxx b/examples/MQ/serialization/data/MyDigi.cxx index 77e4e4bfc9..6ff54fd42e 100644 --- a/examples/MQ/serialization/data/MyDigi.cxx +++ b/examples/MQ/serialization/data/MyDigi.cxx @@ -30,5 +30,4 @@ MyDigi::MyDigi(Int_t x, Int_t y, Int_t z, Double_t timeStamp, Double_t timeStamp , fZ(z) {} -MyDigi::~MyDigi() -{} +MyDigi::~MyDigi() {} diff --git a/examples/MQ/serialization/data/MyDigi.h b/examples/MQ/serialization/data/MyDigi.h index f8ea7dd1e4..964fc30cea 100644 --- a/examples/MQ/serialization/data/MyDigi.h +++ b/examples/MQ/serialization/data/MyDigi.h @@ -14,23 +14,26 @@ */ #ifndef MYDIGIDATA_H -#define MYDIGIDATA_H +#define MYDIGIDATA_H -#include "FairTimeStamp.h" // for FairTimeStamp +#include "FairTimeStamp.h" // for FairTimeStamp -#include // for ostream -#include // for Int_t, etc +#include // for Int_t, etc +#include // for ostream +#include // for operator<<, basic_ostream, etc -#include // for operator<<, basic_ostream, etc - -namespace boost { namespace serialization { class access; } } +namespace boost { +namespace serialization { +class access; +} +} // namespace boost #include class MyDigi : public FairTimeStamp { public: MyDigi(); - MyDigi(Int_t x, Int_t y, Int_t z, Double_t timeStamp, Double_t timeStampError=0.0); + MyDigi(Int_t x, Int_t y, Int_t z, Double_t timeStamp, Double_t timeStampError = 0.0); virtual ~MyDigi(); void SetXYZ(Int_t x, Int_t y, Int_t z) @@ -39,42 +42,22 @@ class MyDigi : public FairTimeStamp SetY(y); SetZ(z); } - void SetX(Int_t x) - { - fX = x; - } - void SetY(Int_t y) - { - fY = y; - } - void SetZ(Int_t z) - { - fZ = z; - } + void SetX(Int_t x) { fX = x; } + void SetY(Int_t y) { fY = y; } + void SetZ(Int_t z) { fZ = z; } - Int_t GetX() const - { - return fX; - } - Int_t GetY() const - { - return fY; - } - Int_t GetZ() const - { - return fZ; - } + Int_t GetX() const { return fX; } + Int_t GetY() const { return fY; } + Int_t GetZ() const { return fZ; } // temporary to avoid serialisation of the parent class virtual bool equal(FairTimeStamp* data) { MyDigi* myDigi = dynamic_cast(data); - if (myDigi != 0) - { + if (myDigi != 0) { if (fX == myDigi->GetX()) if (fY == myDigi->GetY()) - if (fZ == myDigi->GetZ()) - { + if (fZ == myDigi->GetZ()) { return true; } } @@ -83,28 +66,19 @@ class MyDigi : public FairTimeStamp virtual bool operator<(const MyDigi& myDigi) const { - if (fX < myDigi.GetX()) - { + if (fX < myDigi.GetX()) { return true; - } - else if (fX > myDigi.GetX()) - { + } else if (fX > myDigi.GetX()) { return false; } - if (fY < myDigi.GetY()) - { + if (fY < myDigi.GetY()) { return true; - } - else if (fY > myDigi.GetY()) - { + } else if (fY > myDigi.GetY()) { return false; } - if (fZ < myDigi.GetZ()) - { + if (fZ < myDigi.GetZ()) { return true; - } - else if (fZ > myDigi.GetZ()) - { + } else if (fZ > myDigi.GetZ()) { return false; } return false; @@ -118,7 +92,7 @@ class MyDigi : public FairTimeStamp return out; } - template + template void serialize(Archive& ar, const unsigned int /*version*/) { ar& boost::serialization::base_object(*this); @@ -137,5 +111,4 @@ class MyDigi : public FairTimeStamp ClassDef(MyDigi, 1); }; -#endif /* MYDIGIDATA_H */ - +#endif /* MYDIGIDATA_H */ diff --git a/examples/MQ/serialization/data/MyHit.cxx b/examples/MQ/serialization/data/MyHit.cxx index 78aa92d8c9..434d41d63d 100644 --- a/examples/MQ/serialization/data/MyHit.cxx +++ b/examples/MQ/serialization/data/MyHit.cxx @@ -9,32 +9,32 @@ /* * File: MyHit.cxx * Author: winckler - * + * * Created on November 24, 2014, 1:40 PM */ #include "MyHit.h" -#include "MyHit.h" MyHit::MyHit() : FairHit() -{ -} +{} MyHit::MyHit(Int_t detID, Int_t mcindex, const TVector3& pos, const TVector3& dpos) : FairHit(detID, pos, dpos, mcindex) -{ -} +{} -MyHit::MyHit(Int_t detID, Int_t mcindex, const TVector3& pos, const TVector3& dpos, Double_t timeStamp, Double_t timeStampError) - : FairHit(detID, pos, dpos, mcindex)// +MyHit::MyHit(Int_t detID, + Int_t mcindex, + const TVector3& pos, + const TVector3& dpos, + Double_t timeStamp, + Double_t timeStampError) + : FairHit(detID, pos, dpos, mcindex) // { - SetTimeStamp(timeStamp); - SetTimeStampError(timeStampError); + SetTimeStamp(timeStamp); + SetTimeStampError(timeStampError); } -MyHit::~MyHit() -{ -} +MyHit::~MyHit() {} -ClassImp(MyHit) +ClassImp(MyHit); diff --git a/examples/MQ/serialization/data/MyHit.h b/examples/MQ/serialization/data/MyHit.h index 914e3c793d..4de1a62524 100644 --- a/examples/MQ/serialization/data/MyHit.h +++ b/examples/MQ/serialization/data/MyHit.h @@ -14,13 +14,17 @@ */ #ifndef MYHITDATA_H -#define MYHITDATA_H +#define MYHITDATA_H -#include "FairHit.h" // for FairHit +#include "FairHit.h" // for FairHit -#include // for MyHit::Class, etc +#include // for MyHit::Class, etc -namespace boost { namespace serialization { class access; } } +namespace boost { +namespace serialization { +class access; +} +} // namespace boost #include class TVector3; @@ -33,12 +37,17 @@ class MyHit : public FairHit /** Constructor **/ MyHit(Int_t detID, Int_t mcindex, const TVector3& pos, const TVector3& dpos); - MyHit(Int_t detID, Int_t mcindex, const TVector3& pos, const TVector3& dpos, Double_t timeStamp, Double_t timeStampError); + MyHit(Int_t detID, + Int_t mcindex, + const TVector3& pos, + const TVector3& dpos, + Double_t timeStamp, + Double_t timeStampError); /** Destructor **/ virtual ~MyHit(); - template + template void serialize(Archive& ar, const unsigned int /*version*/) { ar& boost::serialization::base_object(*this); @@ -50,6 +59,4 @@ class MyHit : public FairHit ClassDef(MyHit, 1); }; - -#endif /* MYHITDATA_H */ - +#endif /* MYHITDATA_H */ diff --git a/examples/MQ/serialization/data/MyPodData.cxx b/examples/MQ/serialization/data/MyPodData.cxx index a425d879a2..57b2a7a12c 100644 --- a/examples/MQ/serialization/data/MyPodData.cxx +++ b/examples/MQ/serialization/data/MyPodData.cxx @@ -9,7 +9,7 @@ /* * File: MyPodData.cxx * Author: winckler - * + * * Created on November 24, 2014, 1:46 PM */ diff --git a/examples/MQ/serialization/data/MyPodData.h b/examples/MQ/serialization/data/MyPodData.h index 97248a0b81..70bf3a38f6 100644 --- a/examples/MQ/serialization/data/MyPodData.h +++ b/examples/MQ/serialization/data/MyPodData.h @@ -14,84 +14,84 @@ */ #ifndef MYPODDATA_H -#define MYPODDATA_H +#define MYPODDATA_H // for root types -#include -#include +#include +#include -namespace boost { namespace serialization { class access; } } +namespace boost { +namespace serialization { +class access; +} +} // namespace boost #include -namespace MyPodData +namespace MyPodData { + +class TimeStamp { + public: + Double_t fTimeStamp; + Double_t fTimeStampError; - class TimeStamp + // method to use boost serialization + template + void serialize(Archive& ar, const unsigned int /*version*/) { - public: - Double_t fTimeStamp; - Double_t fTimeStampError; - - // method to use boost serialization - template - void serialize(Archive & ar, const unsigned int /*version*/) - { - ar & fTimeStamp; - ar & fTimeStampError; - } - friend class boost::serialization::access; - - }; + ar& fTimeStamp; + ar& fTimeStampError; + } + friend class boost::serialization::access; +}; - class Digi : public TimeStamp - { - public: - Int_t fX; - Int_t fY; - Int_t fZ; - - // method to use boost serialization - template - void serialize(Archive & ar, const unsigned int /*version*/) - { - ar & boost::serialization::base_object(*this); - ar & fX; - ar & fY; - ar & fZ; - } - friend class boost::serialization::access; - - }; +class Digi : public TimeStamp +{ + public: + Int_t fX; + Int_t fY; + Int_t fZ; - class Hit : public TimeStamp + // method to use boost serialization + template + void serialize(Archive& ar, const unsigned int /*version*/) { - public: - Int_t detID; - Int_t mcindex; - Double_t posX; - Double_t posY; - Double_t posZ; - Double_t dposX; - Double_t dposY; - Double_t dposZ; - - // method to use boost serialization - template - void serialize(Archive & ar, const unsigned int /*version*/) - { - ar & boost::serialization::base_object(*this); - ar & detID; - ar & mcindex; - ar & posX; - ar & posY; - ar & posZ; - ar & dposX; - ar & dposY; - ar & dposZ; - } - friend class boost::serialization::access; - }; -} + ar& boost::serialization::base_object(*this); + ar& fX; + ar& fY; + ar& fZ; + } + friend class boost::serialization::access; +}; + +class Hit : public TimeStamp +{ + public: + Int_t detID; + Int_t mcindex; + Double_t posX; + Double_t posY; + Double_t posZ; + Double_t dposX; + Double_t dposY; + Double_t dposZ; -#endif /* MYPODDATA_H */ + // method to use boost serialization + template + void serialize(Archive& ar, const unsigned int /*version*/) + { + ar& boost::serialization::base_object(*this); + ar& detID; + ar& mcindex; + ar& posX; + ar& posY; + ar& posZ; + ar& dposX; + ar& dposY; + ar& dposZ; + } + friend class boost::serialization::access; +}; +} // namespace MyPodData +#endif /* MYPODDATA_H */ diff --git a/examples/MQ/serialization/data_generator/RooDataGenerator.h b/examples/MQ/serialization/data_generator/RooDataGenerator.h index 8481897dde..1865c60374 100644 --- a/examples/MQ/serialization/data_generator/RooDataGenerator.h +++ b/examples/MQ/serialization/data_generator/RooDataGenerator.h @@ -1,4 +1,4 @@ -/* +/* * File: RooDataGenerator.h * Author: winckler * @@ -6,20 +6,20 @@ */ #ifndef ROODATAGENERATOR_H -#define ROODATAGENERATOR_H +#define ROODATAGENERATOR_H // root #include // roofit -#include "RooGlobalFunc.h" +#include "RooArgSet.h" #include "RooConstVar.h" -#include "RooRealVar.h" #include "RooDataSet.h" #include "RooGaussian.h" +#include "RooGlobalFunc.h" #include "RooProdPdf.h" -#include "RooArgSet.h" #include "RooRandom.h" +#include "RooRealVar.h" struct RdmVarParameters { @@ -52,7 +52,10 @@ struct PDFConfig , fTErr(0.005, 0.001) {} - void Set(const RdmVarParameters& x, const RdmVarParameters& y, const RdmVarParameters& z, const RdmVarParameters& terr) + void Set(const RdmVarParameters& x, + const RdmVarParameters& y, + const RdmVarParameters& z, + const RdmVarParameters& terr) { fX = x; fY = y; @@ -86,8 +89,14 @@ class MultiVariatePDF , fGaussY("fGaussY", "gaussian PDF", fY, RooFit::RooConst(fOpt.fY.fMean), RooFit::RooConst(fOpt.fY.fSigma)) , fGaussZ("fGaussZ", "gaussian PDF", fZ, RooFit::RooConst(fOpt.fZ.fMean), RooFit::RooConst(fOpt.fZ.fSigma)) , fGaussT("fGaussT", "gaussian PDF", fT, fMeanT, fSigmaT) - , fGaussTErr("fGaussTErr", "gaussian PDF", fTErr, RooFit::RooConst((fTErr.getMin() + fTErr.getMax()) / 2), RooFit::RooConst(fOpt.fTErr.fSigma)) - , fModel("fGaussXyzt_ter", "fGaussX*fGaussY*fGaussZ*fGaussT*fGaussTErr", RooArgList(fGaussX, fGaussY, fGaussZ, fGaussT, fGaussTErr)) + , fGaussTErr("fGaussTErr", + "gaussian PDF", + fTErr, + RooFit::RooConst((fTErr.getMin() + fTErr.getMax()) / 2), + RooFit::RooConst(fOpt.fTErr.fSigma)) + , fModel("fGaussXyzt_ter", + "fGaussX*fGaussY*fGaussZ*fGaussT*fGaussTErr", + RooArgList(fGaussX, fGaussY, fGaussZ, fGaussT, fGaussTErr)) { RooMsgService::instance().setGlobalKillBelow(RooFit::MsgLevel::ERROR); RooRandom::randomGenerator()->SetSeed(TDatime().GetTime()); @@ -96,8 +105,7 @@ class MultiVariatePDF MultiVariatePDF(const MultiVariatePDF&) = delete; MultiVariatePDF operator=(const MultiVariatePDF&) = delete; - ~MultiVariatePDF() - {} + ~MultiVariatePDF() {} RooDataSet* GetGeneratedData(unsigned int n, unsigned int ti) { diff --git a/examples/MQ/serialization/data_generator/runGenerateData.cxx b/examples/MQ/serialization/data_generator/runGenerateData.cxx index a94bc1ae21..4b111d13fb 100644 --- a/examples/MQ/serialization/data_generator/runGenerateData.cxx +++ b/examples/MQ/serialization/data_generator/runGenerateData.cxx @@ -13,45 +13,45 @@ * Created on November 27, 2014, 11:26 AM */ -#include +#include "boost/program_options.hpp" + #include +#include #include #include -#include "boost/program_options.hpp" - // root #include +#include #include #include -#include // FairRoot -#include #include "RootOutFileManager.h" +#include + // FairRoot - Tutorial 7 -#include "RooDataGenerator.h" #include "MyDigi.h" #include "MyPodData.h" +#include "RooDataGenerator.h" using namespace std; // fill data payload and save to file -template +template void SaveDataToFile(ManagerType& outMan, RooDataSet* dataset, bool printval = false); -template +template void SavePodDataToFile(ManagerType& outMan, RooDataSet* dataset, bool printval = false); -typedef MyDigi TDigi; // non POD/complex data -typedef MyPodData::Digi TDigiPod; // POD/trivial data +typedef MyDigi TDigi; // non POD/complex data +typedef MyPodData::Digi TDigiPod; // POD/trivial data typedef RootOutFileManager RootFileManager; int main(int argc, char** argv) { - try - { + try { string filename; string treename; string branchname; @@ -66,34 +66,31 @@ int main(int argc, char** argv) namespace po = boost::program_options; po::options_description desc("Data generator options"); + // clang-format off desc.add_options() ("output-file", po::value(&filename)->required(), "Path to the output root file of generated data") ("tree", po::value(&treename)->default_value("T7SamplerTree"), "Name of the tree") ("branch", po::value(&branchname)->default_value("MyDigi"), "Name of the Branch") ("class-name", po::value(&classname)->default_value("MyDigi"), "Name of the Payload class") ("rootfile-option", po::value(&fileoption)->default_value("RECREATE"), "Root file option.") - ("use-TCA", po::value(&useTClonesArray)->default_value(true), "Store data bunches in TClonesArray") + ("use-TCA", po::value(&useTClonesArray)->default_value(true), "Store data bunches in TClonesArray") ("plot-data", po::value(&plotdata)->default_value(false), "Plot generated data") ("tmax", po::value(&tmax)->default_value(100), "max time index=bunch number") ("Nmean", po::value(&nMean)->default_value(1595), "mean number of generated data / bunch") - ("Nsigma", po::value(&nSigma)->default_value(25.98), "std deviation of the number of generated data / bunch") - ; + ("Nsigma", po::value(&nSigma)->default_value(25.98), "std deviation of the number of generated data / bunch"); + // clang-format on po::variables_map vm; - try - { + try { po::store(po::parse_command_line(argc, argv, desc), vm); - if (vm.count("help")) - { + if (vm.count("help")) { std::cout << "Basic Command Line Parameter App" << std::endl << desc << std::endl; return 0; } po::notify(vm); - } - catch (po::error& e) - { + } catch (po::error& e) { std::cerr << "error: " << e.what() << std::endl << std::endl; std::cerr << desc << std::endl; return 1; @@ -107,20 +104,24 @@ int main(int argc, char** argv) // Init density function for the number of digi/bunch RdmVarParameters nval(nMean, nSigma); RooRealVar n("N", "N", nval.fMin, nval.fMax); - RooGaussian gaussN("gaussN", "gaussian PDF", n, RooFit::RooConst(nval.fMean), RooFit::RooConst(nval.fSigma)); // mean/sigma same as tutorial 3 + RooGaussian gaussN("gaussN", + "gaussian PDF", + n, + RooFit::RooConst(nval.fMean), + RooFit::RooConst(nval.fSigma)); // mean/sigma same as tutorial 3 // Init density function for the (x, y, z, t, terr) random variables - PDFConfig pdfConfig;// default setting (i.e. default range, mean, standard deviation) + PDFConfig pdfConfig; // default setting (i.e. default range, mean, standard deviation) MultiVariatePDF model(pdfConfig); // loop over t (= bunch index), generate data from pdf, fill digi and save to file - for (unsigned int t = 0; t < tmax; t++) - { + for (unsigned int t = 0; t < tmax; t++) { unique_ptr gaussSample(gaussN.generate(n, 1)); unsigned int nDigi = static_cast(gaussSample->get(0)->getRealValue("N")); - LOG(info) << "Bunch number " << t + 1 << "/" << tmax - << " (" << 100. * static_cast(t + 1) / static_cast(tmax) << " %). Number of generated digis: " - << nDigi << ", payload = " << nDigi * (3 * sizeof(Int_t) + 2 * sizeof(Double_t)) << " bytes"; + LOG(info) << "Bunch number " << t + 1 << "/" << tmax << " (" + << 100. * static_cast(t + 1) / static_cast(tmax) + << " %). Number of generated digis: " << nDigi + << ", payload = " << nDigi * (3 * sizeof(Int_t) + 2 * sizeof(Double_t)) << " bytes"; unique_ptr simdataset(model.GetGeneratedData(nDigi, t)); SaveDataToFile(rootman, simdataset.get()); @@ -129,28 +130,32 @@ int main(int argc, char** argv) LOG(info) << "Data generation successful"; // option : plot generated data - if (plotdata) - { + if (plotdata) { RootFileManager man; man.SetFileProperties(filename, treename, branchname, classname, "READ", useTClonesArray); vector> data = man.GetAllObj(filename, treename, branchname); - TH2D histoxy("fxy", "digi.fxy", 100, pdfConfig.fX.fMin, pdfConfig.fX.fMax, 100, pdfConfig.fY.fMin, pdfConfig.fY.fMax); + TH2D histoxy("fxy", + "digi.fxy", + 100, + pdfConfig.fX.fMin, + pdfConfig.fX.fMax, + 100, + pdfConfig.fY.fMin, + pdfConfig.fY.fMax); TH1D histox("fx", "digi.fx", 100, pdfConfig.fX.fMin, pdfConfig.fX.fMax); TH1D histoy("fy", "digi.fy", 100, pdfConfig.fY.fMin, pdfConfig.fY.fMax); TH1D histoz("fz", "digi.fz", 100, pdfConfig.fZ.fMin, pdfConfig.fZ.fMax); - TH1D histot("ftimestamp", "digi.ftimestamp", 10 * tmax, 0., static_cast(tmax + 1)); + TH1D histot("ftimestamp", "digi.ftimestamp", 10 * tmax, 0., static_cast(tmax + 1)); TH1D histoterr("ftimestampErr", "digi.ftimestampErr", 100, pdfConfig.fTErr.fMin, pdfConfig.fTErr.fMax); TH1D histoN("f_N", "Number of digi distribution", 100, nval.fMin, nval.fMax); - for (auto& p : data) - { + for (auto& p : data) { histoN.Fill(static_cast(p.size())); - for (auto& q : p) - { + for (auto& q : p) { histox.Fill(q.GetX()); histoy.Fill(q.GetY()); - histoxy.Fill(q.GetX(),q.GetY()); + histoxy.Fill(q.GetX(), q.GetY()); histoz.Fill(q.GetZ()); histot.Fill(q.GetTimeStamp()); histoterr.Fill(q.GetTimeStampError()); @@ -185,9 +190,7 @@ int main(int argc, char** argv) app.Run(); } - } - catch (exception& e) - { + } catch (exception& e) { LOG(error) << e.what(); return 1; } @@ -195,12 +198,11 @@ int main(int argc, char** argv) return 0; } -template +template void SaveDataToFile(ManagerType& outMan, RooDataSet* dataset, bool printval) { vector dataBunch; - for (int i = 0; i < dataset->numEntries(); i++) - { + for (int i = 0; i < dataset->numEntries(); i++) { T data; data.SetTimeStamp(dataset->get(i)->getRealValue("t")); data.SetTimeStampError(dataset->get(i)->getRealValue("tErr")); @@ -209,13 +211,9 @@ void SaveDataToFile(ManagerType& outMan, RooDataSet* dataset, bool printval) data.SetY(static_cast(round(dataset->get(i)->getRealValue("y")))); data.SetZ(static_cast(round(dataset->get(i)->getRealValue("z")))); - if (printval) - { - LOG(info) << "x=" << data.GetX() - << " y=" << data.GetY() - << " z=" << data.GetZ() - << " t=" << data.GetTimeStamp() - << " tErr=" << data.GetTimeStampError(); + if (printval) { + LOG(info) << "x=" << data.GetX() << " y=" << data.GetY() << " z=" << data.GetZ() + << " t=" << data.GetTimeStamp() << " tErr=" << data.GetTimeStampError(); } dataBunch.push_back(data); } @@ -223,12 +221,11 @@ void SaveDataToFile(ManagerType& outMan, RooDataSet* dataset, bool printval) outMan.AddToFile(dataBunch); } -template +template void SavePodDataToFile(ManagerType& outMan, RooDataSet* dataset, bool printval) { vector dataBunch; - for (int i = 0; i < dataset->numEntries(); i++) - { + for (int i = 0; i < dataset->numEntries(); i++) { T data; data.fTimeStamp = dataset->get(i)->getRealValue("t"); data.fTimeStampError = dataset->get(i)->getRealValue("tErr"); @@ -237,12 +234,8 @@ void SavePodDataToFile(ManagerType& outMan, RooDataSet* dataset, bool printval) data.fY = static_cast(round(dataset->get(i)->getRealValue("y"))); data.fZ = static_cast(round(dataset->get(i)->getRealValue("z"))); - if (printval) - { - LOG(info) << "x=" << data.fX - << " y=" << data.fY - << " z=" << data.fZ - << " t=" << data.fTimeStamp + if (printval) { + LOG(info) << "x=" << data.fX << " y=" << data.fY << " z=" << data.fZ << " t=" << data.fTimeStamp << " tErr=" << data.fTimeStampError; } dataBunch.push_back(data); diff --git a/examples/advanced/MbsTutorial/FairMBSRawItem.cxx b/examples/advanced/MbsTutorial/FairMBSRawItem.cxx index d0c8903366..465d15903b 100644 --- a/examples/advanced/MbsTutorial/FairMBSRawItem.cxx +++ b/examples/advanced/MbsTutorial/FairMBSRawItem.cxx @@ -18,8 +18,7 @@ FairMBSRawItem::FairMBSRawItem() , fClock(0) , fTacData(0) , fQdcData(0) -{ -} +{} FairMBSRawItem::FairMBSRawItem(UShort_t sam, UShort_t gtb, @@ -38,8 +37,7 @@ FairMBSRawItem::FairMBSRawItem(UShort_t sam, , fClock(clock) , fTacData(tacData) , fQdcData(qdcData) -{ -} +{} FairMBSRawItem::FairMBSRawItem(const FairMBSRawItem& right) : TObject(right) @@ -51,7 +49,6 @@ FairMBSRawItem::FairMBSRawItem(const FairMBSRawItem& right) , fClock(right.fClock) , fTacData(right.fTacData) , fQdcData(right.fQdcData) -{ -} +{} -ClassImp(FairMBSRawItem) +ClassImp(FairMBSRawItem); diff --git a/examples/advanced/MbsTutorial/FairMBSTask.cxx b/examples/advanced/MbsTutorial/FairMBSTask.cxx index 62f6cf2dbe..ce6e68e357 100644 --- a/examples/advanced/MbsTutorial/FairMBSTask.cxx +++ b/examples/advanced/MbsTutorial/FairMBSTask.cxx @@ -6,16 +6,16 @@ * copied verbatim in the file "LICENSE" * ********************************************************************************/ -#include -#include -#include -#include +#include "FairMBSTask.h" +#include "FairMBSRawItem.h" #include "FairRootManager.h" #include "FairRunOnline.h" -#include "FairMBSRawItem.h" -#include "FairMBSTask.h" +#include +#include +#include +#include FairMBSTask::FairMBSTask(const char* name, Int_t iVerbose) : FairTask(name, iVerbose) @@ -24,20 +24,17 @@ FairMBSTask::FairMBSTask(const char* name, Int_t iVerbose) , fhTac(nullptr) , fhClock(nullptr) , fhTacCh(nullptr) -{ -} +{} InitStatus FairMBSTask::Init() { FairRootManager* mgr = FairRootManager::Instance(); - if (nullptr == mgr) - { + if (nullptr == mgr) { return kFATAL; } fRawData = static_cast(mgr->GetObject("MBSRawItem")); - if (nullptr == fRawData) - { + if (nullptr == fRawData) { return kERROR; } @@ -47,15 +44,14 @@ InitStatus FairMBSTask::Init() fhTacCh = new TH1F("hTacCh", "Raw TAC Channel distribution", 20, 0., 20.); FairRunOnline* run = FairRunOnline::Instance(); - if (nullptr == run) - { + if (nullptr == run) { return kERROR; } run->AddObject(fhQdc); run->RegisterHttpCommand("/Reset_hQdc", "/hQdc/->Reset()"); - TCanvas *c1 = new TCanvas("c1", "", 10, 10, 500, 500); + TCanvas* c1 = new TCanvas("c1", "", 10, 10, 500, 500); c1->Divide(2, 2); c1->cd(1); fhQdc->Draw(); @@ -68,7 +64,7 @@ InitStatus FairMBSTask::Init() c1->cd(0); run->AddObject(c1); - TFolder *folder = new TFolder("MbsDetFolder", "Example Folder"); + TFolder* folder = new TFolder("MbsDetFolder", "Example Folder"); folder->Add(fhQdc); folder->Add(fhTac); folder->Add(fhClock); @@ -80,17 +76,14 @@ InitStatus FairMBSTask::Init() void FairMBSTask::Exec(Option_t*) { - if (nullptr == fRawData) - { + if (nullptr == fRawData) { return; } Int_t nItems = fRawData->GetEntriesFast(); FairMBSRawItem* item; - for (Int_t i = 0; i < nItems; i++) - { + for (Int_t i = 0; i < nItems; i++) { item = static_cast(fRawData->At(i)); - if (nullptr == item) - { + if (nullptr == item) { continue; } fhQdc->Fill(item->GetQdcData()); @@ -100,4 +93,4 @@ void FairMBSTask::Exec(Option_t*) } } -ClassImp(FairMBSTask) +ClassImp(FairMBSTask); diff --git a/examples/advanced/MbsTutorial/FairMBSUnpack.cxx b/examples/advanced/MbsTutorial/FairMBSUnpack.cxx index 0491eebfc2..c01f87229f 100644 --- a/examples/advanced/MbsTutorial/FairMBSUnpack.cxx +++ b/examples/advanced/MbsTutorial/FairMBSUnpack.cxx @@ -10,8 +10,8 @@ #include // Fair headers -#include "FairRootManager.h" #include "FairLogger.h" +#include "FairRootManager.h" // Land headers #include "FairMBSRawItem.h" @@ -22,8 +22,7 @@ FairMBSUnpack::FairMBSUnpack(Short_t type, Short_t subType, Short_t procId, Shor , fRawData(new TClonesArray("FairMBSRawItem")) , fNHits(0) , fNHitsTotal(0) -{ -} +{} FairMBSUnpack::~FairMBSUnpack() { @@ -42,8 +41,7 @@ void FairMBSUnpack::Register() // LOG(debug) << "Registering"; LOG(info) << "FairMBSUnpack : Registering..."; FairRootManager* fMan = FairRootManager::Instance(); - if (!fMan) - { + if (!fMan) { return; } fMan->Register("MBSRawItem", "MBS", fRawData, kTRUE); @@ -58,24 +56,23 @@ Bool_t FairMBSUnpack::DoUnpack(Int_t* data, Int_t size) Int_t n17 = 0; - while (l_i < size) - { + while (l_i < size) { n17 = 0; UInt_t* p1 = reinterpret_cast(data + l_i); - UInt_t l_sam_id = (p1[0] & 0xf0000000) >> 28; // identifies the sam - UInt_t l_gtb_id = (p1[0] & 0x0f000000) >> 24; // 0 or 1, identifies which of the 2 cables of the sam + UInt_t l_sam_id = (p1[0] & 0xf0000000) >> 28; // identifies the sam + UInt_t l_gtb_id = (p1[0] & 0x0f000000) >> 24; // 0 or 1, identifies which of the 2 cables of the sam UInt_t l_lec = (p1[0] & 0x00f00000) >> 20; UInt_t l_da_siz = (p1[0] & 0x000001ff); - LOG(debug) << "FairMBSUnpack : SAM:" << l_sam_id << ", GTB:" << l_gtb_id << ", lec:" << l_lec << ", size:" << l_da_siz; + LOG(debug) << "FairMBSUnpack : SAM:" << l_sam_id << ", GTB:" << l_gtb_id << ", lec:" << l_lec + << ", size:" << l_da_siz; l_i += 1; p1 = reinterpret_cast((data + l_i)); - for (UInt_t i1 = 0; i1 < l_da_siz; i1 += 2) - { + for (UInt_t i1 = 0; i1 < l_da_siz; i1 += 2) { UInt_t tac_addr; UInt_t tac_ch; UInt_t cal; @@ -90,8 +87,7 @@ Bool_t FairMBSUnpack::DoUnpack(Int_t* data, Int_t size) qdc_data = (p1[i1 + 1] & 0x00000fff); l_i += 2; - if (16 == tac_ch) - { + if (16 == tac_ch) { n17 += 1; } LOG(debug) << "FairMBSUnpack : TAC ADDR IS " << tac_addr << ", TAC CH IS " << tac_ch << ", TAC Data IS " @@ -119,4 +115,4 @@ void FairMBSUnpack::Reset() fNHits = 0; } -ClassImp(FairMBSUnpack) +ClassImp(FairMBSUnpack); diff --git a/examples/advanced/MbsTutorial/FairMBSUnpack.h b/examples/advanced/MbsTutorial/FairMBSUnpack.h index 365f37bab8..075d77194a 100644 --- a/examples/advanced/MbsTutorial/FairMBSUnpack.h +++ b/examples/advanced/MbsTutorial/FairMBSUnpack.h @@ -54,6 +54,7 @@ class FairMBSUnpack : public FairUnpack FairMBSUnpack(const FairMBSUnpack&); FairMBSUnpack& operator=(const FairMBSUnpack&); + public: // Class definition ClassDef(FairMBSUnpack, 1) diff --git a/examples/advanced/MbsTutorial/unpack_mbs.C b/examples/advanced/MbsTutorial/unpack_mbs.C index 9043e80167..041c0fac72 100644 --- a/examples/advanced/MbsTutorial/unpack_mbs.C +++ b/examples/advanced/MbsTutorial/unpack_mbs.C @@ -55,8 +55,7 @@ void unpack_mbs() Double_t rtime = timer.RealTime(); Double_t ctime = timer.CpuTime(); Int_t nHits = unpacker->GetNHitsTotal(); - if(9086 == nHits) - { + if (9086 == nHits) { cout << endl << endl; cout << "Macro finished successfully." << endl; cout << "Real time " << rtime << " s, CPU time " << ctime << "s" << endl << endl; diff --git a/examples/advanced/Tutorial3/MQ/data/FairTestDetectorPayload.h b/examples/advanced/Tutorial3/MQ/data/FairTestDetectorPayload.h index f7208cce14..06d5a0e9a1 100644 --- a/examples/advanced/Tutorial3/MQ/data/FairTestDetectorPayload.h +++ b/examples/advanced/Tutorial3/MQ/data/FairTestDetectorPayload.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /** @@ -15,35 +15,34 @@ #ifndef TESTDETECTORPAYLOAD_H_ #define TESTDETECTORPAYLOAD_H_ -namespace TestDetectorPayload +namespace TestDetectorPayload { +class TimeStamp { - class TimeStamp - { - public: - Double_t fTimeStamp; - Double_t fTimeStampError; - }; + public: + Double_t fTimeStamp; + Double_t fTimeStampError; +}; - class Digi : public TimeStamp - { - public: - Int_t fX; - Int_t fY; - Int_t fZ; - }; +class Digi : public TimeStamp +{ + public: + Int_t fX; + Int_t fY; + Int_t fZ; +}; - class Hit : public TimeStamp - { - public: - Int_t detID; - Int_t mcindex; - Double_t posX; - Double_t posY; - Double_t posZ; - Double_t dposX; - Double_t dposY; - Double_t dposZ; - }; -} +class Hit : public TimeStamp +{ + public: + Int_t detID; + Int_t mcindex; + Double_t posX; + Double_t posY; + Double_t posZ; + Double_t dposX; + Double_t dposY; + Double_t dposZ; +}; +} // namespace TestDetectorPayload #endif /* TESTDETECTORPAYLOAD_H_ */ diff --git a/examples/advanced/Tutorial3/MQ/fileSink/FairTestDetectorFileSink.h b/examples/advanced/Tutorial3/MQ/fileSink/FairTestDetectorFileSink.h index f1fb3e4fdd..8ffc4aa2d2 100644 --- a/examples/advanced/Tutorial3/MQ/fileSink/FairTestDetectorFileSink.h +++ b/examples/advanced/Tutorial3/MQ/fileSink/FairTestDetectorFileSink.h @@ -15,22 +15,20 @@ #ifndef FAIRTESTDETECTORFILESINK_H_ #define FAIRTESTDETECTORFILESINK_H_ +#include "FairTestDetectorHit.h" +#include "FairTestDetectorPayload.h" + #include #include - #include -#include -#include #include +#include #include - -#include "FairTestDetectorPayload.h" -#include "FairTestDetectorHit.h" - -#include +#include #include -#include +#include #include +#include template class FairTestDetectorFileSink : public FairMQDevice @@ -73,10 +71,7 @@ class FairTestDetectorFileSink : public FairMQDevice InitOutputFile(fConfig->GetValue("data-format")); } - virtual void PostRun() - { - LOG(info) << "Received " << fReceivedMsgs << " messages!"; - } + virtual void PostRun() { LOG(info) << "Received " << fReceivedMsgs << " messages!"; } virtual void InitTask(); diff --git a/examples/advanced/Tutorial3/MQ/fileSink/FairTestDetectorFileSinkBin.tpl b/examples/advanced/Tutorial3/MQ/fileSink/FairTestDetectorFileSinkBin.tpl index 816516e655..ca7587677c 100644 --- a/examples/advanced/Tutorial3/MQ/fileSink/FairTestDetectorFileSinkBin.tpl +++ b/examples/advanced/Tutorial3/MQ/fileSink/FairTestDetectorFileSinkBin.tpl @@ -7,11 +7,10 @@ // Implementation of FairTestDetectorFileSink::Run() with pure binary transport data format -template <> +template<> void FairTestDetectorFileSink::InitTask() { - OnData(fInChannelName, [this](FairMQMessagePtr& msg, int /*index*/) - { + OnData(fInChannelName, [this](FairMQMessagePtr& msg, int /*index*/) { ++fReceivedMsgs; fOutput->Delete(); @@ -19,15 +18,13 @@ void FairTestDetectorFileSink::In TestDetectorPayload::Hit* input = static_cast(msg->GetData()); - for (int i = 0; i < numEntries; ++i) - { + for (int i = 0; i < numEntries; ++i) { TVector3 pos(input[i].posX, input[i].posY, input[i].posZ); TVector3 dpos(input[i].dposX, input[i].dposY, input[i].dposZ); new ((*fOutput)[i]) FairTestDetectorHit(input[i].detID, input[i].mcindex, pos, dpos); } - if (fOutput->IsEmpty()) - { + if (fOutput->IsEmpty()) { LOG(error) << "FairTestDetectorFileSink::Run(): No Output array!"; } diff --git a/examples/advanced/Tutorial3/MQ/fileSink/FairTestDetectorFileSinkBoost.tpl b/examples/advanced/Tutorial3/MQ/fileSink/FairTestDetectorFileSinkBoost.tpl index 99253c7d39..5d20cab963 100644 --- a/examples/advanced/Tutorial3/MQ/fileSink/FairTestDetectorFileSinkBoost.tpl +++ b/examples/advanced/Tutorial3/MQ/fileSink/FairTestDetectorFileSinkBoost.tpl @@ -11,7 +11,7 @@ // example TIn: FairTestDetectorHit // example TPayloadIn: boost::archive::binary_iarchive -template +template void FairTestDetectorFileSink::InitTask() { OnData(fInChannelName, [this](FairMQMessagePtr& msg, int /*index*/) { diff --git a/examples/advanced/Tutorial3/MQ/fileSink/FairTestDetectorFileSinkFlatBuffers.tpl b/examples/advanced/Tutorial3/MQ/fileSink/FairTestDetectorFileSinkFlatBuffers.tpl index 3bbca292c0..2ba626fa71 100644 --- a/examples/advanced/Tutorial3/MQ/fileSink/FairTestDetectorFileSinkFlatBuffers.tpl +++ b/examples/advanced/Tutorial3/MQ/fileSink/FairTestDetectorFileSinkFlatBuffers.tpl @@ -2,16 +2,15 @@ #ifdef FLATBUFFERS -#include "flatbuffers/flatbuffers.h" #include "FairTestDetectorPayloadHit_generated.h" +#include "flatbuffers/flatbuffers.h" using namespace TestDetectorFlat; -template <> +template<> void FairTestDetectorFileSink::InitTask() { - OnData(fInChannelName, [this](FairMQMessagePtr& msg, int /*index*/) - { + OnData(fInChannelName, [this](FairMQMessagePtr& msg, int /*index*/) { ++fReceivedMsgs; fOutput->Delete(); @@ -20,16 +19,15 @@ void FairTestDetectorFileSink // int numEntries = hits->size(); - for (auto it = hits->begin(); it != hits->end(); ++it) - { + for (auto it = hits->begin(); it != hits->end(); ++it) { TVector3 pos((*it)->x(), (*it)->y(), (*it)->z()); TVector3 dpos((*it)->dx(), (*it)->dy(), (*it)->dz()); new ((*fOutput)[it - hits->begin()]) FairTestDetectorHit((*it)->detID(), (*it)->mcIndex(), pos, dpos); - // LOG(warn) << " " << (*it)->detID() << " " << (*it)->x() << " " << (*it)->y() << " " << (*it)->z() << " " << (*it)->dx() << " " << (*it)->dy() << " " << (*it)->dz(); + // LOG(warn) << " " << (*it)->detID() << " " << (*it)->x() << " " << (*it)->y() << " " << (*it)->z() << " " + // << (*it)->dx() << " " << (*it)->dy() << " " << (*it)->dz(); } - if (fOutput->IsEmpty()) - { + if (fOutput->IsEmpty()) { LOG(error) << "FairTestDetectorFileSink::Run(): No Output array!"; } diff --git a/examples/advanced/Tutorial3/MQ/fileSink/FairTestDetectorFileSinkMsgpack.tpl b/examples/advanced/Tutorial3/MQ/fileSink/FairTestDetectorFileSinkMsgpack.tpl index 806b5bd0fd..d08a969bbd 100644 --- a/examples/advanced/Tutorial3/MQ/fileSink/FairTestDetectorFileSinkMsgpack.tpl +++ b/examples/advanced/Tutorial3/MQ/fileSink/FairTestDetectorFileSinkMsgpack.tpl @@ -4,15 +4,15 @@ #include -struct MsgPack {}; +struct MsgPack +{}; // struct MsgPackRef { msgpack::vrefbuffer* container; void* content; }; // struct MsgPackStream {}; -template <> +template<> void FairTestDetectorFileSink::InitTask() { - OnData(fInChannelName, [this](FairMQMessagePtr& msg, int /*index*/) - { + OnData(fInChannelName, [this](FairMQMessagePtr& msg, int /*index*/) { ++fReceivedMsgs; // deserialize @@ -33,15 +33,13 @@ void FairTestDetectorFileSink::InitTask() fOutput->Delete(); - for (int i = 0; i < numEntries; ++i) - { + for (int i = 0; i < numEntries; ++i) { TVector3 pos(std::get<2>(hits.at(i)), std::get<3>(hits.at(i)), std::get<4>(hits.at(i))); TVector3 dpos(std::get<5>(hits.at(i)), std::get<6>(hits.at(i)), std::get<7>(hits.at(i))); new ((*fOutput)[i]) FairTestDetectorHit(std::get<0>(hits.at(i)), std::get<1>(hits.at(i)), pos, dpos); } - if (fOutput->IsEmpty()) - { + if (fOutput->IsEmpty()) { LOG(error) << "FairTestDetectorFileSink::Run(): No Output array!"; } diff --git a/examples/advanced/Tutorial3/MQ/fileSink/FairTestDetectorFileSinkProtobuf.tpl b/examples/advanced/Tutorial3/MQ/fileSink/FairTestDetectorFileSinkProtobuf.tpl index 827c36b3ea..3fd5642eb6 100644 --- a/examples/advanced/Tutorial3/MQ/fileSink/FairTestDetectorFileSinkProtobuf.tpl +++ b/examples/advanced/Tutorial3/MQ/fileSink/FairTestDetectorFileSinkProtobuf.tpl @@ -10,11 +10,10 @@ #ifdef PROTOBUF #include "FairTestDetectorPayload.pb.h" -template <> +template<> void FairTestDetectorFileSink::InitTask() { - OnData(fInChannelName, [this](FairMQMessagePtr& msg, int /*index*/) - { + OnData(fInChannelName, [this](FairMQMessagePtr& msg, int /*index*/) { ++fReceivedMsgs; fOutput->Delete(); @@ -23,16 +22,14 @@ void FairTestDetectorFileSinkIsEmpty()) - { + if (fOutput->IsEmpty()) { LOG(error) << "FairTestDetectorFileSink::Run(): No Output array!"; } diff --git a/examples/advanced/Tutorial3/MQ/fileSink/FairTestDetectorFileSinkTMessage.tpl b/examples/advanced/Tutorial3/MQ/fileSink/FairTestDetectorFileSinkTMessage.tpl index 32da7e2479..837100352b 100644 --- a/examples/advanced/Tutorial3/MQ/fileSink/FairTestDetectorFileSinkTMessage.tpl +++ b/examples/advanced/Tutorial3/MQ/fileSink/FairTestDetectorFileSinkTMessage.tpl @@ -9,11 +9,10 @@ #include "RootSerializer.h" -template <> +template<> void FairTestDetectorFileSink::InitTask() { - OnData(fInChannelName, [this](FairMQMessagePtr& msg, int /*index*/) - { + OnData(fInChannelName, [this](FairMQMessagePtr& msg, int /*index*/) { ++fReceivedMsgs; RootSerializer().Deserialize(*msg, fOutput); diff --git a/examples/advanced/Tutorial3/MQ/processorTask/FairTestDetectorMQRecoTask.h b/examples/advanced/Tutorial3/MQ/processorTask/FairTestDetectorMQRecoTask.h index dfb41bace3..e506133515 100644 --- a/examples/advanced/Tutorial3/MQ/processorTask/FairTestDetectorMQRecoTask.h +++ b/examples/advanced/Tutorial3/MQ/processorTask/FairTestDetectorMQRecoTask.h @@ -8,17 +8,16 @@ #ifndef FAIRTESTDETECTORMQRECOTASK_H #define FAIRTESTDETECTORMQRECOTASK_H -#include - +#include "FairMQProcessorTask.h" #include "FairRootManager.h" +#include "FairTestDetectorDigi.h" +#include "FairTestDetectorHit.h" +#include "FairTestDetectorPayload.h" +#include "FairTestDetectorRecoTask.h" + #include -#include "FairMQProcessorTask.h" #include - -#include "FairTestDetectorRecoTask.h" -#include "FairTestDetectorPayload.h" -#include "FairTestDetectorHit.h" -#include "FairTestDetectorDigi.h" +#include template class FairTestDetectorMQRecoTask : public FairMQProcessorTask diff --git a/examples/advanced/Tutorial3/MQ/processorTask/FairTestDetectorMQRecoTaskBin.tpl b/examples/advanced/Tutorial3/MQ/processorTask/FairTestDetectorMQRecoTaskBin.tpl index 28ff0ca6ba..e9753f34a6 100644 --- a/examples/advanced/Tutorial3/MQ/processorTask/FairTestDetectorMQRecoTaskBin.tpl +++ b/examples/advanced/Tutorial3/MQ/processorTask/FairTestDetectorMQRecoTaskBin.tpl @@ -6,8 +6,11 @@ */ // Implementation of FairTestDetectorMQRecoTask::Exec() with pure binary transport data format -template <> -void FairTestDetectorMQRecoTask::Exec(Option_t* opt) +template<> +void FairTestDetectorMQRecoTask::Exec(Option_t* opt) { int inputSize = fPayload->GetSize(); int numEntries = inputSize / sizeof(TestDetectorPayload::Digi); @@ -16,14 +19,13 @@ void FairTestDetectorMQRecoTaskClear(); - for (int i = 0; i < numEntries; ++i) - { - new ((*fRecoTask.fDigiArray)[i]) FairTestDetectorDigi(input[i].fX, input[i].fY, input[i].fZ, input[i].fTimeStamp); + for (int i = 0; i < numEntries; ++i) { + new ((*fRecoTask.fDigiArray)[i]) + FairTestDetectorDigi(input[i].fX, input[i].fY, input[i].fZ, input[i].fTimeStamp); static_cast(((*fRecoTask.fDigiArray)[i]))->SetTimeStampError(input[i].fTimeStampError); } - if (!fRecoTask.fDigiArray) - { + if (!fRecoTask.fDigiArray) { LOG(error) << "FairTestDetectorMQRecoTask::Exec(): No Point array!"; } @@ -35,10 +37,8 @@ void FairTestDetectorMQRecoTask(fPayload->GetData()); - if (inputSize > 0) - { - for (int i = 0; i < numEntries; ++i) - { + if (inputSize > 0) { + for (int i = 0; i < numEntries; ++i) { FairTestDetectorHit* hit = static_cast(fRecoTask.fHitArray->At(i)); output[i].detID = hit->GetDetectorID(); diff --git a/examples/advanced/Tutorial3/MQ/processorTask/FairTestDetectorMQRecoTaskBoost.tpl b/examples/advanced/Tutorial3/MQ/processorTask/FairTestDetectorMQRecoTaskBoost.tpl index 9953ffb06a..9fccf427e5 100644 --- a/examples/advanced/Tutorial3/MQ/processorTask/FairTestDetectorMQRecoTaskBoost.tpl +++ b/examples/advanced/Tutorial3/MQ/processorTask/FairTestDetectorMQRecoTaskBoost.tpl @@ -13,7 +13,7 @@ // example TOut: FairTestDetectorHit // example TPayloadIn: boost::archive::binary_iarchive // example TPayloadOut: boost::archive::binary_oarchive -template +template void FairTestDetectorMQRecoTask::Exec(Option_t* opt) { BoostSerializer().Deserialize(*fPayload, fRecoTask.fDigiArray); diff --git a/examples/advanced/Tutorial3/MQ/processorTask/FairTestDetectorMQRecoTaskFlatBuffers.tpl b/examples/advanced/Tutorial3/MQ/processorTask/FairTestDetectorMQRecoTaskFlatBuffers.tpl index baa7de653e..af043f5796 100644 --- a/examples/advanced/Tutorial3/MQ/processorTask/FairTestDetectorMQRecoTaskFlatBuffers.tpl +++ b/examples/advanced/Tutorial3/MQ/processorTask/FairTestDetectorMQRecoTaskFlatBuffers.tpl @@ -2,14 +2,17 @@ #ifdef FLATBUFFERS -#include "flatbuffers/flatbuffers.h" #include "FairTestDetectorPayloadDigi_generated.h" #include "FairTestDetectorPayloadHit_generated.h" +#include "flatbuffers/flatbuffers.h" using namespace TestDetectorFlat; -template <> -void FairTestDetectorMQRecoTask::Exec(Option_t* opt) +template<> +void FairTestDetectorMQRecoTask::Exec(Option_t* opt) { fRecoTask.fDigiArray->Clear(); @@ -17,15 +20,16 @@ void FairTestDetectorMQRecoTaskdigis(); int numEntries = digis->size(); - for (auto it = digis->begin(); it != digis->end(); ++it) - { - new ((*fRecoTask.fDigiArray)[it - digis->begin()]) FairTestDetectorDigi((*it)->x(), (*it)->y(), (*it)->z(), (*it)->timestamp()); - static_cast(((*fRecoTask.fDigiArray)[it - digis->begin()]))->SetTimeStampError((*it)->timestampError()); - // LOG(info) << (*it)->x() << " " << (*it)->y() << " " << (*it)->z() << " " << (*it)->timestamp() << " " << (*it)->timestampError(); + for (auto it = digis->begin(); it != digis->end(); ++it) { + new ((*fRecoTask.fDigiArray)[it - digis->begin()]) + FairTestDetectorDigi((*it)->x(), (*it)->y(), (*it)->z(), (*it)->timestamp()); + static_cast(((*fRecoTask.fDigiArray)[it - digis->begin()])) + ->SetTimeStampError((*it)->timestampError()); + // LOG(info) << (*it)->x() << " " << (*it)->y() << " " << (*it)->z() << " " << (*it)->timestamp() << " " << + // (*it)->timestampError(); } - if (!fRecoTask.fDigiArray) - { + if (!fRecoTask.fDigiArray) { LOG(error) << "FairTestDetectorMQRecoTask::Exec(): No Point array!"; } @@ -34,37 +38,37 @@ void FairTestDetectorMQRecoTask* hits = new flatbuffers::Offset[numEntries]; - for (int i = 0; i < numEntries; ++i) - { + for (int i = 0; i < numEntries; ++i) { FairTestDetectorHit* hit = (FairTestDetectorHit*)fRecoTask.fHitArray->At(i); - if (!hit) - { + if (!hit) { continue; } - // LOG(warn) << " " << hit->GetDetectorID() << " " << hit->GetX() << " " << hit->GetY() << " " << hit->GetZ() << " " << hit->GetDx() << " " << hit->GetDy() << " " << hit->GetDz(); + // LOG(warn) << " " << hit->GetDetectorID() << " " << hit->GetX() << " " << hit->GetY() << " " << hit->GetZ() << + // " " << hit->GetDx() << " " << hit->GetDy() << " " << hit->GetDz(); HitBuilder hb(*builder); - hb.add_detID(hit->GetDetectorID()); // detID:int - hb.add_mcIndex(hit->GetRefIndex()); // GetRefIndex:int - hb.add_x(hit->GetX()); // x:double - hb.add_y(hit->GetY()); // y:double - hb.add_z(hit->GetZ()); // z:double - hb.add_dx(hit->GetDx()); // dx:double - hb.add_dy(hit->GetDy()); // dy:double - hb.add_dz(hit->GetDz()); // dz:double - hb.add_timestamp(hit->GetTimeStamp()); // timestamp:double - hb.add_timestampError(hit->GetTimeStampError()); // timestampError:double + hb.add_detID(hit->GetDetectorID()); // detID:int + hb.add_mcIndex(hit->GetRefIndex()); // GetRefIndex:int + hb.add_x(hit->GetX()); // x:double + hb.add_y(hit->GetY()); // y:double + hb.add_z(hit->GetZ()); // z:double + hb.add_dx(hit->GetDx()); // dx:double + hb.add_dy(hit->GetDy()); // dy:double + hb.add_dz(hit->GetDz()); // dz:double + hb.add_timestamp(hit->GetTimeStamp()); // timestamp:double + hb.add_timestampError(hit->GetTimeStampError()); // timestampError:double hits[i] = hb.Finish(); } auto hvector = builder->CreateVector(hits, numEntries); auto mloc = CreateHitPayload(*builder, hvector); FinishHitPayloadBuffer(*builder, mloc); - delete [] hits; + delete[] hits; - fPayload->Rebuild(builder->GetBufferPointer(), - builder->GetSize(), - [](void* /* data */, void* obj){ delete static_cast(obj); }, - builder); + fPayload->Rebuild( + builder->GetBufferPointer(), + builder->GetSize(), + [](void* /* data */, void* obj) { delete static_cast(obj); }, + builder); } #endif /* FLATBUFFERS */ diff --git a/examples/advanced/Tutorial3/MQ/processorTask/FairTestDetectorMQRecoTaskMsgpack.tpl b/examples/advanced/Tutorial3/MQ/processorTask/FairTestDetectorMQRecoTaskMsgpack.tpl index 8ea08af08c..5767664e3f 100644 --- a/examples/advanced/Tutorial3/MQ/processorTask/FairTestDetectorMQRecoTaskMsgpack.tpl +++ b/examples/advanced/Tutorial3/MQ/processorTask/FairTestDetectorMQRecoTaskMsgpack.tpl @@ -11,11 +11,12 @@ #include // Types to be used as template parameters. -struct MsgPack {}; -// struct MsgPackRef { msgpack::vrefbuffer vbuf; std::vector> hits; }; -// struct MsgPackStream {}; +struct MsgPack +{}; +// struct MsgPackRef { msgpack::vrefbuffer vbuf; std::vector> hits; }; struct MsgPackStream {}; -template <> +template<> void FairTestDetectorMQRecoTask::Exec(Option_t* opt) { // deserialize @@ -36,14 +37,13 @@ void FairTestDetectorMQRecoTaskClear(); - for (int i = 0; i < numEntries; ++i) - { - new ((*fRecoTask.fDigiArray)[i]) FairTestDetectorDigi(std::get<0>(digis.at(i)), std::get<1>(digis.at(i)), std::get<2>(digis.at(i)), std::get<3>(digis.at(i))); + for (int i = 0; i < numEntries; ++i) { + new ((*fRecoTask.fDigiArray)[i]) FairTestDetectorDigi( + std::get<0>(digis.at(i)), std::get<1>(digis.at(i)), std::get<2>(digis.at(i)), std::get<3>(digis.at(i))); static_cast(((*fRecoTask.fDigiArray)[i]))->SetTimeStampError(std::get<4>(digis.at(i))); } - if (!fRecoTask.fDigiArray) - { + if (!fRecoTask.fDigiArray) { LOG(error) << "FairTestDetectorMQRecoTask::Exec(): No Point array!"; } @@ -58,18 +58,25 @@ void FairTestDetectorMQRecoTask> hits; - for (int i = 0; i < numEntries; ++i) - { + for (int i = 0; i < numEntries; ++i) { FairTestDetectorHit* hit = static_cast(fRecoTask.fHitArray->At(i)); - hits.push_back(std::make_tuple(hit->GetDetectorID(), hit->GetRefIndex(), hit->GetX(), hit->GetY(), hit->GetZ(), hit->GetDx(), hit->GetDy(), hit->GetDz())); + hits.push_back(std::make_tuple(hit->GetDetectorID(), + hit->GetRefIndex(), + hit->GetX(), + hit->GetY(), + hit->GetZ(), + hit->GetDx(), + hit->GetDy(), + hit->GetDz())); } packer.pack(hits); - fPayload->Rebuild(sbuf->data(), - sbuf->size(), - [](void* /* data */, void* obj) { delete static_cast(obj); }, - sbuf); + fPayload->Rebuild( + sbuf->data(), + sbuf->size(), + [](void* /* data */, void* obj) { delete static_cast(obj); }, + sbuf); } // MsgPackRef version sends the vector of tuples without copying it into the sbuffer @@ -79,7 +86,8 @@ void FairTestDetectorMQRecoTask -// void FairTestDetectorMQRecoTask::Exec(Option_t* opt) +// void FairTestDetectorMQRecoTask::Exec(Option_t* +// opt) // { // msgpack::unpacked msg; // msgpack::unpack(&msg, static_cast(fPayload->GetData()), fPayload->GetSize()); @@ -94,7 +102,8 @@ void FairTestDetectorMQRecoTask(digis.at(i)), std::get<1>(digis.at(i)), std::get<2>(digis.at(i)), std::get<3>(digis.at(i))); +// new ((*fRecoTask.fDigiArray)[i]) FairTestDetectorDigi(std::get<0>(digis.at(i)), std::get<1>(digis.at(i)), +// std::get<2>(digis.at(i)), std::get<3>(digis.at(i))); // } // if (!fRecoTask.fDigiArray) @@ -109,16 +118,19 @@ void FairTestDetectorMQRecoTask(fRecoTask.fHitArray->At(i)); -// container->hits.push_back(std::make_tuple(hit->GetDetectorID(), hit->GetX(), hit->GetY(), hit->GetZ(), hit->GetDx(), hit->GetDy(), hit->GetDz())); +// container->hits.push_back(std::make_tuple(hit->GetDetectorID(), hit->GetX(), hit->GetY(), hit->GetZ(), +// hit->GetDx(), hit->GetDy(), hit->GetDz())); // } // msgpack::pack(container->vbuf, container->hits); -// fPayload->Rebuild(container->vbuf.vector()->iov_base, container->vbuf.vector()->iov_len, free_vrefbuffer, container); +// fPayload->Rebuild(container->vbuf.vector()->iov_base, container->vbuf.vector()->iov_len, free_vrefbuffer, +// container); // } // template <> -// void FairTestDetectorMQRecoTask::Exec(Option_t* opt) +// void FairTestDetectorMQRecoTask::Exec(Option_t* opt) // { // fRecoTask.fDigiArray->Clear(); @@ -136,8 +148,8 @@ void FairTestDetectorMQRecoTask digi; // digiObj.convert(&digi); -// new ((*fRecoTask.fDigiArray)[numEntries]) FairTestDetectorDigi(std::get<0>(digi), std::get<1>(digi), std::get<2>(digi), std::get<3>(digi)); -// numEntries++; +// new ((*fRecoTask.fDigiArray)[numEntries]) FairTestDetectorDigi(std::get<0>(digi), std::get<1>(digi), +// std::get<2>(digi), std::get<3>(digi)); numEntries++; // } // if (!fRecoTask.fDigiArray) @@ -153,7 +165,8 @@ void FairTestDetectorMQRecoTask(fRecoTask.fHitArray->At(i)); -// packer.pack(std::make_tuple(hit->GetDetectorID(), hit->GetX(), hit->GetY(), hit->GetZ(), hit->GetDx(), hit->GetDy(), hit->GetDz())); +// packer.pack(std::make_tuple(hit->GetDetectorID(), hit->GetX(), hit->GetY(), hit->GetZ(), hit->GetDx(), +// hit->GetDy(), hit->GetDz())); // } // fPayload->Rebuild(sbuf->data(), sbuf->size(), free_sbuffer, sbuf); diff --git a/examples/advanced/Tutorial3/MQ/processorTask/FairTestDetectorMQRecoTaskProtobuf.tpl b/examples/advanced/Tutorial3/MQ/processorTask/FairTestDetectorMQRecoTaskProtobuf.tpl index 91d1d96002..aa15bb8164 100644 --- a/examples/advanced/Tutorial3/MQ/processorTask/FairTestDetectorMQRecoTaskProtobuf.tpl +++ b/examples/advanced/Tutorial3/MQ/processorTask/FairTestDetectorMQRecoTaskProtobuf.tpl @@ -10,8 +10,11 @@ #ifdef PROTOBUF #include "FairTestDetectorPayload.pb.h" -template <> -void FairTestDetectorMQRecoTask::Exec(Option_t* opt) +template<> +void FairTestDetectorMQRecoTask::Exec(Option_t* opt) { fRecoTask.fDigiArray->Clear(); @@ -20,15 +23,13 @@ void FairTestDetectorMQRecoTask(((*fRecoTask.fDigiArray)[i]))->SetTimeStampError(digi.ftimestamperror()); } - if (!fRecoTask.fDigiArray) - { + if (!fRecoTask.fDigiArray) { LOG(error) << "FairTestDetectorMQRecoTask::Exec(): No Point array!"; } @@ -36,11 +37,9 @@ void FairTestDetectorMQRecoTask(fRecoTask.fHitArray->At(i)); - if (!hit) - { + if (!hit) { continue; } TestDetectorProto::Hit* h = hp.add_hit(); @@ -57,10 +56,11 @@ void FairTestDetectorMQRecoTaskRebuild(const_cast(str->c_str()), - str->length(), - [](void* /* data */, void* obj) { delete static_cast(obj); }, - str); + fPayload->Rebuild( + const_cast(str->c_str()), + str->length(), + [](void* /* data */, void* obj) { delete static_cast(obj); }, + str); } #endif /* PROTOBUF */ diff --git a/examples/advanced/Tutorial3/MQ/processorTask/FairTestDetectorMQRecoTaskTMessage.tpl b/examples/advanced/Tutorial3/MQ/processorTask/FairTestDetectorMQRecoTaskTMessage.tpl index 695e5c4b83..6bdb432264 100644 --- a/examples/advanced/Tutorial3/MQ/processorTask/FairTestDetectorMQRecoTaskTMessage.tpl +++ b/examples/advanced/Tutorial3/MQ/processorTask/FairTestDetectorMQRecoTaskTMessage.tpl @@ -9,7 +9,7 @@ #include "RootSerializer.h" -template <> +template<> void FairTestDetectorMQRecoTask::Exec(Option_t* opt) { RootSerializer().Deserialize(*fPayload, fRecoTask.fDigiArray); diff --git a/examples/advanced/Tutorial3/MQ/run/runTestDetectorFileSink.cxx b/examples/advanced/Tutorial3/MQ/run/runTestDetectorFileSink.cxx index a4bc1ad725..9b158611f0 100644 --- a/examples/advanced/Tutorial3/MQ/run/runTestDetectorFileSink.cxx +++ b/examples/advanced/Tutorial3/MQ/run/runTestDetectorFileSink.cxx @@ -1,49 +1,63 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ -#include "runFairMQDevice.h" #include "FairTestDetectorFileSink.h" +#include "runFairMQDevice.h" namespace bpo = boost::program_options; void addCustomOptions(bpo::options_description& options) { + // clang-format off options.add_options() - ("in-channel", bpo::value()->default_value("data2"), "Name of the input channel") - ("ack-channel", bpo::value()->default_value("ack"), "Name of the acknowledgement channel") + ("in-channel", bpo::value()->default_value("data2"), "Name of the input channel") + ("ack-channel", bpo::value()->default_value("ack"), "Name of the acknowledgement channel") ("data-format", bpo::value()->default_value("binary"), "Data format (binary|boost|flatbuffers|msgpack|protobuf|tmessage)"); + // clang-format on } FairMQDevicePtr getDevice(const FairMQProgOptions& config) { std::string dataFormat = config.GetValue("data-format"); - if (dataFormat == "binary") { return new FairTestDetectorFileSink; } - else if (dataFormat == "boost") { - if (fair::base::serialization::has_BoostSerialization::value == 0) { - LOG(error) << "Boost serialization for Input Payload requested, but the input type does not support it. Check the TIn parameter. Aborting."; + if (dataFormat == "binary") { + return new FairTestDetectorFileSink; + } else if (dataFormat == "boost") { + if (fair::base::serialization::has_BoostSerialization::value + == 0) { + LOG(error) << "Boost serialization for Input Payload requested, but the input type does not support it. " + "Check the TIn parameter. Aborting."; return nullptr; } return new FairTestDetectorFileSink; + } else if (dataFormat == "tmessage") { + return new FairTestDetectorFileSink; } - else if (dataFormat == "tmessage") { return new FairTestDetectorFileSink; } #ifdef FLATBUFFERS - else if (dataFormat == "flatbuffers") { return new FairTestDetectorFileSink; } + else if (dataFormat == "flatbuffers") { + return new FairTestDetectorFileSink; + } #endif #ifdef MSGPACK - else if (dataFormat == "msgpack") { return new FairTestDetectorFileSink; } + else if (dataFormat == "msgpack") { + return new FairTestDetectorFileSink; + } #endif #ifdef PROTOBUF - else if (dataFormat == "protobuf") { return new FairTestDetectorFileSink; } + else if (dataFormat == "protobuf") { + return new FairTestDetectorFileSink; + } #endif - else - { - LOG(error) << "No valid data format provided. (--data-format binary|boost|flatbuffers|msgpack|protobuf|tmessage). "; + else { + LOG(error) + << "No valid data format provided. (--data-format binary|boost|flatbuffers|msgpack|protobuf|tmessage). "; return nullptr; } } diff --git a/examples/advanced/Tutorial3/MQ/run/runTestDetectorProcessor.cxx b/examples/advanced/Tutorial3/MQ/run/runTestDetectorProcessor.cxx index 240c0d4d00..b06c809bfd 100644 --- a/examples/advanced/Tutorial3/MQ/run/runTestDetectorProcessor.cxx +++ b/examples/advanced/Tutorial3/MQ/run/runTestDetectorProcessor.cxx @@ -6,50 +6,81 @@ * copied verbatim in the file "LICENSE" * ********************************************************************************/ -#include "runFairMQDevice.h" #include "FairMQProcessor.h" #include "FairTestDetectorMQRecoTask.h" +#include "runFairMQDevice.h" namespace bpo = boost::program_options; void addCustomOptions(bpo::options_description& options) { + // clang-format off options.add_options() - ("in-channel", bpo::value()->default_value("data1"), "Name of the input channel") - ("out-channel", bpo::value()->default_value("data2"), "Name of the output channel") + ("in-channel", bpo::value()->default_value("data1"), "Name of the input channel") + ("out-channel", bpo::value()->default_value("data2"), "Name of the output channel") ("data-format", bpo::value()->default_value("binary"), "Data format (binary|boost|flatbuffers|msgpack|protobuf|tmessage)"); + // clang-format on } FairMQDevicePtr getDevice(const FairMQProgOptions& config) { std::string dataFormat = config.GetValue("data-format"); - if (dataFormat == "binary") { return new FairMQProcessor>; } - else if (dataFormat == "boost") { - if (fair::base::serialization::has_BoostSerialization::value == 0) { - LOG(error) << "Boost serialization for Input Payload requested, but the input type does not support it. Check the TIn parameter. Aborting."; + if (dataFormat == "binary") { + return new FairMQProcessor>; + } else if (dataFormat == "boost") { + if (fair::base::serialization::has_BoostSerialization::value + == 0) { + LOG(error) << "Boost serialization for Input Payload requested, but the input type does not support it. " + "Check the TIn parameter. Aborting."; return nullptr; } - if (fair::base::serialization::has_BoostSerialization::value == 0) { - LOG(error) << "Boost serialization for Output Payload requested, but the output type does not support it. Check the TOut parameter. Aborting."; + if (fair::base::serialization::has_BoostSerialization::value + == 0) { + LOG(error) << "Boost serialization for Output Payload requested, but the output type does not support it. " + "Check the TOut parameter. Aborting."; return nullptr; } - return new FairMQProcessor>; + return new FairMQProcessor>; + } else if (dataFormat == "tmessage") { + return new FairMQProcessor< + FairTestDetectorMQRecoTask>; } - else if (dataFormat == "tmessage") { return new FairMQProcessor>; } #ifdef FLATBUFFERS - else if (dataFormat == "flatbuffers") { return new FairMQProcessor>; } + else if (dataFormat == "flatbuffers") { + return new FairMQProcessor>; + } #endif #ifdef MSGPACK - else if (dataFormat == "msgpack") { return new FairMQProcessor>; } + else if (dataFormat == "msgpack") { + return new FairMQProcessor< + FairTestDetectorMQRecoTask>; + } #endif #ifdef PROTOBUF - else if (dataFormat == "protobuf") { return new FairMQProcessor>; } + else if (dataFormat == "protobuf") { + return new FairMQProcessor>; + } #endif - else - { - LOG(error) << "No valid data format provided. (--data-format binary|boost|flatbuffers|msgpack|protobuf|tmessage). "; + else { + LOG(error) + << "No valid data format provided. (--data-format binary|boost|flatbuffers|msgpack|protobuf|tmessage). "; return nullptr; } } - diff --git a/examples/advanced/Tutorial3/MQ/run/runTestDetectorSampler.cxx b/examples/advanced/Tutorial3/MQ/run/runTestDetectorSampler.cxx index 77a7f7333f..e7f6cdf341 100644 --- a/examples/advanced/Tutorial3/MQ/run/runTestDetectorSampler.cxx +++ b/examples/advanced/Tutorial3/MQ/run/runTestDetectorSampler.cxx @@ -6,49 +6,63 @@ * copied verbatim in the file "LICENSE" * ********************************************************************************/ -#include "runFairMQDevice.h" #include "FairMQSampler.h" #include "FairTestDetectorDigiLoader.h" +#include "runFairMQDevice.h" namespace bpo = boost::program_options; void addCustomOptions(bpo::options_description& options) { + // clang-format off options.add_options() - ("data-format", bpo::value()->default_value("binary"), "Data format (binary|boost|flatbuffers|msgpack|protobuf|tmessage)") - ("input-file", bpo::value()->required(), "Path to the input file") - ("parameter-file", bpo::value()->default_value(""), "Path to the parameter file") - ("branch", bpo::value()->default_value("FairTestDetectorDigi"), "Name of the Branch") - ("out-channel", bpo::value()->default_value("data1"), "Name of the output channel") - ("ack-channel", bpo::value()->default_value("ack"), "Name of the acknowledgement channel") - ("chain-input", bpo::value()->default_value(0), "Chain input file more than once (default)"); + ("data-format", bpo::value()->default_value("binary"), "Data format (binary|boost|flatbuffers|msgpack|protobuf|tmessage)") + ("input-file", bpo::value()->required(), "Path to the input file") + ("parameter-file", bpo::value()->default_value(""), "Path to the parameter file") + ("branch", bpo::value()->default_value("FairTestDetectorDigi"), "Name of the Branch") + ("out-channel", bpo::value()->default_value("data1"), "Name of the output channel") + ("ack-channel", bpo::value()->default_value("ack"), "Name of the acknowledgement channel") + ("chain-input", bpo::value()->default_value(0), "Chain input file more than once (default)"); + // clang-format on } FairMQDevicePtr getDevice(const FairMQProgOptions& config) { std::string dataFormat = config.GetValue("data-format"); - if (dataFormat == "binary") { return new FairMQSampler>; } - else if (dataFormat == "boost") { - if (fair::base::serialization::has_BoostSerialization::value == 0) { - LOG(error) << "Boost serialization for Output Payload requested, but the output type does not support it. Check the TOut parameter. Aborting."; + if (dataFormat == "binary") { + return new FairMQSampler>; + } else if (dataFormat == "boost") { + if (fair::base::serialization::has_BoostSerialization::value + == 0) { + LOG(error) << "Boost serialization for Output Payload requested, but the output type does not support it. " + "Check the TOut parameter. Aborting."; return nullptr; } return new FairMQSampler>; + } else if (dataFormat == "tmessage") { + return new FairMQSampler>; } - else if (dataFormat == "tmessage") { return new FairMQSampler>; } #ifdef FLATBUFFERS - else if (dataFormat == "flatbuffers") { return new FairMQSampler>; } + else if (dataFormat == "flatbuffers") { + return new FairMQSampler>; + } #endif #ifdef MSGPACK - else if (dataFormat == "msgpack") { return new FairMQSampler>; } + else if (dataFormat == "msgpack") { + return new FairMQSampler>; + } #endif #ifdef PROTOBUF - else if (dataFormat == "protobuf") { return new FairMQSampler>; } + else if (dataFormat == "protobuf") { + return new FairMQSampler>; + } #endif - else - { - LOG(error) << "No valid data format provided. (--data-format binary|boost|flatbuffers|msgpack|protobuf|tmessage). "; + else { + LOG(error) + << "No valid data format provided. (--data-format binary|boost|flatbuffers|msgpack|protobuf|tmessage). "; exit(EXIT_FAILURE); } } diff --git a/examples/advanced/Tutorial3/MQ/samplerTask/FairTestDetectorDigiLoader.h b/examples/advanced/Tutorial3/MQ/samplerTask/FairTestDetectorDigiLoader.h index 425d5dd8bb..297cc51bf8 100644 --- a/examples/advanced/Tutorial3/MQ/samplerTask/FairTestDetectorDigiLoader.h +++ b/examples/advanced/Tutorial3/MQ/samplerTask/FairTestDetectorDigiLoader.h @@ -14,14 +14,13 @@ #ifndef FAIRTESTDETECTORDIGILOADER_H #define FAIRTESTDETECTORDIGILOADER_H -#include -#include - -#include "FairTestDetectorPayload.h" +#include "FairMQSamplerTask.h" #include "FairTestDetectorDigi.h" +#include "FairTestDetectorPayload.h" -#include "FairMQSamplerTask.h" #include +#include +#include template class FairTestDetectorDigiLoader : public FairMQSamplerTask diff --git a/examples/advanced/Tutorial3/MQ/samplerTask/FairTestDetectorDigiLoaderBin.tpl b/examples/advanced/Tutorial3/MQ/samplerTask/FairTestDetectorDigiLoaderBin.tpl index a2778319ac..975b71b7d4 100644 --- a/examples/advanced/Tutorial3/MQ/samplerTask/FairTestDetectorDigiLoaderBin.tpl +++ b/examples/advanced/Tutorial3/MQ/samplerTask/FairTestDetectorDigiLoaderBin.tpl @@ -6,7 +6,7 @@ */ // Implementation of FairTestDetectorDigiLoader::Exec() with pure binary transport data format -template <> +template<> void FairTestDetectorDigiLoader::Exec(Option_t* /*opt*/) { int numEntries = fInput->GetEntriesFast(); @@ -16,11 +16,9 @@ void FairTestDetectorDigiLoader TestDetectorPayload::Digi* digiPayload = static_cast(fPayload->GetData()); - for (int i = 0; i < numEntries; ++i) - { + for (int i = 0; i < numEntries; ++i) { FairTestDetectorDigi* digi = static_cast(fInput->At(i)); - if (!digi) - { + if (!digi) { continue; } new (&digiPayload[i]) TestDetectorPayload::Digi(); diff --git a/examples/advanced/Tutorial3/MQ/samplerTask/FairTestDetectorDigiLoaderBoost.tpl b/examples/advanced/Tutorial3/MQ/samplerTask/FairTestDetectorDigiLoaderBoost.tpl index f7d78af057..02ecc1cb65 100644 --- a/examples/advanced/Tutorial3/MQ/samplerTask/FairTestDetectorDigiLoaderBoost.tpl +++ b/examples/advanced/Tutorial3/MQ/samplerTask/FairTestDetectorDigiLoaderBoost.tpl @@ -11,7 +11,7 @@ // example TOut: FairTestDetectorDigi // example TPayloadOut: boost::archive::binary_oarchive -template +template void FairTestDetectorDigiLoader::Exec(Option_t* /*opt*/) { fPayload = FairMQMessagePtr(fTransportFactory->CreateMessage()); diff --git a/examples/advanced/Tutorial3/MQ/samplerTask/FairTestDetectorDigiLoaderFlatBuffers.tpl b/examples/advanced/Tutorial3/MQ/samplerTask/FairTestDetectorDigiLoaderFlatBuffers.tpl index 13e48e932f..5d69475af9 100644 --- a/examples/advanced/Tutorial3/MQ/samplerTask/FairTestDetectorDigiLoaderFlatBuffers.tpl +++ b/examples/advanced/Tutorial3/MQ/samplerTask/FairTestDetectorDigiLoaderFlatBuffers.tpl @@ -2,12 +2,12 @@ #ifdef FLATBUFFERS -#include "flatbuffers/flatbuffers.h" #include "FairTestDetectorPayloadDigi_generated.h" +#include "flatbuffers/flatbuffers.h" using namespace TestDetectorFlat; -template <> +template<> void FairTestDetectorDigiLoader::Exec(Option_t* /*opt*/) { int nDigis = fInput->GetEntriesFast(); @@ -15,35 +15,35 @@ void FairTestDetectorDigiLoader* digis = new flatbuffers::Offset[nDigis]; - for (int i = 0; i < nDigis; ++i) - { + for (int i = 0; i < nDigis; ++i) { FairTestDetectorDigi* digi = static_cast(fInput->At(i)); - if (!digi) - { + if (!digi) { continue; } DigiBuilder db(*builder); - db.add_x(digi->GetX()); // x:int - db.add_y(digi->GetY()); // y:int - db.add_z(digi->GetZ()); // z:int - db.add_timestamp(digi->GetTimeStamp()); // timestamp:double - db.add_timestampError(digi->GetTimeStampError()); // timestampError:double + db.add_x(digi->GetX()); // x:int + db.add_y(digi->GetY()); // y:int + db.add_z(digi->GetZ()); // z:int + db.add_timestamp(digi->GetTimeStamp()); // timestamp:double + db.add_timestampError(digi->GetTimeStampError()); // timestampError:double digis[i] = db.Finish(); - // LOG(info) << digi->GetX() << " " << digi->GetY() << " " << digi->GetZ() << " " << digi->GetTimeStamp() << " " << digi->GetTimeStampError(); + // LOG(info) << digi->GetX() << " " << digi->GetY() << " " << digi->GetZ() << " " << digi->GetTimeStamp() << " " + // << digi->GetTimeStampError(); } auto dvector = builder->CreateVector(digis, nDigis); auto mloc = CreateDigiPayload(*builder, dvector); FinishDigiPayloadBuffer(*builder, mloc); - delete [] digis; + delete[] digis; - fPayload = FairMQMessagePtr(fTransportFactory->CreateMessage(builder->GetBufferPointer(), - builder->GetSize(), - [](void* /* data */, void* obj) { delete static_cast(obj); }, - builder)); + fPayload = FairMQMessagePtr(fTransportFactory->CreateMessage( + builder->GetBufferPointer(), + builder->GetSize(), + [](void* /* data */, void* obj) { delete static_cast(obj); }, + builder)); } #endif /* FLATBUFFERS */ diff --git a/examples/advanced/Tutorial3/MQ/samplerTask/FairTestDetectorDigiLoaderMsgpack.tpl b/examples/advanced/Tutorial3/MQ/samplerTask/FairTestDetectorDigiLoaderMsgpack.tpl index cacce0cf58..74579f33cd 100644 --- a/examples/advanced/Tutorial3/MQ/samplerTask/FairTestDetectorDigiLoaderMsgpack.tpl +++ b/examples/advanced/Tutorial3/MQ/samplerTask/FairTestDetectorDigiLoaderMsgpack.tpl @@ -11,11 +11,12 @@ #include // Types to be used as template parameters. -struct MsgPack {}; -// struct MsgPackRef { msgpack::vrefbuffer vbuf; std::vector> digis; }; -// struct MsgPackStream {}; +struct MsgPack +{}; +// struct MsgPackRef { msgpack::vrefbuffer vbuf; std::vector> digis; +// }; struct MsgPackStream {}; -template <> +template<> void FairTestDetectorDigiLoader::Exec(Option_t* /*opt*/) { int nDigis = fInput->GetEntriesFast(); @@ -25,18 +26,19 @@ void FairTestDetectorDigiLoader::Exec(Option_t* / std::vector> digis; - for (int i = 0; i < nDigis; ++i) - { + for (int i = 0; i < nDigis; ++i) { FairTestDetectorDigi* digi = static_cast(fInput->At(i)); - digis.push_back(std::make_tuple(digi->GetX(), digi->GetY(), digi->GetZ(), digi->GetTimeStamp(), digi->GetTimeStampError())); + digis.push_back( + std::make_tuple(digi->GetX(), digi->GetY(), digi->GetZ(), digi->GetTimeStamp(), digi->GetTimeStampError())); } packer.pack(digis); - fPayload = FairMQMessagePtr(fTransportFactory->CreateMessage(sbuf->data(), - sbuf->size(), - [](void* /* data */, void* obj) { delete static_cast(obj); }, - sbuf)); + fPayload = FairMQMessagePtr(fTransportFactory->CreateMessage( + sbuf->data(), + sbuf->size(), + [](void* /* data */, void* obj) { delete static_cast(obj); }, + sbuf)); } // MsgPackRef version sends the vector of tuples without copying it into the sbuffer @@ -60,7 +62,8 @@ void FairTestDetectorDigiLoader::Exec(Option_t* / // msgpack::pack(container->vbuf, container->digis); -// fPayload = FairMQMessagePtr(fTransportFactory->CreateMessage(container->vbuf.vector()->iov_base, container->vbuf.vector()->iov_len, free_vrefbuffer, container)); +// fPayload = FairMQMessagePtr(fTransportFactory->CreateMessage(container->vbuf.vector()->iov_base, +// container->vbuf.vector()->iov_len, free_vrefbuffer, container)); // } // MsgPackStream version copies the data values into a stream of tuples. diff --git a/examples/advanced/Tutorial3/MQ/samplerTask/FairTestDetectorDigiLoaderProtobuf.tpl b/examples/advanced/Tutorial3/MQ/samplerTask/FairTestDetectorDigiLoaderProtobuf.tpl index 9a84e536d7..a01e130866 100644 --- a/examples/advanced/Tutorial3/MQ/samplerTask/FairTestDetectorDigiLoaderProtobuf.tpl +++ b/examples/advanced/Tutorial3/MQ/samplerTask/FairTestDetectorDigiLoaderProtobuf.tpl @@ -10,18 +10,16 @@ #include "FairTestDetectorPayload.pb.h" -template <> +template<> void FairTestDetectorDigiLoader::Exec(Option_t* /*opt*/) { int nDigis = fInput->GetEntriesFast(); TestDetectorProto::DigiPayload dp; - for (int i = 0; i < nDigis; ++i) - { + for (int i = 0; i < nDigis; ++i) { FairTestDetectorDigi* digi = static_cast(fInput->At(i)); - if (!digi) - { + if (!digi) { continue; } TestDetectorProto::Digi* d = dp.add_digi(); @@ -35,10 +33,11 @@ void FairTestDetectorDigiLoaderCreateMessage(const_cast(str->c_str()), - str->length(), - [](void* /* data */, void* obj) { delete static_cast(obj); }, - str)); + fPayload = FairMQMessagePtr(fTransportFactory->CreateMessage( + const_cast(str->c_str()), + str->length(), + [](void* /* data */, void* obj) { delete static_cast(obj); }, + str)); } #endif /* PROTOBUF */ diff --git a/examples/advanced/Tutorial3/MQ/samplerTask/FairTestDetectorDigiLoaderTMessage.tpl b/examples/advanced/Tutorial3/MQ/samplerTask/FairTestDetectorDigiLoaderTMessage.tpl index 31ccc852b0..8c5e2b4e35 100644 --- a/examples/advanced/Tutorial3/MQ/samplerTask/FairTestDetectorDigiLoaderTMessage.tpl +++ b/examples/advanced/Tutorial3/MQ/samplerTask/FairTestDetectorDigiLoaderTMessage.tpl @@ -9,7 +9,7 @@ #include "RootSerializer.h" -template <> +template<> void FairTestDetectorDigiLoader::Exec(Option_t* /*opt*/) { fPayload = FairMQMessagePtr(fTransportFactory->CreateMessage()); diff --git a/examples/advanced/Tutorial3/data/FairTestDetectorDigi.cxx b/examples/advanced/Tutorial3/data/FairTestDetectorDigi.cxx index e332f93cbe..1b52ea39d6 100644 --- a/examples/advanced/Tutorial3/data/FairTestDetectorDigi.cxx +++ b/examples/advanced/Tutorial3/data/FairTestDetectorDigi.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* @@ -20,17 +20,13 @@ FairTestDetectorDigi::FairTestDetectorDigi() , fX(0) , fY(0) , fZ(0) -{ -} +{} FairTestDetectorDigi::FairTestDetectorDigi(Int_t x, Int_t y, Int_t z, Double_t timeStamp) : FairTimeStamp(timeStamp) , fX(x) , fY(y) , fZ(z) -{ -} +{} -FairTestDetectorDigi::~FairTestDetectorDigi() -{ -} +FairTestDetectorDigi::~FairTestDetectorDigi() {} diff --git a/examples/advanced/Tutorial3/data/FairTestDetectorDigi.h b/examples/advanced/Tutorial3/data/FairTestDetectorDigi.h index 17009ada15..f56b01cd55 100644 --- a/examples/advanced/Tutorial3/data/FairTestDetectorDigi.h +++ b/examples/advanced/Tutorial3/data/FairTestDetectorDigi.h @@ -15,21 +15,23 @@ #ifndef FAIRTESTDETECTORDIGI_H_ #define FAIRTESTDETECTORDIGI_H_ -#include "FairTimeStamp.h" // for FairTimeStamp +#include "FairTimeStamp.h" // for FairTimeStamp -#include // for ostream -#include // for Int_t, etc - -#include // for operator<<, basic_ostream, etc +#include // for Int_t, etc +#include +#include // for ostream +#include // for operator<<, basic_ostream, etc #include #include - -#include -namespace boost { namespace serialization { class access; } } +namespace boost { +namespace serialization { +class access; +} +} // namespace boost class FairTestDetectorDigi : public FairTimeStamp { - public: + public: FairTestDetectorDigi(); FairTestDetectorDigi(Int_t x, Int_t y, Int_t z, Double_t timeStamp); virtual ~FairTestDetectorDigi(); @@ -40,42 +42,22 @@ class FairTestDetectorDigi : public FairTimeStamp SetY(y); SetZ(z); } - void SetX(Int_t x) - { - fX = x; - } - void SetY(Int_t y) - { - fY = y; - } - void SetZ(Int_t z) - { - fZ = z; - } + void SetX(Int_t x) { fX = x; } + void SetY(Int_t y) { fY = y; } + void SetZ(Int_t z) { fZ = z; } - Int_t GetX() const - { - return fX; - } - Int_t GetY() const - { - return fY; - } - Int_t GetZ() const - { - return fZ; - } + Int_t GetX() const { return fX; } + Int_t GetY() const { return fY; } + Int_t GetZ() const { return fZ; } // temporary to avoid serialisation of the parent class virtual bool equal(FairTimeStamp* data) { FairTestDetectorDigi* myDigi = dynamic_cast(data); - if (myDigi != 0) - { + if (myDigi != 0) { if (fX == myDigi->GetX()) if (fY == myDigi->GetY()) - if (fZ == myDigi->GetZ()) - { + if (fZ == myDigi->GetZ()) { return true; } } @@ -84,28 +66,19 @@ class FairTestDetectorDigi : public FairTimeStamp virtual bool operator<(const FairTestDetectorDigi& myDigi) const { - if (fX < myDigi.GetX()) - { + if (fX < myDigi.GetX()) { return true; - } - else if (fX > myDigi.GetX()) - { + } else if (fX > myDigi.GetX()) { return false; } - if (fY < myDigi.GetY()) - { + if (fY < myDigi.GetY()) { return true; - } - else if (fY > myDigi.GetY()) - { + } else if (fY > myDigi.GetY()) { return false; } - if (fZ < myDigi.GetZ()) - { + if (fZ < myDigi.GetZ()) { return true; - } - else if (fZ > myDigi.GetZ()) - { + } else if (fZ > myDigi.GetZ()) { return false; } return false; @@ -119,24 +92,23 @@ class FairTestDetectorDigi : public FairTimeStamp return out; } - template - std::string ToString (const T& value) + template + std::string ToString(const T& value) { - std::stringstream ss; - ss.precision(5); - ss << value; - return ss.str(); + std::stringstream ss; + ss.precision(5); + ss << value; + return ss.str(); } std::string ToString() { - std::string out = "FairTestDetectorDigi at: (" + ToString(GetX()) - + "/" + ToString(GetY()) + "/" + ToString(GetZ()) - + ") " + " with TimeStamp: " + ToString(GetTimeStamp()); - return out; + std::string out = "FairTestDetectorDigi at: (" + ToString(GetX()) + "/" + ToString(GetY()) + "/" + + ToString(GetZ()) + ") " + " with TimeStamp: " + ToString(GetTimeStamp()); + return out; } - template + template void serialize(Archive& ar, const unsigned int /*version*/) { ar& boost::serialization::base_object(*this); diff --git a/examples/advanced/Tutorial3/data/FairTestDetectorHit.cxx b/examples/advanced/Tutorial3/data/FairTestDetectorHit.cxx index 12ce731889..2b8295356b 100644 --- a/examples/advanced/Tutorial3/data/FairTestDetectorHit.cxx +++ b/examples/advanced/Tutorial3/data/FairTestDetectorHit.cxx @@ -1,24 +1,20 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "FairTestDetectorHit.h" FairTestDetectorHit::FairTestDetectorHit() : FairHit() -{ -} +{} FairTestDetectorHit::FairTestDetectorHit(Int_t detID, Int_t mcindex, const TVector3& pos, const TVector3& dpos) : FairHit(detID, pos, dpos, mcindex) -{ -} +{} -FairTestDetectorHit::~FairTestDetectorHit() -{ -} +FairTestDetectorHit::~FairTestDetectorHit() {} -ClassImp(FairTestDetectorHit) +ClassImp(FairTestDetectorHit); diff --git a/examples/advanced/Tutorial3/data/FairTestDetectorHit.h b/examples/advanced/Tutorial3/data/FairTestDetectorHit.h index f60d7a3107..45048fed93 100644 --- a/examples/advanced/Tutorial3/data/FairTestDetectorHit.h +++ b/examples/advanced/Tutorial3/data/FairTestDetectorHit.h @@ -1,19 +1,22 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRTESTDETECTORHIT_H_ #define FAIRTESTDETECTORHIT_H_ -#include "FairHit.h" // for FairHit - -#include // for FairTestDetectorHit::Class, etc +#include "FairHit.h" // for FairHit +#include // for FairTestDetectorHit::Class, etc #include -namespace boost { namespace serialization { class access; } } +namespace boost { +namespace serialization { +class access; +} +} // namespace boost class TVector3; @@ -29,7 +32,7 @@ class FairTestDetectorHit : public FairHit /** Destructor **/ virtual ~FairTestDetectorHit(); - template + template void serialize(Archive& ar, const unsigned int /*version*/) { ar& boost::serialization::base_object(*this); diff --git a/examples/advanced/Tutorial3/data/FairTestDetectorPoint.cxx b/examples/advanced/Tutorial3/data/FairTestDetectorPoint.cxx index b00da7c01e..62dcc2ad33 100644 --- a/examples/advanced/Tutorial3/data/FairTestDetectorPoint.cxx +++ b/examples/advanced/Tutorial3/data/FairTestDetectorPoint.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "FairTestDetectorPoint.h" @@ -17,8 +17,7 @@ FairTestDetectorPoint::FairTestDetectorPoint() , fPx_out(0.) , fPy_out(0.) , fPz_out(0.) -{ -} +{} FairTestDetectorPoint::FairTestDetectorPoint(Int_t trackID, Int_t detID, @@ -36,21 +35,18 @@ FairTestDetectorPoint::FairTestDetectorPoint(Int_t trackID, , fPx_out(momOut.Px()) , fPy_out(momOut.Py()) , fPz_out(momOut.Pz()) -{ -} +{} -FairTestDetectorPoint::~FairTestDetectorPoint() -{ -} +FairTestDetectorPoint::~FairTestDetectorPoint() {} void FairTestDetectorPoint::Print(const Option_t* /*opt*/) const { - LOG(info) << "FairTestDetectorPoint: FairTestDetector point for track " - << fTrackID << " in detector " << fDetectorID ; - LOG(info) << " Position (" << fX << ", " << fY << ", " << fZ << ") cm" ; + LOG(info) << "FairTestDetectorPoint: FairTestDetector point for track " << fTrackID << " in detector " + << fDetectorID; + LOG(info) << " Position (" << fX << ", " << fY << ", " << fZ << ") cm"; LOG(info) << " Momentum (" << fPx << ", " << fPy << ", " << fPz << ") GeV"; - LOG(info) << " Time " << fTime << " ns, Length " << fLength - << " cm, Energy loss " << fELoss * 1.0e06 << " keV" ; + LOG(info) << " Time " << fTime << " ns, Length " << fLength << " cm, Energy loss " << fELoss * 1.0e06 + << " keV"; } -ClassImp(FairTestDetectorPoint) +ClassImp(FairTestDetectorPoint); diff --git a/examples/advanced/Tutorial3/data/FairTestDetectorPoint.h b/examples/advanced/Tutorial3/data/FairTestDetectorPoint.h index 448d6f396d..915c7ea0b7 100644 --- a/examples/advanced/Tutorial3/data/FairTestDetectorPoint.h +++ b/examples/advanced/Tutorial3/data/FairTestDetectorPoint.h @@ -1,17 +1,17 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRTESTDETECTORPOINT_H_ #define FAIRTESTDETECTORPOINT_H_ -#include "FairMCPoint.h" // for FairMCPoint +#include "FairMCPoint.h" // for FairMCPoint -#include // for Double_t, Double32_t, etc -#include // for TVector3 +#include // for Double_t, Double32_t, etc +#include // for TVector3 class FairTestDetectorPoint : public FairMCPoint { @@ -45,63 +45,21 @@ class FairTestDetectorPoint : public FairMCPoint virtual void Print(const Option_t* opt) const; /** Accessors **/ - Double_t GetXIn() const - { - return fX; - } - Double_t GetYIn() const - { - return fY; - } - Double_t GetZIn() const - { - return fZ; - } - Double_t GetXOut() const - { - return fX_out; - } - Double_t GetYOut() const - { - return fY_out; - } - Double_t GetZOut() const - { - return fZ_out; - } - Double_t GetPxOut() const - { - return fPx_out; - } - Double_t GetPyOut() const - { - return fPy_out; - } - Double_t GetPzOut() const - { - return fPz_out; - } - Double_t GetPxIn() const - { - return fPx; - } - Double_t GetPyIn() const - { - return fPy; - } - Double_t GetPzIn() const - { - return fPz; - } + Double_t GetXIn() const { return fX; } + Double_t GetYIn() const { return fY; } + Double_t GetZIn() const { return fZ; } + Double_t GetXOut() const { return fX_out; } + Double_t GetYOut() const { return fY_out; } + Double_t GetZOut() const { return fZ_out; } + Double_t GetPxOut() const { return fPx_out; } + Double_t GetPyOut() const { return fPy_out; } + Double_t GetPzOut() const { return fPz_out; } + Double_t GetPxIn() const { return fPx; } + Double_t GetPyIn() const { return fPy; } + Double_t GetPzIn() const { return fPz; } - void PositionOut(TVector3& pos) const - { - pos.SetXYZ(fX_out, fY_out, fZ_out); - } - void MomentumOut(TVector3& mom) const - { - mom.SetXYZ(fPx_out, fPy_out, fPz_out); - } + void PositionOut(TVector3& pos) const { pos.SetXYZ(fX_out, fY_out, fZ_out); } + void MomentumOut(TVector3& mom) const { mom.SetXYZ(fPx_out, fPy_out, fPz_out); } private: Double32_t fX_out; diff --git a/examples/advanced/Tutorial3/digitization/FairTestDetectorDigiTask.cxx b/examples/advanced/Tutorial3/digitization/FairTestDetectorDigiTask.cxx index 29a56b717a..e5645899c1 100644 --- a/examples/advanced/Tutorial3/digitization/FairTestDetectorDigiTask.cxx +++ b/examples/advanced/Tutorial3/digitization/FairTestDetectorDigiTask.cxx @@ -1,48 +1,42 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "FairTestDetectorDigiTask.h" -#include "FairLink.h" // for FairLink -#include "FairRootManager.h" // for FairRootManager -#include "FairTestDetectorDigi.h" // for FairTestDetectorDigi -#include "FairTestDetectorPoint.h" // for FairTestDetectorPoint +#include "FairLink.h" // for FairLink +#include "FairRootManager.h" // for FairRootManager +#include "FairTestDetectorDigi.h" // for FairTestDetectorDigi +#include "FairTestDetectorPoint.h" // for FairTestDetectorPoint -#include // for TClonesArray -#include // for Sqrt -#include // for TRandom, gRandom - -#include // for operator<<, basic_ostream, etc +#include // for TClonesArray +#include // for Sqrt +#include // for TRandom, gRandom +#include // for operator<<, basic_ostream, etc FairTestDetectorDigiTask::FairTestDetectorDigiTask() : FairTask("TestDetectorDigTask") , fTimeResolution(0.) , fPointArray(nullptr) , fDigiArray(nullptr) -{ -} +{} -FairTestDetectorDigiTask::~FairTestDetectorDigiTask() -{ -} +FairTestDetectorDigiTask::~FairTestDetectorDigiTask() {} InitStatus FairTestDetectorDigiTask::Init() { FairRootManager* ioman = FairRootManager::Instance(); - if (!ioman) - { - std::cout << "-E- FairTestDetectorDigiTask::Init: " /// todo replace with logger! + if (!ioman) { + std::cout << "-E- FairTestDetectorDigiTask::Init: " /// todo replace with logger! << "RootManager not instantiated!" << std::endl; return kFATAL; } fPointArray = static_cast(ioman->GetObject("FairTestDetectorPoint")); - if (!fPointArray) - { + if (!fPointArray) { std::cout << "-W- FairTestDetectorDigiTask::Init: " << "No Point array!" << std::endl; return kERROR; @@ -62,11 +56,9 @@ void FairTestDetectorDigiTask::Exec(Option_t* /*opt*/) // fill the map - for (int ipnt = 0; ipnt < fPointArray->GetEntries(); ipnt++) - { + for (int ipnt = 0; ipnt < fPointArray->GetEntries(); ipnt++) { FairTestDetectorPoint* point = static_cast(fPointArray->At(ipnt)); - if (!point) - { + if (!point) { continue; } @@ -77,12 +69,9 @@ void FairTestDetectorDigiTask::Exec(Option_t* /*opt*/) Double_t timestamp = CalcTimeStamp(point->GetTime()); FairTestDetectorDigi* digi = new ((*fDigiArray)[ipnt]) FairTestDetectorDigi(xPad, yPad, zPad, timestamp); - if (fTimeResolution > 0) - { + if (fTimeResolution > 0) { digi->SetTimeStampError(fTimeResolution / TMath::Sqrt(fTimeResolution)); - } - else - { + } else { digi->SetTimeStampError(0); } @@ -103,14 +92,11 @@ Double_t FairTestDetectorDigiTask::CalcTimeStamp(Double_t timeOfFlight) Double_t result = eventTime + timeOfFlight + detectionTime; - if (result < 0) - { + if (result < 0) { return 0; - } - else - { + } else { return result; } } -ClassImp(FairTestDetectorDigiTask) +ClassImp(FairTestDetectorDigiTask); diff --git a/examples/advanced/Tutorial3/digitization/FairTestDetectorDigiTask.h b/examples/advanced/Tutorial3/digitization/FairTestDetectorDigiTask.h index 1a3d45fd8e..eb889a894a 100644 --- a/examples/advanced/Tutorial3/digitization/FairTestDetectorDigiTask.h +++ b/examples/advanced/Tutorial3/digitization/FairTestDetectorDigiTask.h @@ -1,16 +1,16 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRTESTDETECTORDIGITASK_H_ #define FAIRTESTDETECTORDIGITASK_H_ -#include "FairTask.h" // for FairTask, InitStatus +#include "FairTask.h" // for FairTask, InitStatus -#include // for Double_t, etc +#include // for Double_t, etc class TClonesArray; @@ -29,14 +29,8 @@ class FairTestDetectorDigiTask : public FairTask /** Virtual method Exec **/ virtual void Exec(Option_t* opt); - void SetTimeResolution(Double_t timeInNs) - { - fTimeResolution = timeInNs; - } - Double_t GetTimeResolution() - { - return fTimeResolution; - } + void SetTimeResolution(Double_t timeInNs) { fTimeResolution = timeInNs; } + Double_t GetTimeResolution() { return fTimeResolution; } private: Int_t CalcPad(Double_t posIn, Double_t posOut); diff --git a/examples/advanced/Tutorial3/digitization/FairTestDetectorHitProducerSmearing.cxx b/examples/advanced/Tutorial3/digitization/FairTestDetectorHitProducerSmearing.cxx index 33ceabfea5..fe97824c9c 100644 --- a/examples/advanced/Tutorial3/digitization/FairTestDetectorHitProducerSmearing.cxx +++ b/examples/advanced/Tutorial3/digitization/FairTestDetectorHitProducerSmearing.cxx @@ -1,40 +1,39 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "FairTestDetectorHitProducerSmearing.h" -#include "FairLogger.h" // for FairLogger, MESSAGE_ORIGIN -#include "FairRootManager.h" // for FairRootManager -#include "FairTestDetectorHit.h" // for FairTestDetectorHit -#include "FairTestDetectorPoint.h" // for FairTestDetectorPoint +#include "FairLogger.h" // for FairLogger, MESSAGE_ORIGIN +#include "FairRootManager.h" // for FairRootManager +#include "FairTestDetectorHit.h" // for FairTestDetectorHit +#include "FairTestDetectorPoint.h" // for FairTestDetectorPoint -#include // for TClonesArray -#include // for TRandom, gRandom -#include // for TVector3 +#include // for TClonesArray +#include // for TRandom, gRandom +#include // for TVector3 FairTestDetectorHitProducerSmearing::FairTestDetectorHitProducerSmearing() : FairTask("FairTestDetectorHitProducerSmearing") , fPointsArray(nullptr) , fHitsArray(new TClonesArray("FairTestDetectorHit", 100)) { - LOG(debug) << "Default Constructor of FairTestDetectorHitProducerSmearing"; + LOG(debug) << "Default Constructor of FairTestDetectorHitProducerSmearing"; } FairTestDetectorHitProducerSmearing::~FairTestDetectorHitProducerSmearing() { - LOG(debug) << "Destructor of FairTestDetectorHitProducerSmearing"; + LOG(debug) << "Destructor of FairTestDetectorHitProducerSmearing"; fHitsArray->Delete(); delete fHitsArray; } void FairTestDetectorHitProducerSmearing::SetParContainers() { - LOG(debug) << "SetParContainers of FairTestDetectorHitProducerSmearing" -; + LOG(debug) << "SetParContainers of FairTestDetectorHitProducerSmearing"; // Load all necessary parameter containers from the runtime data base /* FairRunAna* ana = FairRunAna::Instance(); @@ -47,17 +46,16 @@ void FairTestDetectorHitProducerSmearing::SetParContainers() InitStatus FairTestDetectorHitProducerSmearing::Init() { - LOG(debug) << "Initilization of FairTestDetectorHitProducerSmearing"; + LOG(debug) << "Initilization of FairTestDetectorHitProducerSmearing"; // Get a handle from the IO manager FairRootManager* ioman = FairRootManager::Instance(); // Get a pointer to the previous already existing data level fPointsArray = static_cast(ioman->GetObject("FairTestDetectorPoint")); - if (!fPointsArray) - { - LOG(error) << "No InputDataLevelName array!"; - LOG(error) << "FairTestDetectorHitProducerSmearing will be inactive"; + if (!fPointsArray) { + LOG(error) << "No InputDataLevelName array!"; + LOG(error) << "FairTestDetectorHitProducerSmearing will be inactive"; return kERROR; } @@ -74,24 +72,22 @@ InitStatus FairTestDetectorHitProducerSmearing::Init() InitStatus FairTestDetectorHitProducerSmearing::ReInit() { - LOG(debug) << "Reinitilization of FairTestDetectorHitProducerSmearing"; + LOG(debug) << "Reinitilization of FairTestDetectorHitProducerSmearing"; return kSUCCESS; } void FairTestDetectorHitProducerSmearing::Exec(Option_t* /*option*/) { - LOG(debug) << "Exec of FairTestDetectorHitProducerSmearing"; + LOG(debug) << "Exec of FairTestDetectorHitProducerSmearing"; fHitsArray->Delete(); // fill the map FairTestDetectorPoint* point = nullptr; // FairTestDetectorHit* hit = nullptr; - for (int iPoint = 0; iPoint < fPointsArray->GetEntriesFast(); iPoint++) - { + for (int iPoint = 0; iPoint < fPointsArray->GetEntriesFast(); iPoint++) { point = static_cast(fPointsArray->At(iPoint)); - if (!point) - { + if (!point) { continue; } @@ -109,9 +105,6 @@ void FairTestDetectorHitProducerSmearing::Exec(Option_t* /*option*/) } } -void FairTestDetectorHitProducerSmearing::Finish() -{ - LOG(debug) << "Finish of FairTestDetectorHitProducerSmearing"; -} +void FairTestDetectorHitProducerSmearing::Finish() { LOG(debug) << "Finish of FairTestDetectorHitProducerSmearing"; } -ClassImp(FairTestDetectorHitProducerSmearing) +ClassImp(FairTestDetectorHitProducerSmearing); diff --git a/examples/advanced/Tutorial3/digitization/FairTestDetectorHitProducerSmearing.h b/examples/advanced/Tutorial3/digitization/FairTestDetectorHitProducerSmearing.h index f97b1877f1..65036ce962 100644 --- a/examples/advanced/Tutorial3/digitization/FairTestDetectorHitProducerSmearing.h +++ b/examples/advanced/Tutorial3/digitization/FairTestDetectorHitProducerSmearing.h @@ -1,16 +1,16 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRTESTDETECTORHITPRODUCERSMEARING_H_ #define FAIRTESTDETECTORHITPRODUCERSMEARING_H_ -#include "FairTask.h" // for InitStatus, FairTask +#include "FairTask.h" // for InitStatus, FairTask -#include // for ClassDef +#include // for ClassDef class TClonesArray; diff --git a/examples/advanced/Tutorial3/macro/eventDisplay.C b/examples/advanced/Tutorial3/macro/eventDisplay.C index 5d549ff47b..f3943b3d4d 100644 --- a/examples/advanced/Tutorial3/macro/eventDisplay.C +++ b/examples/advanced/Tutorial3/macro/eventDisplay.C @@ -5,37 +5,36 @@ * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ -eventDisplay(TString mcEngine="TGeant3") +eventDisplay(TString mcEngine = "TGeant3") { - //-----User Settings:----------------------------------------------- - TString InputFile ="data/testrun_" + mcEngine + ".root"; - TString ParFile ="data/testparams_" + mcEngine + ".root"; - TString OutFile ="data/tst.root"; - //------------------------------------------------------------------ + //-----User Settings:----------------------------------------------- + TString InputFile = "data/testrun_" + mcEngine + ".root"; + TString ParFile = "data/testparams_" + mcEngine + ".root"; + TString OutFile = "data/tst.root"; + //------------------------------------------------------------------ - // ----- Reconstruction run ------------------------------------------- - FairRunAna *fRun= new FairRunAna(); - FairFileSource *fFileSource = new FairFileSource(InputFile); - fRun->SetSource(fFileSource); + // ----- Reconstruction run ------------------------------------------- + FairRunAna *fRun = new FairRunAna(); + FairFileSource *fFileSource = new FairFileSource(InputFile); + fRun->SetSource(fFileSource); - fRun->SetSink(new FairRootFileSink(OutFile.Data())); + fRun->SetSink(new FairRootFileSink(OutFile.Data())); - FairRuntimeDb* rtdb = fRun->GetRuntimeDb(); - FairParRootFileIo* parInput1 = new FairParRootFileIo(); - parInput1->open(ParFile.Data()); - rtdb->setFirstInput(parInput1); + FairRuntimeDb *rtdb = fRun->GetRuntimeDb(); + FairParRootFileIo *parInput1 = new FairParRootFileIo(); + parInput1->open(ParFile.Data()); + rtdb->setFirstInput(parInput1); - FairEventManager *fMan= new FairEventManager(); + FairEventManager *fMan = new FairEventManager(); - //----------------------Traks and points ------------------------------------- - FairMCTracks *Track = new FairMCTracks("Monte-Carlo Tracks"); - FairMCPointDraw *TorinoDetectorPoints = new FairMCPointDraw("FairTestDetectorPoint", kRed, kFullSquare); -// FairHitDraw *ToyHits = new FairHitDraw("ToyHit"); + //----------------------Traks and points ------------------------------------- + FairMCTracks *Track = new FairMCTracks("Monte-Carlo Tracks"); + FairMCPointDraw *TorinoDetectorPoints = new FairMCPointDraw("FairTestDetectorPoint", kRed, kFullSquare); + // FairHitDraw *ToyHits = new FairHitDraw("ToyHit"); - fMan->AddTask(Track); - fMan->AddTask(TorinoDetectorPoints); -// fMan->AddTask(ToyHits); + fMan->AddTask(Track); + fMan->AddTask(TorinoDetectorPoints); + // fMan->AddTask(ToyHits); - - fMan->Init(); + fMan->Init(); } diff --git a/examples/advanced/Tutorial3/macro/run_digi.C b/examples/advanced/Tutorial3/macro/run_digi.C index e64add1776..e40c1009c6 100644 --- a/examples/advanced/Tutorial3/macro/run_digi.C +++ b/examples/advanced/Tutorial3/macro/run_digi.C @@ -5,86 +5,84 @@ * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ -void run_digi( TString mcEngine="TGeant3" ) +void run_digi(TString mcEngine = "TGeant3") { - FairLogger *logger = FairLogger::GetLogger(); - // logger->SetLogFileName("MyLog.log"); - // logger->SetLogToScreen(kTRUE); -// logger->SetLogToFile(kTRUE); - logger->SetLogVerbosityLevel("LOW"); -// logger->SetLogFileLevel("DEBUG4"); -// logger->SetLogScreenLevel("DEBUG"); - - // Verbosity level (0=quiet, 1=event level, 2=track level, 3=debug) - Int_t iVerbose = 0; // just forget about it, for the moment - - // Input file (MC events) - TString inFile = "data/testrun_"; - inFile = inFile + mcEngine + ".root"; - - // Parameter file - TString parFile = "data/testparams_"; - parFile = parFile + mcEngine + ".root"; - - // Output file - TString outFile = "data/testdigi_"; - outFile = outFile + mcEngine + ".root"; - - // ----- Timer -------------------------------------------------------- - TStopwatch timer; - - // ----- Reconstruction run ------------------------------------------- - FairRunAna *fRun= new FairRunAna(); - FairFileSource *fFileSource = new FairFileSource(inFile); - fRun->SetSource(fFileSource); - fRun->SetSink(new FairRootFileSink(outFile)); - fRun->SetUseFairLinks(kTRUE); - FairLinkManager::Instance()->AddIncludeType(0); -// FairLinkManager::Instance()->AddIncludeType(1); - fRun->SetGenerateRunInfo(kTRUE); // Create FairRunInfo file - - FairRuntimeDb* rtdb = fRun->GetRuntimeDb(); - FairParRootFileIo* parInput1 = new FairParRootFileIo(); - parInput1->open(parFile.Data()); - rtdb->setFirstInput(parInput1); - - // ----- TorinoDetector hit producers --------------------------------- - FairTestDetectorDigiTask* digiTask = new FairTestDetectorDigiTask(); - fRun->AddTask(digiTask); - - - fRun->Init(); - - timer.Start(); - fRun->Run(); - - // ----- Finish ------------------------------------------------------- - - cout << endl << endl; - - // Extract the maximal used memory an add is as Dart measurement - // This line is filtered by CTest and the value send to CDash - FairSystemInfo sysInfo; - Float_t maxMemory=sysInfo.GetMaxMemory(); - cout << ""; - cout << maxMemory; - cout << "" << endl; - - timer.Stop(); - Double_t rtime = timer.RealTime(); - Double_t ctime = timer.CpuTime(); - - Float_t cpuUsage=ctime/rtime; - cout << ""; - cout << cpuUsage; - cout << "" << endl; - - cout << endl << endl; - cout << "Output file is " << outFile << endl; - cout << "Parameter file is " << parFile << endl; - cout << "Real time " << rtime << " s, CPU time " << ctime - << "s" << endl << endl; - cout << "Macro finished successfully." << endl; - - // ------------------------------------------------------------------------ + FairLogger* logger = FairLogger::GetLogger(); + // logger->SetLogFileName("MyLog.log"); + // logger->SetLogToScreen(kTRUE); + // logger->SetLogToFile(kTRUE); + logger->SetLogVerbosityLevel("LOW"); + // logger->SetLogFileLevel("DEBUG4"); + // logger->SetLogScreenLevel("DEBUG"); + + // Verbosity level (0=quiet, 1=event level, 2=track level, 3=debug) + Int_t iVerbose = 0; // just forget about it, for the moment + + // Input file (MC events) + TString inFile = "data/testrun_"; + inFile = inFile + mcEngine + ".root"; + + // Parameter file + TString parFile = "data/testparams_"; + parFile = parFile + mcEngine + ".root"; + + // Output file + TString outFile = "data/testdigi_"; + outFile = outFile + mcEngine + ".root"; + + // ----- Timer -------------------------------------------------------- + TStopwatch timer; + + // ----- Reconstruction run ------------------------------------------- + FairRunAna* fRun = new FairRunAna(); + FairFileSource* fFileSource = new FairFileSource(inFile); + fRun->SetSource(fFileSource); + fRun->SetSink(new FairRootFileSink(outFile)); + fRun->SetUseFairLinks(kTRUE); + FairLinkManager::Instance()->AddIncludeType(0); + // FairLinkManager::Instance()->AddIncludeType(1); + fRun->SetGenerateRunInfo(kTRUE); // Create FairRunInfo file + + FairRuntimeDb* rtdb = fRun->GetRuntimeDb(); + FairParRootFileIo* parInput1 = new FairParRootFileIo(); + parInput1->open(parFile.Data()); + rtdb->setFirstInput(parInput1); + + // ----- TorinoDetector hit producers --------------------------------- + FairTestDetectorDigiTask* digiTask = new FairTestDetectorDigiTask(); + fRun->AddTask(digiTask); + + fRun->Init(); + + timer.Start(); + fRun->Run(); + + // ----- Finish ------------------------------------------------------- + + cout << endl << endl; + + // Extract the maximal used memory an add is as Dart measurement + // This line is filtered by CTest and the value send to CDash + FairSystemInfo sysInfo; + Float_t maxMemory = sysInfo.GetMaxMemory(); + cout << ""; + cout << maxMemory; + cout << "" << endl; + + timer.Stop(); + Double_t rtime = timer.RealTime(); + Double_t ctime = timer.CpuTime(); + + Float_t cpuUsage = ctime / rtime; + cout << ""; + cout << cpuUsage; + cout << "" << endl; + + cout << endl << endl; + cout << "Output file is " << outFile << endl; + cout << "Parameter file is " << parFile << endl; + cout << "Real time " << rtime << " s, CPU time " << ctime << "s" << endl << endl; + cout << "Macro finished successfully." << endl; + + // ------------------------------------------------------------------------ } diff --git a/examples/advanced/Tutorial3/macro/run_digi_reco_local.C b/examples/advanced/Tutorial3/macro/run_digi_reco_local.C index 6b6de4e690..170be12e40 100644 --- a/examples/advanced/Tutorial3/macro/run_digi_reco_local.C +++ b/examples/advanced/Tutorial3/macro/run_digi_reco_local.C @@ -1,97 +1,96 @@ -void run_digi_reco_local(Int_t nofFiles, TString mcEngine="TGeant3" ) +void run_digi_reco_local(Int_t nofFiles, TString mcEngine = "TGeant3") { - FairLogger *logger = FairLogger::GetLogger(); - // logger->SetLogFileName("MyLog.log"); - // logger->SetLogToScreen(kTRUE); -// logger->SetLogToFile(kTRUE); - logger->SetLogVerbosityLevel("LOW"); -// logger->SetLogFileLevel("DEBUG4"); -// logger->SetLogScreenLevel("DEBUG"); + FairLogger* logger = FairLogger::GetLogger(); + // logger->SetLogFileName("MyLog.log"); + // logger->SetLogToScreen(kTRUE); + // logger->SetLogToFile(kTRUE); + logger->SetLogVerbosityLevel("LOW"); + // logger->SetLogFileLevel("DEBUG4"); + // logger->SetLogScreenLevel("DEBUG"); - TString workDir = gSystem->WorkingDirectory(); + TString workDir = gSystem->WorkingDirectory(); - // Verbosity level (0=quiet, 1=event level, 2=track level, 3=debug) - Int_t iVerbose = 0; // just forget about it, for the moment + // Verbosity level (0=quiet, 1=event level, 2=track level, 3=debug) + Int_t iVerbose = 0; // just forget about it, for the moment - // Input file (MC events) - // TString inFile = "data/testrun_"; - // inFile = inFile + mcEngine + ".root"; + // Input file (MC events) + // TString inFile = "data/testrun_"; + // inFile = inFile + mcEngine + ".root"; - // Parameter file - // TString parFile = "data/testparams_"; - // parFile = parFile + mcEngine + ".root"; + // Parameter file + // TString parFile = "data/testparams_"; + // parFile = parFile + mcEngine + ".root"; - // Output file - TString outFile = Form("data/testDiReLo_%df_",nofFiles); - outFile = outFile + mcEngine + ".root"; + // Output file + TString outFile = Form("data/testDiReLo_%df_", nofFiles); + outFile = outFile + mcEngine + ".root"; - // ----- Timer -------------------------------------------------------- - TStopwatch timer; + // ----- Timer -------------------------------------------------------- + TStopwatch timer; - // ----- Reconstruction run ------------------------------------------- - FairRunAna *fRun= new FairRunAna(); - TString inFile=Form("file://%s/data/testrun_%s_f%d.root",workDir.Data(),mcEngine.Data(),0); - FairFileSource *fFileSource = new FairFileSource(inFile); - fRun->SetSource(fFileSource); + // ----- Reconstruction run ------------------------------------------- + FairRunAna* fRun = new FairRunAna(); + TString inFile = Form("file://%s/data/testrun_%s_f%d.root", workDir.Data(), mcEngine.Data(), 0); + FairFileSource* fFileSource = new FairFileSource(inFile); + fRun->SetSource(fFileSource); - for ( Int_t ifile = 1 ; ifile < nofFiles ; ifile++ ) { - cout << "fRun->AddFile(....f" << ifile << ".root" << endl; - fFileSource->AddFile(Form("file://%s/data/testrun_%s_f%d.root",workDir.Data(),mcEngine.Data(),ifile)); - } + for (Int_t ifile = 1; ifile < nofFiles; ifile++) { + cout << "fRun->AddFile(....f" << ifile << ".root" << endl; + fFileSource->AddFile(Form("file://%s/data/testrun_%s_f%d.root", workDir.Data(), mcEngine.Data(), ifile)); + } - fRun->SetSink(new FairRootFileSink(outFile)); + fRun->SetSink(new FairRootFileSink(outFile)); - FairRuntimeDb* rtdb = fRun->GetRuntimeDb(); - FairParRootFileIo* parInput1 = new FairParRootFileIo(); + FairRuntimeDb* rtdb = fRun->GetRuntimeDb(); + FairParRootFileIo* parInput1 = new FairParRootFileIo(); - TList* fnamelist = new TList(); + TList* fnamelist = new TList(); - for ( Int_t ifile = 0 ; ifile < nofFiles ; ifile++ ) - fnamelist->Add(new TObjString(Form("%s/data/testpar_%s_f%d.root",workDir.Data(),mcEngine.Data(),ifile))); + for (Int_t ifile = 0; ifile < nofFiles; ifile++) + fnamelist->Add(new TObjString(Form("%s/data/testpar_%s_f%d.root", workDir.Data(), mcEngine.Data(), ifile))); - cout << "PAR LIST CREATED" << endl; - parInput1->open(fnamelist); - // parInput1->open(parFile.Data()); + cout << "PAR LIST CREATED" << endl; + parInput1->open(fnamelist); + // parInput1->open(parFile.Data()); - rtdb->setFirstInput(parInput1); + rtdb->setFirstInput(parInput1); - FairTestDetectorDigiTask* digiTask = new FairTestDetectorDigiTask(); - fRun->AddTask(digiTask); + FairTestDetectorDigiTask* digiTask = new FairTestDetectorDigiTask(); + fRun->AddTask(digiTask); - FairTestDetectorRecoTask* hitProducer = new FairTestDetectorRecoTask(); - fRun->AddTask(hitProducer); + FairTestDetectorRecoTask* hitProducer = new FairTestDetectorRecoTask(); + fRun->AddTask(hitProducer); - fRun->Init(); + fRun->Init(); - timer.Start(); - fRun->Run(); + timer.Start(); + fRun->Run(); - // ----- Finish ------------------------------------------------------- + // ----- Finish ------------------------------------------------------- - cout << endl << endl; + cout << endl << endl; - // Extract the maximal used memory an add is as Dart measurement - // This line is filtered by CTest and the value send to CDash - FairSystemInfo sysInfo; - Float_t maxMemory=sysInfo.GetMaxMemory(); - cout << ""; - cout << maxMemory; - cout << "" << endl; + // Extract the maximal used memory an add is as Dart measurement + // This line is filtered by CTest and the value send to CDash + FairSystemInfo sysInfo; + Float_t maxMemory = sysInfo.GetMaxMemory(); + cout << ""; + cout << maxMemory; + cout << "" << endl; - timer.Stop(); - Double_t rtime = timer.RealTime(); - Double_t ctime = timer.CpuTime(); + timer.Stop(); + Double_t rtime = timer.RealTime(); + Double_t ctime = timer.CpuTime(); - Float_t cpuUsage=ctime/rtime; - cout << ""; - cout << cpuUsage; - cout << "" << endl; + Float_t cpuUsage = ctime / rtime; + cout << ""; + cout << cpuUsage; + cout << "" << endl; - cout << endl << endl; - cout << "Output file is " << outFile << endl; - cout << "Real time " << rtime << " s, CPU time " << ctime - << "s" << endl << endl; - cout << "Macro finished successfully." << endl; + cout << endl << endl; + cout << "Output file is " << outFile << endl; + cout << "Real time " << rtime << " s, CPU time " << ctime << "s" << endl << endl; + cout << "Macro finished successfully." << endl; - // ------------------------------------------------------------------------ + // ------------------------------------------------------------------------ } diff --git a/examples/advanced/Tutorial3/macro/run_digi_reco_one.C b/examples/advanced/Tutorial3/macro/run_digi_reco_one.C index 7a87eb0e2a..370e5d75b8 100644 --- a/examples/advanced/Tutorial3/macro/run_digi_reco_one.C +++ b/examples/advanced/Tutorial3/macro/run_digi_reco_one.C @@ -1,93 +1,92 @@ -void run_digi_reco_one( TString mcEngine="TGeant3" ) +void run_digi_reco_one(TString mcEngine = "TGeant3") { - FairLogger *logger = FairLogger::GetLogger(); - // logger->SetLogFileName("MyLog.log"); - // logger->SetLogToScreen(kTRUE); -// logger->SetLogToFile(kTRUE); - logger->SetLogVerbosityLevel("LOW"); -// logger->SetLogFileLevel("DEBUG4"); -// logger->SetLogScreenLevel("DEBUG"); + FairLogger* logger = FairLogger::GetLogger(); + // logger->SetLogFileName("MyLog.log"); + // logger->SetLogToScreen(kTRUE); + // logger->SetLogToFile(kTRUE); + logger->SetLogVerbosityLevel("LOW"); + // logger->SetLogFileLevel("DEBUG4"); + // logger->SetLogScreenLevel("DEBUG"); - TString workDir = gSystem->WorkingDirectory(); + TString workDir = gSystem->WorkingDirectory(); - // Verbosity level (0=quiet, 1=event level, 2=track level, 3=debug) - Int_t iVerbose = 0; // just forget about it, for the moment + // Verbosity level (0=quiet, 1=event level, 2=track level, 3=debug) + Int_t iVerbose = 0; // just forget about it, for the moment - // Input file (MC events) - // TString inFile = "data/testrun_"; - // inFile = inFile + mcEngine + ".root"; + // Input file (MC events) + // TString inFile = "data/testrun_"; + // inFile = inFile + mcEngine + ".root"; - // Parameter file - // TString parFile = "data/testparams_"; - // parFile = parFile + mcEngine + ".root"; + // Parameter file + // TString parFile = "data/testparams_"; + // parFile = parFile + mcEngine + ".root"; - // Output file - TString outFile = Form("data/testDiReOne_"); - outFile = outFile + mcEngine + ".root"; + // Output file + TString outFile = Form("data/testDiReOne_"); + outFile = outFile + mcEngine + ".root"; - // ----- Timer -------------------------------------------------------- - TStopwatch timer; + // ----- Timer -------------------------------------------------------- + TStopwatch timer; - // ----- Reconstruction run ------------------------------------------- - FairRunAna *fRun= new FairRunAna(); - TString inFile=Form("file://%s/data/testrun_%s_f%d.root",workDir.Data(),mcEngine.Data(),0); - FairFileSource *fFileSource = new FairFileSource(inFile); - fRun->SetSource(fFileSource); + // ----- Reconstruction run ------------------------------------------- + FairRunAna* fRun = new FairRunAna(); + TString inFile = Form("file://%s/data/testrun_%s_f%d.root", workDir.Data(), mcEngine.Data(), 0); + FairFileSource* fFileSource = new FairFileSource(inFile); + fRun->SetSource(fFileSource); - fRun->SetSink(new FairRootFileSink(outFile)); + fRun->SetSink(new FairRootFileSink(outFile)); - FairRuntimeDb* rtdb = fRun->GetRuntimeDb(); - FairParRootFileIo* parInput1 = new FairParRootFileIo(); + FairRuntimeDb* rtdb = fRun->GetRuntimeDb(); + FairParRootFileIo* parInput1 = new FairParRootFileIo(); - TList* fnamelist = new TList(); + TList* fnamelist = new TList(); - Int_t ifile = 0; - TString parFile = Form("%s/data/testpar_%s_f%d.root",workDir.Data(),mcEngine.Data(),ifile); + Int_t ifile = 0; + TString parFile = Form("%s/data/testpar_%s_f%d.root", workDir.Data(), mcEngine.Data(), ifile); - cout << "PAR LIST CREATED" << endl; - // parInput1->open(fnamelist); - parInput1->open(parFile.Data()); + cout << "PAR LIST CREATED" << endl; + // parInput1->open(fnamelist); + parInput1->open(parFile.Data()); - rtdb->setFirstInput(parInput1); + rtdb->setFirstInput(parInput1); - FairTestDetectorDigiTask* digiTask = new FairTestDetectorDigiTask(); - fRun->AddTask(digiTask); + FairTestDetectorDigiTask* digiTask = new FairTestDetectorDigiTask(); + fRun->AddTask(digiTask); - FairTestDetectorRecoTask* hitProducer = new FairTestDetectorRecoTask(); - fRun->AddTask(hitProducer); + FairTestDetectorRecoTask* hitProducer = new FairTestDetectorRecoTask(); + fRun->AddTask(hitProducer); - fRun->Init(); + fRun->Init(); - timer.Start(); - fRun->Run(); + timer.Start(); + fRun->Run(); - // ----- Finish ------------------------------------------------------- + // ----- Finish ------------------------------------------------------- - cout << endl << endl; + cout << endl << endl; - // Extract the maximal used memory an add is as Dart measurement - // This line is filtered by CTest and the value send to CDash - FairSystemInfo sysInfo; - Float_t maxMemory=sysInfo.GetMaxMemory(); - cout << ""; - cout << maxMemory; - cout << "" << endl; + // Extract the maximal used memory an add is as Dart measurement + // This line is filtered by CTest and the value send to CDash + FairSystemInfo sysInfo; + Float_t maxMemory = sysInfo.GetMaxMemory(); + cout << ""; + cout << maxMemory; + cout << "" << endl; - timer.Stop(); - Double_t rtime = timer.RealTime(); - Double_t ctime = timer.CpuTime(); + timer.Stop(); + Double_t rtime = timer.RealTime(); + Double_t ctime = timer.CpuTime(); - Float_t cpuUsage=ctime/rtime; - cout << ""; - cout << cpuUsage; - cout << "" << endl; + Float_t cpuUsage = ctime / rtime; + cout << ""; + cout << cpuUsage; + cout << "" << endl; - cout << endl << endl; - cout << "Output file is " << outFile << endl; - cout << "Parameter file is " << parFile << endl; - cout << "Real time " << rtime << " s, CPU time " << ctime - << "s" << endl << endl; - cout << "Macro finished successfully." << endl; + cout << endl << endl; + cout << "Output file is " << outFile << endl; + cout << "Parameter file is " << parFile << endl; + cout << "Real time " << rtime << " s, CPU time " << ctime << "s" << endl << endl; + cout << "Macro finished successfully." << endl; - // ------------------------------------------------------------------------ + // ------------------------------------------------------------------------ } diff --git a/examples/advanced/Tutorial3/macro/run_digi_reco_proof.C b/examples/advanced/Tutorial3/macro/run_digi_reco_proof.C index f213f96dec..93ce2a6f83 100644 --- a/examples/advanced/Tutorial3/macro/run_digi_reco_proof.C +++ b/examples/advanced/Tutorial3/macro/run_digi_reco_proof.C @@ -1,102 +1,101 @@ -void run_digi_reco_proof(Int_t nofFiles, TString mcEngine="TGeant3" ) +void run_digi_reco_proof(Int_t nofFiles, TString mcEngine = "TGeant3") { - FairLogger *logger = FairLogger::GetLogger(); - // logger->SetLogFileName("MyLog.log"); - // logger->SetLogToScreen(kTRUE); -// logger->SetLogToFile(kTRUE); - logger->SetLogVerbosityLevel("LOW"); -// logger->SetLogFileLevel("DEBUG4"); -// logger->SetLogScreenLevel("DEBUG"); + FairLogger* logger = FairLogger::GetLogger(); + // logger->SetLogFileName("MyLog.log"); + // logger->SetLogToScreen(kTRUE); + // logger->SetLogToFile(kTRUE); + logger->SetLogVerbosityLevel("LOW"); + // logger->SetLogFileLevel("DEBUG4"); + // logger->SetLogScreenLevel("DEBUG"); - TString workDir = gSystem->WorkingDirectory(); + TString workDir = gSystem->WorkingDirectory(); - // Verbosity level (0=quiet, 1=event level, 2=track level, 3=debug) - Int_t iVerbose = 0; // just forget about it, for the moment + // Verbosity level (0=quiet, 1=event level, 2=track level, 3=debug) + Int_t iVerbose = 0; // just forget about it, for the moment - // Input file (MC events) - // TString inFile = "data/testrun_"; - // inFile = inFile + mcEngine + ".root"; + // Input file (MC events) + // TString inFile = "data/testrun_"; + // inFile = inFile + mcEngine + ".root"; - // Parameter file - // TString parFile = "data/testparams_"; - // parFile = parFile + mcEngine + ".root"; + // Parameter file + // TString parFile = "data/testparams_"; + // parFile = parFile + mcEngine + ".root"; - // Output file - TString outFile = Form("data/testDiRePr_%df_",nofFiles); - if ( nofFiles == 1 ) - outFile = "data/testDiRePr_"; - outFile = outFile + mcEngine + ".root"; + // Output file + TString outFile = Form("data/testDiRePr_%df_", nofFiles); + if (nofFiles == 1) + outFile = "data/testDiRePr_"; + outFile = outFile + mcEngine + ".root"; - // ----- Timer -------------------------------------------------------- - TStopwatch timer; + // ----- Timer -------------------------------------------------------- + TStopwatch timer; - // ----- Reconstruction run ------------------------------------------- - FairRunAnaProof *fRun= new FairRunAnaProof("workers=4"); - TString inFile=Form("file://%s/data/testrun_%s_f%d.root",workDir.Data(),mcEngine.Data(),0); - if ( nofFiles == 1 ) - inFile=Form("file://%s/data/testrun_%s.root",workDir.Data(),mcEngine.Data()); - FairFileSource *fFileSource = new FairFileSource(inFile); - fRun->SetSource(fFileSource); - for ( Int_t ifile = 1 ; ifile < nofFiles ; ifile++ ) - fFileSource->AddFile(Form("file://%s/data/testrun_%s_f%d.root",workDir.Data(),mcEngine.Data(),ifile)); + // ----- Reconstruction run ------------------------------------------- + FairRunAnaProof* fRun = new FairRunAnaProof("workers=4"); + TString inFile = Form("file://%s/data/testrun_%s_f%d.root", workDir.Data(), mcEngine.Data(), 0); + if (nofFiles == 1) + inFile = Form("file://%s/data/testrun_%s.root", workDir.Data(), mcEngine.Data()); + FairFileSource* fFileSource = new FairFileSource(inFile); + fRun->SetSource(fFileSource); + for (Int_t ifile = 1; ifile < nofFiles; ifile++) + fFileSource->AddFile(Form("file://%s/data/testrun_%s_f%d.root", workDir.Data(), mcEngine.Data(), ifile)); - fRun->SetSink(new FairRootFileSink(outFile)); - fRun->SetProofOutputStatus("merge"); + fRun->SetSink(new FairRootFileSink(outFile)); + fRun->SetProofOutputStatus("merge"); - FairRuntimeDb* rtdb = fRun->GetRuntimeDb(); - FairParRootFileIo* parInput1 = new FairParRootFileIo(); + FairRuntimeDb* rtdb = fRun->GetRuntimeDb(); + FairParRootFileIo* parInput1 = new FairParRootFileIo(); - TList* fnamelist = new TList(); + TList* fnamelist = new TList(); - if ( nofFiles == 1 ) - fnamelist->Add(new TObjString(Form("%s/data/testparams_%s.root",workDir.Data(),mcEngine.Data()))); - else - for ( Int_t ifile = 0 ; ifile < nofFiles ; ifile++ ) - fnamelist->Add(new TObjString(Form("%s/data/testpar_%s_f%d.root",workDir.Data(),mcEngine.Data(),ifile))); + if (nofFiles == 1) + fnamelist->Add(new TObjString(Form("%s/data/testparams_%s.root", workDir.Data(), mcEngine.Data()))); + else + for (Int_t ifile = 0; ifile < nofFiles; ifile++) + fnamelist->Add(new TObjString(Form("%s/data/testpar_%s_f%d.root", workDir.Data(), mcEngine.Data(), ifile))); - cout << "PAR LIST CREATED" << endl; - parInput1->open(fnamelist); + cout << "PAR LIST CREATED" << endl; + parInput1->open(fnamelist); - rtdb->setFirstInput(parInput1); + rtdb->setFirstInput(parInput1); - FairTestDetectorDigiTask* digiTask = new FairTestDetectorDigiTask(); - fRun->AddTask(digiTask); + FairTestDetectorDigiTask* digiTask = new FairTestDetectorDigiTask(); + fRun->AddTask(digiTask); - FairTestDetectorRecoTask* hitProducer = new FairTestDetectorRecoTask(); - fRun->AddTask(hitProducer); + FairTestDetectorRecoTask* hitProducer = new FairTestDetectorRecoTask(); + fRun->AddTask(hitProducer); - fRun->Init(); + fRun->Init(); - cout << "... Init done" << endl; - timer.Start(); - fRun->Run(); + cout << "... Init done" << endl; + timer.Start(); + fRun->Run(); - // ----- Finish ------------------------------------------------------- + // ----- Finish ------------------------------------------------------- - cout << endl << endl; + cout << endl << endl; - // Extract the maximal used memory an add is as Dart measurement - // This line is filtered by CTest and the value send to CDash - FairSystemInfo sysInfo; - Float_t maxMemory=sysInfo.GetMaxMemory(); - cout << ""; - cout << maxMemory; - cout << "" << endl; + // Extract the maximal used memory an add is as Dart measurement + // This line is filtered by CTest and the value send to CDash + FairSystemInfo sysInfo; + Float_t maxMemory = sysInfo.GetMaxMemory(); + cout << ""; + cout << maxMemory; + cout << "" << endl; - timer.Stop(); - Double_t rtime = timer.RealTime(); - Double_t ctime = timer.CpuTime(); + timer.Stop(); + Double_t rtime = timer.RealTime(); + Double_t ctime = timer.CpuTime(); - Float_t cpuUsage=ctime/rtime; - cout << ""; - cout << cpuUsage; - cout << "" << endl; + Float_t cpuUsage = ctime / rtime; + cout << ""; + cout << cpuUsage; + cout << "" << endl; - cout << endl << endl; - cout << "Output file is " << outFile << endl; - cout << "Real time " << rtime << " s, CPU time " << ctime - << "s" << endl << endl; - cout << "Macro finished successfully." << endl; + cout << endl << endl; + cout << "Output file is " << outFile << endl; + cout << "Real time " << rtime << " s, CPU time " << ctime << "s" << endl << endl; + cout << "Macro finished successfully." << endl; - // ------------------------------------------------------------------------ + // ------------------------------------------------------------------------ } diff --git a/examples/advanced/Tutorial3/macro/run_digi_timebased.C b/examples/advanced/Tutorial3/macro/run_digi_timebased.C index 0a4ef6eeaa..1209742318 100644 --- a/examples/advanced/Tutorial3/macro/run_digi_timebased.C +++ b/examples/advanced/Tutorial3/macro/run_digi_timebased.C @@ -5,90 +5,89 @@ * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ -void run_digi_timebased( TString mcEngine="TGeant3" ) +void run_digi_timebased(TString mcEngine = "TGeant3") { - FairLogger *logger = FairLogger::GetLogger(); - logger->SetLogFileName("MyLog.log"); - logger->SetLogToScreen(kTRUE); -// logger->SetLogToFile(kTRUE); - logger->SetLogVerbosityLevel("HIGH"); -// logger->SetLogFileLevel("DEBUG4"); - logger->SetLogScreenLevel("DEBUG"); - - // Verbosity level (0=quiet, 1=event level, 2=track level, 3=debug) - Int_t iVerbose = 0; // just forget about it, for the moment - - // Input file (MC events) - TString inFile = "data/testrun_"; - inFile = inFile + mcEngine + ".root"; - - // Parameter file - TString parFile = "data/testparams_"; - parFile = parFile + mcEngine + ".root"; - - // Output file - TString outFile = "data/testdigitimebased_"; - outFile = outFile + mcEngine + ".root"; - - // ----- Timer -------------------------------------------------------- - TStopwatch timer; - - // ----- Reconstruction run ------------------------------------------- - FairRunAna *fRun= new FairRunAna(); - FairFileSource *fFileSource = new FairFileSource(inFile); - fRun->SetSource(fFileSource); - - fRun->SetSink(new FairRootFileSink(outFile)); - fRun->SetUseFairLinks(kTRUE); - - fRun->SetEventMeanTime(50); - - FairRuntimeDb* rtdb = fRun->GetRuntimeDb(); - FairParRootFileIo* parInput1 = new FairParRootFileIo(); - parInput1->open(parFile.Data()); - rtdb->setFirstInput(parInput1); - - // ----- TorinoDetector hit producers --------------------------------- - FairTestDetectorTimeDigiTask* digiProducer = new FairTestDetectorTimeDigiTask(); - digiProducer->RunTimeBased(); - fRun->AddTask(digiProducer); - - FairTestDetectorDigiSorterTask* digiSorter = new FairTestDetectorDigiSorterTask(5000, 50, "FairTestDetectorDigi", "FairTestDetectorSortedDigi", "toy"); - fRun->AddTask(digiSorter); - - - fRun->Init(); - - timer.Start(); - fRun->Run(); - - // ----- Finish ------------------------------------------------------- - - cout << endl << endl; - - // Extract the maximal used memory an add is as Dart measurement - // This line is filtered by CTest and the value send to CDash - FairSystemInfo sysInfo; - Float_t maxMemory=sysInfo.GetMaxMemory(); - cout << ""; - cout << maxMemory; - cout << "" << endl; - - timer.Stop(); - Double_t rtime = timer.RealTime(); - Double_t ctime = timer.CpuTime(); - - Float_t cpuUsage=ctime/rtime; - cout << ""; - cout << cpuUsage; - cout << "" << endl; - - cout << endl << endl; - cout << "Output file is " << outFile << endl; - cout << "Parameter file is " << parFile << endl; - cout << "Real time " << rtime << " s, CPU time " << ctime - << "s" << endl << endl; - cout << "Macro finished successfully." << endl; - - // ------------------------------------------------------------------------ + FairLogger* logger = FairLogger::GetLogger(); + logger->SetLogFileName("MyLog.log"); + logger->SetLogToScreen(kTRUE); + // logger->SetLogToFile(kTRUE); + logger->SetLogVerbosityLevel("HIGH"); + // logger->SetLogFileLevel("DEBUG4"); + logger->SetLogScreenLevel("DEBUG"); + + // Verbosity level (0=quiet, 1=event level, 2=track level, 3=debug) + Int_t iVerbose = 0; // just forget about it, for the moment + + // Input file (MC events) + TString inFile = "data/testrun_"; + inFile = inFile + mcEngine + ".root"; + + // Parameter file + TString parFile = "data/testparams_"; + parFile = parFile + mcEngine + ".root"; + + // Output file + TString outFile = "data/testdigitimebased_"; + outFile = outFile + mcEngine + ".root"; + + // ----- Timer -------------------------------------------------------- + TStopwatch timer; + + // ----- Reconstruction run ------------------------------------------- + FairRunAna* fRun = new FairRunAna(); + FairFileSource* fFileSource = new FairFileSource(inFile); + fRun->SetSource(fFileSource); + + fRun->SetSink(new FairRootFileSink(outFile)); + fRun->SetUseFairLinks(kTRUE); + + fRun->SetEventMeanTime(50); + + FairRuntimeDb* rtdb = fRun->GetRuntimeDb(); + FairParRootFileIo* parInput1 = new FairParRootFileIo(); + parInput1->open(parFile.Data()); + rtdb->setFirstInput(parInput1); + + // ----- TorinoDetector hit producers --------------------------------- + FairTestDetectorTimeDigiTask* digiProducer = new FairTestDetectorTimeDigiTask(); + digiProducer->RunTimeBased(); + fRun->AddTask(digiProducer); + + FairTestDetectorDigiSorterTask* digiSorter = + new FairTestDetectorDigiSorterTask(5000, 50, "FairTestDetectorDigi", "FairTestDetectorSortedDigi", "toy"); + fRun->AddTask(digiSorter); + + fRun->Init(); + + timer.Start(); + fRun->Run(); + + // ----- Finish ------------------------------------------------------- + + cout << endl << endl; + + // Extract the maximal used memory an add is as Dart measurement + // This line is filtered by CTest and the value send to CDash + FairSystemInfo sysInfo; + Float_t maxMemory = sysInfo.GetMaxMemory(); + cout << ""; + cout << maxMemory; + cout << "" << endl; + + timer.Stop(); + Double_t rtime = timer.RealTime(); + Double_t ctime = timer.CpuTime(); + + Float_t cpuUsage = ctime / rtime; + cout << ""; + cout << cpuUsage; + cout << "" << endl; + + cout << endl << endl; + cout << "Output file is " << outFile << endl; + cout << "Parameter file is " << parFile << endl; + cout << "Real time " << rtime << " s, CPU time " << ctime << "s" << endl << endl; + cout << "Macro finished successfully." << endl; + + // ------------------------------------------------------------------------ } diff --git a/examples/advanced/Tutorial3/macro/run_reco.C b/examples/advanced/Tutorial3/macro/run_reco.C index 9771624382..cc4a0d042e 100644 --- a/examples/advanced/Tutorial3/macro/run_reco.C +++ b/examples/advanced/Tutorial3/macro/run_reco.C @@ -5,89 +5,86 @@ * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ -void run_reco( TString mcEngine="TGeant3" ) +void run_reco(TString mcEngine = "TGeant3") { - gSystem->Load("libFairTestDetector"); - FairLogger *logger = FairLogger::GetLogger(); - logger->SetLogFileName("MyLog.log"); - logger->SetLogToScreen(kTRUE); -// logger->SetLogToFile(kTRUE); - logger->SetLogVerbosityLevel("LOW"); -// logger->SetLogFileLevel("DEBUG4"); - logger->SetLogScreenLevel("INFO"); - - // Verbosity level (0=quiet, 1=event level, 2=track level, 3=debug) - Int_t iVerbose = 0; // just forget about it, for the moment - - // Input file (MC events) - TString inFile = "data/testdigi_"; - inFile = inFile + mcEngine + ".root"; - - // Parameter file - TString parFile = "data/testparams_"; - parFile = parFile + mcEngine + ".root"; - - // Output file - TString outFile = "data/testreco_"; - outFile = outFile + mcEngine + ".root"; - - // ----- Timer -------------------------------------------------------- - TStopwatch timer; - - // ----- Reconstruction run ------------------------------------------- - FairRunAna *fRun= new FairRunAna(); - FairFileSource *fFileSource = new FairFileSource(inFile); - fRun->SetSource(fFileSource); - fRun->SetSink(new FairRootFileSink(outFile)); - fRun->SetUseFairLinks(kTRUE); - FairLinkManager::Instance()->AddIncludeType(0); -// FairLinkManager::Instance()->AddIncludeType(1); - fRun->SetGenerateRunInfo(kTRUE); // Create FairRunInfo file - - - FairRuntimeDb* rtdb = fRun->GetRuntimeDb(); - FairParRootFileIo* parInput1 = new FairParRootFileIo(); - parInput1->open(parFile.Data()); - rtdb->setFirstInput(parInput1); - - // ----- TorinoDetector hit producers --------------------------------- - FairTestDetectorRecoTask* hitProducer = new FairTestDetectorRecoTask(); - fRun->AddTask(hitProducer); - - - fRun->Init(); - - timer.Start(); - fRun->Run(); - - // ----- Finish ------------------------------------------------------- - - cout << endl << endl; - - // Extract the maximal used memory an add is as Dart measurement - // This line is filtered by CTest and the value send to CDash - FairSystemInfo sysInfo; - Float_t maxMemory=sysInfo.GetMaxMemory(); - cout << ""; - cout << maxMemory; - cout << "" << endl; - - timer.Stop(); - Double_t rtime = timer.RealTime(); - Double_t ctime = timer.CpuTime(); - - Float_t cpuUsage=ctime/rtime; - cout << ""; - cout << cpuUsage; - cout << "" << endl; - - cout << endl << endl; - cout << "Output file is " << outFile << endl; - cout << "Parameter file is " << parFile << endl; - cout << "Real time " << rtime << " s, CPU time " << ctime - << "s" << endl << endl; - cout << "Macro finished successfully." << endl; - - // ------------------------------------------------------------------------ + gSystem->Load("libFairTestDetector"); + FairLogger* logger = FairLogger::GetLogger(); + logger->SetLogFileName("MyLog.log"); + logger->SetLogToScreen(kTRUE); + // logger->SetLogToFile(kTRUE); + logger->SetLogVerbosityLevel("LOW"); + // logger->SetLogFileLevel("DEBUG4"); + logger->SetLogScreenLevel("INFO"); + + // Verbosity level (0=quiet, 1=event level, 2=track level, 3=debug) + Int_t iVerbose = 0; // just forget about it, for the moment + + // Input file (MC events) + TString inFile = "data/testdigi_"; + inFile = inFile + mcEngine + ".root"; + + // Parameter file + TString parFile = "data/testparams_"; + parFile = parFile + mcEngine + ".root"; + + // Output file + TString outFile = "data/testreco_"; + outFile = outFile + mcEngine + ".root"; + + // ----- Timer -------------------------------------------------------- + TStopwatch timer; + + // ----- Reconstruction run ------------------------------------------- + FairRunAna* fRun = new FairRunAna(); + FairFileSource* fFileSource = new FairFileSource(inFile); + fRun->SetSource(fFileSource); + fRun->SetSink(new FairRootFileSink(outFile)); + fRun->SetUseFairLinks(kTRUE); + FairLinkManager::Instance()->AddIncludeType(0); + // FairLinkManager::Instance()->AddIncludeType(1); + fRun->SetGenerateRunInfo(kTRUE); // Create FairRunInfo file + + FairRuntimeDb* rtdb = fRun->GetRuntimeDb(); + FairParRootFileIo* parInput1 = new FairParRootFileIo(); + parInput1->open(parFile.Data()); + rtdb->setFirstInput(parInput1); + + // ----- TorinoDetector hit producers --------------------------------- + FairTestDetectorRecoTask* hitProducer = new FairTestDetectorRecoTask(); + fRun->AddTask(hitProducer); + + fRun->Init(); + + timer.Start(); + fRun->Run(); + + // ----- Finish ------------------------------------------------------- + + cout << endl << endl; + + // Extract the maximal used memory an add is as Dart measurement + // This line is filtered by CTest and the value send to CDash + FairSystemInfo sysInfo; + Float_t maxMemory = sysInfo.GetMaxMemory(); + cout << ""; + cout << maxMemory; + cout << "" << endl; + + timer.Stop(); + Double_t rtime = timer.RealTime(); + Double_t ctime = timer.CpuTime(); + + Float_t cpuUsage = ctime / rtime; + cout << ""; + cout << cpuUsage; + cout << "" << endl; + + cout << endl << endl; + cout << "Output file is " << outFile << endl; + cout << "Parameter file is " << parFile << endl; + cout << "Real time " << rtime << " s, CPU time " << ctime << "s" << endl << endl; + cout << "Macro finished successfully." << endl; + + // ------------------------------------------------------------------------ } diff --git a/examples/advanced/Tutorial3/macro/run_reco_timebased.C b/examples/advanced/Tutorial3/macro/run_reco_timebased.C index c266f266b3..1e3581a7d6 100644 --- a/examples/advanced/Tutorial3/macro/run_reco_timebased.C +++ b/examples/advanced/Tutorial3/macro/run_reco_timebased.C @@ -2,86 +2,85 @@ * 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, * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ -void run_reco_timebased(TString mcEngine = "TGeant3") { - FairLogger *logger = FairLogger::GetLogger(); - logger->SetLogFileName("MyLog.log"); - // logger->SetLogToScreen(kTRUE); - // logger->SetLogToFile(kTRUE); - // logger->SetLogVerbosityLevel("HIGH"); - // logger->SetLogFileLevel("DEBUG4"); - // logger->SetLogScreenLevel("DEBUG"); - - // Verbosity level (0=quiet, 1=event level, 2=track level, 3=debug) - Int_t iVerbose = 0; // just forget about it, for the moment - - // Input file (MC events) - TString inFile = "data/testdigitimebased_"; - inFile = inFile + mcEngine + ".root"; - - // Parameter file - TString parFile = "data/testparams_"; - parFile = parFile + mcEngine + ".root"; - - // Output file - TString outFile = "data/testrecotimebased_"; - outFile = outFile + mcEngine + ".root"; - - // ----- Timer -------------------------------------------------------- - TStopwatch timer; - - // ----- Reconstruction run ------------------------------------------- - - FairRunAna *fRun = new FairRunAna(); - FairFileSource *fFileSource = new FairFileSource(inFile); - fRun->SetSink(new FairRootFileSink(outFile)); - fRun->RunWithTimeStamps(); - fRun->SetUseFairLinks(kTRUE); - - FairRuntimeDb *rtdb = fRun->GetRuntimeDb(); - FairParRootFileIo *parInput1 = new FairParRootFileIo(); - parInput1->open(parFile.Data()); - rtdb->setFirstInput(parInput1); - - // ----- TorinoDetector hit producers --------------------------------- - FairTestDetectorTimeRecoTask *hitProducer = - new FairTestDetectorTimeRecoTask(); - fRun->AddTask(hitProducer); - - fRun->Init(); - - timer.Start(); - fRun->Run(); - - // ----- Finish ------------------------------------------------------- - - cout << endl << endl; - - // Extract the maximal used memory an add is as Dart measurement - // This line is filtered by CTest and the value send to CDash - FairSystemInfo sysInfo; - Float_t maxMemory = sysInfo.GetMaxMemory(); - cout << ""; - cout << maxMemory; - cout << "" << endl; - - timer.Stop(); - Double_t rtime = timer.RealTime(); - Double_t ctime = timer.CpuTime(); - - Float_t cpuUsage = ctime / rtime; - cout << ""; - cout << cpuUsage; - cout << "" << endl; - - cout << endl << endl; - cout << "Output file is " << outFile << endl; - cout << "Parameter file is " << parFile << endl; - cout << "Real time " << rtime << " s, CPU time " << ctime << "s" << endl - << endl; - cout << "Macro finished successfully." << endl; - - // ------------------------------------------------------------------------ +void run_reco_timebased(TString mcEngine = "TGeant3") +{ + FairLogger *logger = FairLogger::GetLogger(); + logger->SetLogFileName("MyLog.log"); + // logger->SetLogToScreen(kTRUE); + // logger->SetLogToFile(kTRUE); + // logger->SetLogVerbosityLevel("HIGH"); + // logger->SetLogFileLevel("DEBUG4"); + // logger->SetLogScreenLevel("DEBUG"); + + // Verbosity level (0=quiet, 1=event level, 2=track level, 3=debug) + Int_t iVerbose = 0; // just forget about it, for the moment + + // Input file (MC events) + TString inFile = "data/testdigitimebased_"; + inFile = inFile + mcEngine + ".root"; + + // Parameter file + TString parFile = "data/testparams_"; + parFile = parFile + mcEngine + ".root"; + + // Output file + TString outFile = "data/testrecotimebased_"; + outFile = outFile + mcEngine + ".root"; + + // ----- Timer -------------------------------------------------------- + TStopwatch timer; + + // ----- Reconstruction run ------------------------------------------- + + FairRunAna *fRun = new FairRunAna(); + FairFileSource *fFileSource = new FairFileSource(inFile); + fRun->SetSink(new FairRootFileSink(outFile)); + fRun->RunWithTimeStamps(); + fRun->SetUseFairLinks(kTRUE); + + FairRuntimeDb *rtdb = fRun->GetRuntimeDb(); + FairParRootFileIo *parInput1 = new FairParRootFileIo(); + parInput1->open(parFile.Data()); + rtdb->setFirstInput(parInput1); + + // ----- TorinoDetector hit producers --------------------------------- + FairTestDetectorTimeRecoTask *hitProducer = new FairTestDetectorTimeRecoTask(); + fRun->AddTask(hitProducer); + + fRun->Init(); + + timer.Start(); + fRun->Run(); + + // ----- Finish ------------------------------------------------------- + + cout << endl << endl; + + // Extract the maximal used memory an add is as Dart measurement + // This line is filtered by CTest and the value send to CDash + FairSystemInfo sysInfo; + Float_t maxMemory = sysInfo.GetMaxMemory(); + cout << ""; + cout << maxMemory; + cout << "" << endl; + + timer.Stop(); + Double_t rtime = timer.RealTime(); + Double_t ctime = timer.CpuTime(); + + Float_t cpuUsage = ctime / rtime; + cout << ""; + cout << cpuUsage; + cout << "" << endl; + + cout << endl << endl; + cout << "Output file is " << outFile << endl; + cout << "Parameter file is " << parFile << endl; + cout << "Real time " << rtime << " s, CPU time " << ctime << "s" << endl << endl; + cout << "Macro finished successfully." << endl; + + // ------------------------------------------------------------------------ } diff --git a/examples/advanced/Tutorial3/macro/run_sim.C b/examples/advanced/Tutorial3/macro/run_sim.C index d6000dcd00..8b92de2444 100644 --- a/examples/advanced/Tutorial3/macro/run_sim.C +++ b/examples/advanced/Tutorial3/macro/run_sim.C @@ -1,101 +1,98 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ -void run_sim(Int_t nEvents=100, TString mcEngine="TGeant3") +void run_sim(Int_t nEvents = 100, TString mcEngine = "TGeant3") { - TStopwatch timer; - timer.Start(); - gDebug=0; - - // Use non default gconfig and geometry directories - TString dir = getenv("VMCWORKDIR"); - TString tutdir = dir + "/"; - - TString tut_geomdir = tutdir + "/common/geometry"; - gSystem->Setenv("GEOMPATH",tut_geomdir.Data()); - - TString tut_configdir = tutdir + "/common/gconfig"; - gSystem->Setenv("CONFIG_DIR",tut_configdir.Data()); - - // create Instance of Run Manager class - FairRunSim *fRun = new FairRunSim(); - fRun->SetUseFairLinks(kTRUE); -// FairLinkManager::Instance()->AddIncludeType(0); - // set the MC version used - // ------------------------ - - fRun->SetName(mcEngine); - - TString outFile = "data/testrun_"; - outFile = outFile + mcEngine + ".root"; - - TString geoFile = "data/geofile_"; - geoFile = geoFile + mcEngine + "_full.root"; - - TString parFile = "data/testparams_"; - parFile = parFile + mcEngine + ".root"; - - - fRun->SetSink(new FairRootFileSink(outFile)); - fRun->SetGenerateRunInfo(kTRUE); // Create FairRunInfo file - - // ----- Magnetic field ------------------------------------------- - // Constant Field - FairConstField *fMagField = new FairConstField(); - fMagField->SetField(0., 10. ,0. ); // values are in kG - fMagField->SetFieldRegion(-50, 50,-50, 50, 350, 450);// values are in cm (xmin,xmax,ymin,ymax,zmin,zmax) - fRun->SetField(fMagField); - // -------------------------------------------------------------------- - - - // Set Material file Name - //----------------------- - fRun->SetMaterials("media.geo"); - - // Create and add detectors - //------------------------- - FairModule *Cave= new FairCave("CAVE"); - Cave->SetGeometryFileName("cave.geo"); - fRun->AddModule(Cave); - - FairModule *Magnet= new FairMagnet("MAGNET"); - Magnet->SetGeometryFileName("magnet.geo"); - fRun->AddModule(Magnet); - - FairDetector *Torino= new FairTestDetector("TORINO", kTRUE); - Torino->SetGeometryFileName("torino.geo"); - fRun->AddModule(Torino); - - // Create and Set Event Generator - //------------------------------- - - FairPrimaryGenerator* primGen = new FairPrimaryGenerator(); - fRun->SetGenerator(primGen); - - // Box Generator - FairBoxGenerator* boxGen = new FairBoxGenerator(2212, 10); // 13 = muon; 1 = multipl. - boxGen->SetPRange(2., 2.); // GeV/c //setPRange vs setPtRange - boxGen->SetPhiRange(0, 360); // Azimuth angle range [degree] - boxGen->SetThetaRange(3, 10); // Polar angle in lab system range [degree] - boxGen->SetCosTheta();//uniform generation on all the solid angle(default) - - // boxGen->SetXYZ(0., 0.37, 0.); - primGen->AddGenerator(boxGen); - - fRun->SetStoreTraj(kTRUE); - - fRun->Init(); - - - // -Trajectories Visualization (TGeoManager Only ) - // ----------------------------------------------- - - // Set cuts for storing the trajectpries - /* FairTrajFilter* trajFilter = FairTrajFilter::Instance(); + TStopwatch timer; + timer.Start(); + gDebug = 0; + + // Use non default gconfig and geometry directories + TString dir = getenv("VMCWORKDIR"); + TString tutdir = dir + "/"; + + TString tut_geomdir = tutdir + "/common/geometry"; + gSystem->Setenv("GEOMPATH", tut_geomdir.Data()); + + TString tut_configdir = tutdir + "/common/gconfig"; + gSystem->Setenv("CONFIG_DIR", tut_configdir.Data()); + + // create Instance of Run Manager class + FairRunSim *fRun = new FairRunSim(); + fRun->SetUseFairLinks(kTRUE); + // FairLinkManager::Instance()->AddIncludeType(0); + // set the MC version used + // ------------------------ + + fRun->SetName(mcEngine); + + TString outFile = "data/testrun_"; + outFile = outFile + mcEngine + ".root"; + + TString geoFile = "data/geofile_"; + geoFile = geoFile + mcEngine + "_full.root"; + + TString parFile = "data/testparams_"; + parFile = parFile + mcEngine + ".root"; + + fRun->SetSink(new FairRootFileSink(outFile)); + fRun->SetGenerateRunInfo(kTRUE); // Create FairRunInfo file + + // ----- Magnetic field ------------------------------------------- + // Constant Field + FairConstField *fMagField = new FairConstField(); + fMagField->SetField(0., 10., 0.); // values are in kG + fMagField->SetFieldRegion(-50, 50, -50, 50, 350, 450); // values are in cm (xmin,xmax,ymin,ymax,zmin,zmax) + fRun->SetField(fMagField); + // -------------------------------------------------------------------- + + // Set Material file Name + //----------------------- + fRun->SetMaterials("media.geo"); + + // Create and add detectors + //------------------------- + FairModule *Cave = new FairCave("CAVE"); + Cave->SetGeometryFileName("cave.geo"); + fRun->AddModule(Cave); + + FairModule *Magnet = new FairMagnet("MAGNET"); + Magnet->SetGeometryFileName("magnet.geo"); + fRun->AddModule(Magnet); + + FairDetector *Torino = new FairTestDetector("TORINO", kTRUE); + Torino->SetGeometryFileName("torino.geo"); + fRun->AddModule(Torino); + + // Create and Set Event Generator + //------------------------------- + + FairPrimaryGenerator *primGen = new FairPrimaryGenerator(); + fRun->SetGenerator(primGen); + + // Box Generator + FairBoxGenerator *boxGen = new FairBoxGenerator(2212, 10); // 13 = muon; 1 = multipl. + boxGen->SetPRange(2., 2.); // GeV/c //setPRange vs setPtRange + boxGen->SetPhiRange(0, 360); // Azimuth angle range [degree] + boxGen->SetThetaRange(3, 10); // Polar angle in lab system range [degree] + boxGen->SetCosTheta(); // uniform generation on all the solid angle(default) + + // boxGen->SetXYZ(0., 0.37, 0.); + primGen->AddGenerator(boxGen); + + fRun->SetStoreTraj(kTRUE); + + fRun->Init(); + + // -Trajectories Visualization (TGeoManager Only ) + // ----------------------------------------------- + + // Set cuts for storing the trajectpries + /* FairTrajFilter* trajFilter = FairTrajFilter::Instance(); trajFilter->SetStepSizeCut(0.01); // 1 cm trajFilter->SetVertexCut(-2000., -2000., 4., 2000., 2000., 100.); trajFilter->SetMomentumCutP(10e-3); // p_lab > 10 MeV @@ -104,55 +101,52 @@ void run_sim(Int_t nEvents=100, TString mcEngine="TGeant3") trajFilter->SetStoreSecondaries(kTRUE); */ + // Fill the Parameter containers for this run + //------------------------------------------- - // Fill the Parameter containers for this run - //------------------------------------------- - - FairRuntimeDb *rtdb=fRun->GetRuntimeDb(); - Bool_t kParameterMerged=kTRUE; - FairParRootFileIo* output=new FairParRootFileIo(kParameterMerged); - output->open(parFile); - rtdb->setOutput(output); + FairRuntimeDb *rtdb = fRun->GetRuntimeDb(); + Bool_t kParameterMerged = kTRUE; + FairParRootFileIo *output = new FairParRootFileIo(kParameterMerged); + output->open(parFile); + rtdb->setOutput(output); - rtdb->saveOutput(); - rtdb->print(); + rtdb->saveOutput(); + rtdb->print(); - // Transport nEvents - // ----------------- + // Transport nEvents + // ----------------- - // Int_t nEvents = 1; - fRun->Run(nEvents); + // Int_t nEvents = 1; + fRun->Run(nEvents); - fRun->CreateGeometryFile(geoFile); + fRun->CreateGeometryFile(geoFile); - // ----- Finish ------------------------------------------------------- + // ----- Finish ------------------------------------------------------- - cout << endl << endl; + cout << endl << endl; - // Extract the maximal used memory an add is as Dart measurement - // This line is filtered by CTest and the value send to CDash - FairSystemInfo sysInfo; - Float_t maxMemory=sysInfo.GetMaxMemory(); - cout << ""; - cout << maxMemory; - cout << "" << endl; + // Extract the maximal used memory an add is as Dart measurement + // This line is filtered by CTest and the value send to CDash + FairSystemInfo sysInfo; + Float_t maxMemory = sysInfo.GetMaxMemory(); + cout << ""; + cout << maxMemory; + cout << "" << endl; - timer.Stop(); - Double_t rtime = timer.RealTime(); - Double_t ctime = timer.CpuTime(); + timer.Stop(); + Double_t rtime = timer.RealTime(); + Double_t ctime = timer.CpuTime(); - Float_t cpuUsage=ctime/rtime; - cout << ""; - cout << cpuUsage; - cout << "" << endl; + Float_t cpuUsage = ctime / rtime; + cout << ""; + cout << cpuUsage; + cout << "" << endl; - cout << endl << endl; - cout << "Output file is " << outFile << endl; - cout << "Parameter file is " << parFile << endl; - cout << "Real time " << rtime << " s, CPU time " << ctime - << "s" << endl << endl; - cout << "Macro finished successfully." << endl; + cout << endl << endl; + cout << "Output file is " << outFile << endl; + cout << "Parameter file is " << parFile << endl; + cout << "Real time " << rtime << " s, CPU time " << ctime << "s" << endl << endl; + cout << "Macro finished successfully." << endl; - // ------------------------------------------------------------------------ -} - + // ------------------------------------------------------------------------ +} diff --git a/examples/advanced/Tutorial3/macro/run_sim_sep.C b/examples/advanced/Tutorial3/macro/run_sim_sep.C index d99a53b2b3..cca86f2520 100644 --- a/examples/advanced/Tutorial3/macro/run_sim_sep.C +++ b/examples/advanced/Tutorial3/macro/run_sim_sep.C @@ -1,89 +1,85 @@ -void run_sim_sep(Int_t fileId, Int_t nEvents=1000, TString mcEngine="TGeant3") +void run_sim_sep(Int_t fileId, Int_t nEvents = 1000, TString mcEngine = "TGeant3") { - gRandom->SetSeed(1111*fileId); - - TStopwatch timer; - timer.Start(); - gDebug=0; - - // Use non default gconfig and geometry directories - TString dir = getenv("VMCWORKDIR"); - TString tutdir = dir + "/"; - - TString tut_geomdir = tutdir + "/common/geometry"; - gSystem->Setenv("GEOMPATH",tut_geomdir.Data()); - - TString tut_configdir = tutdir + "/common/gconfig"; - gSystem->Setenv("CONFIG_DIR",tut_configdir.Data()); - - // create Instance of Run Manager class - FairRunSim *fRun = new FairRunSim(); - - // set the MC version used - // ------------------------ - - fRun->SetName(mcEngine); - - TString outfile = Form("data/testrun_%s_f%d.root",mcEngine.Data(),fileId); - TString outparam = Form("data/testpar_%s_f%d.root",mcEngine.Data(),fileId); - - - fRun->SetSink(new FairRootFileSink(outfile)); - - - // ----- Magnetic field ------------------------------------------- - // Constant Field - FairConstField *fMagField = new FairConstField(); - fMagField->SetField(0., 10. ,0. ); // values are in kG - fMagField->SetFieldRegion(-50, 50,-50, 50, 350, 450);// values are in cm (xmin,xmax,ymin,ymax,zmin,zmax) - fRun->SetField(fMagField); - // -------------------------------------------------------------------- - - - // Set Material file Name - //----------------------- - fRun->SetMaterials("media.geo"); - - // Create and add detectors - //------------------------- - FairModule *Cave= new FairCave("CAVE"); - Cave->SetGeometryFileName("cave.geo"); - fRun->AddModule(Cave); - - FairModule *Magnet= new FairMagnet("MAGNET"); - Magnet->SetGeometryFileName("magnet.geo"); - fRun->AddModule(Magnet); - - FairDetector *Torino= new FairTestDetector("TORINO", kTRUE); - Torino->SetGeometryFileName("torino.geo"); - fRun->AddModule(Torino); - - // Create and Set Event Generator - //------------------------------- - - FairPrimaryGenerator* primGen = new FairPrimaryGenerator(); - fRun->SetGenerator(primGen); - - // Box Generator - FairBoxGenerator* boxGen = new FairBoxGenerator(13, 10); // 13 = muon; 1 = multipl. - boxGen->SetPRange(2., 2.); // GeV/c //setPRange vs setPtRange - boxGen->SetPhiRange(0, 360); // Azimuth angle range [degree] - boxGen->SetThetaRange(3, 10); // Polar angle in lab system range [degree] - boxGen->SetCosTheta();//uniform generation on all the solid angle(default) - - // boxGen->SetXYZ(0., 0.37, 0.); - primGen->AddGenerator(boxGen); - - fRun->SetStoreTraj(kTRUE); - - fRun->Init(); - - - // -Trajectories Visualization (TGeoManager Only ) - // ----------------------------------------------- - - // Set cuts for storing the trajectpries - /* FairTrajFilter* trajFilter = FairTrajFilter::Instance(); + gRandom->SetSeed(1111 * fileId); + + TStopwatch timer; + timer.Start(); + gDebug = 0; + + // Use non default gconfig and geometry directories + TString dir = getenv("VMCWORKDIR"); + TString tutdir = dir + "/"; + + TString tut_geomdir = tutdir + "/common/geometry"; + gSystem->Setenv("GEOMPATH", tut_geomdir.Data()); + + TString tut_configdir = tutdir + "/common/gconfig"; + gSystem->Setenv("CONFIG_DIR", tut_configdir.Data()); + + // create Instance of Run Manager class + FairRunSim *fRun = new FairRunSim(); + + // set the MC version used + // ------------------------ + + fRun->SetName(mcEngine); + + TString outfile = Form("data/testrun_%s_f%d.root", mcEngine.Data(), fileId); + TString outparam = Form("data/testpar_%s_f%d.root", mcEngine.Data(), fileId); + + fRun->SetSink(new FairRootFileSink(outfile)); + + // ----- Magnetic field ------------------------------------------- + // Constant Field + FairConstField *fMagField = new FairConstField(); + fMagField->SetField(0., 10., 0.); // values are in kG + fMagField->SetFieldRegion(-50, 50, -50, 50, 350, 450); // values are in cm (xmin,xmax,ymin,ymax,zmin,zmax) + fRun->SetField(fMagField); + // -------------------------------------------------------------------- + + // Set Material file Name + //----------------------- + fRun->SetMaterials("media.geo"); + + // Create and add detectors + //------------------------- + FairModule *Cave = new FairCave("CAVE"); + Cave->SetGeometryFileName("cave.geo"); + fRun->AddModule(Cave); + + FairModule *Magnet = new FairMagnet("MAGNET"); + Magnet->SetGeometryFileName("magnet.geo"); + fRun->AddModule(Magnet); + + FairDetector *Torino = new FairTestDetector("TORINO", kTRUE); + Torino->SetGeometryFileName("torino.geo"); + fRun->AddModule(Torino); + + // Create and Set Event Generator + //------------------------------- + + FairPrimaryGenerator *primGen = new FairPrimaryGenerator(); + fRun->SetGenerator(primGen); + + // Box Generator + FairBoxGenerator *boxGen = new FairBoxGenerator(13, 10); // 13 = muon; 1 = multipl. + boxGen->SetPRange(2., 2.); // GeV/c //setPRange vs setPtRange + boxGen->SetPhiRange(0, 360); // Azimuth angle range [degree] + boxGen->SetThetaRange(3, 10); // Polar angle in lab system range [degree] + boxGen->SetCosTheta(); // uniform generation on all the solid angle(default) + + // boxGen->SetXYZ(0., 0.37, 0.); + primGen->AddGenerator(boxGen); + + fRun->SetStoreTraj(kTRUE); + + fRun->Init(); + + // -Trajectories Visualization (TGeoManager Only ) + // ----------------------------------------------- + + // Set cuts for storing the trajectpries + /* FairTrajFilter* trajFilter = FairTrajFilter::Instance(); trajFilter->SetStepSizeCut(0.01); // 1 cm trajFilter->SetVertexCut(-2000., -2000., 4., 2000., 2000., 100.); trajFilter->SetMomentumCutP(10e-3); // p_lab > 10 MeV @@ -92,54 +88,52 @@ void run_sim_sep(Int_t fileId, Int_t nEvents=1000, TString mcEngine="TGeant3") trajFilter->SetStoreSecondaries(kTRUE); */ + // Fill the Parameter containers for this run + //------------------------------------------- - // Fill the Parameter containers for this run - //------------------------------------------- - - FairRuntimeDb *rtdb=fRun->GetRuntimeDb(); - Bool_t kParameterMerged=kTRUE; - FairParRootFileIo* output=new FairParRootFileIo(kParameterMerged); - output->open(outparam); - rtdb->setOutput(output); + FairRuntimeDb *rtdb = fRun->GetRuntimeDb(); + Bool_t kParameterMerged = kTRUE; + FairParRootFileIo *output = new FairParRootFileIo(kParameterMerged); + output->open(outparam); + rtdb->setOutput(output); - rtdb->saveOutput(); - rtdb->print(); + rtdb->saveOutput(); + rtdb->print(); - // Transport nEvents - // ----------------- + // Transport nEvents + // ----------------- - // Int_t nEvents = 1; - fRun->Run(nEvents); + // Int_t nEvents = 1; + fRun->Run(nEvents); - fRun->CreateGeometryFile("data/geofile_full.root"); + fRun->CreateGeometryFile("data/geofile_full.root"); - // ----- Finish ------------------------------------------------------- + // ----- Finish ------------------------------------------------------- - cout << endl << endl; + cout << endl << endl; - // Extract the maximal used memory an add is as Dart measurement - // This line is filtered by CTest and the value send to CDash - FairSystemInfo sysInfo; - Float_t maxMemory=sysInfo.GetMaxMemory(); - cout << ""; - cout << maxMemory; - cout << "" << endl; + // Extract the maximal used memory an add is as Dart measurement + // This line is filtered by CTest and the value send to CDash + FairSystemInfo sysInfo; + Float_t maxMemory = sysInfo.GetMaxMemory(); + cout << ""; + cout << maxMemory; + cout << "" << endl; - timer.Stop(); - Double_t rtime = timer.RealTime(); - Double_t ctime = timer.CpuTime(); + timer.Stop(); + Double_t rtime = timer.RealTime(); + Double_t ctime = timer.CpuTime(); - Float_t cpuUsage=ctime/rtime; - cout << ""; - cout << cpuUsage; - cout << "" << endl; + Float_t cpuUsage = ctime / rtime; + cout << ""; + cout << cpuUsage; + cout << "" << endl; - cout << endl << endl; - cout << "Output file is " << outfile << endl; - cout << "Parameter file is " << outparam << endl; - cout << "Real time " << rtime << " s, CPU time " << ctime - << "s" << endl << endl; - cout << "Macro finished successfully." << endl; + cout << endl << endl; + cout << "Output file is " << outfile << endl; + cout << "Parameter file is " << outparam << endl; + cout << "Real time " << rtime << " s, CPU time " << ctime << "s" << endl << endl; + cout << "Macro finished successfully." << endl; - // ------------------------------------------------------------------------ -} + // ------------------------------------------------------------------------ +} diff --git a/examples/advanced/Tutorial3/reconstruction/FairTestDetectorRecoTask.cxx b/examples/advanced/Tutorial3/reconstruction/FairTestDetectorRecoTask.cxx index cf6dd81ae3..27ebffd220 100644 --- a/examples/advanced/Tutorial3/reconstruction/FairTestDetectorRecoTask.cxx +++ b/examples/advanced/Tutorial3/reconstruction/FairTestDetectorRecoTask.cxx @@ -1,28 +1,27 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "FairTestDetectorRecoTask.h" -#include "FairLink.h" // for FairLink -#include "FairRootManager.h" // for FairRootManager -#include "FairTestDetectorDigi.h" // for FairTestDetectorDigi -#include "FairTestDetectorHit.h" // for FairTestDetectorHit +#include "FairLink.h" // for FairLink #include "FairLogger.h" +#include "FairRootManager.h" // for FairRootManager +#include "FairTestDetectorDigi.h" // for FairTestDetectorDigi +#include "FairTestDetectorHit.h" // for FairTestDetectorHit -#include // for TClonesArray -#include // for Sqrt -#include // for TVector3 +#include // for TClonesArray +#include // for Sqrt +#include // for TVector3 FairTestDetectorRecoTask::FairTestDetectorRecoTask() : FairTask() , fDigiArray(nullptr) , fHitArray(nullptr) -{ -} +{} FairTestDetectorRecoTask::FairTestDetectorRecoTask(Int_t verbose) : FairTask() @@ -32,22 +31,18 @@ FairTestDetectorRecoTask::FairTestDetectorRecoTask(Int_t verbose) fVerbose = verbose; } -FairTestDetectorRecoTask::~FairTestDetectorRecoTask() -{ -} +FairTestDetectorRecoTask::~FairTestDetectorRecoTask() {} InitStatus FairTestDetectorRecoTask::Init() { FairRootManager* ioman = FairRootManager::Instance(); - if (!ioman) - { + if (!ioman) { LOG(error) << "-E- FairTestDetectorRecoTask::Init: RootManager not instantiated!"; return kFATAL; } fDigiArray = static_cast(ioman->GetObject("FairTestDetectorDigi")); - if (!fDigiArray) - { + if (!fDigiArray) { LOG(warn) << "-W- FairTestDetectorRecoTask::Init: No Point array!"; return kERROR; } @@ -64,8 +59,7 @@ void FairTestDetectorRecoTask::Exec(Option_t* /*opt*/) fHitArray->Clear(); // fill the map - for (int ipnt = 0; ipnt < fDigiArray->GetEntriesFast(); ipnt++) - { + for (int ipnt = 0; ipnt < fDigiArray->GetEntriesFast(); ipnt++) { FairTestDetectorDigi* digi = static_cast(fDigiArray->At(ipnt)); if (!digi) continue; @@ -81,11 +75,14 @@ void FairTestDetectorRecoTask::Exec(Option_t* /*opt*/) TVector3 dpos(1 / TMath::Sqrt(12), 1 / TMath::Sqrt(12), 1 / TMath::Sqrt(12)); FairTestDetectorHit* hit = new ((*fHitArray)[ipnt]) FairTestDetectorHit(-1, -1, pos, dpos); - if ( fStreamProcessing == kFALSE ) - hit->AddLink(FairLink(-1, FairRootManager::Instance()->GetEntryNr(), FairRootManager::Instance()->GetBranchId("FairTestDetectorDigi"), ipnt)); + if (fStreamProcessing == kFALSE) + hit->AddLink(FairLink(-1, + FairRootManager::Instance()->GetEntryNr(), + FairRootManager::Instance()->GetBranchId("FairTestDetectorDigi"), + ipnt)); hit->SetTimeStamp(digi->GetTimeStamp()); hit->SetTimeStampError(digi->GetTimeStampError()); } } -ClassImp(FairTestDetectorRecoTask) +ClassImp(FairTestDetectorRecoTask); diff --git a/examples/advanced/Tutorial3/reconstruction/FairTestDetectorRecoTask.h b/examples/advanced/Tutorial3/reconstruction/FairTestDetectorRecoTask.h index b6dc1c0797..32bbce68f2 100644 --- a/examples/advanced/Tutorial3/reconstruction/FairTestDetectorRecoTask.h +++ b/examples/advanced/Tutorial3/reconstruction/FairTestDetectorRecoTask.h @@ -1,14 +1,14 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRTESTDETECTORRECOTASK_H_ #define FAIRTESTDETECTORRECOTASK_H_ -#include "FairTask.h" // for FairTask, InitStatus +#include "FairTask.h" // for FairTask, InitStatus class TClonesArray; diff --git a/examples/advanced/Tutorial3/simulation/FairConstField.cxx b/examples/advanced/Tutorial3/simulation/FairConstField.cxx index e658528780..a55d1e7d91 100644 --- a/examples/advanced/Tutorial3/simulation/FairConstField.cxx +++ b/examples/advanced/Tutorial3/simulation/FairConstField.cxx @@ -11,17 +11,16 @@ // ------------------------------------------------------------------------- #include "FairConstField.h" -#include "FairConstPar.h" // for FairConstPar -#include "FairRun.h" // for FairRun -#include "FairRuntimeDb.h" // for FairRuntimeDb -#include "FairLogger.h" // for logging +#include "FairConstPar.h" // for FairConstPar +#include "FairLogger.h" // for logging +#include "FairRun.h" // for FairRun +#include "FairRuntimeDb.h" // for FairRuntimeDb -#include // for operator<<, TString +#include // for operator<<, TString +#include // for operator<<, setw -#include // for operator<<, setw - -using std::setw; using std::setprecision; +using std::setw; FairConstField::FairConstField() : fXmin(0) @@ -74,13 +73,10 @@ FairConstField::FairConstField(FairConstPar* fieldPar) , fBy(0) , fBz(0) { - if (!fieldPar) - { + if (!fieldPar) { LOG(warn) << "empty parameter container!"; fType = -1; - } - else - { + } else { fXmin = fieldPar->GetXmin(); fXmax = fieldPar->GetXmax(); fYmin = fieldPar->GetYmin(); @@ -94,11 +90,14 @@ FairConstField::FairConstField(FairConstPar* fieldPar) } } -FairConstField::~FairConstField() -{ -} +FairConstField::~FairConstField() {} -void FairConstField::SetFieldRegion(Double_t xMin, Double_t xMax, Double_t yMin, Double_t yMax, Double_t zMin, Double_t zMax) +void FairConstField::SetFieldRegion(Double_t xMin, + Double_t xMax, + Double_t yMin, + Double_t yMax, + Double_t zMin, + Double_t zMax) { fXmin = xMin; fXmax = xMax; @@ -117,8 +116,7 @@ void FairConstField::SetField(Double_t bX, Double_t bY, Double_t bZ) Double_t FairConstField::GetBx(Double_t x, Double_t y, Double_t z) { - if (x < fXmin || x > fXmax || y < fYmin || y > fYmax || z < fZmin || z > fZmax) - { + if (x < fXmin || x > fXmax || y < fYmin || y > fYmax || z < fZmin || z > fZmax) { return 0.; } return fBx; @@ -126,8 +124,7 @@ Double_t FairConstField::GetBx(Double_t x, Double_t y, Double_t z) Double_t FairConstField::GetBy(Double_t x, Double_t y, Double_t z) { - if (x < fXmin || x > fXmax || y < fYmin || y > fYmax || z < fZmin || z > fZmax) - { + if (x < fXmin || x > fXmax || y < fYmin || y > fYmax || z < fZmin || z > fZmax) { return 0.; } return fBy; @@ -135,8 +132,7 @@ Double_t FairConstField::GetBy(Double_t x, Double_t y, Double_t z) Double_t FairConstField::GetBz(Double_t x, Double_t y, Double_t z) { - if (x < fXmin || x > fXmax || y < fYmin || y > fYmax || z < fZmin || z > fZmax) - { + if (x < fXmin || x > fXmax || y < fYmin || y > fYmax || z < fZmin || z > fZmax) { return 0.; } return fBz; @@ -144,7 +140,7 @@ Double_t FairConstField::GetBz(Double_t x, Double_t y, Double_t z) void FairConstField::Print(Option_t*) const { - LOG(info) << "======================================================" ; + LOG(info) << "======================================================"; LOG(info) << "---- " << fTitle << " : " << fName; LOG(info) << "----"; LOG(info) << "---- Field type : constant"; @@ -163,11 +159,11 @@ void FairConstField::FillParContainer() // LOG(info) << "FairConstField::FillParContainer() "; FairRun* fRun = FairRun::Instance(); FairRuntimeDb* rtdb = fRun->GetRuntimeDb(); - //Bool_t kParameterMerged = kTRUE; + // Bool_t kParameterMerged = kTRUE; FairConstPar* Par = static_cast(rtdb->getContainer("FairConstPar")); Par->SetParameters(this); Par->setInputVersion(fRun->GetRunId(), 1); Par->setChanged(); } -ClassImp(FairConstField) +ClassImp(FairConstField); diff --git a/examples/advanced/Tutorial3/simulation/FairConstField.h b/examples/advanced/Tutorial3/simulation/FairConstField.h index ba93b610fc..15c66e62fc 100644 --- a/examples/advanced/Tutorial3/simulation/FairConstField.h +++ b/examples/advanced/Tutorial3/simulation/FairConstField.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /** FairConstField.h @@ -15,9 +15,9 @@ #ifndef FairConstFIELD_H #define FairConstFIELD_H 1 -#include "FairField.h" // for FairField +#include "FairField.h" // for FairField -#include // for Double_t, etc +#include // for Double_t, etc class FairConstPar; @@ -73,44 +73,17 @@ class FairConstField : public FairField 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; - } + 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; - } + Double_t GetBx() const { return fBx; } + Double_t GetBy() const { return fBy; } + Double_t GetBz() const { return fBz; } /** Screen output **/ virtual void Print(Option_t*) const; diff --git a/examples/advanced/Tutorial3/simulation/FairConstPar.cxx b/examples/advanced/Tutorial3/simulation/FairConstPar.cxx index 7fab73894e..52b48b5a32 100644 --- a/examples/advanced/Tutorial3/simulation/FairConstPar.cxx +++ b/examples/advanced/Tutorial3/simulation/FairConstPar.cxx @@ -7,10 +7,10 @@ ********************************************************************************/ #include "FairConstPar.h" -#include "FairConstField.h" // for FairConstField -#include "FairParamList.h" // for FairParamList +#include "FairConstField.h" // for FairConstField +#include "FairParamList.h" // for FairParamList -#include // for TString +#include // for TString class FairField; @@ -32,14 +32,11 @@ FairConstPar::FairConstPar() fType = 0; } -FairConstPar::~FairConstPar() -{ -} +FairConstPar::~FairConstPar() {} void FairConstPar::putParams(FairParamList* list) { - if (!list) - { + if (!list) { return; } @@ -58,48 +55,37 @@ void FairConstPar::putParams(FairParamList* list) Bool_t FairConstPar::getParams(FairParamList* list) { - if (!list) - { + if (!list) { return kFALSE; } - if (!list->fill("Field Type", &fType)) - { + if (!list->fill("Field Type", &fType)) { return kFALSE; } - if (!list->fill("Field min x", &fXmin)) - { + if (!list->fill("Field min x", &fXmin)) { return kFALSE; } - if (!list->fill("Field max x", &fXmax)) - { + if (!list->fill("Field max x", &fXmax)) { return kFALSE; } - if (!list->fill("Field min y", &fYmin)) - { + if (!list->fill("Field min y", &fYmin)) { return kFALSE; } - if (!list->fill("Field max y", &fYmax)) - { + if (!list->fill("Field max y", &fYmax)) { return kFALSE; } - if (!list->fill("Field min z", &fZmin)) - { + if (!list->fill("Field min z", &fZmin)) { return kFALSE; } - if (!list->fill("Field max z", &fZmax)) - { + if (!list->fill("Field max z", &fZmax)) { return kFALSE; } - if (!list->fill("Field Bx", &fBx)) - { + if (!list->fill("Field Bx", &fBx)) { return kFALSE; } - if (!list->fill("Field By", &fBy)) - { + if (!list->fill("Field By", &fBy)) { return kFALSE; } - if (!list->fill("Field Bz", &fBz)) - { + if (!list->fill("Field Bz", &fBz)) { return kFALSE; } return kTRUE; @@ -122,4 +108,4 @@ void FairConstPar::SetParameters(FairField* field) fType = fieldConst->GetType(); } -ClassImp(FairConstPar) +ClassImp(FairConstPar); diff --git a/examples/advanced/Tutorial3/simulation/FairConstPar.h b/examples/advanced/Tutorial3/simulation/FairConstPar.h index baa0510bf9..e313611977 100644 --- a/examples/advanced/Tutorial3/simulation/FairConstPar.h +++ b/examples/advanced/Tutorial3/simulation/FairConstPar.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /** FairConstPar.h @@ -16,9 +16,9 @@ #ifndef FairConstPAR_H #define FairConstPAR_H 1 -#include "FairMapPar.h" // for FairMapPar +#include "FairMapPar.h" // for FairMapPar -#include // for Double_t, etc +#include // for Double_t, etc class FairField; class FairParamList; @@ -44,18 +44,9 @@ class FairConstPar : public FairMapPar /** Set parameters from FairField **/ void SetParameters(FairField* field); - Double_t GetBx() const - { - return fBx; - } - Double_t GetBy() const - { - return fBy; - } - Double_t GetBz() const - { - return fBz; - } + Double_t GetBx() const { return fBx; } + Double_t GetBy() const { return fBy; } + Double_t GetBz() const { return fBz; } protected: /** Field values in [kG] **/ diff --git a/examples/advanced/Tutorial3/simulation/FairMapPar.cxx b/examples/advanced/Tutorial3/simulation/FairMapPar.cxx index 22b8fff84f..ce35f3886c 100644 --- a/examples/advanced/Tutorial3/simulation/FairMapPar.cxx +++ b/examples/advanced/Tutorial3/simulation/FairMapPar.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "FairMapPar.h" @@ -21,8 +21,7 @@ FairMapPar::FairMapPar(const char* name, const char* title, const char* context) , fPosY(0) , fPosZ(0) , fScale(0) -{ -} +{} FairMapPar::FairMapPar() : fType(-1) @@ -37,11 +36,8 @@ FairMapPar::FairMapPar() , fPosY(0) , fPosZ(0) , fScale(0) -{ -} +{} -FairMapPar::~FairMapPar() -{ -} +FairMapPar::~FairMapPar() {} -ClassImp(FairMapPar) +ClassImp(FairMapPar); diff --git a/examples/advanced/Tutorial3/simulation/FairMapPar.h b/examples/advanced/Tutorial3/simulation/FairMapPar.h index 6e31334546..3552730c12 100644 --- a/examples/advanced/Tutorial3/simulation/FairMapPar.h +++ b/examples/advanced/Tutorial3/simulation/FairMapPar.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ @@ -17,10 +17,10 @@ #ifndef FairMAPPAR_H #define FairMAPPAR_H 1 -#include "FairParGenericSet.h" // for FairParGenericSet +#include "FairParGenericSet.h" // for FairParGenericSet -#include // for Double_t, FairMapPar::Class, etc -#include // for TString +#include // for Double_t, FairMapPar::Class, etc +#include // for TString class FairMapPar : public FairParGenericSet { @@ -35,54 +35,18 @@ class FairMapPar : public FairParGenericSet ~FairMapPar(); /** 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; - } - 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; - } + 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; } + 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; } protected: /** Field type diff --git a/examples/advanced/Tutorial3/simulation/FairTestDetector.cxx b/examples/advanced/Tutorial3/simulation/FairTestDetector.cxx index 35e696a01c..87ac6eefaa 100644 --- a/examples/advanced/Tutorial3/simulation/FairTestDetector.cxx +++ b/examples/advanced/Tutorial3/simulation/FairTestDetector.cxx @@ -1,26 +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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "FairTestDetector.h" -#include "FairDetectorList.h" // for DetectorId::kTutDet -#include "FairRootManager.h" // for FairRootManager -#include "FairRun.h" // for FairRun -#include "FairRuntimeDb.h" // for FairRuntimeDb -#include "FairStack.h" // for FairStack -#include "FairTestDetectorGeo.h" // for FairTestDetectorGeo -#include "FairTestDetectorGeoPar.h" // for FairTestDetectorGeoPar -#include "FairTestDetectorPoint.h" // for FairTestDetectorPoint -#include "FairVolume.h" // for FairVolume -#include "FairLink.h" // for FairLink - -#include // for TClonesArray -#include // for TVirtualMC -#include // for TVirtualMCStack +#include "FairDetectorList.h" // for DetectorId::kTutDet +#include "FairLink.h" // for FairLink +#include "FairRootManager.h" // for FairRootManager +#include "FairRun.h" // for FairRun +#include "FairRuntimeDb.h" // for FairRuntimeDb +#include "FairStack.h" // for FairStack +#include "FairTestDetectorGeo.h" // for FairTestDetectorGeo +#include "FairTestDetectorGeoPar.h" // for FairTestDetectorGeoPar +#include "FairTestDetectorPoint.h" // for FairTestDetectorPoint +#include "FairVolume.h" // for FairVolume + +#include // for TClonesArray +#include // for TVirtualMC +#include // for TVirtualMCStack FairTestDetector::FairTestDetector() : FairDetector("FairTestDetector", kTRUE, kTutDet) @@ -33,10 +33,9 @@ FairTestDetector::FairTestDetector() , fTime(-1.) , fLength(-1.) , fELoss(-1) - , fEventNr(0) + , fEventNr(0) , fFairTestDetectorPointCollection(new TClonesArray("FairTestDetectorPoint")) -{ -} +{} FairTestDetector::FairTestDetector(const char* name, Bool_t active) : FairDetector(name, active, kTutDet) @@ -51,13 +50,11 @@ FairTestDetector::FairTestDetector(const char* name, Bool_t active) , fELoss(-1) , fEventNr(0) , fFairTestDetectorPointCollection(new TClonesArray("FairTestDetectorPoint")) -{ -} +{} FairTestDetector::~FairTestDetector() { - if (fFairTestDetectorPointCollection) - { + if (fFairTestDetectorPointCollection) { fFairTestDetectorPointCollection->Delete(); delete fFairTestDetectorPointCollection; } @@ -75,8 +72,7 @@ Bool_t FairTestDetector::ProcessHits(FairVolume* vol) /** This method is called from the MC stepping */ // Set parameters at entrance of volume. Reset ELoss. - if (TVirtualMC::GetMC()->IsTrackEntering()) - { + if (TVirtualMC::GetMC()->IsTrackEntering()) { fELoss = 0.; fTime = TVirtualMC::GetMC()->TrackTime() * 1.0e09; fLength = TVirtualMC::GetMC()->TrackLength(); @@ -88,14 +84,13 @@ Bool_t FairTestDetector::ProcessHits(FairVolume* vol) fELoss += TVirtualMC::GetMC()->Edep(); // Create FairTestDetectorPoint at exit of active volume - if (TVirtualMC::GetMC()->IsTrackExiting() || TVirtualMC::GetMC()->IsTrackStop() || TVirtualMC::GetMC()->IsTrackDisappeared()) - { + if (TVirtualMC::GetMC()->IsTrackExiting() || TVirtualMC::GetMC()->IsTrackStop() + || TVirtualMC::GetMC()->IsTrackDisappeared()) { fTrackID = TVirtualMC::GetMC()->GetStack()->GetCurrentTrackNumber(); fVolumeID = vol->getMCid(); TVirtualMC::GetMC()->TrackPosition(fPosOut); TVirtualMC::GetMC()->TrackMomentum(fMomOut); - if (fELoss == 0.) - { + if (fELoss == 0.) { return kFALSE; } AddHit(fTrackID, @@ -132,25 +127,20 @@ void FairTestDetector::Register() only during the simulation. */ - FairRootManager::Instance()->Register("FairTestDetectorPoint", "FairTestDetector", fFairTestDetectorPointCollection, kTRUE); + FairRootManager::Instance()->Register( + "FairTestDetectorPoint", "FairTestDetector", fFairTestDetectorPointCollection, kTRUE); } TClonesArray* FairTestDetector::GetCollection(Int_t iColl) const { - if (iColl == 0) - { + if (iColl == 0) { return fFairTestDetectorPointCollection; - } - else - { + } else { return nullptr; } } -void FairTestDetector::Reset() -{ - fFairTestDetectorPointCollection->Clear(); -} +void FairTestDetector::Reset() { fFairTestDetectorPointCollection->Clear(); } void FairTestDetector::ConstructGeometry() { @@ -174,9 +164,10 @@ FairTestDetectorPoint* FairTestDetector::AddHit(Int_t trackID, { TClonesArray& clref = *fFairTestDetectorPointCollection; Int_t size = clref.GetEntriesFast(); - FairTestDetectorPoint* myPoint = new (clref[size]) FairTestDetectorPoint(trackID, detID, pos, mom, posOut, momOut, time, length, eLoss); + FairTestDetectorPoint* myPoint = + new (clref[size]) FairTestDetectorPoint(trackID, detID, pos, mom, posOut, momOut, time, length, eLoss); myPoint->SetLink(FairLink(-1, fEventNr, FairRootManager::Instance()->GetBranchId("MCTrack"), trackID)); return myPoint; } -ClassImp(FairTestDetector) +ClassImp(FairTestDetector); diff --git a/examples/advanced/Tutorial3/simulation/FairTestDetector.h b/examples/advanced/Tutorial3/simulation/FairTestDetector.h index 059c81ede4..2afcb3817f 100644 --- a/examples/advanced/Tutorial3/simulation/FairTestDetector.h +++ b/examples/advanced/Tutorial3/simulation/FairTestDetector.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRTESTDETECTOR_H_ @@ -10,9 +10,9 @@ #include "FairDetector.h" -#include // for Int_t, Double32_t, Double_t, etc -#include // for TLorentzVector -#include // for TVector3 +#include // for Int_t, Double32_t, Double_t, etc +#include // for TLorentzVector +#include // for TVector3 class FairTestDetectorPoint; class FairVolume; @@ -24,7 +24,7 @@ class FairTestDetector : public FairDetector /** Name : Detector Name * Active: kTRUE for active detectors (ProcessHits() will be called) * kFALSE for inactive detectors - */ + */ FairTestDetector(const char* Name, Bool_t Active); /** default constructor */ @@ -38,7 +38,7 @@ class FairTestDetector : public FairDetector /** this method is called for each step during simulation * (see FairMCApplication::Stepping()) - */ + */ virtual Bool_t ProcessHits(FairVolume* v = 0); /** Registers the produced collections in FAIRRootManager. */ @@ -55,64 +55,50 @@ class FairTestDetector : public FairDetector /** This method is an example of how to add your own point * of type FairTestDetectorPoint to the clones array - */ - FairTestDetectorPoint* - AddHit(Int_t trackID, Int_t detID, TVector3 pos, TVector3 mom, TVector3 posOut, TVector3 momOut, Double_t time, Double_t length, Double_t eLoss); + */ + FairTestDetectorPoint* AddHit(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + TVector3 posOut, + TVector3 momOut, + Double_t time, + Double_t length, + Double_t eLoss); /** 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 SetSpecialPhysicsCuts() { ; } virtual void EndOfEvent(); - virtual void FinishPrimary() - { - ; - } - virtual void FinishRun() - { - ; - } - virtual void BeginPrimary() - { - ; - } - virtual void PostTrack() - { - ; - } - virtual void PreTrack() - { - ; - } - virtual void BeginEvent() - { - ; - } + virtual void FinishPrimary() { ; } + virtual void FinishRun() { ; } + virtual void BeginPrimary() { ; } + virtual void PostTrack() { ; } + virtual void PreTrack() { ; } + virtual void BeginEvent() { ; } 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 - TLorentzVector fPosOut; //! position at entrance - TLorentzVector fMomOut; //! momentum at entrance - Double32_t fTime; //! time - Double32_t fLength; //! length - Double32_t fELoss; //! energy loss - Int_t fEventNr; //! current event number; + Int_t fTrackID; //! track index + Int_t fVolumeID; //! volume id + TLorentzVector fPos; //! position at entrance + TLorentzVector fMom; //! momentum at entrance + TLorentzVector fPosOut; //! position at entrance + TLorentzVector fMomOut; //! momentum at entrance + Double32_t fTime; //! time + Double32_t fLength; //! length + Double32_t fELoss; //! energy loss + Int_t fEventNr; //! current event number; /** container for data points */ diff --git a/examples/advanced/Tutorial3/simulation/FairTestDetectorContFact.cxx b/examples/advanced/Tutorial3/simulation/FairTestDetectorContFact.cxx index 2fd4cc925d..5afa0e3b9e 100644 --- a/examples/advanced/Tutorial3/simulation/FairTestDetectorContFact.cxx +++ b/examples/advanced/Tutorial3/simulation/FairTestDetectorContFact.cxx @@ -1,24 +1,25 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "FairTestDetectorContFact.h" -#include "FairConstPar.h" // for FairConstPar -#include "FairRuntimeDb.h" // for FairRuntimeDb -#include "FairTestDetectorGeoPar.h" // for FairTestDetectorGeoPar +#include "FairConstPar.h" // for FairConstPar +#include "FairRuntimeDb.h" // for FairRuntimeDb +#include "FairTestDetectorGeoPar.h" // for FairTestDetectorGeoPar -#include // for TList -#include // for TString - -#include // for strcmp +#include // for TList +#include // for TString +#include // for strcmp class FairParSet; -ClassImp(FairTestDetectorContFact) static FairTestDetectorContFact gFairTestDetectorContFact; +ClassImp(FairTestDetectorContFact); + +static FairTestDetectorContFact gFairTestDetectorContFact; FairTestDetectorContFact::FairTestDetectorContFact() : FairContFact() @@ -37,7 +38,8 @@ void FairTestDetectorContFact::setAllContainers() the list of containers for the FairTestDetector library. */ - FairContainer* p = new FairContainer("FairTestDetectorGeoPar", "FairTestDetector Geometry Parameters", "TestDefaultContext"); + FairContainer* p = + new FairContainer("FairTestDetectorGeoPar", "FairTestDetector Geometry Parameters", "TestDefaultContext"); p->addContext("TestNonDefaultContext"); FairContainer* p1 = new FairContainer("FairConstPar", "Constant Field Parameters", "TestDefaultContext"); @@ -56,12 +58,10 @@ FairParSet* FairTestDetectorContFact::createContainer(FairContainer* c) */ const char* name = c->GetName(); FairParSet* p = nullptr; - if (strcmp(name, "FairTestDetectorGeoPar") == 0) - { + if (strcmp(name, "FairTestDetectorGeoPar") == 0) { p = new FairTestDetectorGeoPar(c->getConcatName().Data(), c->GetTitle(), c->getContext()); } - if (strcmp(name, "FairConstPar") == 0) - { + if (strcmp(name, "FairConstPar") == 0) { p = new FairConstPar(c->getConcatName().Data(), c->GetTitle(), c->getContext()); } diff --git a/examples/advanced/Tutorial3/simulation/FairTestDetectorContFact.h b/examples/advanced/Tutorial3/simulation/FairTestDetectorContFact.h index 8031415d1e..3e267f7e08 100644 --- a/examples/advanced/Tutorial3/simulation/FairTestDetectorContFact.h +++ b/examples/advanced/Tutorial3/simulation/FairTestDetectorContFact.h @@ -1,16 +1,16 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRTESTDETECTORCONTFACT_H_ #define FAIRTESTDETECTORCONTFACT_H_ -#include "FairContFact.h" // for FairContFact, etc +#include "FairContFact.h" // for FairContFact, etc -#include // for ClassDef +#include // for ClassDef class FairParSet; @@ -21,11 +21,9 @@ class FairTestDetectorContFact : public FairContFact public: FairTestDetectorContFact(); - ~FairTestDetectorContFact() - { - } + ~FairTestDetectorContFact() {} FairParSet* createContainer(FairContainer*); - ClassDef(FairTestDetectorContFact, 0) // Factory for all FairTestDetector parameter containers + ClassDef(FairTestDetectorContFact, 0) // Factory for all FairTestDetector parameter containers }; #endif /* FAIRTESTDETECTORCONTFACT_H_ */ diff --git a/examples/advanced/Tutorial3/simulation/FairTestDetectorGeo.cxx b/examples/advanced/Tutorial3/simulation/FairTestDetectorGeo.cxx index 94a97a4580..5b15c401f1 100644 --- a/examples/advanced/Tutorial3/simulation/FairTestDetectorGeo.cxx +++ b/examples/advanced/Tutorial3/simulation/FairTestDetectorGeo.cxx @@ -1,15 +1,15 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "FairTestDetectorGeo.h" -#include // for sprintf +#include // for sprintf -ClassImp(FairTestDetectorGeo) +ClassImp(FairTestDetectorGeo); FairTestDetectorGeo::FairTestDetectorGeo() : FairGeoSet() diff --git a/examples/advanced/Tutorial3/simulation/FairTestDetectorGeo.h b/examples/advanced/Tutorial3/simulation/FairTestDetectorGeo.h index 160c938d8f..369d8b59fd 100644 --- a/examples/advanced/Tutorial3/simulation/FairTestDetectorGeo.h +++ b/examples/advanced/Tutorial3/simulation/FairTestDetectorGeo.h @@ -1,28 +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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRTESTDETECTORGEO_H_ #define FAIRTESTDETECTORGEO_H_ -#include "FairGeoSet.h" // for FairGeoSet +#include "FairGeoSet.h" // for FairGeoSet -#include // for Int_t, etc -#include // for TString +#include // for Int_t, etc +#include // for TString class FairTestDetectorGeo : public FairGeoSet { protected: - char modName[20]; // name of module - char eleName[20]; // substring for elements in module + char modName[20]; // name of module + char eleName[20]; // substring for elements in module public: FairTestDetectorGeo(); - ~FairTestDetectorGeo() - { - } + ~FairTestDetectorGeo() {} const char* getModuleName(Int_t); const char* getEleName(Int_t); inline Int_t getModNumInMod(const TString&); @@ -36,7 +34,7 @@ inline Int_t FairTestDetectorGeo::getModNumInMod(const TString& name) .geo file. For example if all nodes in this file starts with newdetector ?? has to be 11. */ - return static_cast((name[6] - '0') - 1); // + return static_cast((name[6] - '0') - 1); // } #endif /* FAIRTESTDETECTORGEO_H_ */ diff --git a/examples/advanced/Tutorial3/simulation/FairTestDetectorGeoPar.cxx b/examples/advanced/Tutorial3/simulation/FairTestDetectorGeoPar.cxx index a2617bd424..e99ddbabd0 100644 --- a/examples/advanced/Tutorial3/simulation/FairTestDetectorGeoPar.cxx +++ b/examples/advanced/Tutorial3/simulation/FairTestDetectorGeoPar.cxx @@ -1,25 +1,25 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "FairTestDetectorGeoPar.h" -#include "FairParamList.h" // for FairParamList -#include // for TObjArray +#include "FairParamList.h" // for FairParamList -ClassImp(FairTestDetectorGeoPar) FairTestDetectorGeoPar::FairTestDetectorGeoPar(const char* name, const char* title, const char* context) +#include // for TObjArray + +ClassImp(FairTestDetectorGeoPar); + +FairTestDetectorGeoPar::FairTestDetectorGeoPar(const char* name, const char* title, const char* context) : FairParGenericSet(name, title, context) , fGeoSensNodes(new TObjArray()) , fGeoPassNodes(new TObjArray()) -{ -} +{} -FairTestDetectorGeoPar::~FairTestDetectorGeoPar(void) -{ -} +FairTestDetectorGeoPar::~FairTestDetectorGeoPar(void) {} void FairTestDetectorGeoPar::clear(void) { @@ -29,8 +29,7 @@ void FairTestDetectorGeoPar::clear(void) void FairTestDetectorGeoPar::putParams(FairParamList* l) { - if (!l) - { + if (!l) { return; } l->addObject("FairGeoNodes Sensitive List", fGeoSensNodes); @@ -39,16 +38,13 @@ void FairTestDetectorGeoPar::putParams(FairParamList* l) Bool_t FairTestDetectorGeoPar::getParams(FairParamList* l) { - if (!l) - { + if (!l) { return kFALSE; } - if (!l->fillObject("FairGeoNodes Sensitive List", fGeoSensNodes)) - { + if (!l->fillObject("FairGeoNodes Sensitive List", fGeoSensNodes)) { return kFALSE; } - if (!l->fillObject("FairGeoNodes Passive List", fGeoPassNodes)) - { + if (!l->fillObject("FairGeoNodes Passive List", fGeoPassNodes)) { return kFALSE; } return kTRUE; diff --git a/examples/advanced/Tutorial3/simulation/FairTestDetectorGeoPar.h b/examples/advanced/Tutorial3/simulation/FairTestDetectorGeoPar.h index 5eb0e370af..8621ab25c7 100644 --- a/examples/advanced/Tutorial3/simulation/FairTestDetectorGeoPar.h +++ b/examples/advanced/Tutorial3/simulation/FairTestDetectorGeoPar.h @@ -1,16 +1,16 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRTESTDETECTORGEOPAR_H_ #define FAIRTESTDETECTORGEOPAR_H_ -#include "FairParGenericSet.h" // for FairParGenericSet +#include "FairParGenericSet.h" // for FairParGenericSet -#include // for Class Def +#include // for Class Def class TObjArray; class FairParamList; @@ -31,14 +31,8 @@ class FairTestDetectorGeoPar : public FairParGenericSet void clear(void); void putParams(FairParamList*); Bool_t getParams(FairParamList*); - TObjArray* GetGeoSensitiveNodes() - { - return fGeoSensNodes; - } - TObjArray* GetGeoPassiveNodes() - { - return fGeoPassNodes; - } + TObjArray* GetGeoSensitiveNodes() { return fGeoSensNodes; } + TObjArray* GetGeoPassiveNodes() { return fGeoPassNodes; } private: FairTestDetectorGeoPar(const FairTestDetectorGeoPar&); diff --git a/examples/advanced/Tutorial3/timeBasedSimulation/FairTestDetectorDigiRingSorter.cxx b/examples/advanced/Tutorial3/timeBasedSimulation/FairTestDetectorDigiRingSorter.cxx index 0ab1a2e019..343862f5fa 100644 --- a/examples/advanced/Tutorial3/timeBasedSimulation/FairTestDetectorDigiRingSorter.cxx +++ b/examples/advanced/Tutorial3/timeBasedSimulation/FairTestDetectorDigiRingSorter.cxx @@ -14,7 +14,7 @@ #include "FairTestDetectorDigiRingSorter.h" -#include "FairTestDetectorDigi.h" // for FairTestDetectorDigi +#include "FairTestDetectorDigi.h" // for FairTestDetectorDigi class FairTimeStamp; diff --git a/examples/advanced/Tutorial3/timeBasedSimulation/FairTestDetectorDigiRingSorter.h b/examples/advanced/Tutorial3/timeBasedSimulation/FairTestDetectorDigiRingSorter.h index 26ea9af823..3a258a9168 100644 --- a/examples/advanced/Tutorial3/timeBasedSimulation/FairTestDetectorDigiRingSorter.h +++ b/examples/advanced/Tutorial3/timeBasedSimulation/FairTestDetectorDigiRingSorter.h @@ -15,9 +15,8 @@ #ifndef FairTestDetectorDigiRingSorter_H_ #define FairTestDetectorDigiRingSorter_H_ -#include // for FairRingSorter - -#include // for ClassDef +#include // for FairRingSorter +#include // for ClassDef class FairTimeStamp; diff --git a/examples/advanced/Tutorial3/timeBasedSimulation/FairTestDetectorDigiSorterTask.cxx b/examples/advanced/Tutorial3/timeBasedSimulation/FairTestDetectorDigiSorterTask.cxx index a70dc6e0b2..09e8ee6303 100644 --- a/examples/advanced/Tutorial3/timeBasedSimulation/FairTestDetectorDigiSorterTask.cxx +++ b/examples/advanced/Tutorial3/timeBasedSimulation/FairTestDetectorDigiSorterTask.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* @@ -15,11 +15,11 @@ #include "FairTestDetectorDigiSorterTask.h" #include "FairLogger.h" -#include "FairRootManager.h" // for FairRootManager -#include "FairTestDetectorDigi.h" // for FairTestDetectorDigi, etc +#include "FairRootManager.h" // for FairRootManager +#include "FairTestDetectorDigi.h" // for FairTestDetectorDigi, etc #include "FairTestDetectorDigiRingSorter.h" -#include // for TClonesArray +#include // for TClonesArray class FairRingSorter; class FairTimeStamp; @@ -40,8 +40,7 @@ void FairTestDetectorDigiSorterTask::AddNewDataToTClonesArray(FairTimeStamp* dat { FairRootManager* ioman = FairRootManager::Instance(); TClonesArray* myArray = ioman->GetTClonesArray(fOutputBranch); - if (fVerbose > 1) - { + if (fVerbose > 1) { LOG(info) << "AddNewDataToTClonesArray Data: "; LOG(info) << static_cast(data)->ToString(); } diff --git a/examples/advanced/Tutorial3/timeBasedSimulation/FairTestDetectorDigiSorterTask.h b/examples/advanced/Tutorial3/timeBasedSimulation/FairTestDetectorDigiSorterTask.h index 0ab81949a2..ba8d7ee4b9 100644 --- a/examples/advanced/Tutorial3/timeBasedSimulation/FairTestDetectorDigiSorterTask.h +++ b/examples/advanced/Tutorial3/timeBasedSimulation/FairTestDetectorDigiSorterTask.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* @@ -15,10 +15,9 @@ #ifndef FairTestDetectorDigiSorterTask_H_ #define FairTestDetectorDigiSorterTask_H_ -#include // for FairRingSorterTask - -#include // for Double_t, etc -#include // for TString +#include // for FairRingSorterTask +#include // for Double_t, etc +#include // for TString class FairRingSorter; class FairTimeStamp; @@ -28,9 +27,13 @@ class FairTestDetectorDigiSorterTask : public FairRingSorterTask public: FairTestDetectorDigiSorterTask(); FairTestDetectorDigiSorterTask(const char* name) - : FairRingSorterTask(name) {}; - FairTestDetectorDigiSorterTask(Int_t numberOfCells, Double_t widthOfCells, TString inputBranch, TString outputBranch, TString folderName) - : FairRingSorterTask(numberOfCells, widthOfCells, inputBranch, outputBranch, folderName) {}; + : FairRingSorterTask(name){}; + FairTestDetectorDigiSorterTask(Int_t numberOfCells, + Double_t widthOfCells, + TString inputBranch, + TString outputBranch, + TString folderName) + : FairRingSorterTask(numberOfCells, widthOfCells, inputBranch, outputBranch, folderName){}; virtual ~FairTestDetectorDigiSorterTask(); diff --git a/examples/advanced/Tutorial3/timeBasedSimulation/FairTestDetectorDigiWriteoutBuffer.cxx b/examples/advanced/Tutorial3/timeBasedSimulation/FairTestDetectorDigiWriteoutBuffer.cxx index 8b95da268e..67f210349e 100644 --- a/examples/advanced/Tutorial3/timeBasedSimulation/FairTestDetectorDigiWriteoutBuffer.cxx +++ b/examples/advanced/Tutorial3/timeBasedSimulation/FairTestDetectorDigiWriteoutBuffer.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* @@ -14,13 +14,12 @@ #include "FairTestDetectorDigiWriteoutBuffer.h" -#include "FairRootManager.h" // for FairRootManager -#include "FairTestDetectorDigi.h" // for FairTestDetectorDigi, etc -#include "FairLogger.h" // for logging +#include "FairLogger.h" // for logging +#include "FairRootManager.h" // for FairRootManager +#include "FairTestDetectorDigi.h" // for FairTestDetectorDigi, etc -#include // for TClonesArray - -#include // for pair +#include // for TClonesArray +#include // for pair ClassImp(FairTestDetectorDigiWriteoutBuffer); @@ -31,11 +30,12 @@ FairTestDetectorDigiWriteoutBuffer::FairTestDetectorDigiWriteoutBuffer() // TODO Auto-generated constructor stub } -FairTestDetectorDigiWriteoutBuffer::FairTestDetectorDigiWriteoutBuffer(TString branchName, TString folderName, Bool_t persistance) +FairTestDetectorDigiWriteoutBuffer::FairTestDetectorDigiWriteoutBuffer(TString branchName, + TString folderName, + Bool_t persistance) : FairWriteoutBuffer(branchName, "FairTestDetectorDigi", folderName, persistance) , fData_map() -{ -} +{} FairTestDetectorDigiWriteoutBuffer::~FairTestDetectorDigiWriteoutBuffer() { @@ -46,9 +46,8 @@ void FairTestDetectorDigiWriteoutBuffer::AddNewDataToTClonesArray(FairTimeStamp* { FairRootManager* ioman = FairRootManager::Instance(); TClonesArray* myArray = ioman->GetTClonesArray(fBranchName); - if (fVerbose > 1) - { - LOG(info) << "Data Inserted: " << static_cast(data)->ToString(); + if (fVerbose > 1) { + LOG(info) << "Data Inserted: " << static_cast(data)->ToString(); } new ((*myArray)[myArray->GetEntries()]) FairTestDetectorDigi(*static_cast((data))); } @@ -58,12 +57,9 @@ double FairTestDetectorDigiWriteoutBuffer::FindTimeForData(FairTimeStamp* data) std::map::iterator it; FairTestDetectorDigi myData = *static_cast(data); it = fData_map.find(myData); - if (it == fData_map.end()) - { + if (it == fData_map.end()) { return -1; - } - else - { + } else { return it->second; } } @@ -77,8 +73,7 @@ void FairTestDetectorDigiWriteoutBuffer::FillDataMap(FairTimeStamp* data, double void FairTestDetectorDigiWriteoutBuffer::EraseDataFromDataMap(FairTimeStamp* data) { FairTestDetectorDigi myData = *static_cast(data); - if (fData_map.find(myData) != fData_map.end()) - { + if (fData_map.find(myData) != fData_map.end()) { fData_map.erase(fData_map.find(myData)); } } diff --git a/examples/advanced/Tutorial3/timeBasedSimulation/FairTestDetectorDigiWriteoutBuffer.h b/examples/advanced/Tutorial3/timeBasedSimulation/FairTestDetectorDigiWriteoutBuffer.h index 452700128d..fbcc5cd70f 100644 --- a/examples/advanced/Tutorial3/timeBasedSimulation/FairTestDetectorDigiWriteoutBuffer.h +++ b/examples/advanced/Tutorial3/timeBasedSimulation/FairTestDetectorDigiWriteoutBuffer.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* @@ -15,14 +15,12 @@ #ifndef FairTestDetectorDigiWriteoutBuffer_H_ #define FairTestDetectorDigiWriteoutBuffer_H_ -#include "FairWriteoutBuffer.h" // for FairWriteoutBuffer - -#include "FairTestDetectorDigi.h" // for FairTestDetectorDigi +#include "FairTestDetectorDigi.h" // for FairTestDetectorDigi +#include "FairWriteoutBuffer.h" // for FairWriteoutBuffer #include -#include // for TString - -#include // for map +#include // for TString +#include // for map class FairTimeStamp; diff --git a/examples/advanced/Tutorial3/timeBasedSimulation/FairTestDetectorTimeDigiTask.cxx b/examples/advanced/Tutorial3/timeBasedSimulation/FairTestDetectorTimeDigiTask.cxx index a97ff081ee..590ecbfe3c 100644 --- a/examples/advanced/Tutorial3/timeBasedSimulation/FairTestDetectorTimeDigiTask.cxx +++ b/examples/advanced/Tutorial3/timeBasedSimulation/FairTestDetectorTimeDigiTask.cxx @@ -7,17 +7,17 @@ ********************************************************************************/ #include "FairTestDetectorTimeDigiTask.h" -#include "FairLink.h" // for FairLink -#include "FairRootManager.h" // for FairRootManager -#include "FairTestDetectorDigi.h" // for FairTestDetectorDigi -#include "FairTestDetectorDigiWriteoutBuffer.h" -#include "FairTestDetectorPoint.h" // for FairTestDetectorPoint +#include "FairLink.h" // for FairLink #include "FairLogger.h" +#include "FairRootManager.h" // for FairRootManager +#include "FairTestDetectorDigi.h" // for FairTestDetectorDigi +#include "FairTestDetectorDigiWriteoutBuffer.h" +#include "FairTestDetectorPoint.h" // for FairTestDetectorPoint -#include // for TClonesArray -#include // for Sqrt -#include // for TRandom, gRandom -#include // for TString +#include // for TClonesArray +#include // for Sqrt +#include // for TRandom, gRandom +#include // for TString FairTestDetectorTimeDigiTask::FairTestDetectorTimeDigiTask() : FairTask() @@ -26,32 +26,28 @@ FairTestDetectorTimeDigiTask::FairTestDetectorTimeDigiTask() , fDigiArray(nullptr) , fDataBuffer(nullptr) , fTimeOrderedDigi(kFALSE) -{ -} +{} -FairTestDetectorTimeDigiTask::~FairTestDetectorTimeDigiTask() -{ -} +FairTestDetectorTimeDigiTask::~FairTestDetectorTimeDigiTask() {} InitStatus FairTestDetectorTimeDigiTask::Init() { FairRootManager* ioman = FairRootManager::Instance(); - if (!ioman) - { + if (!ioman) { LOG(error) << "FairTestDetectorTimeDigiTask::Init: RootManager not instantiated!"; return kFATAL; } fPointArray = static_cast(ioman->GetObject("FairTestDetectorPoint")); - if (!fPointArray) - { + if (!fPointArray) { LOG(warn) << "FairTestDetectorTimeDigiTask::Init: No Point array!"; return kERROR; } // Create and register output array fDataBuffer = new FairTestDetectorDigiWriteoutBuffer("FairTestDetectorDigi", "TOY", kTRUE); - fDataBuffer = static_cast(ioman->RegisterWriteoutBuffer("FairTestDetectorDigi", fDataBuffer)); + fDataBuffer = static_cast( + ioman->RegisterWriteoutBuffer("FairTestDetectorDigi", fDataBuffer)); fDataBuffer->ActivateBuffering(fTimeOrderedDigi); return kSUCCESS; @@ -64,11 +60,9 @@ void FairTestDetectorTimeDigiTask::Exec(Option_t* /*opt*/) // fill the map LOG(info) << "EventTime: " << FairRootManager::Instance()->GetEventTime(); - for (int ipnt = 0; ipnt < fPointArray->GetEntries(); ipnt++) - { + for (int ipnt = 0; ipnt < fPointArray->GetEntries(); ipnt++) { FairTestDetectorPoint* point = static_cast(fPointArray->At(ipnt)); - if (!point) - { + if (!point) { continue; } @@ -79,12 +73,9 @@ void FairTestDetectorTimeDigiTask::Exec(Option_t* /*opt*/) Double_t timestamp = CalcTimeStamp(point->GetTime()); FairTestDetectorDigi* digi = new FairTestDetectorDigi(xPad, yPad, zPad, timestamp); - if (fTimeResolution > 0) - { + if (fTimeResolution > 0) { digi->SetTimeStampError(fTimeResolution / TMath::Sqrt(fTimeResolution)); - } - else - { + } else { digi->SetTimeStampError(0); } @@ -110,14 +101,11 @@ Double_t FairTestDetectorTimeDigiTask::CalcTimeStamp(Double_t timeOfFlight) Double_t result = eventTime + timeOfFlight + detectionTime; - if (result < 0) - { + if (result < 0) { return 0; - } - else - { + } else { return result; } } -ClassImp(FairTestDetectorTimeDigiTask) +ClassImp(FairTestDetectorTimeDigiTask); diff --git a/examples/advanced/Tutorial3/timeBasedSimulation/FairTestDetectorTimeDigiTask.h b/examples/advanced/Tutorial3/timeBasedSimulation/FairTestDetectorTimeDigiTask.h index 650527dc0b..5fa909c13b 100644 --- a/examples/advanced/Tutorial3/timeBasedSimulation/FairTestDetectorTimeDigiTask.h +++ b/examples/advanced/Tutorial3/timeBasedSimulation/FairTestDetectorTimeDigiTask.h @@ -1,16 +1,16 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FairTestDetectorTimeDigiTask_H #define FairTestDetectorTimeDigiTask_H -#include "FairTask.h" // for FairTask, InitStatus +#include "FairTask.h" // for FairTask, InitStatus -#include // for Double_t, etc +#include // for Double_t, etc class TClonesArray; class FairTestDetectorDigiWriteoutBuffer; @@ -30,19 +30,10 @@ class FairTestDetectorTimeDigiTask : public FairTask /** Virtual method Exec **/ virtual void Exec(Option_t* opt); - void SetTimeResolution(Double_t timeInNs) - { - fTimeResolution = timeInNs; - } - Double_t GetTimeResolution() - { - return fTimeResolution; - } - - void RunTimeBased() - { - fTimeOrderedDigi = kTRUE; - } + void SetTimeResolution(Double_t timeInNs) { fTimeResolution = timeInNs; } + Double_t GetTimeResolution() { return fTimeResolution; } + + void RunTimeBased() { fTimeOrderedDigi = kTRUE; } private: Int_t CalcPad(Double_t posIn, Double_t posOut); diff --git a/examples/advanced/Tutorial3/timeBasedSimulation/FairTestDetectorTimeRecoTask.cxx b/examples/advanced/Tutorial3/timeBasedSimulation/FairTestDetectorTimeRecoTask.cxx index acf6505a57..f920c56994 100644 --- a/examples/advanced/Tutorial3/timeBasedSimulation/FairTestDetectorTimeRecoTask.cxx +++ b/examples/advanced/Tutorial3/timeBasedSimulation/FairTestDetectorTimeRecoTask.cxx @@ -1,31 +1,30 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "FairTestDetectorTimeRecoTask.h" -#include "FairRootManager.h" // for FairRootManager -#include "FairRunAna.h" // for FairRunAna -#include "FairTSBufferFunctional.h" // for StopTime -#include "FairTestDetectorDigi.h" // for FairTestDetectorDigi -#include "FairTestDetectorHit.h" // for FairTestDetectorHit #include "FairLogger.h" +#include "FairRootManager.h" // for FairRootManager +#include "FairRunAna.h" // for FairRunAna +#include "FairTSBufferFunctional.h" // for StopTime +#include "FairTestDetectorDigi.h" // for FairTestDetectorDigi +#include "FairTestDetectorHit.h" // for FairTestDetectorHit -#include // for TClonesArray -#include // for Sqrt -#include // for TVector3 +#include // for TClonesArray +#include // for Sqrt +#include // for TVector3 FairTestDetectorTimeRecoTask::FairTestDetectorTimeRecoTask() : FairTask() , fDigiArray(nullptr) , fHitArray(nullptr) - , fTime (0.) + , fTime(0.) , fFunctor(nullptr) -{ -} +{} FairTestDetectorTimeRecoTask::FairTestDetectorTimeRecoTask(Int_t verbose) : FairTask() @@ -37,22 +36,18 @@ FairTestDetectorTimeRecoTask::FairTestDetectorTimeRecoTask(Int_t verbose) fVerbose = verbose; } -FairTestDetectorTimeRecoTask::~FairTestDetectorTimeRecoTask() -{ -} +FairTestDetectorTimeRecoTask::~FairTestDetectorTimeRecoTask() {} InitStatus FairTestDetectorTimeRecoTask::Init() { FairRootManager* ioman = FairRootManager::Instance(); - if (!ioman) - { - LOG(error) <<"FairTestDetectorTimeRecoTask::Init: RootManager not instantiated!"; + if (!ioman) { + LOG(error) << "FairTestDetectorTimeRecoTask::Init: RootManager not instantiated!"; return kFATAL; } fDigiArray = static_cast(ioman->GetObject("FairTestDetectorSortedDigi")); - if (!fDigiArray) - { + if (!fDigiArray) { LOG(warn) << "FairTestDetectorTimeRecoTask::Init: No Point array!"; return kERROR; } @@ -71,20 +66,18 @@ void FairTestDetectorTimeRecoTask::Exec(Option_t* /*opt*/) fHitArray->Delete(); fTime += 200; - if (FairRunAna::Instance()->IsTimeStamp()) - { + if (FairRunAna::Instance()->IsTimeStamp()) { fDigiArray = FairRootManager::Instance()->GetData("FairTestDetectorSortedDigi", fFunctor, fTime); - // LOG(info) << "EventTime: " << FairRootManager::Instance()->GetEntryNr() << " " << FairRootManager::Instance()->GetEventTime(); + // LOG(info) << "EventTime: " << FairRootManager::Instance()->GetEntryNr() << " " << + // FairRootManager::Instance()->GetEventTime(); } // fill the map // LOG(info) << "NDigis: " << fDigiArray->GetEntries(); - for (int ipnt = 0; ipnt < fDigiArray->GetEntries(); ipnt++) - { + for (int ipnt = 0; ipnt < fDigiArray->GetEntries(); ipnt++) { FairTestDetectorDigi* digi = static_cast(fDigiArray->At(ipnt)); - if (!digi) - { - LOG(warn) << "No digi!"; + if (!digi) { + LOG(warn) << "No digi!"; continue; } @@ -104,4 +97,4 @@ void FairTestDetectorTimeRecoTask::Exec(Option_t* /*opt*/) fDigiArray->Delete(); } -ClassImp(FairTestDetectorTimeRecoTask) +ClassImp(FairTestDetectorTimeRecoTask); diff --git a/examples/advanced/Tutorial3/timeBasedSimulation/FairTestDetectorTimeRecoTask.h b/examples/advanced/Tutorial3/timeBasedSimulation/FairTestDetectorTimeRecoTask.h index 3d9eea3ac2..f71aea35ad 100644 --- a/examples/advanced/Tutorial3/timeBasedSimulation/FairTestDetectorTimeRecoTask.h +++ b/examples/advanced/Tutorial3/timeBasedSimulation/FairTestDetectorTimeRecoTask.h @@ -1,16 +1,16 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FairTestDetectorTimeRecoTask_H #define FairTestDetectorTimeRecoTask_H -#include "FairTask.h" // for FairTask, InitStatus +#include "FairTask.h" // for FairTask, InitStatus -#include // for ClassDef +#include // for ClassDef class BinaryFunctor; class TClonesArray; @@ -37,7 +37,7 @@ class FairTestDetectorTimeRecoTask : public FairTask Double_t fTime; - BinaryFunctor* fFunctor; //! + BinaryFunctor* fFunctor; //! FairTestDetectorTimeRecoTask(const FairTestDetectorTimeRecoTask&); FairTestDetectorTimeRecoTask& operator=(const FairTestDetectorTimeRecoTask&); diff --git a/examples/advanced/propagator/macros/runMC.C b/examples/advanced/propagator/macros/runMC.C index a58425a4ad..fc10a9e9e3 100644 --- a/examples/advanced/propagator/macros/runMC.C +++ b/examples/advanced/propagator/macros/runMC.C @@ -5,7 +5,7 @@ * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ -int runMC(Int_t nEvents = 1000, TString mcEngine = "TGeant4", Bool_t isMT=false) +int runMC(Int_t nEvents = 1000, TString mcEngine = "TGeant4", Bool_t isMT = false) { UInt_t randomSeed = 123456; gRandom->SetSeed(randomSeed); @@ -13,28 +13,26 @@ int runMC(Int_t nEvents = 1000, TString mcEngine = "TGeant4", Bool_t isMT=false) TString dir = getenv("VMCWORKDIR"); TString tut_geomdir = dir + "/common/geometry"; - gSystem->Setenv("GEOMPATH",tut_geomdir.Data()); + gSystem->Setenv("GEOMPATH", tut_geomdir.Data()); TString tut_configdir = dir + "/common/gconfig"; - gSystem->Setenv("CONFIG_DIR",tut_configdir.Data()); + gSystem->Setenv("CONFIG_DIR", tut_configdir.Data()); // TString partName[] = {"pions","eplus","proton"}; - Int_t partPdgC[] = { 211, 11, 2212}; - Int_t chosenPart = 0; + Int_t partPdgC[] = {211, 11, 2212}; + Int_t chosenPart = 0; Double_t momentum = 2.; - Double_t theta = 10.; + Double_t theta = 10.; TString outDir = "./"; // Output file name - TString outFile = Form("%s/prop.mc.root", - outDir.Data()); + TString outFile = Form("%s/prop.mc.root", outDir.Data()); // Parameter file name - TString parFile = Form("%s/prop.par.root", - outDir.Data()); + TString parFile = Form("%s/prop.par.root", outDir.Data()); TString geoFile = "geofile_" + mcEngine + "_full.root"; @@ -52,24 +50,24 @@ int runMC(Int_t nEvents = 1000, TString mcEngine = "TGeant4", Bool_t isMT=false) // ----- Create simulation run ---------------------------------------- FairRunSim* run = new FairRunSim(); - run->SetName(mcEngine); // Transport engine + run->SetName(mcEngine); // Transport engine // run->SetSimulationConfig(new FairVMCConfig()); - run->SetIsMT(isMT); // Multi-threading mode (Geant4 only) - run->SetSink(new FairRootFileSink(outFile)); // Output file + run->SetIsMT(isMT); // Multi-threading mode (Geant4 only) + run->SetSink(new FairRootFileSink(outFile)); // Output file FairRuntimeDb* rtdb = run->GetRuntimeDb(); // ------------------------------------------------------------------------ // ----- Create media ------------------------------------------------- - run->SetMaterials("media.geo"); // Materials + run->SetMaterials("media.geo"); // Materials // ------------------------------------------------------------------------ // ----- Create geometry ---------------------------------------------- - FairModule* cave= new FairCave("CAVE"); + FairModule* cave = new FairCave("CAVE"); cave->SetGeometryFileName("cave_vacuum.geo"); run->AddModule(cave); - FairTutPropDet* det = new FairTutPropDet("TutPropDetector", kTRUE); + FairTutPropDet* det = new FairTutPropDet("TutPropDetector", kTRUE); det->SetGeometryFileName("pixel.geo"); run->AddModule(det); // ------------------------------------------------------------------------ @@ -78,16 +76,16 @@ int runMC(Int_t nEvents = 1000, TString mcEngine = "TGeant4", Bool_t isMT=false) FairPrimaryGenerator* primGen = new FairPrimaryGenerator(); FairBoxGenerator* boxGen = new FairBoxGenerator(partPdgC[chosenPart], 1); - boxGen->SetThetaRange ( theta, theta+0.01); - boxGen->SetPRange (momentum,momentum+0.01); - boxGen->SetPhiRange (0.,360.); // 10.,10. when looking for PCA + boxGen->SetThetaRange(theta, theta + 0.01); + boxGen->SetPRange(momentum, momentum + 0.01); + boxGen->SetPhiRange(0., 360.); // 10.,10. when looking for PCA boxGen->SetDebug(kTRUE); primGen->AddGenerator(boxGen); - FairConstField *fMagField=new FairConstField(); - fMagField->SetField(0.,0.,20.); // values are in kG - fMagField->SetFieldRegion(-150, 150, -150, 150, -250, 250);// values are in cm (xmin,xmax,ymin,ymax,zmin,zmax) + FairConstField* fMagField = new FairConstField(); + fMagField->SetField(0., 0., 20.); // values are in kG + fMagField->SetFieldRegion(-150, 150, -150, 150, -250, 250); // values are in cm (xmin,xmax,ymin,ymax,zmin,zmax) run->SetField(fMagField); run->SetGenerator(primGen); @@ -119,7 +117,7 @@ int runMC(Int_t nEvents = 1000, TString mcEngine = "TGeant4", Bool_t isMT=false) // Extract the maximal used memory an add is as Dart measurement // This line is filtered by CTest and the value send to CDash FairSystemInfo sysInfo; - Float_t maxMemory=sysInfo.GetMaxMemory(); + Float_t maxMemory = sysInfo.GetMaxMemory(); cout << ""; cout << maxMemory; cout << "" << endl; @@ -128,16 +126,15 @@ int runMC(Int_t nEvents = 1000, TString mcEngine = "TGeant4", Bool_t isMT=false) Double_t rtime = timer.RealTime(); Double_t ctime = timer.CpuTime(); - Float_t cpuUsage=ctime/rtime; + Float_t cpuUsage = ctime / rtime; cout << ""; cout << cpuUsage; cout << "" << endl; cout << endl << endl; - cout << "Output file is " << outFile << endl; + cout << "Output file is " << outFile << endl; cout << "Parameter file is " << parFile << endl; - cout << "Real time " << rtime << " s, CPU time " << ctime - << "s" << endl << endl; + cout << "Real time " << rtime << " s, CPU time " << ctime << "s" << endl << endl; cout << "Macro finished successfully." << endl; // ------------------------------------------------------------------------ diff --git a/examples/advanced/propagator/macros/runProp.C b/examples/advanced/propagator/macros/runProp.C index 717b9c955a..86d3d7d73b 100644 --- a/examples/advanced/propagator/macros/runProp.C +++ b/examples/advanced/propagator/macros/runProp.C @@ -5,9 +5,9 @@ * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ -int runProp(std::string propName="rk") +int runProp(std::string propName = "rk") { - if ( propName!="geane" && propName!="rk" ) { + if (propName != "geane" && propName != "rk") { cout << "Choose either \"geane\" or \"rk\"." << endl; return 1; } @@ -15,13 +15,13 @@ int runProp(std::string propName="rk") TString dir = getenv("VMCWORKDIR"); TString tut_geomdir = dir + "/common/geometry"; - gSystem->Setenv("GEOMPATH",tut_geomdir.Data()); + gSystem->Setenv("GEOMPATH", tut_geomdir.Data()); TString tut_configdir = dir + "/common/gconfig"; - gSystem->Setenv("CONFIG_DIR",tut_configdir.Data()); + gSystem->Setenv("CONFIG_DIR", tut_configdir.Data()); // Verbosity level (0=quiet, 1=event level, 2=track level, 3=debug) - Int_t iVerbose = 0; // just forget about it, for the moment + Int_t iVerbose = 0; // just forget about it, for the moment // Input file (MC events) TString inFile = "prop.mc.root"; @@ -30,15 +30,15 @@ int runProp(std::string propName="rk") TString parFile = "prop.par.root"; // Output file - TString outFile = Form("prop.%s.cal.root",propName.data()); + TString outFile = Form("prop.%s.cal.root", propName.data()); // ----- Timer -------------------------------------------------------- TStopwatch timer; // ----- Reconstruction run ------------------------------------------- - FairRunAna *fRun= new FairRunAna(); - fRun->SetSource(new FairFileSource (inFile)); - fRun->SetSink (new FairRootFileSink(outFile)); + FairRunAna* fRun = new FairRunAna(); + fRun->SetSource(new FairFileSource(inFile)); + fRun->SetSink(new FairRootFileSink(outFile)); FairRuntimeDb* rtdb = fRun->GetRuntimeDb(); FairParRootFileIo* parInput1 = new FairParRootFileIo(); @@ -46,19 +46,19 @@ int runProp(std::string propName="rk") rtdb->setFirstInput(parInput1); - FairConstField *fMagField=new FairConstField(); - fMagField->SetField(0.,0.,20.); // values are in kG - fMagField->SetFieldRegion(-150, 150, -150, 150, -250, 250);// values are in cm (xmin,xmax,ymin,ymax,zmin,zmax) + FairConstField* fMagField = new FairConstField(); + fMagField->SetField(0., 0., 20.); // values are in kG + fMagField->SetFieldRegion(-150, 150, -150, 150, -250, 250); // values are in cm (xmin,xmax,ymin,ymax,zmin,zmax) fRun->SetField(fMagField); // ----- Set propagator and run --------------------------------------- - if ( propName == "geane" ) { - FairGeane *Geane = new FairGeane(); + if (propName == "geane") { + FairGeane* Geane = new FairGeane(); fRun->AddTask(Geane); } FairTutPropTr* propTask = new FairTutPropTr(); - if ( propName == "rk" ) { + if (propName == "rk") { FairRKPropagator* propagator = new FairRKPropagator(fMagField); propTask->SetPropagator(propagator); } @@ -66,8 +66,8 @@ int runProp(std::string propName="rk") fRun->Init(); - if ( propName == "geane" ) { - FairGeanePro *GeaneProp = new FairGeanePro(); + if (propName == "geane") { + FairGeanePro* GeaneProp = new FairGeanePro(); propTask->SetPropagator(GeaneProp); } @@ -81,7 +81,7 @@ int runProp(std::string propName="rk") // Extract the maximal used memory an add is as Dart measurement // This line is filtered by CTest and the value send to CDash FairSystemInfo sysInfo; - Float_t maxMemory=sysInfo.GetMaxMemory(); + Float_t maxMemory = sysInfo.GetMaxMemory(); cout << ""; cout << maxMemory; cout << "" << endl; @@ -90,18 +90,17 @@ int runProp(std::string propName="rk") Double_t rtime = timer.RealTime(); Double_t ctime = timer.CpuTime(); - Float_t cpuUsage=ctime/rtime; + Float_t cpuUsage = ctime / rtime; cout << ""; cout << cpuUsage; cout << "" << endl; cout << endl << endl; - cout << "Output file is " << outFile << endl; + cout << "Output file is " << outFile << endl; cout << "Parameter file is " << parFile << endl; - cout << "Real time " << rtime << " s, CPU time " << ctime - << "s" << endl << endl; + cout << "Real time " << rtime << " s, CPU time " << ctime << "s" << endl << endl; cout << "Macro finished successfully." << endl; - // ------------------------------------------------------------------------ + // ------------------------------------------------------------------------ return 0; } diff --git a/examples/advanced/propagator/macros/runPull.C b/examples/advanced/propagator/macros/runPull.C index b609a265c8..4eb4aaa2f3 100644 --- a/examples/advanced/propagator/macros/runPull.C +++ b/examples/advanced/propagator/macros/runPull.C @@ -5,9 +5,9 @@ * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ -int runPull(std::string propName="rk", bool drawHist = false) +int runPull(std::string propName = "rk", bool drawHist = false) { - if ( propName!="geane" && propName!="rk" ) { + if (propName != "geane" && propName != "rk") { cout << "Choose either \"geane\" or \"rk\"." << endl; return 1; } @@ -15,39 +15,39 @@ int runPull(std::string propName="rk", bool drawHist = false) gROOT->Reset(); gStyle->SetOptFit(1); - TFile *f=new TFile(Form("prop.%s.cal.root",propName.data())); - TTree *simtree=(TTree*)f->Get("cbmsim") ; + TFile *f = new TFile(Form("prop.%s.cal.root", propName.data())); + TTree *simtree = (TTree *)f->Get("cbmsim"); - TClonesArray* fTrackParProp = new TClonesArray("FairTrackParP"); - TClonesArray* fTrackParIni = new TClonesArray("FairTrackParP"); - TClonesArray* fTrackParFinal = new TClonesArray("FairTrackParP"); + TClonesArray *fTrackParProp = new TClonesArray("FairTrackParP"); + TClonesArray *fTrackParIni = new TClonesArray("FairTrackParP"); + TClonesArray *fTrackParFinal = new TClonesArray("FairTrackParP"); Double_t maxDist = 0.1; - TH1F *hQP = new TH1F("hQP","charge over momentum",200,-maxDist,maxDist); - TH1F *hX = new TH1F("hX", "position X",200,-maxDist,maxDist); - TH1F *hY = new TH1F("hY", "position Y",200,-maxDist,maxDist); - TH1F *hPx = new TH1F("hPx","momentum X",200,-maxDist,maxDist); - TH1F *hPy = new TH1F("hPy","momentum Y",200,-maxDist,maxDist); - TH1F *hPz = new TH1F("hPz","momentum Z",200,-maxDist,maxDist); + TH1F *hQP = new TH1F("hQP", "charge over momentum", 200, -maxDist, maxDist); + TH1F *hX = new TH1F("hX", "position X", 200, -maxDist, maxDist); + TH1F *hY = new TH1F("hY", "position Y", 200, -maxDist, maxDist); + TH1F *hPx = new TH1F("hPx", "momentum X", 200, -maxDist, maxDist); + TH1F *hPy = new TH1F("hPy", "momentum Y", 200, -maxDist, maxDist); + TH1F *hPz = new TH1F("hPz", "momentum Z", 200, -maxDist, maxDist); - simtree->SetBranchAddress("PropTrackFinal",&fTrackParFinal); - simtree->SetBranchAddress("PropTrackPar",&fTrackParProp); + simtree->SetBranchAddress("PropTrackFinal", &fTrackParFinal); + simtree->SetBranchAddress("PropTrackPar", &fTrackParProp); FairTrackParP *fTrkF; FairTrackParP *fTrkG; - Int_t Nevents= simtree->GetEntriesFast(); - cout<GetEntriesFast(); + cout << Nevents << endl; + for (Int_t i = 0; i < Nevents; i++) { simtree->GetEntry(i); - for (Int_t k=0; kGetEntriesFast(); k++) { + for (Int_t k = 0; k < fTrackParProp->GetEntriesFast(); k++) { fTrkF = (FairTrackParP *)fTrackParFinal->At(k); - fTrkG = (FairTrackParP *)fTrackParProp ->At(k); - if(fTrkF &&fTrkG ){ - hQP->Fill(fTrkF->GetQp()-fTrkG->GetQp()); - hX ->Fill(fTrkF->GetX() -fTrkG->GetX()); - hY ->Fill(fTrkF->GetY() -fTrkG->GetY()); - hPx->Fill(fTrkF->GetPx()-fTrkG->GetPx()); - hPy->Fill(fTrkF->GetPy()-fTrkG->GetPy()); - hPz->Fill(fTrkF->GetPz()-fTrkG->GetPz()); + fTrkG = (FairTrackParP *)fTrackParProp->At(k); + if (fTrkF && fTrkG) { + hQP->Fill(fTrkF->GetQp() - fTrkG->GetQp()); + hX->Fill(fTrkF->GetX() - fTrkG->GetX()); + hY->Fill(fTrkF->GetY() - fTrkG->GetY()); + hPx->Fill(fTrkF->GetPx() - fTrkG->GetPx()); + hPy->Fill(fTrkF->GetPy() - fTrkG->GetPy()); + hPz->Fill(fTrkF->GetPz() - fTrkG->GetPz()); // if(fTrkG->GetDQp()) hQP->Fill((fTrkF->GetQp()-fTrkG->GetQp())/fTrkG->GetDQp()); // if(fTrkG->GetDX() ) hX ->Fill((fTrkF->GetX() -fTrkG->GetX()) /fTrkG->GetDX()); // if(fTrkG->GetDY() ) hY ->Fill((fTrkF->GetY() -fTrkG->GetY()) /fTrkG->GetDY()); @@ -57,39 +57,41 @@ int runPull(std::string propName="rk", bool drawHist = false) } } } - if ( drawHist ) { - TCanvas *c=new TCanvas("c","c",900,600); - c->Divide(3,2); + if (drawHist) { + TCanvas *c = new TCanvas("c", "c", 900, 600); + c->Divide(3, 2); c->cd(1); hQP->Draw(); - hQP-> Fit("gaus"); + hQP->Fit("gaus"); c->cd(2); hX->Draw(); - hX-> Fit("gaus"); + hX->Fit("gaus"); c->cd(3); hY->Draw(); - hY-> Fit("gaus"); + hY->Fit("gaus"); c->cd(4); hPx->Draw(); - hPx-> Fit("gaus"); + hPx->Fit("gaus"); c->cd(5); hPy->Draw(); - hPy-> Fit("gaus"); + hPy->Fit("gaus"); c->cd(6); hPz->Draw(); - hPz-> Fit("gaus"); + hPz->Fit("gaus"); c->cd(); } - TF1* fitX = new TF1("fitX","gaus",-5.,5.); - hX->Fit("fitX","QN"); + TF1 *fitX = new TF1("fitX", "gaus", -5., 5.); + hX->Fit("fitX", "QN"); - if ( fitX->GetParameter(1) > -1.e-3 && fitX->GetParameter(1) < 1.e-3 && - fitX->GetParameter(2) > 0. && fitX->GetParameter(2) < 1.e-2 ) - cout << "Macro finished successfully. Mean (" << fitX->GetParameter(1) << ") and sigma (" << fitX->GetParameter(2) << ") inside limits." << endl; + if (fitX->GetParameter(1) > -1.e-3 && fitX->GetParameter(1) < 1.e-3 && fitX->GetParameter(2) > 0. + && fitX->GetParameter(2) < 1.e-2) + cout << "Macro finished successfully. Mean (" << fitX->GetParameter(1) << ") and sigma (" + << fitX->GetParameter(2) << ") inside limits." << endl; else - cout << "Macro failed. Mean (" << fitX->GetParameter(1) << ") or sigma (" << fitX->GetParameter(2) << ") too far off." << endl; + cout << "Macro failed. Mean (" << fitX->GetParameter(1) << ") or sigma (" << fitX->GetParameter(2) + << ") too far off." << endl; return 0; } diff --git a/examples/advanced/propagator/src/FairTutPropContFact.cxx b/examples/advanced/propagator/src/FairTutPropContFact.cxx index 03993b35be..cf4d22f3f1 100644 --- a/examples/advanced/propagator/src/FairTutPropContFact.cxx +++ b/examples/advanced/propagator/src/FairTutPropContFact.cxx @@ -7,13 +7,12 @@ ********************************************************************************/ #include "FairTutPropContFact.h" -#include "FairRuntimeDb.h" // for FairRuntimeDb -#include "FairTutPropGeoPar.h" // for FairTutPropGeoPar +#include "FairRuntimeDb.h" // for FairRuntimeDb +#include "FairTutPropGeoPar.h" // for FairTutPropGeoPar +#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; @@ -50,12 +49,11 @@ FairParSet* FairTutPropContFact::createContainer(FairContainer* c) of this container, the name is concatinated with the context. */ const char* name = c->GetName(); - if (strcmp(name, "FairTutPropGeoPar") == 0) - { + if (strcmp(name, "FairTutPropGeoPar") == 0) { return new FairTutPropGeoPar(c->getConcatName().Data(), c->GetTitle(), c->getContext()); } return nullptr; } -ClassImp(FairTutPropContFact) +ClassImp(FairTutPropContFact); diff --git a/examples/advanced/propagator/src/FairTutPropContFact.h b/examples/advanced/propagator/src/FairTutPropContFact.h index a2823d75da..e5935f52cc 100644 --- a/examples/advanced/propagator/src/FairTutPropContFact.h +++ b/examples/advanced/propagator/src/FairTutPropContFact.h @@ -8,9 +8,8 @@ #ifndef FAIRTUTPROPCONTFACT_H_ #define FAIRTUTPROPCONTFACT_H_ -#include "FairContFact.h" // for FairContFact, etc - -#include "Rtypes.h" // for ClassDef +#include "FairContFact.h" // for FairContFact, etc +#include "Rtypes.h" // for ClassDef class FairParSet; @@ -21,11 +20,9 @@ class FairTutPropContFact : public FairContFact public: FairTutPropContFact(); - ~FairTutPropContFact() - { - } + ~FairTutPropContFact() {} FairParSet* createContainer(FairContainer*); - ClassDef(FairTutPropContFact, 0) // Factory for all FairTutProp parameter containers + ClassDef(FairTutPropContFact, 0) // Factory for all FairTutProp parameter containers }; #endif /* FAIRTUTPROPCONTFACT_H_ */ diff --git a/examples/advanced/propagator/src/FairTutPropDet.cxx b/examples/advanced/propagator/src/FairTutPropDet.cxx index 9456432aad..967b6493ad 100644 --- a/examples/advanced/propagator/src/FairTutPropDet.cxx +++ b/examples/advanced/propagator/src/FairTutPropDet.cxx @@ -7,62 +7,51 @@ ********************************************************************************/ #include "FairTutPropDet.h" -#include "FairTutPropPoint.h" +#include "FairDetectorList.h" // for DetectorId::kTutDet +#include "FairGeoInterface.h" // for FairGeoInterface +#include "FairGeoLoader.h" // for FairGeoLoader +#include "FairGeoNode.h" // for FairGeoNode +#include "FairGeoVolume.h" // for FairGeoVolume +#include "FairLogger.h" // for logging +#include "FairRootManager.h" // for FairRootManager +#include "FairRun.h" // for FairRun +#include "FairRuntimeDb.h" // for FairRuntimeDb +#include "FairStack.h" // for FairStack #include "FairTutPropGeo.h" #include "FairTutPropGeoPar.h" - - - -#include "FairDetectorList.h" // for DetectorId::kTutDet -#include "FairGeoInterface.h" // for FairGeoInterface -#include "FairGeoLoader.h" // for FairGeoLoader -#include "FairGeoNode.h" // for FairGeoNode -#include "FairGeoVolume.h" // for FairGeoVolume -#include "FairRootManager.h" // for FairRootManager -#include "FairRun.h" // for FairRun -#include "FairRuntimeDb.h" // for FairRuntimeDb -#include "FairStack.h" // for FairStack -#include "FairVolume.h" // for FairVolume -#include "FairLogger.h" // for logging - - - -#include // for ostream -#include "TClonesArray.h" // for TClonesArray -#include "TList.h" // for TListIter, TList (ptr only) -#include "TObjArray.h" // for TObjArray -#include "TString.h" // for TString -#include "TVirtualMC.h" // for TVirtualMC -#include "TVirtualMCStack.h" // for TVirtualMCStack - -#include "TGeoPhysicalNode.h" +#include "FairTutPropPoint.h" +#include "FairVolume.h" // for FairVolume +#include "TClonesArray.h" // for TClonesArray #include "TGeoManager.h" #include "TGeoMatrix.h" +#include "TGeoPhysicalNode.h" +#include "TList.h" // for TListIter, TList (ptr only) +#include "TObjArray.h" // for TObjArray +#include "TString.h" // for TString +#include "TVirtualMC.h" // for TVirtualMC +#include "TVirtualMCStack.h" // for TVirtualMCStack -#include // for NULL - - +#include // for ostream #include +#include // for NULL using std::cout; using std::endl; FairTutPropDet::FairTutPropDet() : FairTutPropDet("FairTutPropDet", kTRUE) -{ -} +{} FairTutPropDet::FairTutPropDet(const char* name, Bool_t active) - : FairDetector(name, active, kTutProp), - fTrackID(-1), - fVolumeID(-1), - fPos(), - fMom(), - fTime(-1.), - fLength(-1.), - fELoss(-1), - fFairTutPropPointCollection(new TClonesArray("FairTutPropPoint")) -{ -} + : FairDetector(name, active, kTutProp) + , fTrackID(-1) + , fVolumeID(-1) + , fPos() + , fMom() + , fTime(-1.) + , fLength(-1.) + , fELoss(-1) + , fFairTutPropPointCollection(new TClonesArray("FairTutPropPoint")) +{} FairTutPropDet::~FairTutPropDet() { @@ -72,19 +61,16 @@ FairTutPropDet::~FairTutPropDet() } } -void FairTutPropDet::Initialize() -{ - FairDetector::Initialize(); -} +void FairTutPropDet::Initialize() { FairDetector::Initialize(); } -Bool_t FairTutPropDet::ProcessHits(FairVolume* vol) +Bool_t FairTutPropDet::ProcessHits(FairVolume* vol) { /** This method is called from the MC stepping */ - //Set parameters at entrance of volume. Reset ELoss. - if ( TVirtualMC::GetMC()->IsTrackEntering() ) { - fELoss = 0.; - fTime = TVirtualMC::GetMC()->TrackTime() * 1.0e09; + // Set parameters at entrance of volume. Reset ELoss. + if (TVirtualMC::GetMC()->IsTrackEntering()) { + fELoss = 0.; + fTime = TVirtualMC::GetMC()->TrackTime() * 1.0e09; fLength = TVirtualMC::GetMC()->TrackLength(); TVirtualMC::GetMC()->TrackPosition(fPos); TVirtualMC::GetMC()->TrackMomentum(fMom); @@ -94,13 +80,14 @@ Bool_t FairTutPropDet::ProcessHits(FairVolume* vol) fELoss += TVirtualMC::GetMC()->Edep(); // Create FairTutPropPoint at exit of active volume - if ( TVirtualMC::GetMC()->IsTrackExiting() || - TVirtualMC::GetMC()->IsTrackStop() || - TVirtualMC::GetMC()->IsTrackDisappeared() ) { - fTrackID = TVirtualMC::GetMC()->GetStack()->GetCurrentTrackNumber(); + if (TVirtualMC::GetMC()->IsTrackExiting() || TVirtualMC::GetMC()->IsTrackStop() + || TVirtualMC::GetMC()->IsTrackDisappeared()) { + fTrackID = TVirtualMC::GetMC()->GetStack()->GetCurrentTrackNumber(); fVolumeID = vol->getMCid(); - if (fELoss == 0. ) { return kFALSE; } + if (fELoss == 0.) { + return kFALSE; + } // Taking stationNr and sectorNr from string is almost effortless. // Simulation of 100k events with 5 pions without magnetic field takes: @@ -108,16 +95,20 @@ Bool_t FairTutPropDet::ProcessHits(FairVolume* vol) // - Real time 142.407 s, CPU time 140.64s WITHOUT THE FOLLOWING TString OPERATIONS { TString detPath = TVirtualMC::GetMC()->CurrentVolPath(); - detPath.Remove (0,detPath.Last('/')+1); - detPath.Remove (0,detPath.First("Pixel")+5); + detPath.Remove(0, detPath.Last('/') + 1); + detPath.Remove(0, detPath.First("Pixel") + 5); Int_t stationNr = detPath.Atoi(); - detPath.Remove (0,detPath.First("_")+1); - Int_t sectorNr = detPath.Atoi(); - fVolumeID = stationNr*256+sectorNr; + detPath.Remove(0, detPath.First("_") + 1); + Int_t sectorNr = detPath.Atoi(); + fVolumeID = stationNr * 256 + sectorNr; } - AddHit(fTrackID, fVolumeID, TVector3(fPos.X(), fPos.Y(), fPos.Z()), - TVector3(fMom.Px(), fMom.Py(), fMom.Pz()), fTime, fLength, + AddHit(fTrackID, + fVolumeID, + TVector3(fPos.X(), fPos.Y(), fPos.Z()), + TVector3(fMom.Px(), fMom.Py(), fMom.Pz()), + fTime, + fLength, fELoss); // Increment number of FairTutPropDet points in TParticle @@ -128,12 +119,7 @@ Bool_t FairTutPropDet::ProcessHits(FairVolume* vol) return kTRUE; } -void FairTutPropDet::EndOfEvent() -{ - fFairTutPropPointCollection->Clear(); -} - - +void FairTutPropDet::EndOfEvent() { fFairTutPropPointCollection->Clear(); } void FairTutPropDet::Register() { @@ -144,12 +130,9 @@ void FairTutPropDet::Register() only during the simulation. */ - FairRootManager::Instance()->Register("FairTutPropPoint", "FairTutPropDet", - fFairTutPropPointCollection, kTRUE); - + FairRootManager::Instance()->Register("FairTutPropPoint", "FairTutPropDet", fFairTutPropPointCollection, kTRUE); } - TClonesArray* FairTutPropDet::GetCollection(Int_t iColl) const { if (iColl == 0) { @@ -158,10 +141,7 @@ TClonesArray* FairTutPropDet::GetCollection(Int_t iColl) const return NULL; } -void FairTutPropDet::Reset() -{ - fFairTutPropPointCollection->Clear(); -} +void FairTutPropDet::Reset() { fFairTutPropPointCollection->Clear(); } void FairTutPropDet::ConstructGeometry() { @@ -169,18 +149,20 @@ void FairTutPropDet::ConstructGeometry() just copy this and use it for your detector, otherwise you can implement here you own way of constructing the geometry. */ - FairTutPropGeo* Geo = new FairTutPropGeo(); + FairTutPropGeo* Geo = new FairTutPropGeo(); ConstructASCIIGeometry(Geo, "FairTutPropGeoPar"); } -FairTutPropPoint* FairTutPropDet::AddHit(Int_t trackID, Int_t detID, - TVector3 pos, TVector3 mom, - Double_t time, Double_t length, - Double_t eLoss) +FairTutPropPoint* FairTutPropDet::AddHit(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t time, + Double_t length, + Double_t eLoss) { Int_t size = fFairTutPropPointCollection->GetEntriesFast(); - return new ((*fFairTutPropPointCollection)[size]) - FairTutPropPoint(trackID, detID, pos, mom, time, length, eLoss); + return new ((*fFairTutPropPointCollection)[size]) FairTutPropPoint(trackID, detID, pos, mom, time, length, eLoss); } -ClassImp(FairTutPropDet) +ClassImp(FairTutPropDet); diff --git a/examples/advanced/propagator/src/FairTutPropDet.h b/examples/advanced/propagator/src/FairTutPropDet.h index e762e4601e..623ceb4ea0 100644 --- a/examples/advanced/propagator/src/FairTutPropDet.h +++ b/examples/advanced/propagator/src/FairTutPropDet.h @@ -8,24 +8,22 @@ #ifndef FAIRTUTPROPDET_H #define FAIRTUTPROPDET_H -#include "FairDetector.h" // for FairDetector - -#include "Rtypes.h" // for Int_t, Double32_t, Double_t, etc -#include "TLorentzVector.h" // for TLorentzVector -#include "TVector3.h" // for TVector3 +#include "FairDetector.h" // for FairDetector +#include "Rtypes.h" // for Int_t, Double32_t, Double_t, etc +#include "TLorentzVector.h" // for TLorentzVector +#include "TVector3.h" // for TVector3 class FairTutPropPoint; class FairVolume; class TClonesArray; -class FairTutPropDet: public FairDetector +class FairTutPropDet : public FairDetector { public: - /** Name : Detector Name * Active: kTRUE for active detectors (ProcessHits() will be called) * kFALSE for inactive detectors - */ + */ FairTutPropDet(const char* Name, Bool_t Active); /** default constructor */ @@ -35,70 +33,66 @@ class FairTutPropDet: public FairDetector virtual ~FairTutPropDet(); /** 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(); /** This method is an example of how to add your own point * of type FairTutPropDetPoint to the clones array - */ - FairTutPropPoint* AddHit(Int_t trackID, Int_t detID, - TVector3 pos, TVector3 mom, - Double_t time, Double_t length, - Double_t eLoss); + */ + FairTutPropPoint* + AddHit(Int_t trackID, Int_t detID, TVector3 pos, TVector3 mom, Double_t time, Double_t length, Double_t eLoss); /** 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() { ; } 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* fFairTutPropPointCollection; + TClonesArray* fFairTutPropPointCollection; FairTutPropDet(const FairTutPropDet&); FairTutPropDet& operator=(const FairTutPropDet&); - ClassDef(FairTutPropDet,1) + ClassDef(FairTutPropDet, 1) }; -#endif //FAIRTUTPROPDET_H +#endif // FAIRTUTPROPDET_H diff --git a/examples/advanced/propagator/src/FairTutPropGeo.cxx b/examples/advanced/propagator/src/FairTutPropGeo.cxx index 2e596dd842..bf782647a8 100644 --- a/examples/advanced/propagator/src/FairTutPropGeo.cxx +++ b/examples/advanced/propagator/src/FairTutPropGeo.cxx @@ -1,43 +1,44 @@ /******************************************************************************** * Copyright (C) 2019 GSI Helmholtzzentrum fuer Schwerionenforschung GmbH * * * - * This software is distributed under the terms of the * - * GNU Lesser General Public Licence (LGPL) version 3, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "FairTutPropGeo.h" -#include // for sprintf -ClassImp(FairTutPropGeo) +#include // for sprintf + +ClassImp(FairTutPropGeo); // ----- Default constructor ------------------------------------------- FairTutPropGeo::FairTutPropGeo() - : FairGeoSet() + : FairGeoSet() { - // Constructor - // fName has to be the name used in the geometry for all volumes. - // If there is a mismatch the geometry cannot be build. - fName="Pixel"; - maxSectors=0; - maxModules=10; + // Constructor + // fName has to be the name used in the geometry for all volumes. + // If there is a mismatch the geometry cannot be build. + fName = "Pixel"; + maxSectors = 0; + maxModules = 10; } // ------------------------------------------------------------------------- const char* FairTutPropGeo::getModuleName(Int_t m) { - /** Returns the module name of Pixel number m + /** Returns the module name of Pixel number m Setting Pixel here means that all modules names in the ASCII file should start with Pixel otherwise they will not be constructed */ - sprintf(modName,"Pixel%i",m+1); - return modName; + sprintf(modName, "Pixel%i", m + 1); + return modName; } const char* FairTutPropGeo::getEleName(Int_t m) { - /** Returns the element name of Det number m */ - sprintf(eleName,"Pixel%i",m+1); - return eleName; + /** Returns the element name of Det number m */ + sprintf(eleName, "Pixel%i", m + 1); + return eleName; } diff --git a/examples/advanced/propagator/src/FairTutPropGeo.h b/examples/advanced/propagator/src/FairTutPropGeo.h index dc8bb77bd0..35c4250704 100644 --- a/examples/advanced/propagator/src/FairTutPropGeo.h +++ b/examples/advanced/propagator/src/FairTutPropGeo.h @@ -1,40 +1,40 @@ /******************************************************************************** * Copyright (C) 2019 GSI Helmholtzzentrum fuer Schwerionenforschung GmbH * * * - * This software is distributed under the terms of the * - * GNU Lesser General Public Licence (LGPL) version 3, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRTUTPROPGEO_H #define FAIRTUTPROPGEO_H -#include "FairGeoSet.h" // for FairGeoSet -#include "Rtypes.h" // for FairTutPropGeo::Class, ClassDef, FairTutPropGeo::Streamer -#include "TString.h" // for TString +#include "FairGeoSet.h" // for FairGeoSet +#include "Rtypes.h" // for FairTutPropGeo::Class, ClassDef, FairTutPropGeo::Streamer +#include "TString.h" // for TString -class FairTutPropGeo : public FairGeoSet +class FairTutPropGeo : public FairGeoSet { protected: - char modName[20]; // name of module - char eleName[20]; // substring for elements in module + char modName[20]; // name of module + char eleName[20]; // substring for elements in module public: FairTutPropGeo(); ~FairTutPropGeo() {} const char* getModuleName(Int_t); const char* getEleName(Int_t); inline Int_t getModNumInMod(const TString&); - ClassDef(FairTutPropGeo,1) + ClassDef(FairTutPropGeo, 1) }; inline Int_t FairTutPropGeo::getModNumInMod(const TString& name) { - /** returns the module index from module name + /** returns the module index from module name ?? in name[??] has to be the length of the detector name in the .geo file. For example if all nodes in this file starts with newdetector ?? has to be 11. */ - return static_cast((name[5]-'0')-1); // + return static_cast((name[5] - '0') - 1); // } -#endif //FAIRTUTPROPGEO_H +#endif // FAIRTUTPROPGEO_H diff --git a/examples/advanced/propagator/src/FairTutPropGeoPar.cxx b/examples/advanced/propagator/src/FairTutPropGeoPar.cxx index e1260bf781..d410015abb 100644 --- a/examples/advanced/propagator/src/FairTutPropGeoPar.cxx +++ b/examples/advanced/propagator/src/FairTutPropGeoPar.cxx @@ -1,50 +1,52 @@ /******************************************************************************** * Copyright (C) 2019 GSI Helmholtzzentrum fuer Schwerionenforschung GmbH * * * - * This software is distributed under the terms of the * - * GNU Lesser General Public Licence (LGPL) version 3, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "FairTutPropGeoPar.h" #include "FairParamList.h" - #include "TObjArray.h" #include -ClassImp(FairTutPropGeoPar) +ClassImp(FairTutPropGeoPar); -FairTutPropGeoPar ::FairTutPropGeoPar(const char* name, - const char* title, - const char* context) - : FairParGenericSet(name,title,context), - fGeoSensNodes(new TObjArray()), - fGeoPassNodes(new TObjArray()) -{ -} +FairTutPropGeoPar ::FairTutPropGeoPar(const char* name, const char* title, const char* context) + : FairParGenericSet(name, title, context) + , fGeoSensNodes(new TObjArray()) + , fGeoPassNodes(new TObjArray()) +{} -FairTutPropGeoPar::~FairTutPropGeoPar(void) -{ -} +FairTutPropGeoPar::~FairTutPropGeoPar(void) {} void FairTutPropGeoPar::clear(void) { - delete fGeoSensNodes; - delete fGeoPassNodes; + delete fGeoSensNodes; + delete fGeoPassNodes; } void FairTutPropGeoPar::putParams(FairParamList* l) { - if (!l) { return; } - l->addObject("FairGeoNodes Sensitive List", fGeoSensNodes); - l->addObject("FairGeoNodes Passive List", fGeoPassNodes); + if (!l) { + return; + } + l->addObject("FairGeoNodes Sensitive List", fGeoSensNodes); + l->addObject("FairGeoNodes Passive List", fGeoPassNodes); } Bool_t FairTutPropGeoPar::getParams(FairParamList* l) { - if (!l) { return kFALSE; } - if (!l->fillObject("FairGeoNodes Sensitive List", fGeoSensNodes)) { return kFALSE; } - if (!l->fillObject("FairGeoNodes Passive List", fGeoPassNodes)) { return kFALSE; } - return kTRUE; + if (!l) { + return kFALSE; + } + if (!l->fillObject("FairGeoNodes Sensitive List", fGeoSensNodes)) { + return kFALSE; + } + if (!l->fillObject("FairGeoNodes Passive List", fGeoPassNodes)) { + return kFALSE; + } + return kTRUE; } diff --git a/examples/advanced/propagator/src/FairTutPropGeoPar.h b/examples/advanced/propagator/src/FairTutPropGeoPar.h index 9e2a84e08e..625324c570 100644 --- a/examples/advanced/propagator/src/FairTutPropGeoPar.h +++ b/examples/advanced/propagator/src/FairTutPropGeoPar.h @@ -1,43 +1,42 @@ /******************************************************************************** * Copyright (C) 2019 GSI Helmholtzzentrum fuer Schwerionenforschung GmbH * * * - * This software is distributed under the terms of the * - * GNU Lesser General Public Licence (LGPL) version 3, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRTUTPROPGEOPAR_H #define FAIRTUTPROPGEOPAR_H -#include "FairParGenericSet.h" // for FairParGenericSet -#include "Rtypes.h" // for FairTutPropGeoPar::Class, ClassDef, PixelGe... -class FairParamList; // lines 14-14 -class TObjArray; // lines 13-13 +#include "FairParGenericSet.h" // for FairParGenericSet +#include "Rtypes.h" // for FairTutPropGeoPar::Class, ClassDef, PixelGe... +class FairParamList; // lines 14-14 +class TObjArray; // lines 13-13 -class FairTutPropGeoPar : public FairParGenericSet +class FairTutPropGeoPar : public FairParGenericSet { public: - /** List of FairGeoNodes for sensitive volumes */ - TObjArray* fGeoSensNodes; + TObjArray* fGeoSensNodes; /** List of FairGeoNodes for sensitive volumes */ - TObjArray* fGeoPassNodes; + TObjArray* fGeoPassNodes; - FairTutPropGeoPar(const char* name="FairTutPropGeoPar", - const char* title="Pixel Geometry Parameters", - const char* context="TestDefaultContext"); + FairTutPropGeoPar(const char* name = "FairTutPropGeoPar", + const char* title = "Pixel Geometry Parameters", + const char* context = "TestDefaultContext"); ~FairTutPropGeoPar(void); void clear(void); void putParams(FairParamList*); Bool_t getParams(FairParamList*); - TObjArray* GetGeoSensitiveNodes() {return fGeoSensNodes;} - TObjArray* GetGeoPassiveNodes() {return fGeoPassNodes;} + TObjArray* GetGeoSensitiveNodes() { return fGeoSensNodes; } + TObjArray* GetGeoPassiveNodes() { return fGeoPassNodes; } private: FairTutPropGeoPar(const FairTutPropGeoPar&); FairTutPropGeoPar& operator=(const FairTutPropGeoPar&); - ClassDef(FairTutPropGeoPar,1) + ClassDef(FairTutPropGeoPar, 1) }; -#endif //FAIRTUTPROPGEOPAR_H +#endif // FAIRTUTPROPGEOPAR_H diff --git a/examples/advanced/propagator/src/FairTutPropPoint.cxx b/examples/advanced/propagator/src/FairTutPropPoint.cxx index d2b1d78df9..0a75929244 100644 --- a/examples/advanced/propagator/src/FairTutPropPoint.cxx +++ b/examples/advanced/propagator/src/FairTutPropPoint.cxx @@ -8,29 +8,28 @@ #include "FairTutPropPoint.h" #include - #include - // ----- Default constructor ------------------------------------------- FairTutPropPoint::FairTutPropPoint() - : FairMCPoint() -{ -} + : FairMCPoint() +{} // ------------------------------------------------------------------------- // ----- Standard constructor ------------------------------------------ -FairTutPropPoint::FairTutPropPoint(Int_t trackID, Int_t detID, - TVector3 pos, TVector3 mom, - Double_t tof, Double_t length, +FairTutPropPoint::FairTutPropPoint(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t tof, + Double_t length, Double_t eLoss) : FairMCPoint(trackID, detID, pos, mom, tof, length, eLoss) -{ -} +{} // ------------------------------------------------------------------------- // ----- Destructor ---------------------------------------------------- -FairTutPropPoint::~FairTutPropPoint() { } +FairTutPropPoint::~FairTutPropPoint() {} // ------------------------------------------------------------------------- // ----- Public method Print ------------------------------------------- @@ -39,15 +38,12 @@ void FairTutPropPoint::Print(const Option_t* /*opt*/) const using std::cout; using std::endl; - cout << "-I- FairTutPropPoint: FairTutProp 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- FairTutPropPoint: FairTutProp 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; } // ------------------------------------------------------------------------- -ClassImp(FairTutPropPoint) +ClassImp(FairTutPropPoint); diff --git a/examples/advanced/propagator/src/FairTutPropPoint.h b/examples/advanced/propagator/src/FairTutPropPoint.h index 4990355e25..0e2e5ee21e 100644 --- a/examples/advanced/propagator/src/FairTutPropPoint.h +++ b/examples/advanced/propagator/src/FairTutPropPoint.h @@ -16,7 +16,6 @@ class FairTutPropPoint : public FairMCPoint { public: - /** Default constructor **/ FairTutPropPoint(); @@ -29,8 +28,13 @@ class FairTutPropPoint : public FairMCPoint *@param length Track length since creation [cm] *@param eLoss Energy deposit [GeV] **/ - FairTutPropPoint(Int_t trackID, Int_t detID, TVector3 pos, TVector3 mom, - Double_t tof, Double_t length, Double_t eLoss); + FairTutPropPoint(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t tof, + Double_t length, + Double_t eLoss); /** Destructor **/ virtual ~FairTutPropPoint(); @@ -43,7 +47,7 @@ class FairTutPropPoint : public FairMCPoint FairTutPropPoint(const FairTutPropPoint& point); FairTutPropPoint operator=(const FairTutPropPoint& point); - ClassDef(FairTutPropPoint,1) + ClassDef(FairTutPropPoint, 1) }; -#endif //FAIRTUTPROPPOINT_H +#endif // FAIRTUTPROPPOINT_H diff --git a/examples/advanced/propagator/src/FairTutPropTr.cxx b/examples/advanced/propagator/src/FairTutPropTr.cxx index 97b94cb379..7b805aa7d7 100644 --- a/examples/advanced/propagator/src/FairTutPropTr.cxx +++ b/examples/advanced/propagator/src/FairTutPropTr.cxx @@ -14,12 +14,10 @@ #include "FairTutPropTr.h" -#include "FairTutPropPoint.h" - #include "FairLogger.h" #include "FairRootManager.h" #include "FairTrackParP.h" - +#include "FairTutPropPoint.h" #include "TClonesArray.h" #include "TDatabasePDG.h" @@ -33,67 +31,68 @@ FairTutPropTr::FairTutPropTr() , fTrackParProp(0) , fTrackParWrong(0) , fPro(0) -{ } +{} // ------------------------------------------------------------------------- // ----- Destructor ---------------------------------------------------- FairTutPropTr::~FairTutPropTr() { - Reset(); - if ( fTrackParIni ) { - fTrackParIni->Delete(); - delete fTrackParIni; - } - if ( fTrackParProp ) { - fTrackParProp->Delete(); - delete fTrackParProp; - } - if ( fTrackParWrong ) { - fTrackParWrong->Delete(); - delete fTrackParWrong; - } - if ( fTrackParFinal ) { - fTrackParFinal->Delete(); - delete fTrackParFinal; - } + Reset(); + if (fTrackParIni) { + fTrackParIni->Delete(); + delete fTrackParIni; + } + if (fTrackParProp) { + fTrackParProp->Delete(); + delete fTrackParProp; + } + if (fTrackParWrong) { + fTrackParWrong->Delete(); + delete fTrackParWrong; + } + if (fTrackParFinal) { + fTrackParFinal->Delete(); + delete fTrackParFinal; + } } // ------------------------------------------------------------------------- // ----- Public method Init -------------------------------------------- -InitStatus FairTutPropTr::Init() { +InitStatus FairTutPropTr::Init() +{ - // Get RootManager + // Get RootManager FairRootManager* ioman = FairRootManager::Instance(); - if ( ! ioman ) { + if (!ioman) { LOG(error) << "FairTutPropTr::Init: RootManager not instantised!"; return kFATAL; } fTrackParIni = new TClonesArray("FairTrackParP"); - ioman->Register("PropTrackIni","Prop", fTrackParIni, kTRUE); + ioman->Register("PropTrackIni", "Prop", fTrackParIni, kTRUE); fTrackParFinal = new TClonesArray("FairTrackParP"); - ioman->Register("PropTrackFinal","Prop", fTrackParFinal, kTRUE); + ioman->Register("PropTrackFinal", "Prop", fTrackParFinal, kTRUE); fTrackParProp = new TClonesArray("FairTrackParP"); - ioman->Register("PropTrackPar","Prop", fTrackParProp, kTRUE); + ioman->Register("PropTrackPar", "Prop", fTrackParProp, kTRUE); fTrackParWrong = new TClonesArray("FairTrackParP"); - ioman->Register("PropTrackParWrong","Prop", fTrackParWrong, kTRUE); + ioman->Register("PropTrackParWrong", "Prop", fTrackParWrong, kTRUE); // Get input array fPointArray = static_cast(ioman->GetObject("FairTutPropPoint")); return kSUCCESS; - } // ------------------------------------------------------------------------- // ----- Private method InitPropagator --------------------------------- -void FairTutPropTr::InitPropagator() { - TVector3 planePoint(0.,0.,20.); - TVector3 planeVectJ(1.,0.,0.); - TVector3 planeVectK(0.,1.,0.); +void FairTutPropTr::InitPropagator() +{ + TVector3 planePoint(0., 0., 20.); + TVector3 planeVectJ(1., 0., 0.); + TVector3 planeVectK(0., 1., 0.); fPro->SetDestinationPlane(planePoint, planeVectJ, planeVectK); @@ -103,66 +102,85 @@ void FairTutPropTr::InitPropagator() { // ------------------------------------------------------------------------- // ----- Public method Exec -------------------------------------------- -void FairTutPropTr::Exec(Option_t*) { +void FairTutPropTr::Exec(Option_t*) +{ Reset(); - if ( !fPropagatorSet ) { + if (!fPropagatorSet) { InitPropagator(); } LOG(debug) << "FairTutPropTr::Exec"; - Int_t NoOfEntries=fPointArray->GetEntriesFast(); + Int_t NoOfEntries = fPointArray->GetEntriesFast(); LOG(debug) << "fPointArray has " << NoOfEntries << " entries"; - for (Int_t i=0; i(fPointArray->At(i)); - if ( point1->GetZ() > 6. ) continue; - LOG(debug) << "first loop for " << i << "from "<< NoOfEntries << " entries "; - Int_t trId=point1->GetTrackID(); + if (point1->GetZ() > 6.) + continue; + LOG(debug) << "first loop for " << i << "from " << NoOfEntries << " entries "; + Int_t trId = point1->GetTrackID(); FairTutPropPoint* point2 = 0; - for (Int_t k=0; k(fPointArray->At(k)); - if ( point2->GetZ() < 15. ) continue; + if (point2->GetZ() < 15.) + continue; LOG(debug) << "second loop for " << k; - if(point2->GetTrackID()==trId) break; + if (point2->GetTrackID() == trId) + break; } - if(point2==0) break; + if (point2 == 0) + break; - TVector3 StartPos (point1->GetX(),point1->GetY(),point1->GetZ()); - TVector3 StartPosErr(0,0,0); - TVector3 StartMom (point1->GetPx(),point1->GetPy(),point1->GetPz()); - TVector3 StartMomErr(0,0,0); + TVector3 StartPos(point1->GetX(), point1->GetY(), point1->GetZ()); + TVector3 StartPosErr(0, 0, 0); + TVector3 StartMom(point1->GetPx(), point1->GetPy(), point1->GetPz()); + TVector3 StartMomErr(0, 0, 0); - TVector3 EndPos (point2->GetX(),point2->GetY(),point2->GetZ()); - TVector3 EndPosErr(0,0,0); - TVector3 EndMom (point2->GetPx(),point2->GetPy(),point2->GetPz()); - TVector3 EndMomErr(0,0,0); + TVector3 EndPos(point2->GetX(), point2->GetY(), point2->GetZ()); + TVector3 EndPosErr(0, 0, 0); + TVector3 EndMom(point2->GetPx(), point2->GetPy(), point2->GetPz()); + TVector3 EndMomErr(0, 0, 0); - Int_t PDGCode= -13; + Int_t PDGCode = -13; - TDatabasePDG *fdbPDG= TDatabasePDG::Instance(); - TParticlePDG *fParticle= fdbPDG->GetParticle(PDGCode); - Double_t fCharge= fParticle->Charge(); + TDatabasePDG* fdbPDG = TDatabasePDG::Instance(); + TParticlePDG* fParticle = fdbPDG->GetParticle(PDGCode); + Double_t fCharge = fParticle->Charge(); TClonesArray& clref1 = *fTrackParIni; Int_t size1 = clref1.GetEntriesFast(); - FairTrackParP *fStart= new (clref1[size1]) FairTrackParP(StartPos, StartMom, StartPosErr, StartMomErr, fCharge, TVector3(0.,0.,5.), TVector3(1.,0.,0.), TVector3(0.,1.,0.)); + FairTrackParP* fStart = new (clref1[size1]) FairTrackParP(StartPos, + StartMom, + StartPosErr, + StartMomErr, + fCharge, + TVector3(0., 0., 5.), + TVector3(1., 0., 0.), + TVector3(0., 1., 0.)); // fStart->Print(); TClonesArray& clref = *fTrackParProp; Int_t size = clref.GetEntriesFast(); - FairTrackParP *fRes= new(clref[size]) FairTrackParP(); + FairTrackParP* fRes = new (clref[size]) FairTrackParP(); // fRes->Print(); TClonesArray& clrew = *fTrackParWrong; Int_t sizeW = clrew.GetEntriesFast(); - FairTrackParP *fWro= new(clrew[sizeW]) FairTrackParP(); + FairTrackParP* fWro = new (clrew[sizeW]) FairTrackParP(); // fRes->Print(); TClonesArray& clref2 = *fTrackParFinal; Int_t size2 = clref2.GetEntriesFast(); - FairTrackParP *fFinal= new(clref2[size2]) FairTrackParP(EndPos, EndMom, EndPosErr, EndMomErr, fCharge, TVector3(0.,0.,20.), TVector3(1.,0.,0.), TVector3(0.,1.,0.)); + FairTrackParP* fFinal = new (clref2[size2]) FairTrackParP(EndPos, + EndMom, + EndPosErr, + EndMomErr, + fCharge, + TVector3(0., 0., 20.), + TVector3(1., 0., 0.), + TVector3(0., 1., 0.)); fPro->Propagate(fStart, fRes, PDGCode); @@ -174,33 +192,48 @@ void FairTutPropTr::Exec(Option_t*) { << " / " << fFinal->GetPx() << ", " << fFinal->GetPy() << ", " << fFinal->GetPz(); fPro->SetPCAPropagation(1,-1,fFinal); LOG(info) << "FindPCA"; - PCAOutputStruct pcaToPoint = fPro->FindPCA(1, PDGCode, TVector3(2.5,0.5,15.), TVector3(0.,0.,0.), TVector3(0.,0.,0.), 15.); - LOG(info) << "findpca = " << pcaToPoint.PCAStatusFlag << " with distance " << pcaToPoint.Distance - << ", closest point at (" << pcaToPoint.OnTrackPCA.X() << "," << pcaToPoint.OnTrackPCA.Y() << "," << pcaToPoint.OnTrackPCA.Z() << ")"; - - PCAOutputStruct pcaToWire = fPro->FindPCA(2, PDGCode, TVector3(0.,0.,0.), TVector3(-10.,-10.,15.), TVector3(10.,10.,15.), 15.); - LOG(info) << "findpca = " << pcaToWire.PCAStatusFlag << " with distance " << pcaToWire.Distance - << ", closest point at (" << pcaToWire.OnTrackPCA.X() << "," << pcaToWire.OnTrackPCA.Y() << "," << pcaToWire.OnTrackPCA.Z() << ")" - << ", on the wire (" << pcaToWire.OnWirePCA.X() << "," << pcaToWire.OnWirePCA.Y() << "," << pcaToWire.OnWirePCA.Z() << ")"; + PCAOutputStruct pcaToPoint = fPro->FindPCA(1, PDGCode, TVector3(2.5,0.5,15.), TVector3(0.,0.,0.), + TVector3(0.,0.,0.), 15.); LOG(info) << "findpca = " << pcaToPoint.PCAStatusFlag << " with distance " << + pcaToPoint.Distance + << ", closest point at (" << pcaToPoint.OnTrackPCA.X() << "," << pcaToPoint.OnTrackPCA.Y() << "," << + pcaToPoint.OnTrackPCA.Z() << ")"; + + PCAOutputStruct pcaToWire = fPro->FindPCA(2, PDGCode, TVector3(0.,0.,0.), TVector3(-10.,-10.,15.), + TVector3(10.,10.,15.), 15.); LOG(info) << "findpca = " << pcaToWire.PCAStatusFlag << " with distance " << + pcaToWire.Distance + << ", closest point at (" << pcaToWire.OnTrackPCA.X() << "," << pcaToWire.OnTrackPCA.Y() << "," << + pcaToWire.OnTrackPCA.Z() << ")" + << ", on the wire (" << pcaToWire.OnWirePCA.X() << "," << pcaToWire.OnWirePCA.Y() << "," << + pcaToWire.OnWirePCA.Z() << ")"; */ } } // ----- Private method Reset ------------------------------------------ -void FairTutPropTr::Reset() { - if ( fTrackParIni ) fTrackParIni ->Clear(); - if ( fTrackParProp ) fTrackParProp ->Clear(); - if ( fTrackParWrong ) fTrackParWrong->Clear(); - if ( fTrackParFinal ) fTrackParFinal->Clear(); +void FairTutPropTr::Reset() +{ + if (fTrackParIni) + fTrackParIni->Clear(); + if (fTrackParProp) + fTrackParProp->Clear(); + if (fTrackParWrong) + fTrackParWrong->Clear(); + if (fTrackParFinal) + fTrackParFinal->Clear(); } // ------------------------------------------------------------------------- // ----- Public method Finish ------------------------------------------ -void FairTutPropTr::Finish() { - if ( fTrackParIni ) fTrackParIni ->Delete(); - if ( fTrackParProp ) fTrackParProp ->Delete(); - if ( fTrackParWrong ) fTrackParWrong->Delete(); - if ( fTrackParFinal ) fTrackParFinal->Delete(); +void FairTutPropTr::Finish() +{ + if (fTrackParIni) + fTrackParIni->Delete(); + if (fTrackParProp) + fTrackParProp->Delete(); + if (fTrackParWrong) + fTrackParWrong->Delete(); + if (fTrackParFinal) + fTrackParFinal->Delete(); } -ClassImp(FairTutPropTr) +ClassImp(FairTutPropTr); diff --git a/examples/advanced/propagator/src/FairTutPropTr.h b/examples/advanced/propagator/src/FairTutPropTr.h index 4373aa4259..4062eb3093 100644 --- a/examples/advanced/propagator/src/FairTutPropTr.h +++ b/examples/advanced/propagator/src/FairTutPropTr.h @@ -15,51 +15,50 @@ #ifndef FAIRTUTGEANETR_H #define FAIRTUTGEANETR_H 1 - -#include "FairTask.h" #include "FairPropagator.h" +#include "FairTask.h" class TClonesArray; class FairTutPropPoint; class FairTutPropTr : public FairTask { - public: - /** Default constructor **/ - FairTutPropTr(); + public: + /** Default constructor **/ + FairTutPropTr(); - /** Destructor **/ - ~FairTutPropTr(); + /** Destructor **/ + ~FairTutPropTr(); - /** Virtual method Init **/ - virtual InitStatus Init(); + /** Virtual method Init **/ + virtual InitStatus Init(); - /** Virtual method Exec **/ - virtual void Exec(Option_t* opt); + /** Virtual method Exec **/ + virtual void Exec(Option_t* opt); - void SetPropagator(FairPropagator* prop) { fPro = prop; } + void SetPropagator(FairPropagator* prop) { fPro = prop; } - private: - void Reset(); + private: + void Reset(); - /** Finish at the end of run **/ - virtual void Finish(); + /** Finish at the end of run **/ + virtual void Finish(); - void InitPropagator(); - bool fPropagatorSet; + void InitPropagator(); + bool fPropagatorSet; - /** Input array of Points **/ - TClonesArray* fPointArray; + /** Input array of Points **/ + TClonesArray* fPointArray; - /** Output array of Hits **/ - TClonesArray* fTrackParIni; // initial MC track parameters - TClonesArray* fTrackParFinal; // final MC track parameters - TClonesArray* fTrackParProp; // calculated track parameters - TClonesArray* fTrackParWrong; // demonstrate effect of wrong charge + /** Output array of Hits **/ + TClonesArray* fTrackParIni; // initial MC track parameters + TClonesArray* fTrackParFinal; // final MC track parameters + TClonesArray* fTrackParProp; // calculated track parameters + TClonesArray* fTrackParWrong; // demonstrate effect of wrong charge - FairPropagator *fPro; + FairPropagator* fPro; - ClassDef(FairTutPropTr,1); + ClassDef(FairTutPropTr, 1); }; -#endif //FAIRTUTGEANETR_H +#endif // FAIRTUTGEANETR_H diff --git a/examples/common/gconfig/DecayConfig.C b/examples/common/gconfig/DecayConfig.C index 8c21290e78..191e289e0c 100644 --- a/examples/common/gconfig/DecayConfig.C +++ b/examples/common/gconfig/DecayConfig.C @@ -5,92 +5,94 @@ * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ -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: - // TVirtualMC::GetMC()->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. - TVirtualMC::GetMC()->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: + // TVirtualMC::GetMC()->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. + TVirtualMC::GetMC()->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(TVirtualMC::GetMC()->GetName()) == "TGeant3") TVirtualMC::GetMC()->SetUserDecay(ipdg);// Force the decay to be done w/external decayer + if (TString(TVirtualMC::GetMC()->GetName()) == "TGeant3") + TVirtualMC::GetMC()->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(TVirtualMC::GetMC()->GetName()) == "TGeant3") TVirtualMC::GetMC()->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(TVirtualMC::GetMC()->GetName()) == "TGeant3") + TVirtualMC::GetMC()->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/examples/common/gconfig/DecayConfigPythia8.C b/examples/common/gconfig/DecayConfigPythia8.C index 18d8020809..028dcd5f88 100644 --- a/examples/common/gconfig/DecayConfigPythia8.C +++ b/examples/common/gconfig/DecayConfigPythia8.C @@ -1,23 +1,21 @@ -void DecayConfigPythia8() { - // Create a new external decayer instance - TPythia8Decayer* decayer = new TPythia8Decayer(); +void DecayConfigPythia8() +{ + // Create a new external decayer instance + TPythia8Decayer* decayer = new TPythia8Decayer(); - // Create a new TPythia8 instance - TPythia8* pythia8 = TPythia8::Instance(); + // Create a new TPythia8 instance + TPythia8* pythia8 = TPythia8::Instance(); - TVirtualMC::GetMC()->SetExternalDecayer(decayer); + TVirtualMC::GetMC()->SetExternalDecayer(decayer); - const Int_t npartnf = 9; - 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]; - TVirtualMC::GetMC()->SetUserDecay(ipdg);// Force the decay to be done w/external decayer - } - - decayer->Init(); + const Int_t npartnf = 9; + 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]; + TVirtualMC::GetMC()->SetUserDecay(ipdg); // Force the decay to be done w/external decayer + } + decayer->Init(); } -void DecayConfig() { - DecayConfigPythia8(); -} +void DecayConfig() { DecayConfigPythia8(); } diff --git a/examples/common/gconfig/FairVMCConfig.cxx b/examples/common/gconfig/FairVMCConfig.cxx index df833646f9..8d5accea83 100644 --- a/examples/common/gconfig/FairVMCConfig.cxx +++ b/examples/common/gconfig/FairVMCConfig.cxx @@ -19,19 +19,18 @@ FairVMCConfig::FairVMCConfig() : FairYamlVMCConfig() -{ -} +{} -FairVMCConfig::~FairVMCConfig() -{ -} +FairVMCConfig::~FairVMCConfig() {} void FairVMCConfig::SetupStack() { FairStack *stack = new FairStack(1000); - if ( fYamlConfig["FairStack_StoreSecondaries"] ) stack->StoreSecondaries(fYamlConfig["FairStack_StoreSecondaries"].as()); - if ( fYamlConfig["FairStack_MinPoints"] ) stack->SetMinPoints (fYamlConfig["FairStack_MinPoints"].as()); + if (fYamlConfig["FairStack_StoreSecondaries"]) + stack->StoreSecondaries(fYamlConfig["FairStack_StoreSecondaries"].as()); + if (fYamlConfig["FairStack_MinPoints"]) + stack->SetMinPoints(fYamlConfig["FairStack_MinPoints"].as()); TVirtualMC::GetMC()->SetStack(stack); } -ClassImp(FairVMCConfig) +ClassImp(FairVMCConfig); diff --git a/examples/common/gconfig/FairVMCConfig.h b/examples/common/gconfig/FairVMCConfig.h index d3c2a66763..4712b3f945 100644 --- a/examples/common/gconfig/FairVMCConfig.h +++ b/examples/common/gconfig/FairVMCConfig.h @@ -21,7 +21,7 @@ class FairVMCConfig : public FairYamlVMCConfig FairVMCConfig(); virtual ~FairVMCConfig(); - private: + private: virtual void SetupStack(); }; diff --git a/examples/common/gconfig/Geane.C b/examples/common/gconfig/Geane.C index 02076ff878..f5535b6f22 100644 --- a/examples/common/gconfig/Geane.C +++ b/examples/common/gconfig/Geane.C @@ -10,74 +10,70 @@ void Config() { - TGeant3TGeo* 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 ) ; + TGeant3TGeo* 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/examples/common/gconfig/SetCuts.C b/examples/common/gconfig/SetCuts.C index d394a4774e..8f678b1a2f 100644 --- a/examples/common/gconfig/SetCuts.C +++ b/examples/common/gconfig/SetCuts.C @@ -13,47 +13,47 @@ 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. - TVirtualMC *MC =TVirtualMC::GetMC(); + // ------>>>> 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. + TVirtualMC *MC = TVirtualMC::GetMC(); - MC->SetProcess("PAIR",1); /** pair production*/ - MC->SetProcess("COMP",1); /**Compton scattering*/ - MC->SetProcess("PHOT",1); /** photo electric effect */ - MC->SetProcess("PFIS",0); /**photofission*/ - MC->SetProcess("DRAY",1); /**delta-ray*/ - MC->SetProcess("ANNI",1); /**annihilation*/ - MC->SetProcess("BREM",1); /**bremsstrahlung*/ - MC->SetProcess("HADR",1); /**hadronic process*/ - MC->SetProcess("MUNU",1); /**muon nuclear interaction*/ - MC->SetProcess("DCAY",1); /**decay*/ - MC->SetProcess("LOSS",1); /**energy loss*/ - MC->SetProcess("MULS",1); /**multiple scattering*/ + MC->SetProcess("PAIR", 1); /** pair production*/ + MC->SetProcess("COMP", 1); /**Compton scattering*/ + MC->SetProcess("PHOT", 1); /** photo electric effect */ + MC->SetProcess("PFIS", 0); /**photofission*/ + MC->SetProcess("DRAY", 1); /**delta-ray*/ + MC->SetProcess("ANNI", 1); /**annihilation*/ + MC->SetProcess("BREM", 1); /**bremsstrahlung*/ + MC->SetProcess("HADR", 1); /**hadronic process*/ + MC->SetProcess("MUNU", 1); /**muon nuclear interaction*/ + MC->SetProcess("DCAY", 1); /**decay*/ + MC->SetProcess("LOSS", 1); /**energy loss*/ + MC->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.." < 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)*/ - MC->SetCut("CUTELE",cut1); /** electrons (GeV)*/ - MC->SetCut("CUTNEU",cut1); /** neutral hadrons (GeV)*/ - MC->SetCut("CUTHAD",cut1); /** charged hadrons (GeV)*/ - MC->SetCut("CUTMUO",cut1); /** muons (GeV)*/ - MC->SetCut("BCUTE",cut1); /** electron bremsstrahlung (GeV)*/ - MC->SetCut("BCUTM",cut1); /** muon and hadron bremsstrahlung(GeV)*/ - MC->SetCut("DCUTE",cut1); /** delta-rays by electrons (GeV)*/ - MC->SetCut("DCUTM",cut1); /** delta-rays by muons (GeV)*/ - MC->SetCut("PPCUTM",cut1); /** direct pair production by muons (GeV)*/ - MC->SetCut("TOFMAX",tofmax); /**time of flight cut in seconds*/ + MC->SetCut("CUTGAM", cut1); /** gammas (GeV)*/ + MC->SetCut("CUTELE", cut1); /** electrons (GeV)*/ + MC->SetCut("CUTNEU", cut1); /** neutral hadrons (GeV)*/ + MC->SetCut("CUTHAD", cut1); /** charged hadrons (GeV)*/ + MC->SetCut("CUTMUO", cut1); /** muons (GeV)*/ + MC->SetCut("BCUTE", cut1); /** electron bremsstrahlung (GeV)*/ + MC->SetCut("BCUTM", cut1); /** muon and hadron bremsstrahlung(GeV)*/ + MC->SetCut("DCUTE", cut1); /** delta-rays by electrons (GeV)*/ + MC->SetCut("DCUTM", cut1); /** delta-rays by muons (GeV)*/ + MC->SetCut("PPCUTM", cut1); /** direct pair production by muons (GeV)*/ + MC->SetCut("TOFMAX", tofmax); /**time of flight cut in seconds*/ } diff --git a/examples/common/gconfig/UserDecay.C b/examples/common/gconfig/UserDecay.C index 602d4ae8e7..de77f1a828 100644 --- a/examples/common/gconfig/UserDecay.C +++ b/examples/common/gconfig/UserDecay.C @@ -5,34 +5,37 @@ * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ -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"); + 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 ; + 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.; + /* bratio[1] = 50.; mode[1][0] =2212 ; mode[1][1] =AlphaPDG ; */ - TVirtual::GetMC()->SetDecayMode(He5PDG,bratio,mode); + TVirtual::GetMC()->SetDecayMode(He5PDG, bratio, mode); } diff --git a/examples/common/gconfig/basiclibs.C b/examples/common/gconfig/basiclibs.C index 4a3bbdd209..85c3e0d4fb 100644 --- a/examples/common/gconfig/basiclibs.C +++ b/examples/common/gconfig/basiclibs.C @@ -11,7 +11,7 @@ void basiclibs() { - /* gSystem->Load("libGeom"); + /* gSystem->Load("libGeom"); gSystem->Load("libGeomPainter"); @@ -23,21 +23,21 @@ void basiclibs() gSystem->Load("libMinuit"); gSystem->Load("libTree"); */ - 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("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("libProof"); - gSystem->Load("libProofPlayer"); - gSystem->Load("libGX11TTF"); - gSystem->Load("libGX11"); + gSystem->Load("libProof"); + gSystem->Load("libProofPlayer"); + gSystem->Load("libGX11TTF"); + gSystem->Load("libGX11"); } diff --git a/examples/common/gconfig/flConfig.C b/examples/common/gconfig/flConfig.C index a32820648d..74b10f4d40 100644 --- a/examples/common/gconfig/flConfig.C +++ b/examples/common/gconfig/flConfig.C @@ -10,19 +10,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; FairStack *st = new FairStack(); st->SetMinPoints(0); - TVirtual::GetMC()->SetStack( st ) ; - TVirtual::GetMC()->SetProcess("CKOV",1); + TVirtual::GetMC()->SetStack(st); + TVirtual::GetMC()->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/examples/common/gconfig/fllibs.C b/examples/common/gconfig/fllibs.C index 7bb0f907c6..89f2b45894 100644 --- a/examples/common/gconfig/fllibs.C +++ b/examples/common/gconfig/fllibs.C @@ -23,11 +23,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/examples/common/gconfig/g3Config.C b/examples/common/gconfig/g3Config.C index 0cd9817196..088bb17eee 100644 --- a/examples/common/gconfig/g3Config.C +++ b/examples/common/gconfig/g3Config.C @@ -11,37 +11,34 @@ 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 - FairStack *st = new FairStack(); - 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 + FairStack* st = new FairStack(); + 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(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->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(1); // cerenkov photons - + geant3->SetCKOV(1); // cerenkov photons } diff --git a/examples/common/gconfig/g3Config_new.C b/examples/common/gconfig/g3Config_new.C index a659cbda24..8a8d201ea3 100644 --- a/examples/common/gconfig/g3Config_new.C +++ b/examples/common/gconfig/g3Config_new.C @@ -11,63 +11,56 @@ 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 - FairStack *st = new FairStack(); - st->SetMinPoints(0); - 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 + FairStack* st = new FairStack(); + st->SetMinPoints(0); + geant3->SetStack(st); - // ******* Geant3 configuration for simulated Runs ******* - geant3->SetTRIG(1); //Number of events to be processed + // ******* Geant3 configuration for simulated Runs ******* + geant3->SetTRIG(1); // Number of events to be processed geant3->SetSWIT(4, 100); geant3->SetDEBU(0, 0, 1); geant3->SetDCAY(1); geant3->SetPAIR(1); geant3->SetCOMP(1); geant3->SetPHOT(1); - geant3->SetPFIS(0); // + geant3->SetPFIS(0); // geant3->SetDRAY(1); geant3->SetANNI(1); geant3->SetBREM(1); geant3->SetMUNU(1); geant3->SetCKOV(1); - geant3->SetHADR(3); //Select pure GEANH (HADR 1) or GEANH/NUCRIN (HADR 3) //5==GCALOR + geant3->SetHADR(3); // Select pure GEANH (HADR 1) or GEANH/NUCRIN (HADR 3) //5==GCALOR geant3->SetLOSS(1); geant3->SetMULS(1); geant3->SetRAYL(1); 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->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); - - Float_t cut = 1. e-3; // 1MeV cut by default + Float_t cut = 1. e - 3; // 1MeV cut by default Float_t tofmax = 1.e10; // Float_t cut2 = 1.e-10; // 1 keV? Float_t cut2 = cut; - Float_t cut3 =50.e-6 ; // Threshold for delta electrons + Float_t cut3 = 50.e-6; // Threshold for delta electrons - Float_t cut5[5] ={0,0,0,0,0}; + Float_t cut5[5] = {0, 0, 0, 0, 0}; // set cuts here // GAM ELEC NHAD CHAD MUON EBREM MUHAB EDEL MUDEL MUPA TOFMAX -// geant3->SetCUTS(cut2, cut2, cut2, cut2, cut, cut2, cut2, cut3, cut2, cut2, -// tofmax); - geant3->SetCUTS(cut2, cut2, cut2, cut2, cut, cut2, cut2, cut2, cut2, cut2, - tofmax,cut5); + // geant3->SetCUTS(cut2, cut2, cut2, cut2, cut, cut2, cut2, cut3, cut2, cut2, + // tofmax); + geant3->SetCUTS(cut2, cut2, cut2, cut2, cut, cut2, cut2, cut2, cut2, cut2, tofmax, cut5); } diff --git a/examples/common/gconfig/g3libs.C b/examples/common/gconfig/g3libs.C index 916d9e8949..710450f303 100644 --- a/examples/common/gconfig/g3libs.C +++ b/examples/common/gconfig/g3libs.C @@ -9,11 +9,11 @@ void g3libs() { - // cout << "Loading Geant3 libraries ..." << endl; + // cout << "Loading Geant3 libraries ..." << endl; - gSystem->Load("libPythia6"); - gSystem->Load("libEGPythia6"); - gSystem->Load("libgeant321"); + gSystem->Load("libPythia6"); + gSystem->Load("libEGPythia6"); + gSystem->Load("libgeant321"); - // cout << "Loading Geant3 libraries ... finished" << endl; + // cout << "Loading Geant3 libraries ... finished" << endl; } diff --git a/examples/common/gconfig/g4Config.C b/examples/common/gconfig/g4Config.C index 021a2776e0..aedfbfd71a 100644 --- a/examples/common/gconfig/g4Config.C +++ b/examples/common/gconfig/g4Config.C @@ -8,63 +8,62 @@ // 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. + /// 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. - Bool_t mtMode = FairRunSim::Instance()->IsMT(); - Bool_t specialStacking = false; - FairFastSimRunConfiguration* runConfiguration - = new FairFastSimRunConfiguration("geomRoot", "QGSP_BERT_EMV", "stepLimiter+specialCuts+specialControls", - specialStacking, mtMode); - // TG4RunConfiguration* runConfiguration - // = new TG4RunConfiguration("geomRoot", "QGSP_BERT_EMV", "stepLimiter+specialCuts+specialControls", - // specialStacking, mtMode); + Bool_t mtMode = FairRunSim::Instance()->IsMT(); + Bool_t specialStacking = false; + FairFastSimRunConfiguration* runConfiguration = new FairFastSimRunConfiguration( + "geomRoot", "QGSP_BERT_EMV", "stepLimiter+specialCuts+specialControls", specialStacking, mtMode); + // TG4RunConfiguration* runConfiguration + // = new TG4RunConfiguration("geomRoot", "QGSP_BERT_EMV", "stepLimiter+specialCuts+specialControls", + // specialStacking, mtMode); -/// Create the G4 VMC - TGeant4* geant4 = new TGeant4("TGeant4", "The Geant4 Monte Carlo", runConfiguration); - cout << "Geant4 has been created." << endl; + /// Create the G4 VMC + TGeant4* geant4 = new TGeant4("TGeant4", "The Geant4 Monte Carlo", runConfiguration); + cout << "Geant4 has been created." << endl; -/// create the Specific stack - FairStack *stack = new FairStack(1000); - stack->StoreSecondaries(kTRUE); - stack->SetMinPoints(0); - geant4->SetStack(stack); + /// create the Specific stack + FairStack* stack = new FairStack(1000); + stack->StoreSecondaries(kTRUE); + stack->SetMinPoints(0); + geant4->SetStack(stack); - if(FairRunSim::Instance()->IsExtDecayer()){ - TVirtualMCDecayer* decayer = TVirtualMC::GetMC()->GetDecayer(); -// TVirtualMCDecayer* decayer = TPythia6Decayer::Instance(); - geant4->SetExternalDecayer(decayer); - } + if (FairRunSim::Instance()->IsExtDecayer()) { + TVirtualMCDecayer* decayer = TVirtualMC::GetMC()->GetDecayer(); + // TVirtualMCDecayer* decayer = TPythia6Decayer::Instance(); + 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 + "/common/gconfig/g4config.in"; - cout << " -I g4Config() using g4conf macro: " << configm1 << endl; + TString configm(gSystem->Getenv("VMCWORKDIR")); + TString configm1 = configm + "/common/gconfig/g4config.in"; + cout << " -I g4Config() using g4conf macro: " << configm1 << endl; - //set geant4 specific stuff - geant4->SetMaxNStep(10000); // default is 30000 - geant4->ProcessGeantMacro(configm1.Data()); + // set geant4 specific stuff + geant4->SetMaxNStep(10000); // default is 30000 + geant4->ProcessGeantMacro(configm1.Data()); } diff --git a/examples/common/gconfig/rootlogon.C b/examples/common/gconfig/rootlogon.C index 707f2ec1df..8d401a1ea4 100644 --- a/examples/common/gconfig/rootlogon.C +++ b/examples/common/gconfig/rootlogon.C @@ -7,18 +7,18 @@ ********************************************************************************/ 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/examples/common/mcstack/FairDetectorList.h b/examples/common/mcstack/FairDetectorList.h index de9c88af39..5bcc0ae199 100644 --- a/examples/common/mcstack/FairDetectorList.h +++ b/examples/common/mcstack/FairDetectorList.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ @@ -12,6 +12,14 @@ #define FAIRDETECTORLIST_H 1 // kSTOPHERE is needed for iteration over the enum. All detectors have to be put before. -enum DetectorId {kREF, kFairRutherford, kTutDet, kSTOPHERE, kTutProp, kPixel}; +enum DetectorId +{ + kREF, + kFairRutherford, + kTutDet, + kSTOPHERE, + kTutProp, + kPixel +}; #endif diff --git a/examples/common/mcstack/FairMCTrack.cxx b/examples/common/mcstack/FairMCTrack.cxx index 1a032a0c50..4f0f699cde 100644 --- a/examples/common/mcstack/FairMCTrack.cxx +++ b/examples/common/mcstack/FairMCTrack.cxx @@ -11,137 +11,153 @@ // ------------------------------------------------------------------------- #include "FairMCTrack.h" -#include "FairLogger.h" // for FairLogger, etc +#include "FairLogger.h" // for FairLogger, etc -#include // for TDatabasePDG -#include // for TParticle -#include // for TParticlePDG +#include // for TDatabasePDG +#include // for TParticle +#include // for TParticlePDG FairMCTrack::FairMCTrack() - : TObject(), - fPdgCode(0), - fMotherId(-1), - fPx(0.), - fPy(0.), - fPz(0.), - fStartX(0.), - fStartY(0.), - fStartZ(0.), - fStartT(0.), - fNPoints(0) -{ -} - -FairMCTrack::FairMCTrack(Int_t pdgCode, Int_t motherId, Double_t px, - Double_t py, Double_t pz, Double_t x, Double_t y, - Double_t z, Double_t t, Int_t nPoints = 0) - : TObject(), - fPdgCode(pdgCode), - fMotherId(motherId), - fPx(px), - fPy(py), - fPz(pz), - fStartX(x), - fStartY(y), - fStartZ(z), - fStartT(t), - fNPoints(nPoints) -{ -} + : TObject() + , fPdgCode(0) + , fMotherId(-1) + , fPx(0.) + , fPy(0.) + , fPz(0.) + , fStartX(0.) + , fStartY(0.) + , fStartZ(0.) + , fStartT(0.) + , fNPoints(0) +{} + +FairMCTrack::FairMCTrack(Int_t pdgCode, + Int_t motherId, + Double_t px, + Double_t py, + Double_t pz, + Double_t x, + Double_t y, + Double_t z, + Double_t t, + Int_t nPoints = 0) + : TObject() + , fPdgCode(pdgCode) + , fMotherId(motherId) + , fPx(px) + , fPy(py) + , fPz(pz) + , fStartX(x) + , fStartY(y) + , fStartZ(z) + , fStartT(t) + , fNPoints(nPoints) +{} FairMCTrack::FairMCTrack(const FairMCTrack& track) - : TObject(track), - fPdgCode(track.fPdgCode), - fMotherId(track.fMotherId), - fPx(track.fPx), - fPy(track.fPy), - fPz(track.fPz), - fStartX(track.fStartX), - fStartY(track.fStartY), - fStartZ(track.fStartZ), - fStartT(track.fStartT), - fNPoints(track.fNPoints) -{ -} + : TObject(track) + , fPdgCode(track.fPdgCode) + , fMotherId(track.fMotherId) + , fPx(track.fPx) + , fPy(track.fPy) + , fPz(track.fPz) + , fStartX(track.fStartX) + , fStartY(track.fStartY) + , fStartZ(track.fStartZ) + , fStartT(track.fStartT) + , fNPoints(track.fNPoints) +{} FairMCTrack::FairMCTrack(TParticle* part) - : TObject(), - fPdgCode(part->GetPdgCode()), - fMotherId(part->GetMother(0)), - fPx(part->Px()), - fPy(part->Py()), - fPz(part->Pz()), - fStartX(part->Vx()), - fStartY(part->Vy()), - fStartZ(part->Vz()), - fStartT(part->T()*1e09), - fNPoints(0) -{ -} - -FairMCTrack::~FairMCTrack() { } + : TObject() + , fPdgCode(part->GetPdgCode()) + , fMotherId(part->GetMother(0)) + , fPx(part->Px()) + , fPy(part->Py()) + , fPz(part->Pz()) + , fStartX(part->Vx()) + , fStartY(part->Vy()) + , fStartZ(part->Vz()) + , fStartT(part->T() * 1e09) + , fNPoints(0) +{} + +FairMCTrack::~FairMCTrack() {} void FairMCTrack::Print(Int_t trackId) const { - LOG(debug) << "Track " << trackId << ", mother : " << fMotherId << ", Type " - << fPdgCode << ", momentum (" << fPx << ", " << fPy << ", " - << fPz << ") GeV"; - LOG(debug2) << " Ref " << GetNPoints(kREF) - << ", TutDet " << GetNPoints(kTutDet) - << ", Rutherford " << GetNPoints(kFairRutherford); + LOG(debug) << "Track " << trackId << ", mother : " << fMotherId << ", Type " << fPdgCode << ", momentum (" << fPx + << ", " << fPy << ", " << fPz << ") GeV"; + LOG(debug2) << " Ref " << GetNPoints(kREF) << ", TutDet " << GetNPoints(kTutDet) << ", Rutherford " + << GetNPoints(kFairRutherford); } Double_t FairMCTrack::GetMass() const { - if ( TDatabasePDG::Instance() ) { - TParticlePDG* particle = TDatabasePDG::Instance()->GetParticle(fPdgCode); - if ( particle ) { return particle->Mass(); } - else { return 0.; } - } - return 0.; + if (TDatabasePDG::Instance()) { + TParticlePDG* particle = TDatabasePDG::Instance()->GetParticle(fPdgCode); + if (particle) { + return particle->Mass(); + } else { + return 0.; + } + } + return 0.; } Double_t FairMCTrack::GetRapidity() const { - Double_t e = GetEnergy(); - Double_t y = 0.5 * TMath::Log( (e+fPz) / (e-fPz) ); - return y; + Double_t e = GetEnergy(); + Double_t y = 0.5 * TMath::Log((e + fPz) / (e - fPz)); + return y; } Int_t FairMCTrack::GetNPoints(DetectorId detId) const { - // TODO: Where does this come from - if ( detId == kREF ) { return ( fNPoints & 1); } - else if ( detId == kTutDet ) { return ( (fNPoints & ( 7 << 1) ) >> 1); } - else if ( detId == kFairRutherford ) { return ( (fNPoints & (31 << 4) ) >> 4); } - else { - LOG(error) << "Unknown detector ID " - << detId; - return 0; - } + // TODO: Where does this come from + if (detId == kREF) { + return (fNPoints & 1); + } else if (detId == kTutDet) { + return ((fNPoints & (7 << 1)) >> 1); + } else if (detId == kFairRutherford) { + return ((fNPoints & (31 << 4)) >> 4); + } else { + LOG(error) << "Unknown detector ID " << detId; + return 0; + } } void FairMCTrack::SetNPoints(Int_t iDet, Int_t nPoints) { - if ( iDet == kREF ) { - if ( nPoints < 0 ) { nPoints = 0; } - else if ( nPoints > 1 ) { nPoints = 1; } - fNPoints = ( fNPoints & ( ~ 1 ) ) | nPoints; - } - - else if ( iDet == kTutDet ) { - if ( nPoints < 0 ) { nPoints = 0; } - else if ( nPoints > 7 ) { nPoints = 7; } - fNPoints = ( fNPoints & ( ~ ( 7 << 1 ) ) ) | ( nPoints << 1 ); - } - - else if ( iDet == kFairRutherford ) { - if ( nPoints < 0 ) { nPoints = 0; } - else if ( nPoints > 31 ) { nPoints = 31; } - fNPoints = ( fNPoints & ( ~ ( 31 << 4 ) ) ) | ( nPoints << 4 ); - } - - else LOG(error) << "Unknown detector ID " << iDet; + if (iDet == kREF) { + if (nPoints < 0) { + nPoints = 0; + } else if (nPoints > 1) { + nPoints = 1; + } + fNPoints = (fNPoints & (~1)) | nPoints; + } + + else if (iDet == kTutDet) { + if (nPoints < 0) { + nPoints = 0; + } else if (nPoints > 7) { + nPoints = 7; + } + fNPoints = (fNPoints & (~(7 << 1))) | (nPoints << 1); + } + + else if (iDet == kFairRutherford) { + if (nPoints < 0) { + nPoints = 0; + } else if (nPoints > 31) { + nPoints = 31; + } + fNPoints = (fNPoints & (~(31 << 4))) | (nPoints << 4); + } + + else + LOG(error) << "Unknown detector ID " << iDet; } -ClassImp(FairMCTrack) +ClassImp(FairMCTrack); diff --git a/examples/common/mcstack/FairMCTrack.h b/examples/common/mcstack/FairMCTrack.h index 7e36759320..90fd380394 100644 --- a/examples/common/mcstack/FairMCTrack.h +++ b/examples/common/mcstack/FairMCTrack.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -23,14 +23,13 @@ #ifndef FAIRMCTRACK_H #define FAIRMCTRACK_H 1 -#include // for TObject +#include "FairDetectorList.h" // for DetectorId -#include "FairDetectorList.h" // for DetectorId - -#include // for Double_t, Int_t, Double32_t, etc -#include // for TLorentzVector -#include // for Sqrt -#include // for TVector3 +#include // for Double_t, Int_t, Double32_t, etc +#include // for TLorentzVector +#include // for Sqrt +#include // for TObject +#include // for TVector3 class TParticle; @@ -41,9 +40,16 @@ class FairMCTrack : public TObject FairMCTrack(); /** Standard constructor **/ - FairMCTrack(Int_t pdgCode, Int_t motherID, Double_t px, Double_t py, - Double_t pz, Double_t x, Double_t y, Double_t z, - Double_t t, Int_t nPoints); + FairMCTrack(Int_t pdgCode, + Int_t motherID, + Double_t px, + Double_t py, + Double_t pz, + Double_t x, + Double_t y, + Double_t z, + Double_t t, + Int_t nPoints); /** Copy constructor **/ FairMCTrack(const FairMCTrack& track); @@ -64,26 +70,26 @@ class FairMCTrack : public TObject #pragma clang diagnostic pop #endif /** Accessors **/ - Int_t GetPdgCode() const { return fPdgCode; } - Int_t GetMotherId() const { return fMotherId; } - Double_t GetPx() const { return fPx; } - Double_t GetPy() const { return fPy; } - Double_t GetPz() const { return fPz; } - Double_t GetStartX() const { return fStartX; } - Double_t GetStartY() const { return fStartY; } - Double_t GetStartZ() const { return fStartZ; } - Double_t GetStartT() const { return fStartT; } - Double_t GetMass() const; - Double_t GetEnergy() const; - Double_t GetPt() const { return TMath::Sqrt(fPx*fPx+fPy*fPy); } - Double_t GetP() const { return TMath::Sqrt(fPx*fPx+fPy*fPy+fPz*fPz); } + Int_t GetPdgCode() const { return fPdgCode; } + Int_t GetMotherId() const { return fMotherId; } + Double_t GetPx() const { return fPx; } + Double_t GetPy() const { return fPy; } + Double_t GetPz() const { return fPz; } + Double_t GetStartX() const { return fStartX; } + Double_t GetStartY() const { return fStartY; } + Double_t GetStartZ() const { return fStartZ; } + Double_t GetStartT() const { return fStartT; } + Double_t GetMass() const; + Double_t GetEnergy() const; + Double_t GetPt() const { return TMath::Sqrt(fPx * fPx + fPy * fPy); } + Double_t GetP() const { return TMath::Sqrt(fPx * fPx + fPy * fPy + fPz * fPz); } Double_t GetRapidity() const; void GetMomentum(TVector3& momentum); void Get4Momentum(TLorentzVector& momentum); void GetStartVertex(TVector3& vertex); /** Accessors to the number of MCPoints in the detectors **/ - Int_t GetNPoints(DetectorId detId) const; + Int_t GetNPoints(DetectorId detId) const; /** Modifiers **/ void SetMotherId(Int_t id) { fMotherId = id; } @@ -91,10 +97,10 @@ class FairMCTrack : public TObject private: /** PDG particle code **/ - Int_t fPdgCode; + Int_t fPdgCode; /** Index of mother track. -1 for primary particles. **/ - Int_t fMotherId; + Int_t fMotherId; /** Momentum components at start vertex [GeV] **/ Double32_t fPx, fPy, fPz; @@ -119,30 +125,21 @@ class FairMCTrack : public TObject **/ Int_t fNPoints; - ClassDef(FairMCTrack,2); + ClassDef(FairMCTrack, 2); }; // ========== Inline functions ======================================== inline Double_t FairMCTrack::GetEnergy() const { - Double_t mass = GetMass(); - return TMath::Sqrt(mass*mass + fPx*fPx + fPy*fPy + fPz*fPz ); + Double_t mass = GetMass(); + return TMath::Sqrt(mass * mass + fPx * fPx + fPy * fPy + fPz * fPz); } -inline void FairMCTrack::GetMomentum(TVector3& momentum) -{ - momentum.SetXYZ(fPx,fPy,fPz); -} +inline void FairMCTrack::GetMomentum(TVector3& momentum) { momentum.SetXYZ(fPx, fPy, fPz); } -inline void FairMCTrack::Get4Momentum(TLorentzVector& momentum) -{ - momentum.SetXYZT(fPx,fPy,fPz,GetEnergy()); -} +inline void FairMCTrack::Get4Momentum(TLorentzVector& momentum) { momentum.SetXYZT(fPx, fPy, fPz, GetEnergy()); } -inline void FairMCTrack::GetStartVertex(TVector3& vertex) -{ - vertex.SetXYZ(fStartX,fStartY,fStartZ); -} +inline void FairMCTrack::GetStartVertex(TVector3& vertex) { vertex.SetXYZ(fStartX, fStartY, fStartZ); } #endif diff --git a/examples/common/mcstack/FairStack.cxx b/examples/common/mcstack/FairStack.cxx index 4b1420915b..ddc7edc59d 100644 --- a/examples/common/mcstack/FairStack.cxx +++ b/examples/common/mcstack/FairStack.cxx @@ -11,222 +11,239 @@ // ------------------------------------------------------------------------- #include "FairStack.h" -#include "FairDetector.h" // for FairDetector -#include "FairLink.h" // for FairLink -#include "FairMCPoint.h" // for FairMCPoint -#include "FairMCTrack.h" // for FairMCTrack -#include "FairRootManager.h" // for FairRootManager -#include "FairLogger.h" // for FairLogger, MESSAGE_ORIGIN - -#include // for TClonesArray -#include // for TIterator -#include // for TLorentzVector -#include // for TParticle -#include // for TRefArray -#include // for gMC +#include "FairDetector.h" // for FairDetector +#include "FairLink.h" // for FairLink +#include "FairLogger.h" // for FairLogger, MESSAGE_ORIGIN +#include "FairMCPoint.h" // for FairMCPoint +#include "FairMCTrack.h" // for FairMCTrack +#include "FairRootManager.h" // for FairRootManager + +#include // for TClonesArray +#include // for TIterator +#include // for TLorentzVector +#include // for TParticle +#include // for TRefArray +#include // for gMC using std::pair; FairStack::FairStack(Int_t size) - : FairGenericStack(), - fStack(), - fParticles(new TClonesArray("TParticle", size)), - fTracks(new TClonesArray("FairMCTrack", size)), - fStoreMap(), - fStoreIter(), - fIndexMap(), - fIndexIter(), - fPointsMap(), - fCurrentTrack(-1), - fNPrimaries(0), - fNParticles(0), - fNTracks(0), - fIndex(0), - fStoreSecondaries(kTRUE), - fMinPoints(1), - fEnergyCut(0.), - fStoreMothers(kTRUE) -{ -} + : FairGenericStack() + , fStack() + , fParticles(new TClonesArray("TParticle", size)) + , fTracks(new TClonesArray("FairMCTrack", size)) + , fStoreMap() + , fStoreIter() + , fIndexMap() + , fIndexIter() + , fPointsMap() + , fCurrentTrack(-1) + , fNPrimaries(0) + , fNParticles(0) + , fNTracks(0) + , fIndex(0) + , fStoreSecondaries(kTRUE) + , fMinPoints(1) + , fEnergyCut(0.) + , fStoreMothers(kTRUE) +{} FairStack::~FairStack() { - if (fParticles) { - fParticles->Delete(); - delete fParticles; - } - if (fTracks) { - fTracks->Delete(); - delete fTracks; - } + if (fParticles) { + fParticles->Delete(); + delete fParticles; + } + if (fTracks) { + fTracks->Delete(); + delete fTracks; + } } -void FairStack::PushTrack(Int_t toBeDone, Int_t parentId, Int_t pdgCode, - Double_t px, Double_t py, Double_t pz, - Double_t e, Double_t vx, Double_t vy, Double_t vz, - Double_t time, Double_t polx, Double_t poly, - Double_t polz, TMCProcess proc, Int_t& ntr, - Double_t weight, Int_t is) +void FairStack::PushTrack(Int_t toBeDone, + Int_t parentId, + Int_t pdgCode, + Double_t px, + Double_t py, + Double_t pz, + Double_t e, + Double_t vx, + Double_t vy, + Double_t vz, + Double_t time, + Double_t polx, + Double_t poly, + Double_t polz, + TMCProcess proc, + Int_t& ntr, + Double_t weight, + Int_t is) { - PushTrack( toBeDone, parentId, pdgCode, - px, py, pz, - e, vx, vy, vz, - time, polx, poly, - polz, proc, ntr, - weight, is, -1); + PushTrack( + toBeDone, parentId, pdgCode, px, py, pz, e, vx, vy, vz, time, polx, poly, polz, proc, ntr, weight, is, -1); } -void FairStack::PushTrack(Int_t toBeDone, Int_t parentId, Int_t pdgCode, - Double_t px, Double_t py, Double_t pz, - Double_t e, Double_t vx, Double_t vy, Double_t vz, - Double_t time, Double_t polx, Double_t poly, - Double_t polz, TMCProcess proc, Int_t& ntr, - Double_t weight, Int_t /*is*/, Int_t /*secondparentID*/) +void FairStack::PushTrack(Int_t toBeDone, + Int_t parentId, + Int_t pdgCode, + Double_t px, + Double_t py, + Double_t pz, + Double_t e, + Double_t vx, + Double_t vy, + Double_t vz, + Double_t time, + Double_t polx, + Double_t poly, + Double_t polz, + TMCProcess proc, + Int_t& ntr, + Double_t weight, + Int_t /*is*/, + Int_t /*secondparentID*/) { // LOG(info) << "FairStack::PushTrack(" << toBeDone << ", " << parentId << ", " << pdgCode << ": " // << vx << ", " << vy << ", " << vz << " / " // << px << ", " << py << ", " << pz <<")"; - // --> Get TParticle array - TClonesArray& partArray = *fParticles; - - // --> Create new TParticle and add it to the TParticle array - Int_t trackId = fNParticles; - Int_t nPoints = 0; - Int_t daughter1Id = -1; - Int_t daughter2Id = -1; - TParticle* particle = - new(partArray[fNParticles++]) TParticle(pdgCode, trackId, parentId, - nPoints, daughter1Id, - daughter2Id, px, py, pz, e, - vx, vy, vz, time); - particle->SetPolarisation(polx, poly, polz); - particle->SetWeight(weight); - particle->SetUniqueID(proc); - - // --> Increment counter - if (parentId < 0) { fNPrimaries++; } - - // --> Set argument variable - ntr = trackId; - - // --> Push particle on the stack if toBeDone is set - if (toBeDone == 1) { fStack.push(particle); } + // --> Get TParticle array + TClonesArray& partArray = *fParticles; + + // --> Create new TParticle and add it to the TParticle array + Int_t trackId = fNParticles; + Int_t nPoints = 0; + Int_t daughter1Id = -1; + Int_t daughter2Id = -1; + TParticle* particle = new (partArray[fNParticles++]) + TParticle(pdgCode, trackId, parentId, nPoints, daughter1Id, daughter2Id, px, py, pz, e, vx, vy, vz, time); + particle->SetPolarisation(polx, poly, polz); + particle->SetWeight(weight); + particle->SetUniqueID(proc); + + // --> Increment counter + if (parentId < 0) { + fNPrimaries++; + } + // --> Set argument variable + ntr = trackId; + + // --> Push particle on the stack if toBeDone is set + if (toBeDone == 1) { + fStack.push(particle); + } } TParticle* FairStack::PopNextTrack(Int_t& iTrack) { - // If end of stack: Return empty pointer - if (fStack.empty()) { - iTrack = -1; - return nullptr; - } - - // If not, get next particle from stack - TParticle* thisParticle = fStack.top(); - fStack.pop(); + // If end of stack: Return empty pointer + if (fStack.empty()) { + iTrack = -1; + return nullptr; + } - if ( !thisParticle) { - iTrack = 0; - return nullptr; - } + // If not, get next particle from stack + TParticle* thisParticle = fStack.top(); + fStack.pop(); - fCurrentTrack = thisParticle->GetStatusCode(); - iTrack = fCurrentTrack; + if (!thisParticle) { + iTrack = 0; + return nullptr; + } - return thisParticle; + fCurrentTrack = thisParticle->GetStatusCode(); + iTrack = fCurrentTrack; + return thisParticle; } TParticle* FairStack::PopPrimaryForTracking(Int_t iPrim) { - // Get the iPrimth particle from the fStack TClonesArray. This - // should be a primary (if the index is correct). - - // Test for index - if (iPrim < 0 || iPrim >= fNPrimaries) { - LOG(fatal) << "Primary index out of range!" << iPrim; - } + // Get the iPrimth particle from the fStack TClonesArray. This + // should be a primary (if the index is correct). - // Return the iPrim-th TParticle from the fParticle array. This should be - // a primary. - TParticle* part = static_cast(fParticles->At(iPrim)); - if ( ! (part->GetMother(0) < 0) ) { - LOG(fatal) << "Not a primary track!" << iPrim; - } + // Test for index + if (iPrim < 0 || iPrim >= fNPrimaries) { + LOG(fatal) << "Primary index out of range!" << iPrim; + } - return part; + // Return the iPrim-th TParticle from the fParticle array. This should be + // a primary. + TParticle* part = static_cast(fParticles->At(iPrim)); + if (!(part->GetMother(0) < 0)) { + LOG(fatal) << "Not a primary track!" << iPrim; + } + return part; } TParticle* FairStack::GetCurrentTrack() const { - TParticle* currentPart = GetParticle(fCurrentTrack); - if ( ! currentPart) { - LOG(warn) << "Current track not found in stack!" ; - } - return currentPart; + TParticle* currentPart = GetParticle(fCurrentTrack); + if (!currentPart) { + LOG(warn) << "Current track not found in stack!"; + } + return currentPart; } void FairStack::AddParticle(TParticle* oldPart) { - TClonesArray& array = *fParticles; - TParticle* newPart = new(array[fIndex]) TParticle(*oldPart); - newPart->SetWeight(oldPart->GetWeight()); - newPart->SetUniqueID(oldPart->GetUniqueID()); - fIndex++; + TClonesArray& array = *fParticles; + TParticle* newPart = new (array[fIndex]) TParticle(*oldPart); + newPart->SetWeight(oldPart->GetWeight()); + newPart->SetUniqueID(oldPart->GetUniqueID()); + fIndex++; } void FairStack::FillTrackArray() { - LOG(debug) << "Filling MCTrack array..."; + LOG(debug) << "Filling MCTrack array..."; - // --> Reset index map and number of output tracks - fIndexMap.clear(); - fNTracks = 0; + // --> Reset index map and number of output tracks + fIndexMap.clear(); + fNTracks = 0; - // --> Check tracks for selection criteria - SelectTracks(); + // --> Check tracks for selection criteria + SelectTracks(); - // --> Loop over fParticles array and copy selected tracks - for (Int_t iPart=0; iPart Loop over fParticles array and copy selected tracks + for (Int_t iPart = 0; iPart < fNParticles; iPart++) { + Bool_t store = kFALSE; - fStoreIter = fStoreMap.find(iPart); - if (fStoreIter == fStoreMap.end() ) { - LOG(fatal) << "Particle " << iPart << " not found in storage map! "; - } else { - store = (*fStoreIter).second; - } + fStoreIter = fStoreMap.find(iPart); + if (fStoreIter == fStoreMap.end()) { + LOG(fatal) << "Particle " << iPart << " not found in storage map! "; + } else { + store = (*fStoreIter).second; + } - if (store) { - FairMCTrack* track = - new( (*fTracks)[fNTracks]) FairMCTrack(GetParticle(iPart)); - fIndexMap[iPart] = fNTracks; - // --> Set the number of points in the detectors for this track - for (Int_t iDet=kREF; iDet a(iPart, iDet); - track->SetNPoints(iDet, fPointsMap[a]); - } - fNTracks++; - } else { - fIndexMap[iPart] = -2; + if (store) { + FairMCTrack* track = new ((*fTracks)[fNTracks]) FairMCTrack(GetParticle(iPart)); + fIndexMap[iPart] = fNTracks; + // --> Set the number of points in the detectors for this track + for (Int_t iDet = kREF; iDet < kSTOPHERE; iDet++) { + pair a(iPart, iDet); + track->SetNPoints(iDet, fPointsMap[a]); + } + fNTracks++; + } else { + fIndexMap[iPart] = -2; + } } - } + // --> Map index for primary mothers + fIndexMap[-1] = -1; - // --> Map index for primary mothers - fIndexMap[-1] = -1; - - // --> Screen output - //Print(1); + // --> Screen output + // Print(1); } Int_t FairStack::GetCurrentTrackNumber() const { - std::map::const_iterator tempIter = fFSTrackMap.find(fCurrentTrack); // check if the track was created by FastSimulation - if ( tempIter != fFSTrackMap.end() ) { + std::map::const_iterator tempIter = + fFSTrackMap.find(fCurrentTrack); // check if the track was created by FastSimulation + if (tempIter != fFSTrackMap.end()) { return tempIter->second; } return fCurrentTrack; @@ -234,206 +251,229 @@ Int_t FairStack::GetCurrentTrackNumber() const void FairStack::UpdateTrackIndex(TRefArray* detList) { - Int_t nColl = 0; - - // First update mother ID in MCTracks - for (Int_t i=0; i(fTracks->At(i)); - Int_t iMotherOld = track->GetMotherId(); - fIndexIter = fIndexMap.find(iMotherOld); - if (fIndexIter == fIndexMap.end()) { - LOG(fatal) << "Particle index " << iMotherOld << " not found in index map!"; - } else { - track->SetMotherId( (*fIndexIter).second ); - } - } - - if(fDetList==0) { - // Now iterate through all active detectors - fDetIter = detList->MakeIterator(); - fDetIter->Reset(); - } else { - fDetIter->Reset(); - } - - FairDetector* det = nullptr; - while( (det = static_cast(fDetIter->Next()) ) ) { - - // --> Get hit collections from detector - Int_t iColl = 0; - TClonesArray* hitArray; - while ( (hitArray = det->GetCollection(iColl++)) ) { - nColl++; - Int_t nPoints = hitArray->GetEntriesFast(); - - // --> Update track index for all MCPoints in the collection - for (Int_t iPoint=0; iPoint(hitArray->At(iPoint)); - Int_t iTrack = point->GetTrackID(); - - // LOG(debug) << "point at " << point->GetX() << "," << point->GetY() << "," << point->GetZ() << " has trackID = " << point->GetTrackID(); - FastSimUpdateTrackIndex(point, iTrack); - - fIndexIter = fIndexMap.find(iTrack); + Int_t nColl = 0; + + // First update mother ID in MCTracks + for (Int_t i = 0; i < fNTracks; i++) { + FairMCTrack* track = static_cast(fTracks->At(i)); + Int_t iMotherOld = track->GetMotherId(); + fIndexIter = fIndexMap.find(iMotherOld); if (fIndexIter == fIndexMap.end()) { - LOG(fatal) << "Particle index " << iTrack << " not found in index map!"; + LOG(fatal) << "Particle index " << iMotherOld << " not found in index map!"; } else { - point->SetTrackID((*fIndexIter).second); - point->SetLink(FairLink("MCTrack", (*fIndexIter).second)); + track->SetMotherId((*fIndexIter).second); } - } + } - } // Collections of this detector - } // List of active detectors - LOG(debug) << "...stack and " << nColl << " collections updated."; + if (fDetList == 0) { + // Now iterate through all active detectors + fDetIter = detList->MakeIterator(); + fDetIter->Reset(); + } else { + fDetIter->Reset(); + } + + FairDetector* det = nullptr; + while ((det = static_cast(fDetIter->Next()))) { + + // --> Get hit collections from detector + Int_t iColl = 0; + TClonesArray* hitArray; + while ((hitArray = det->GetCollection(iColl++))) { + nColl++; + Int_t nPoints = hitArray->GetEntriesFast(); + + // --> Update track index for all MCPoints in the collection + for (Int_t iPoint = 0; iPoint < nPoints; iPoint++) { + FairMCPoint* point = static_cast(hitArray->At(iPoint)); + Int_t iTrack = point->GetTrackID(); + + // LOG(debug) << "point at " << point->GetX() << "," << point->GetY() << "," << point->GetZ() << + // " has trackID = " << point->GetTrackID(); + FastSimUpdateTrackIndex(point, iTrack); + + fIndexIter = fIndexMap.find(iTrack); + if (fIndexIter == fIndexMap.end()) { + LOG(fatal) << "Particle index " << iTrack << " not found in index map!"; + } else { + point->SetTrackID((*fIndexIter).second); + point->SetLink(FairLink("MCTrack", (*fIndexIter).second)); + } + } + + } // Collections of this detector + } // List of active detectors + LOG(debug) << "...stack and " << nColl << " collections updated."; } void FairStack::Reset() { - fIndex = 0; - fCurrentTrack = -1; - fNPrimaries = fNParticles = fNTracks = 0; - while (! fStack.empty() ) { fStack.pop(); } - fParticles->Clear(); - fTracks->Clear(); - fFSTrackMap.clear(); - fPointsMap.clear(); + fIndex = 0; + fCurrentTrack = -1; + fNPrimaries = fNParticles = fNTracks = 0; + while (!fStack.empty()) { + fStack.pop(); + } + fParticles->Clear(); + fTracks->Clear(); + fFSTrackMap.clear(); + fPointsMap.clear(); } void FairStack::Register() { - if ( gMC ) { - FairRootManager::Instance()->Register("MCTrack", "Stack", fTracks,kTRUE); - } else { - FairRootManager::Instance()->RegisterAny("MCTrack",fTracks,kTRUE); - } + if (gMC) { + FairRootManager::Instance()->Register("MCTrack", "Stack", fTracks, kTRUE); + } else { + FairRootManager::Instance()->RegisterAny("MCTrack", fTracks, kTRUE); + } } void FairStack::Print(Option_t*) const { - LOG(info) << "FairStack: Number of primaries = " << fNPrimaries; - LOG(info) << " Total number of particles = " << fNParticles; - LOG(info) << " Number of tracks in output = " << fNTracks; - if (gLogger->IsLogNeeded(fair::Severity::DEBUG1)) { - for (Int_t iTrack=0; iTrack( fTracks->At(iTrack))->Print(iTrack)); + LOG(info) << "FairStack: Number of primaries = " << fNPrimaries; + LOG(info) << " Total number of particles = " << fNParticles; + LOG(info) << " Number of tracks in output = " << fNTracks; + if (gLogger->IsLogNeeded(fair::Severity::DEBUG1)) { + for (Int_t iTrack = 0; iTrack < fNTracks; iTrack++) { + (static_cast(fTracks->At(iTrack))->Print(iTrack)); + } } - } } void FairStack::AddPoint(DetectorId detId) { - Int_t iDet = detId; - Int_t iTr = fCurrentTrack; - fFSTrackIter = fFSTrackMap.find(iTr); // check if this track is not already created by FastSimulation - if ( fFSTrackIter != fFSTrackMap.end() ) { // indeed the track has been created by the FastSimulation mechanism - iTr = fFSTrackIter->second; // use the ID of the original track - } - - pair a(iTr, iDet); - if ( fPointsMap.find(a) == fPointsMap.end() ) { fPointsMap[a] = 1; } - else { fPointsMap[a]++; } + Int_t iDet = detId; + Int_t iTr = fCurrentTrack; + fFSTrackIter = fFSTrackMap.find(iTr); // check if this track is not already created by FastSimulation + if (fFSTrackIter != fFSTrackMap.end()) { // indeed the track has been created by the FastSimulation mechanism + iTr = fFSTrackIter->second; // use the ID of the original track + } + + pair a(iTr, iDet); + if (fPointsMap.find(a) == fPointsMap.end()) { + fPointsMap[a] = 1; + } else { + fPointsMap[a]++; + } } void FairStack::AddPoint(DetectorId detId, Int_t iTrack) { - if ( iTrack < 0 ) { return; } - Int_t iDet = detId; - Int_t iTr = iTrack; - fFSTrackIter = fFSTrackMap.find(iTr); // check if this track is not already created by FastSimulation - if ( fFSTrackIter != fFSTrackMap.end() ) { // indeed the track has been created by the FastSimulation mechanism - iTr = fFSTrackIter->second; // use the ID of the original track - } - pair a(iTr, iDet); - if ( fPointsMap.find(a) == fPointsMap.end() ) { fPointsMap[a] = 1; } - else { fPointsMap[a]++; } + if (iTrack < 0) { + return; + } + Int_t iDet = detId; + Int_t iTr = iTrack; + fFSTrackIter = fFSTrackMap.find(iTr); // check if this track is not already created by FastSimulation + if (fFSTrackIter != fFSTrackMap.end()) { // indeed the track has been created by the FastSimulation mechanism + iTr = fFSTrackIter->second; // use the ID of the original track + } + pair a(iTr, iDet); + if (fPointsMap.find(a) == fPointsMap.end()) { + fPointsMap[a] = 1; + } else { + fPointsMap[a]++; + } } Int_t FairStack::GetCurrentParentTrackNumber() const { - TParticle* currentPart = GetCurrentTrack(); - if ( currentPart ) { return currentPart->GetFirstMother(); } - else { return -1; } + TParticle* currentPart = GetCurrentTrack(); + if (currentPart) { + return currentPart->GetFirstMother(); + } else { + return -1; + } } TParticle* FairStack::GetParticle(Int_t trackID) const { - if (trackID < 0 || trackID >= fNParticles) { - LOG(fatal) << "Particle index " << trackID << " out of range."; - } - return static_cast(fParticles->At(trackID)); + if (trackID < 0 || trackID >= fNParticles) { + LOG(fatal) << "Particle index " << trackID << " out of range."; + } + return static_cast(fParticles->At(trackID)); } void FairStack::SelectTracks() { - // --> Clear storage map - fStoreMap.clear(); - - // loop over tracks created by FastSim to order the tracks - for ( fFSTrackIter = fFSTrackMap.begin(); fFSTrackIter != fFSTrackMap.end(); ++fFSTrackIter ) { - for (Int_t i=0; iGetMother(0) == fFSTrackIter->first ) - thisPart->SetMother(0,fFSTrackIter->second); - } - } - - // --> Check particles in the fParticle array - for (Int_t i=0; i Get track parameters - Int_t iMother = thisPart->GetMother(0); - TLorentzVector p; - thisPart->Momentum(p); - Double_t energy = p.E(); - Double_t mass = p.M(); -// Double_t mass = thisPart->GetMass(); - Double_t eKin = energy - mass; - - // --> Calculate number of points - Int_t nPoints = 0; - for (Int_t iDet=kREF; iDet a(i, iDet); - if ( fPointsMap.find(a) != fPointsMap.end() ) { - nPoints += fPointsMap[a]; - } + // --> Clear storage map + fStoreMap.clear(); + + // loop over tracks created by FastSim to order the tracks + for (fFSTrackIter = fFSTrackMap.begin(); fFSTrackIter != fFSTrackMap.end(); ++fFSTrackIter) { + for (Int_t i = 0; i < fNParticles; i++) { + TParticle* thisPart = GetParticle(i); + if (thisPart->GetMother(0) == fFSTrackIter->first) + thisPart->SetMother(0, fFSTrackIter->second); + } } - // check if the track was created by the FastSim mechanism. Do not store such tracks - Bool_t fastSimTrack = kFALSE; - fFSTrackIter = fFSTrackMap.find(i); - if ( fFSTrackIter != fFSTrackMap.end() ) - fastSimTrack = kTRUE; - - // --> Check for cuts (store primaries in any case) - if (iMother < 0) { store = kTRUE; } - else { - if (!fStoreSecondaries) { store = kFALSE; } - if (nPoints < fMinPoints) { store = kFALSE; } - if (eKin < fEnergyCut) { store = kFALSE; } - if (fastSimTrack) { store = kFALSE; } + // --> Check particles in the fParticle array + for (Int_t i = 0; i < fNParticles; i++) { + + TParticle* thisPart = GetParticle(i); + Bool_t store = kTRUE; + + // --> Get track parameters + Int_t iMother = thisPart->GetMother(0); + TLorentzVector p; + thisPart->Momentum(p); + Double_t energy = p.E(); + Double_t mass = p.M(); + // Double_t mass = thisPart->GetMass(); + Double_t eKin = energy - mass; + + // --> Calculate number of points + Int_t nPoints = 0; + for (Int_t iDet = kREF; iDet < kSTOPHERE; iDet++) { + pair a(i, iDet); + if (fPointsMap.find(a) != fPointsMap.end()) { + nPoints += fPointsMap[a]; + } + } + + // check if the track was created by the FastSim mechanism. Do not store such tracks + Bool_t fastSimTrack = kFALSE; + fFSTrackIter = fFSTrackMap.find(i); + if (fFSTrackIter != fFSTrackMap.end()) + fastSimTrack = kTRUE; + + // --> Check for cuts (store primaries in any case) + if (iMother < 0) { + store = kTRUE; + } else { + if (!fStoreSecondaries) { + store = kFALSE; + } + if (nPoints < fMinPoints) { + store = kFALSE; + } + if (eKin < fEnergyCut) { + store = kFALSE; + } + if (fastSimTrack) { + store = kFALSE; + } + } + + // --> Set storage flag + fStoreMap[i] = store; } - // --> Set storage flag - fStoreMap[i] = store; - } - - // --> If flag is set, flag recursively mothers of selected tracks - if (fStoreMothers) { - for (Int_t i=0; iGetMother(0); - while(iMother >= 0) { - fStoreMap[iMother] = kTRUE; - iMother = GetParticle(iMother)->GetMother(0); + // --> If flag is set, flag recursively mothers of selected tracks + if (fStoreMothers) { + for (Int_t i = 0; i < fNParticles; i++) { + if (fStoreMap[i]) { + Int_t iMother = GetParticle(i)->GetMother(0); + while (iMother >= 0) { + fStoreMap[iMother] = kTRUE; + iMother = GetParticle(iMother)->GetMother(0); + } + } } - } } - } } -ClassImp(FairStack) +ClassImp(FairStack); diff --git a/examples/common/mcstack/FairStack.h b/examples/common/mcstack/FairStack.h index 9a39f1cc20..7bff1db7e6 100644 --- a/examples/common/mcstack/FairStack.h +++ b/examples/common/mcstack/FairStack.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -35,18 +35,15 @@ #ifndef FAIRSTACK_H #define FAIRSTACK_H -#include "FairGenericStack.h" // for FairGenericStack - -#include "FairDetectorList.h" // for DetectorId - -#include // for Int_t, Double_t, Bool_t, etc -#include // for TMCProcess - -#include // for map, map<>::iterator -#include // for stack -#include // for pair +#include "FairDetectorList.h" // for DetectorId +#include "FairGenericStack.h" // for FairGenericStack +#include // for Int_t, Double_t, Bool_t, etc +#include // for TMCProcess #include +#include // for map, map<>::iterator +#include // for stack +#include // for pair class TClonesArray; class TRefArray; @@ -77,19 +74,44 @@ class FairStack : public FairGenericStack *@param weight Particle weight *@param is Generation status code (whatever that means) **/ - virtual void PushTrack(Int_t toBeDone, Int_t parentID, Int_t pdgCode, - Double_t px, Double_t py, Double_t pz, - Double_t e, Double_t vx, Double_t vy, - Double_t vz, Double_t time, Double_t polx, - Double_t poly, Double_t polz, TMCProcess proc, - Int_t& ntr, Double_t weight, Int_t is); - - virtual void PushTrack(Int_t toBeDone, Int_t parentID, Int_t pdgCode, - Double_t px, Double_t py, Double_t pz, - Double_t e, Double_t vx, Double_t vy, - Double_t vz, Double_t time, Double_t polx, - Double_t poly, Double_t polz, TMCProcess proc, - Int_t& ntr, Double_t weight, Int_t is,Int_t secondParentId); + virtual void PushTrack(Int_t toBeDone, + Int_t parentID, + Int_t pdgCode, + Double_t px, + Double_t py, + Double_t pz, + Double_t e, + Double_t vx, + Double_t vy, + Double_t vz, + Double_t time, + Double_t polx, + Double_t poly, + Double_t polz, + TMCProcess proc, + Int_t& ntr, + Double_t weight, + Int_t is); + + virtual void PushTrack(Int_t toBeDone, + Int_t parentID, + Int_t pdgCode, + Double_t px, + Double_t py, + Double_t pz, + Double_t e, + Double_t vx, + Double_t vy, + Double_t vz, + Double_t time, + Double_t polx, + Double_t poly, + Double_t polz, + TMCProcess proc, + Int_t& ntr, + Double_t weight, + Int_t is, + Int_t secondParentId); /** Get next particle for tracking from the stack. ** Declared in TVirtualMCStack @@ -109,7 +131,7 @@ class FairStack : public FairGenericStack ** Declared in TVirtualMCStack *@param iTrack track number **/ - virtual void SetCurrentTrack(Int_t iTrack) { fCurrentTrack = iTrack; } + virtual void SetCurrentTrack(Int_t iTrack) { fCurrentTrack = iTrack; } /** Get total number of tracks ** Declared in TVirtualMCStack @@ -129,7 +151,7 @@ class FairStack : public FairGenericStack /** Get the number of the current track ** Declared in TVirtualMCStack **/ - virtual Int_t GetCurrentTrackNumber() const;// { return fCurrentTrack; } + virtual Int_t GetCurrentTrackNumber() const; // { return fCurrentTrack; } /** Get the track number of the parent of the current track ** Declared in TVirtualMCStack @@ -143,7 +165,7 @@ class FairStack : public FairGenericStack virtual void FillTrackArray(); /** Update the track index in the MCTracks and MCPoints **/ - virtual void UpdateTrackIndex(TRefArray* detArray=0); + virtual void UpdateTrackIndex(TRefArray* detArray = 0); /** Resets arrays and stack and deletes particles and tracks **/ virtual void Reset(); @@ -158,9 +180,9 @@ class FairStack : public FairGenericStack /** Modifiers **/ void StoreSecondaries(Bool_t choice = kTRUE) { fStoreSecondaries = choice; } - void SetMinPoints(Int_t min) { fMinPoints = min; } - void SetEnergyCut(Double_t eMin) { fEnergyCut = eMin; } - void StoreMothers(Bool_t choice = kTRUE) { fStoreMothers = choice; } + void SetMinPoints(Int_t min) { fMinPoints = min; } + void SetEnergyCut(Double_t eMin) { fEnergyCut = eMin; } + void StoreMothers(Bool_t choice = kTRUE) { fStoreMothers = choice; } /** Increment number of points for the current track in a given detector *@param iDet Detector unique identifier @@ -177,8 +199,9 @@ class FairStack : public FairGenericStack TParticle* GetParticle(Int_t trackId) const; TClonesArray* GetListOfParticles() { return fParticles; } - void SetParticleArray(TClonesArray* partArray) { - for ( Int_t ipart = 0 ; ipart < partArray->GetEntries() ; ipart++ ) { + void SetParticleArray(TClonesArray* partArray) + { + for (Int_t ipart = 0; ipart < partArray->GetEntries(); ipart++) { ((TParticle*)(partArray->At(ipart)))->SetUniqueID(fNPrimaries); fStack.push((TParticle*)partArray->At(ipart)); AddParticle((TParticle*)partArray->At(ipart)); @@ -187,8 +210,9 @@ class FairStack : public FairGenericStack } } - void SetParticleArray(TClonesArray* partArray, Int_t partFrom, Int_t partTo) { - for ( Int_t ipart = partFrom ; ipart < partTo ; ipart++ ) { + void SetParticleArray(TClonesArray* partArray, Int_t partFrom, Int_t partTo) + { + for (Int_t ipart = partFrom; ipart < partTo; ipart++) { ((TParticle*)(partArray->At(ipart)))->SetUniqueID(fNPrimaries); ((TParticle*)(partArray->At(ipart)))->SetStatusCode(fNPrimaries); fStack.push((TParticle*)partArray->At(ipart)); @@ -199,7 +223,8 @@ class FairStack : public FairGenericStack } /** Clone this object (used in MT mode only) */ - virtual FairGenericStack* CloneStack() const { + virtual FairGenericStack* CloneStack() const + { FairStack* clonedStack = new FairStack(); clonedStack->StoreSecondaries(fStoreSecondaries); clonedStack->SetMinPoints(fMinPoints); @@ -210,39 +235,39 @@ class FairStack : public FairGenericStack private: /** STL stack (FILO) used to handle the TParticles for tracking **/ - std::stack fStack; //! + std::stack fStack; //! /** Array of TParticles (contains all TParticles put into or created ** by the transport **/ - TClonesArray* fParticles; //! + TClonesArray* fParticles; //! /** Array of FairMCTracks containg the tracks written to the output **/ TClonesArray* fTracks; /** STL map from particle index to storage flag **/ - std::map fStoreMap; //! - std::map::iterator fStoreIter; //! + std::map fStoreMap; //! + std::map::iterator fStoreIter; //! /** STL map from particle index to track index **/ - std::map fIndexMap; //! - std::map::iterator fIndexIter; //! + std::map fIndexMap; //! + std::map::iterator fIndexIter; //! /** STL map from track index and detector ID to number of MCPoints **/ - std::map, Int_t> fPointsMap; //! + std::map, Int_t> fPointsMap; //! /** Some indizes and counters **/ - Int_t fCurrentTrack; //! Index of current track - Int_t fNPrimaries; //! Number of primary particles - Int_t fNParticles; //! Number of entries in fParticles - Int_t fNTracks; //! Number of entries in fTracks - Int_t fIndex; //! Used for merging + Int_t fCurrentTrack; //! Index of current track + Int_t fNPrimaries; //! Number of primary particles + Int_t fNParticles; //! Number of entries in fParticles + Int_t fNTracks; //! Number of entries in fTracks + Int_t fIndex; //! Used for merging /** Variables defining the criteria for output selection **/ - Bool_t fStoreSecondaries; - Int_t fMinPoints; + Bool_t fStoreSecondaries; + Int_t fMinPoints; Double32_t fEnergyCut; - Bool_t fStoreMothers; + Bool_t fStoreMothers; /** Mark tracks for output using selection criteria **/ void SelectTracks(); @@ -250,7 +275,7 @@ class FairStack : public FairGenericStack FairStack(const FairStack&); FairStack& operator=(const FairStack&); - ClassDef(FairStack,1) + ClassDef(FairStack, 1) }; #endif diff --git a/examples/common/passive/FairCave.cxx b/examples/common/passive/FairCave.cxx index 353594f28a..e3c5f18c60 100644 --- a/examples/common/passive/FairCave.cxx +++ b/examples/common/passive/FairCave.cxx @@ -1,88 +1,82 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* Generated by Together */ #include "FairCave.h" -#include "FairGeoCave.h" // for FairGeoCave -#include "FairGeoInterface.h" // for FairGeoInterface -#include "FairGeoLoader.h" // for FairGeoLoader -#include "FairGeoNode.h" // for FairGeoNode -#include "FairGeoPassivePar.h" // for FairGeoPassivePar -#include "FairGeoVolume.h" // for FairGeoVolume -#include "FairRun.h" // for FairRun -#include "FairRuntimeDb.h" // for FairRuntimeDb +#include "FairGeoCave.h" // for FairGeoCave +#include "FairGeoInterface.h" // for FairGeoInterface +#include "FairGeoLoader.h" // for FairGeoLoader +#include "FairGeoNode.h" // for FairGeoNode +#include "FairGeoPassivePar.h" // for FairGeoPassivePar +#include "FairGeoVolume.h" // for FairGeoVolume +#include "FairRun.h" // for FairRun +#include "FairRuntimeDb.h" // for FairRuntimeDb -#include // for TListIter, TList (ptr only) -#include // for TObjArray -#include // for TString +#include // for TListIter, TList (ptr only) +#include // for TObjArray +#include // for TString -ClassImp(FairCave) +ClassImp(FairCave); void FairCave::ConstructGeometry() { - FairGeoLoader* loader = FairGeoLoader::Instance(); - FairGeoInterface* GeoInterface = loader->getGeoInterface(); - FairGeoCave* MGeo = new FairGeoCave(); - MGeo->setGeomFile(GetGeometryFileName()); - GeoInterface->addGeoModule(MGeo); - Bool_t rc = GeoInterface->readSet(MGeo); - if (rc) { MGeo->create(loader->getGeoBuilder()); } + FairGeoLoader* loader = FairGeoLoader::Instance(); + FairGeoInterface* GeoInterface = loader->getGeoInterface(); + FairGeoCave* MGeo = new FairGeoCave(); + MGeo->setGeomFile(GetGeometryFileName()); + GeoInterface->addGeoModule(MGeo); + Bool_t rc = GeoInterface->readSet(MGeo); + if (rc) { + MGeo->create(loader->getGeoBuilder()); + } - TList* volList = MGeo->getListOfVolumes(); - // store geo parameter - FairRun* fRun = FairRun::Instance(); - FairRuntimeDb* rtdb = FairRun::Instance()->GetRuntimeDb(); - FairGeoPassivePar* par = static_cast(rtdb->getContainer("FairGeoPassivePar")); - TObjArray* fSensNodes = par->GetGeoSensitiveNodes(); - TObjArray* fPassNodes = par->GetGeoPassiveNodes(); + TList* volList = MGeo->getListOfVolumes(); + // store geo parameter + FairRun* fRun = FairRun::Instance(); + FairRuntimeDb* rtdb = FairRun::Instance()->GetRuntimeDb(); + FairGeoPassivePar* par = static_cast(rtdb->getContainer("FairGeoPassivePar")); + TObjArray* fSensNodes = par->GetGeoSensitiveNodes(); + TObjArray* fPassNodes = par->GetGeoPassiveNodes(); - TListIter iter(volList); - FairGeoNode* node = nullptr; - FairGeoVolume* aVol = nullptr; + TListIter iter(volList); + FairGeoNode* node = nullptr; + FairGeoVolume* aVol = nullptr; - while ((node = static_cast(iter.Next()))) { - aVol = dynamic_cast ( node ); - if (node->isSensitive()) { - fSensNodes->AddLast( aVol ); - } else { - fPassNodes->AddLast( aVol ); + while ((node = static_cast(iter.Next()))) { + aVol = dynamic_cast(node); + if (node->isSensitive()) { + fSensNodes->AddLast(aVol); + } else { + fPassNodes->AddLast(aVol); + } } - } - par->setChanged(); - par->setInputVersion(fRun->GetRunId(),1); - + par->setChanged(); + par->setInputVersion(fRun->GetRunId(), 1); } FairCave::FairCave(const FairCave& rhs) - : FairModule(rhs) + : FairModule(rhs) { - world[0] = rhs.world[0]; - world[1] = rhs.world[1]; - world[2] = rhs.world[2]; + world[0] = rhs.world[0]; + world[1] = rhs.world[1]; + world[2] = rhs.world[2]; } -FairCave::FairCave() -{ -} +FairCave::FairCave() {} -FairCave::~FairCave() -{ -} +FairCave::~FairCave() {} -FairCave::FairCave(const char* name, const char* Title) - : FairModule(name ,Title) +FairCave::FairCave(const char* name, const char* Title) + : FairModule(name, Title) { - world[0] = 0; - world[1] = 0; - world[2] = 0; + world[0] = 0; + world[1] = 0; + world[2] = 0; } -FairModule* FairCave::CloneModule() const -{ - return new FairCave(*this); -} +FairModule* FairCave::CloneModule() const { return new FairCave(*this); } diff --git a/examples/common/passive/FairCave.h b/examples/common/passive/FairCave.h index 93a1e34676..9a94f641af 100644 --- a/examples/common/passive/FairCave.h +++ b/examples/common/passive/FairCave.h @@ -1,21 +1,21 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef Cave_H #define Cave_H -#include "FairModule.h" // for FairModule +#include "FairModule.h" // for FairModule -#include // for FairCave::Class, ClassDef, etc +#include // for FairCave::Class, ClassDef, etc class FairCave : public FairModule { public: - FairCave(const char* name, const char* Title="Exp Cave"); + FairCave(const char* name, const char* Title = "Exp Cave"); FairCave(); virtual ~FairCave(); virtual void ConstructGeometry(); @@ -25,8 +25,7 @@ class FairCave : public FairModule private: FairCave(const FairCave& rhs); Double_t world[3]; - ClassDef(FairCave,1) //PNDCaveSD + ClassDef(FairCave, 1) // PNDCaveSD }; -#endif //Cave_H - +#endif // Cave_H diff --git a/examples/common/passive/FairGeoCave.cxx b/examples/common/passive/FairGeoCave.cxx index 2feaaa7973..b931032c2e 100644 --- a/examples/common/passive/FairGeoCave.cxx +++ b/examples/common/passive/FairGeoCave.cxx @@ -17,109 +17,120 @@ #include "FairGeoCave.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 // for TList - -#include // for strcmp -#include // for cout -#include // for fstream +#include // for TList +#include // for fstream +#include // for cout +#include // for strcmp using namespace std; -ClassImp(FairGeoCave) +ClassImp(FairGeoCave); FairGeoCave::FairGeoCave() - : FairGeoSet(), - name("cave") + : FairGeoSet() + , name("cave") { - fName = "cave"; - name = "cave"; - maxModules=1; + fName = "cave"; + maxModules = 1; } -Bool_t FairGeoCave::read(std::fstream& fin,FairGeoMedia* media) +Bool_t FairGeoCave::read(std::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 FairGeoCave::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 FairGeoCave::write(std::fstream& fout) { - // Writes the geometry to file - std::ios_base::fmtflags tmp = 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 + std::ios_base::fmtflags tmp = 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); + } } - } - fout.setf(tmp); + fout.setf(tmp); } void FairGeoCave::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/examples/common/passive/FairGeoCave.h b/examples/common/passive/FairGeoCave.h index d803b1bed0..5a56987685 100644 --- a/examples/common/passive/FairGeoCave.h +++ b/examples/common/passive/FairGeoCave.h @@ -1,22 +1,22 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef PNDGEOCAVE_H #define PNDGEOCAVE_H -#include "FairGeoSet.h" // for FairGeoSet +#include "FairGeoSet.h" // for FairGeoSet -#include // for fstream -#include // for FairGeoCave::Class, Bool_t, etc -#include // for TString +#include // for FairGeoCave::Class, Bool_t, etc +#include // for TString +#include // for fstream class FairGeoMedia; -class FairGeoCave : public FairGeoSet +class FairGeoCave : public FairGeoSet { protected: TString name; @@ -24,12 +24,12 @@ class FairGeoCave : public FairGeoSet public: FairGeoCave(); ~FairGeoCave() {} - 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(FairGeoCave,0) // Class for the geometry of CAVE + ClassDef(FairGeoCave, 0) // Class for the geometry of CAVE }; -#endif /* !PNDGEOCAVE_H */ +#endif /* !PNDGEOCAVE_H */ diff --git a/examples/common/passive/FairGeoMagnet.cxx b/examples/common/passive/FairGeoMagnet.cxx index 892db579c2..a57bd8519e 100644 --- a/examples/common/passive/FairGeoMagnet.cxx +++ b/examples/common/passive/FairGeoMagnet.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ //*-- AUTHOR : Ilse Koenig @@ -17,19 +17,18 @@ #include "FairGeoMagnet.h" -#include // for TString +#include // for TString +#include // for strcpy -#include // for strcpy - -ClassImp(FairGeoMagnet) +ClassImp(FairGeoMagnet); FairGeoMagnet::FairGeoMagnet() - : FairGeoSet() + : FairGeoSet() { - // Constructor - fName="magnet"; - maxSectors=0; - maxModules=1; - strcpy(modName,"m"); - strcpy(eleName,"m"); + // Constructor + fName = "magnet"; + maxSectors = 0; + maxModules = 1; + strcpy(modName, "m"); + strcpy(eleName, "m"); } diff --git a/examples/common/passive/FairGeoMagnet.h b/examples/common/passive/FairGeoMagnet.h index 60846a64c3..f9f71483d3 100644 --- a/examples/common/passive/FairGeoMagnet.h +++ b/examples/common/passive/FairGeoMagnet.h @@ -1,29 +1,29 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef PNDGEOMAGNET_H #define PNDGEOMAGNET_H -#include "FairGeoSet.h" // for FairGeoSet +#include "FairGeoSet.h" // for FairGeoSet -#include // for FairGeoMagnet::Class, Int_t, etc +#include // for FairGeoMagnet::Class, Int_t, etc -class FairGeoMagnet : public FairGeoSet +class FairGeoMagnet : public FairGeoSet { protected: - char modName[2]; // name of module - char eleName[2]; // substring for elements in module + char modName[2]; // name of module + char eleName[2]; // substring for elements in module public: FairGeoMagnet(); ~FairGeoMagnet() {} - const char* getModuleName(Int_t) {return modName;} - const char* getEleName(Int_t) {return eleName;} - ClassDef(FairGeoMagnet,0) // Class for the geometry of Magnet + const char* getModuleName(Int_t) { return modName; } + const char* getEleName(Int_t) { return eleName; } + ClassDef(FairGeoMagnet, 0) // Class for the geometry of Magnet }; -#endif /* !FAIRGEOMAGNET_H */ +#endif /* !FAIRGEOMAGNET_H */ diff --git a/examples/common/passive/FairGeoPassivePar.cxx b/examples/common/passive/FairGeoPassivePar.cxx index 6176d82664..51e7b1afa8 100644 --- a/examples/common/passive/FairGeoPassivePar.cxx +++ b/examples/common/passive/FairGeoPassivePar.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ //*-- AUTHOR : Denis Bertini @@ -10,43 +10,48 @@ #include "FairGeoPassivePar.h" -#include "FairParamList.h" // for FairParamList +#include "FairParamList.h" // for FairParamList -#include // for TObjArray +#include // for TObjArray using namespace std; -ClassImp(FairGeoPassivePar) +ClassImp(FairGeoPassivePar); -FairGeoPassivePar::FairGeoPassivePar(const char* name,const char* title,const char* context) - : FairParGenericSet(name,title,context), - fGeoSensNodes(new TObjArray()), - fGeoPassNodes(new TObjArray()) -{ -} +FairGeoPassivePar::FairGeoPassivePar(const char* name, const char* title, const char* context) + : FairParGenericSet(name, title, context) + , fGeoSensNodes(new TObjArray()) + , fGeoPassNodes(new TObjArray()) +{} -FairGeoPassivePar::~FairGeoPassivePar(void) -{ -} +FairGeoPassivePar::~FairGeoPassivePar(void) {} void FairGeoPassivePar::clear(void) { - delete fGeoSensNodes; - delete fGeoPassNodes; + delete fGeoSensNodes; + delete fGeoPassNodes; } void FairGeoPassivePar::putParams(FairParamList* l) { - if (!l) { return; } - l->addObject("FairGeoNodes Sensitive List", fGeoSensNodes); - l->addObject("FairGeoNodes Passive List", fGeoPassNodes); + if (!l) { + return; + } + l->addObject("FairGeoNodes Sensitive List", fGeoSensNodes); + l->addObject("FairGeoNodes Passive List", fGeoPassNodes); } Bool_t FairGeoPassivePar::getParams(FairParamList* l) { - if (!l) { return kFALSE; } - if (!l->fillObject("FairGeoNodes Sensitive List", fGeoSensNodes)) { return kFALSE; } - if (!l->fillObject("FairGeoNodes Passive List", fGeoPassNodes)) { return kFALSE; } - - return kTRUE; + if (!l) { + return kFALSE; + } + if (!l->fillObject("FairGeoNodes Sensitive List", fGeoSensNodes)) { + return kFALSE; + } + if (!l->fillObject("FairGeoNodes Passive List", fGeoPassNodes)) { + return kFALSE; + } + + return kTRUE; } diff --git a/examples/common/passive/FairGeoPassivePar.h b/examples/common/passive/FairGeoPassivePar.h index f665966c6e..a792709ee2 100644 --- a/examples/common/passive/FairGeoPassivePar.h +++ b/examples/common/passive/FairGeoPassivePar.h @@ -1,16 +1,16 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef PNDGEOPASSIVEPAR_H #define PNDGEOPASSIVEPAR_H -#include "FairParGenericSet.h" // for FairParGenericSet +#include "FairParGenericSet.h" // for FairParGenericSet -#include // for FairGeoPassivePar::Class, etc +#include // for FairGeoPassivePar::Class, etc class FairParamList; class TObjArray; @@ -18,24 +18,24 @@ class TObjArray; class FairGeoPassivePar : public FairParGenericSet { public: - TObjArray* fGeoSensNodes; // List of FairGeoNodes for sensitive volumes - TObjArray* fGeoPassNodes; // List of FairGeoNodes for sensitive volumes + TObjArray* fGeoSensNodes; // List of FairGeoNodes for sensitive volumes + TObjArray* fGeoPassNodes; // List of FairGeoNodes for sensitive volumes - FairGeoPassivePar(const char* name="FairGeoPassivePar", - const char* title="Passive Geometry Parameters", - const char* context="TestDefaultContext"); + FairGeoPassivePar(const char* name = "FairGeoPassivePar", + const char* title = "Passive Geometry Parameters", + const char* context = "TestDefaultContext"); ~FairGeoPassivePar(void); void clear(void); void putParams(FairParamList*); Bool_t getParams(FairParamList*); - TObjArray* GetGeoSensitiveNodes() {return fGeoSensNodes;} - TObjArray* GetGeoPassiveNodes() {return fGeoPassNodes;} + TObjArray* GetGeoSensitiveNodes() { return fGeoSensNodes; } + TObjArray* GetGeoPassiveNodes() { return fGeoPassNodes; } private: FairGeoPassivePar(const FairGeoPassivePar&); FairGeoPassivePar& operator=(const FairGeoPassivePar&); - ClassDef(FairGeoPassivePar,1) + ClassDef(FairGeoPassivePar, 1) }; #endif /* !PNDGEOPASSIVEPAR_H */ diff --git a/examples/common/passive/FairGeoPipe.cxx b/examples/common/passive/FairGeoPipe.cxx index 0e9f80c819..1990985b4e 100644 --- a/examples/common/passive/FairGeoPipe.cxx +++ b/examples/common/passive/FairGeoPipe.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ //*-- AUTHOR : Ilse Koenig @@ -16,44 +16,39 @@ ///////////////////////////////////////////////////////////// #include "FairGeoPipe.h" -#include "FairGeoInterface.h" // for FairGeoInterface -#include "FairGeoLoader.h" // for FairGeoLoader -#include "FairGeoNode.h" // for FairGeoNode +#include "FairGeoInterface.h" // for FairGeoInterface +#include "FairGeoLoader.h" // for FairGeoLoader +#include "FairGeoNode.h" // for FairGeoNode -#include // for TList -#include // for TString - -#include // for strcpy +#include // for TList +#include // for TString +#include // for strcpy class FairGeoBuilder; class TObject; -ClassImp(FairGeoPipe) +ClassImp(FairGeoPipe); FairGeoPipe::FairGeoPipe() - : FairGeoSet() + : FairGeoSet() { - // Constructor - fName="pipe"; - strcpy(modName,"p"); - strcpy(eleName,"p"); - maxSectors=0; - maxModules=1; + // Constructor + fName = "pipe"; + strcpy(modName, "p"); + strcpy(eleName, "p"); + maxSectors = 0; + maxModules = 1; } -Bool_t FairGeoPipe::create ( FairGeoBuilder* build ) +Bool_t FairGeoPipe::create(FairGeoBuilder* build) { - Bool_t rc = FairGeoSet::create( build ); - if ( rc ) { - FairGeoLoader* loader = FairGeoLoader::Instance(); - FairGeoInterface* GeoInterface =loader->getGeoInterface(); - - GeoInterface->getMasterNodes()->Add( static_cast( getVolume("pipeCentral") ) ); - } - return rc; -} - -FairGeoPipe::~FairGeoPipe() -{ - + Bool_t rc = FairGeoSet::create(build); + if (rc) { + FairGeoLoader* loader = FairGeoLoader::Instance(); + FairGeoInterface* GeoInterface = loader->getGeoInterface(); + + GeoInterface->getMasterNodes()->Add(static_cast(getVolume("pipeCentral"))); + } + return rc; } +FairGeoPipe::~FairGeoPipe() {} diff --git a/examples/common/passive/FairGeoPipe.h b/examples/common/passive/FairGeoPipe.h index 1384196409..6f042b04ae 100644 --- a/examples/common/passive/FairGeoPipe.h +++ b/examples/common/passive/FairGeoPipe.h @@ -1,32 +1,32 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef PNDGEOPIPE_H #define PNDGEOPIPE_H -#include "FairGeoSet.h" // for FairGeoSet +#include "FairGeoSet.h" // for FairGeoSet -#include // for FairGeoPipe::Class, Int_t, etc +#include // for FairGeoPipe::Class, Int_t, etc class FairGeoBuilder; -class FairGeoPipe : public FairGeoSet +class FairGeoPipe : public FairGeoSet { protected: - char modName[2]; // name of module - char eleName[2]; // substring for elements in module + char modName[2]; // name of module + char eleName[2]; // substring for elements in module public: FairGeoPipe(); virtual ~FairGeoPipe(); - const char* getModuleName(Int_t) {return modName;} - const char* getEleName(Int_t) {return eleName;} + const char* getModuleName(Int_t) { return modName; } + const char* getEleName(Int_t) { return eleName; } Bool_t create(FairGeoBuilder*); - ClassDef(FairGeoPipe,0) // Class for geometry of beam pipe + ClassDef(FairGeoPipe, 0) // Class for geometry of beam pipe }; -#endif /* !PNDGEOPIPE_H */ +#endif /* !PNDGEOPIPE_H */ diff --git a/examples/common/passive/FairGeoTarget.cxx b/examples/common/passive/FairGeoTarget.cxx index 610c99cbae..a0e558050c 100644 --- a/examples/common/passive/FairGeoTarget.cxx +++ b/examples/common/passive/FairGeoTarget.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ //*-- AUTHOR : Ilse Koenig @@ -17,19 +17,18 @@ #include "FairGeoTarget.h" -#include // for TString +#include // for TString +#include // for strcpy -#include // for strcpy - -ClassImp(FairGeoTarget) +ClassImp(FairGeoTarget); FairGeoTarget::FairGeoTarget() - : FairGeoSet() + : FairGeoSet() { - // Constructor - fName="target"; - strcpy(modName,"t"); - strcpy(eleName,"t"); - maxSectors=0; - maxModules=1; + // Constructor + fName = "target"; + strcpy(modName, "t"); + strcpy(eleName, "t"); + maxSectors = 0; + maxModules = 1; } diff --git a/examples/common/passive/FairGeoTarget.h b/examples/common/passive/FairGeoTarget.h index f12102bfc8..d70e4077f8 100644 --- a/examples/common/passive/FairGeoTarget.h +++ b/examples/common/passive/FairGeoTarget.h @@ -1,28 +1,28 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef PNDGEOTARGET_H #define PNDGEOTARGET_H -#include "FairGeoSet.h" // for FairGeoSet +#include "FairGeoSet.h" // for FairGeoSet -#include // for FairGeoTarget::Class, Int_t, etc +#include // for FairGeoTarget::Class, Int_t, etc -class FairGeoTarget : public FairGeoSet +class FairGeoTarget : public FairGeoSet { protected: - char modName[2]; // name of module - char eleName[2]; // substring for elements in module + char modName[2]; // name of module + char eleName[2]; // substring for elements in module public: FairGeoTarget(); ~FairGeoTarget() {} - const char* getModuleName(Int_t) {return modName;} - const char* getEleName(Int_t) {return eleName;} - ClassDef(FairGeoTarget,0) // Class for geometry of Target + const char* getModuleName(Int_t) { return modName; } + const char* getEleName(Int_t) { return eleName; } + ClassDef(FairGeoTarget, 0) // Class for geometry of Target }; -#endif /* !PNDGEOTARGET_H */ +#endif /* !PNDGEOTARGET_H */ diff --git a/examples/common/passive/FairMagnet.cxx b/examples/common/passive/FairMagnet.cxx index 739cf4a2d4..8d760e9591 100644 --- a/examples/common/passive/FairMagnet.cxx +++ b/examples/common/passive/FairMagnet.cxx @@ -1,68 +1,59 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* Generated by Together */ #include "FairMagnet.h" -#include "FairGeoMagnet.h" // for FairGeoMagnet -#include "FairGeoPassivePar.h" // for FairGeoPassivePar +#include "FairGeoMagnet.h" // for FairGeoMagnet +#include "FairGeoPassivePar.h" // for FairGeoPassivePar -#include // for TString +#include // for TString +#include // for operator<<, basic_ostream, etc -#include // for operator<<, basic_ostream, etc - -FairMagnet::~FairMagnet() -{ -} +FairMagnet::~FairMagnet() {} FairMagnet::FairMagnet() - : FairModule("FairMagnet", "") -{ -} + : FairModule("FairMagnet", "") +{} FairMagnet::FairMagnet(const char* name, const char* Title) - : FairModule(name ,Title) -{ -} + : FairModule(name, Title) +{} FairMagnet::FairMagnet(const FairMagnet& rhs) - : FairModule(rhs) -{ -} + : FairModule(rhs) +{} void FairMagnet::ConstructGeometry() { - TString fileName=GetGeometryFileName(); - if (fileName.EndsWith(".geo")) { - ConstructASCIIGeometry(); - } else if(fileName.EndsWith(".root")) { - ConstructRootGeometry(); - } else { - std::cout<< "Geometry format not supported " <(MGeo, "FairGeoPassivePar"); } -FairModule* FairMagnet::CloneModule() const -{ - return new FairMagnet(*this); -} +FairModule* FairMagnet::CloneModule() const { return new FairMagnet(*this); } -ClassImp(FairMagnet) +ClassImp(FairMagnet); diff --git a/examples/common/passive/FairMagnet.h b/examples/common/passive/FairMagnet.h index 2c9f206b9f..6dae1047e9 100644 --- a/examples/common/passive/FairMagnet.h +++ b/examples/common/passive/FairMagnet.h @@ -1,23 +1,22 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef MAGNET_H #define MAGNET_H -#include "FairModule.h" // for FairModule +#include "FairModule.h" // for FairModule -#include // for FairMagnet::Class, Bool_t, etc - -#include // for string +#include // for FairMagnet::Class, Bool_t, etc +#include // for string class FairMagnet : public FairModule { public: - FairMagnet(const char* name, const char* Title="PND Magnet"); + FairMagnet(const char* name, const char* Title = "PND Magnet"); FairMagnet(); virtual ~FairMagnet(); void ConstructGeometry(); @@ -28,8 +27,7 @@ class FairMagnet : public FairModule private: FairMagnet(const FairMagnet& rhs); - ClassDef(FairMagnet,1) + ClassDef(FairMagnet, 1) }; -#endif //MAGNET_H - +#endif // MAGNET_H diff --git a/examples/common/passive/FairPassiveContFact.cxx b/examples/common/passive/FairPassiveContFact.cxx index f33b86a71a..5ac8f0c6d3 100644 --- a/examples/common/passive/FairPassiveContFact.cxx +++ b/examples/common/passive/FairPassiveContFact.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ //*-- AUTHOR : Denis Bertini @@ -17,55 +17,51 @@ ///////////////////////////////////////////////////////////// #include "FairPassiveContFact.h" -#include "FairGeoPassivePar.h" // for FairGeoPassivePar -#include "FairRuntimeDb.h" // for FairRuntimeDb +#include "FairGeoPassivePar.h" // for FairGeoPassivePar +#include "FairRuntimeDb.h" // for FairRuntimeDb -#include // for TList -#include // for TString - -#include // for strcmp +#include // for TList +#include // for TString +#include // for strcmp class FairParSet; using namespace std; -ClassImp(FairPassiveContFact) +ClassImp(FairPassiveContFact); static FairPassiveContFact gFairPassiveContFact; FairPassiveContFact::FairPassiveContFact() - : FairContFact() + : FairContFact() { - // Constructor (called when the library is loaded) - fName="FairPassiveContFact"; - fTitle="Factory for parameter containers in libPassive"; - setAllContainers(); - FairRuntimeDb::instance()->addContFactory(this); + // Constructor (called when the library is loaded) + fName = "FairPassiveContFact"; + fTitle = "Factory for parameter containers in libPassive"; + setAllContainers(); + FairRuntimeDb::instance()->addContFactory(this); } void FairPassiveContFact::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* FairPassiveContFact::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=nullptr; - if (strcmp(name,"FairGeoPassivePar") == 0) { - p = new FairGeoPassivePar(c->getConcatName().Data(), c->GetTitle(), c->getContext()); - } - return p; + /** 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 = nullptr; + if (strcmp(name, "FairGeoPassivePar") == 0) { + p = new FairGeoPassivePar(c->getConcatName().Data(), c->GetTitle(), c->getContext()); + } + return p; } - diff --git a/examples/common/passive/FairPassiveContFact.h b/examples/common/passive/FairPassiveContFact.h index d6f8a1b5b3..ee79b4816e 100644 --- a/examples/common/passive/FairPassiveContFact.h +++ b/examples/common/passive/FairPassiveContFact.h @@ -1,16 +1,16 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef PNDPASSIVECONTFACT_H #define PNDPASSIVECONTFACT_H -#include "FairContFact.h" // for FairContFact, etc +#include "FairContFact.h" // for FairContFact, etc -#include // for FairPassiveContFact::Class, etc +#include // for FairPassiveContFact::Class, etc class FairParSet; @@ -24,7 +24,7 @@ class FairPassiveContFact : public FairContFact ~FairPassiveContFact() {} FairParSet* createContainer(FairContainer*); - ClassDef( FairPassiveContFact,0) // Factory for all Passive parameter containers + ClassDef(FairPassiveContFact, 0) // Factory for all Passive parameter containers }; -#endif /* !PNDPASSIVECONTFACT_H */ +#endif /* !PNDPASSIVECONTFACT_H */ diff --git a/examples/common/passive/FairPipe.cxx b/examples/common/passive/FairPipe.cxx index cbfed23dca..3a977c8cb7 100644 --- a/examples/common/passive/FairPipe.cxx +++ b/examples/common/passive/FairPipe.cxx @@ -1,226 +1,181 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* Generated by Together */ #include "FairPipe.h" -#include "FairGeoBuilder.h" // for FairGeoBuilder -#include "FairGeoInterface.h" // for FairGeoInterface -#include "FairGeoLoader.h" // for FairGeoLoader -#include "FairGeoMedia.h" // for FairGeoMedia +#include "FairGeoBuilder.h" // for FairGeoBuilder +#include "FairGeoInterface.h" // for FairGeoInterface +#include "FairGeoLoader.h" // for FairGeoLoader +#include "FairGeoMedia.h" // for FairGeoMedia -#include // for TGeoCompositeShape -#include // for TGeoManager, gGeoManager -#include // for TGeoRotation -#include // for TGeoPcon -#include // for TGeoVolume, etc +#include // for TGeoCompositeShape +#include // for TGeoManager, gGeoManager +#include // for TGeoRotation +#include // for TGeoPcon +#include // for TGeoVolume, etc class FairGeoMedium; -FairPipe::~FairPipe() -{ -} +FairPipe::~FairPipe() {} FairPipe::FairPipe() - : FairModule("FairPipe", "") -{ -} + : FairModule("FairPipe", "") +{} FairPipe::FairPipe(const char* name, const char* title) - : FairModule(name ,title) -{ -} + : FairModule(name, title) +{} FairPipe::FairPipe(const FairPipe& rhs) - : FairModule(rhs) -{ -} + : FairModule(rhs) +{} void FairPipe::ConstructGeometry() { -/* + /* FairRun* fRun = FairRun::Instance(); FairRuntimeDb* rtdb= fRun->GetRuntimeDb(); FairGeoPassivePar* par=(FairGeoPassivePar*)(rtdb->getContainer("FairGeoPassivePar")); */ - FairGeoLoader* loader = FairGeoLoader::Instance(); - FairGeoInterface* GeoInterface = loader->getGeoInterface(); - FairGeoMedia* Media = GeoInterface->getMedia(); - FairGeoBuilder* geobuild = loader->getGeoBuilder(); + FairGeoLoader* loader = FairGeoLoader::Instance(); + FairGeoInterface* GeoInterface = loader->getGeoInterface(); + FairGeoMedia* Media = GeoInterface->getMedia(); + FairGeoBuilder* geobuild = loader->getGeoBuilder(); - // Call materials - FairGeoMedium* medVacuum = Media->getMedium("vacuum"); - FairGeoMedium* medSteel = Media->getMedium("steel"); - FairGeoMedium* medAlBe = Media->getMedium("Al+Be"); + // Call materials + FairGeoMedium* medVacuum = Media->getMedium("vacuum"); + FairGeoMedium* medSteel = Media->getMedium("steel"); + FairGeoMedium* medAlBe = Media->getMedium("Al+Be"); -/* + /* Int_t nMedVacuum = geobuild->createMedium(medVacuum); Int_t nMedSteel = geobuild->createMedium(medSteel); Int_t nMedAlBe = geobuild->createMedium(medAlBe); */ - geobuild->createMedium(medVacuum); - geobuild->createMedium(medSteel); - geobuild->createMedium(medAlBe); - - Double_t parPipeLeft[9] = { 0., 360., 2, - -200., 7.9, 8., - -32., 7.9, 8. - }; - - // The central part is totally filled because of the crossing operations - Double_t parPipeCentral[12] = { 0., 360., 3, - -32., 0., 8., - -2., 0., .9, - 20., 0., .9 - }; - - Double_t parPipeRight[18] = { 0., 360., 5, - 20., .8873, .9, - 22., 2.073, 2.1, - 120., 2.05, 2.1, - 300.1, 2.85, 2.9, - 1050., 5.4, 5.5 - }; - - Double_t parPipeVacuumLeft[9] = { 0., 360., 2, - -200., 0., 7.9, - -32., 0., 7.9 - }; - - Double_t parPipeVacuumCentral[12] = { 0., 360., 3, - -32., 0., 7.9, - -2., 0., .873, - 20., 0., .873 - }; - - Double_t parPipeVacuumRight[18] = { 0., 360., 5, - 20., 0., .873, - 22., 0., 2.073, - 120., 0., 2.05, - 300.1, 0., 2.85, - 1050., 0., 5.4 - }; - - - Double_t parPipeTargetDown[27] = { 0., 360., 8, - -215., 17.4, 17.5, - -183., 17.4, 17.5, - -173., 4.5, 4.6, - -96., 4.5, 4.6, - -95., 2.4, 2.5, - -55., 2.4, 2.5, - -54., 2.056, 2.1, - -15., 1.067, 1.1, - }; - - Double_t parPipeTargetCentral[9] = { 0., 360., 2, - -15., 0., 1.1, - 15., 0., 1.1, - }; - - Double_t parPipeTargetUp[27] = { 0., 360., 8, - 15., 1.067, 1.1, - 54., 2.056, 2.1, - 55., 2.4, 2.5, - 95., 2.4, 2.5, - 96., 4.5, 4.6, - 145., 4.5, 4.6, - 155., 14.4, 14.5, - 215., 14.4, 14.5 - }; - - Double_t parPipeVacuumTargetDown[27] = { 0., 360., 8, - -215., 0., 17.4, - -183., 0., 17.4, - -173., 0., 4.5, - -96., 0., 4.5, - -95., 0., 2.4, - -55., 0., 2.4, - -54., 0., 2.056, - -15., 0., 1.067 - }; - - Double_t parPipeVacuumTargetCentral[9] = { 0., 360., 2, - -15., 0., 1.067, - 15., 0., 1.067, - }; - - Double_t parPipeVacuumTargetUp[27] = { 0., 360., 8, - 15., 0., 1.067, - 54., 0., 2.056, - 55., 0., 2.4, - 95., 0., 2.4, - 96., 0., 4.5, - 145., 0., 4.5, - 155., 0., 14.4, - 215., 0., 14.4 - }; - - TGeoPcon* pipeLeft = new TGeoPcon(parPipeLeft); - TGeoPcon* pipeCentral = new TGeoPcon(parPipeCentral); - pipeCentral->SetName("PIPE_CN"); - TGeoPcon* pipeRight = new TGeoPcon(parPipeRight); - TGeoPcon* pipeTargetDown = new TGeoPcon(parPipeTargetDown); - TGeoPcon* pipeTargetCentral = new TGeoPcon(parPipeTargetCentral); - pipeTargetCentral->SetName("TRG_CN"); - TGeoPcon* pipeTargetUp = new TGeoPcon(parPipeTargetUp); - - TGeoPcon* pipeVacuumLeft = new TGeoPcon(parPipeVacuumLeft); - TGeoPcon* pipeVacuumCentral = new TGeoPcon(parPipeVacuumCentral); - pipeVacuumCentral->SetName("PIPEV_CN"); - TGeoPcon* pipeVacuumRight = new TGeoPcon(parPipeVacuumRight); - TGeoPcon* pipeVacuumTargetDown = new TGeoPcon(parPipeVacuumTargetDown); - TGeoPcon* pipeVacuumTargetCentral = new TGeoPcon(parPipeVacuumTargetCentral); - pipeVacuumTargetCentral->SetName("TRGV_CN"); - TGeoPcon* pipeVacuumTargetUp = new TGeoPcon(parPipeVacuumTargetUp); - - TGeoRotation* r1 = new TGeoRotation("r1"); - r1->RotateX(90.); - r1->RegisterYourself(); - - TGeoCompositeShape* pipeCross = new TGeoCompositeShape("pipeCross", "(PIPE_CN+TRG_CN:r1) - (PIPEV_CN+TRGV_CN:r1)"); - TGeoCompositeShape* pipeVacuumCross = new TGeoCompositeShape("pipeVacuumCross", "PIPEV_CN+TRGV_CN:r1"); - - - TGeoVolume* volPipeLeft = new TGeoVolume("PipeLeft", pipeLeft, gGeoManager->GetMedium("steel")); - TGeoVolume* volPipeCross = new TGeoVolume("PipeCross", pipeCross, gGeoManager->GetMedium("Al+Be")); - TGeoVolume* volPipeRight = new TGeoVolume("PipeRight", pipeRight, gGeoManager->GetMedium("steel")); - TGeoVolume* volPipeTargetUp = new TGeoVolume("PipeTargetUp", pipeTargetUp, gGeoManager->GetMedium("steel")); - TGeoVolume* volPipeTargetDown = new TGeoVolume("PipeTargetDown", pipeTargetDown, gGeoManager->GetMedium("steel")); - - TGeoVolume* volPipeVacuumLeft = new TGeoVolume("PipeVacuumLeft", pipeVacuumLeft, gGeoManager->GetMedium("vacuum")); - TGeoVolume* volPipeVacuumCross = new TGeoVolume("PipeVacuumCross", pipeVacuumCross, gGeoManager->GetMedium("vacuum")); - TGeoVolume* volPipeVacuumRight = new TGeoVolume("PipeVacuumRight", pipeVacuumRight, gGeoManager->GetMedium("vacuum")); - TGeoVolume* volPipeVacuumTargetUp = new TGeoVolume("PipeVacuumTargetUp", pipeVacuumTargetUp, gGeoManager->GetMedium("vacuum")); - TGeoVolume* volPipeVacuumTargetDown = new TGeoVolume("PipeVacuumTargetDown", pipeVacuumTargetDown, gGeoManager->GetMedium("vacuum")); - - TGeoRotation rot; - rot.RotateX(90.); - - TGeoVolume* beamPipe = new TGeoVolumeAssembly("BeamPipe"); - beamPipe->AddNode(volPipeLeft, 0); - beamPipe->AddNode(volPipeRight, 0); - beamPipe->AddNode(volPipeVacuumLeft, 0); - beamPipe->AddNode(volPipeVacuumRight, 0); - beamPipe->AddNode(volPipeTargetUp, 0, new TGeoRotation(rot)); - beamPipe->AddNode(volPipeTargetDown, 0, new TGeoRotation(rot)); - beamPipe->AddNode(volPipeVacuumTargetUp, 0, new TGeoRotation(rot)); - beamPipe->AddNode(volPipeVacuumTargetDown, 0, new TGeoRotation(rot)); - beamPipe->AddNode(volPipeCross, 0); - beamPipe->AddNode(volPipeVacuumCross, 0); - - TGeoVolume* cave = gGeoManager->GetTopVolume(); - cave->AddNode(beamPipe, 1); + geobuild->createMedium(medVacuum); + geobuild->createMedium(medSteel); + geobuild->createMedium(medAlBe); + + Double_t parPipeLeft[9] = {0., 360., 2, -200., 7.9, 8., -32., 7.9, 8.}; + + // The central part is totally filled because of the crossing operations + Double_t parPipeCentral[12] = {0., 360., 3, -32., 0., 8., -2., 0., .9, 20., 0., .9}; + + Double_t parPipeRight[18] = { + 0., 360., 5, 20., .8873, .9, 22., 2.073, 2.1, 120., 2.05, 2.1, 300.1, 2.85, 2.9, 1050., 5.4, 5.5}; + + Double_t parPipeVacuumLeft[9] = {0., 360., 2, -200., 0., 7.9, -32., 0., 7.9}; + + Double_t parPipeVacuumCentral[12] = {0., 360., 3, -32., 0., 7.9, -2., 0., .873, 20., 0., .873}; + + Double_t parPipeVacuumRight[18] = { + 0., 360., 5, 20., 0., .873, 22., 0., 2.073, 120., 0., 2.05, 300.1, 0., 2.85, 1050., 0., 5.4}; + + Double_t parPipeTargetDown[27] = { + 0., 360., 8, -215., 17.4, 17.5, -183., 17.4, 17.5, -173., 4.5, 4.6, -96., 4.5, + 4.6, -95., 2.4, 2.5, -55., 2.4, 2.5, -54., 2.056, 2.1, -15., 1.067, 1.1, + }; + + Double_t parPipeTargetCentral[9] = { + 0., + 360., + 2, + -15., + 0., + 1.1, + 15., + 0., + 1.1, + }; + + Double_t parPipeTargetUp[27] = {0., 360., 8, 15., 1.067, 1.1, 54., 2.056, 2.1, 55., 2.4, 2.5, 95., 2.4, + 2.5, 96., 4.5, 4.6, 145., 4.5, 4.6, 155., 14.4, 14.5, 215., 14.4, 14.5}; + + Double_t parPipeVacuumTargetDown[27] = {0., 360., 8, -215., 0., 17.4, -183., 0., 17.4, + -173., 0., 4.5, -96., 0., 4.5, -95., 0., 2.4, + -55., 0., 2.4, -54., 0., 2.056, -15., 0., 1.067}; + + Double_t parPipeVacuumTargetCentral[9] = { + 0., + 360., + 2, + -15., + 0., + 1.067, + 15., + 0., + 1.067, + }; + + Double_t parPipeVacuumTargetUp[27] = {0., 360., 8, 15., 0., 1.067, 54., 0., 2.056, 55., 0., 2.4, 95., 0., + 2.4, 96., 0., 4.5, 145., 0., 4.5, 155., 0., 14.4, 215., 0., 14.4}; + + TGeoPcon* pipeLeft = new TGeoPcon(parPipeLeft); + TGeoPcon* pipeCentral = new TGeoPcon(parPipeCentral); + pipeCentral->SetName("PIPE_CN"); + TGeoPcon* pipeRight = new TGeoPcon(parPipeRight); + TGeoPcon* pipeTargetDown = new TGeoPcon(parPipeTargetDown); + TGeoPcon* pipeTargetCentral = new TGeoPcon(parPipeTargetCentral); + pipeTargetCentral->SetName("TRG_CN"); + TGeoPcon* pipeTargetUp = new TGeoPcon(parPipeTargetUp); + + TGeoPcon* pipeVacuumLeft = new TGeoPcon(parPipeVacuumLeft); + TGeoPcon* pipeVacuumCentral = new TGeoPcon(parPipeVacuumCentral); + pipeVacuumCentral->SetName("PIPEV_CN"); + TGeoPcon* pipeVacuumRight = new TGeoPcon(parPipeVacuumRight); + TGeoPcon* pipeVacuumTargetDown = new TGeoPcon(parPipeVacuumTargetDown); + TGeoPcon* pipeVacuumTargetCentral = new TGeoPcon(parPipeVacuumTargetCentral); + pipeVacuumTargetCentral->SetName("TRGV_CN"); + TGeoPcon* pipeVacuumTargetUp = new TGeoPcon(parPipeVacuumTargetUp); + + TGeoRotation* r1 = new TGeoRotation("r1"); + r1->RotateX(90.); + r1->RegisterYourself(); + + TGeoCompositeShape* pipeCross = new TGeoCompositeShape("pipeCross", "(PIPE_CN+TRG_CN:r1) - (PIPEV_CN+TRGV_CN:r1)"); + TGeoCompositeShape* pipeVacuumCross = new TGeoCompositeShape("pipeVacuumCross", "PIPEV_CN+TRGV_CN:r1"); + + TGeoVolume* volPipeLeft = new TGeoVolume("PipeLeft", pipeLeft, gGeoManager->GetMedium("steel")); + TGeoVolume* volPipeCross = new TGeoVolume("PipeCross", pipeCross, gGeoManager->GetMedium("Al+Be")); + TGeoVolume* volPipeRight = new TGeoVolume("PipeRight", pipeRight, gGeoManager->GetMedium("steel")); + TGeoVolume* volPipeTargetUp = new TGeoVolume("PipeTargetUp", pipeTargetUp, gGeoManager->GetMedium("steel")); + TGeoVolume* volPipeTargetDown = new TGeoVolume("PipeTargetDown", pipeTargetDown, gGeoManager->GetMedium("steel")); + + TGeoVolume* volPipeVacuumLeft = new TGeoVolume("PipeVacuumLeft", pipeVacuumLeft, gGeoManager->GetMedium("vacuum")); + TGeoVolume* volPipeVacuumCross = + new TGeoVolume("PipeVacuumCross", pipeVacuumCross, gGeoManager->GetMedium("vacuum")); + TGeoVolume* volPipeVacuumRight = + new TGeoVolume("PipeVacuumRight", pipeVacuumRight, gGeoManager->GetMedium("vacuum")); + TGeoVolume* volPipeVacuumTargetUp = + new TGeoVolume("PipeVacuumTargetUp", pipeVacuumTargetUp, gGeoManager->GetMedium("vacuum")); + TGeoVolume* volPipeVacuumTargetDown = + new TGeoVolume("PipeVacuumTargetDown", pipeVacuumTargetDown, gGeoManager->GetMedium("vacuum")); + + TGeoRotation rot; + rot.RotateX(90.); + + TGeoVolume* beamPipe = new TGeoVolumeAssembly("BeamPipe"); + beamPipe->AddNode(volPipeLeft, 0); + beamPipe->AddNode(volPipeRight, 0); + beamPipe->AddNode(volPipeVacuumLeft, 0); + beamPipe->AddNode(volPipeVacuumRight, 0); + beamPipe->AddNode(volPipeTargetUp, 0, new TGeoRotation(rot)); + beamPipe->AddNode(volPipeTargetDown, 0, new TGeoRotation(rot)); + beamPipe->AddNode(volPipeVacuumTargetUp, 0, new TGeoRotation(rot)); + beamPipe->AddNode(volPipeVacuumTargetDown, 0, new TGeoRotation(rot)); + beamPipe->AddNode(volPipeCross, 0); + beamPipe->AddNode(volPipeVacuumCross, 0); + + TGeoVolume* cave = gGeoManager->GetTopVolume(); + cave->AddNode(beamPipe, 1); } -FairModule* FairPipe::CloneModule() const -{ - return new FairPipe(*this); -} +FairModule* FairPipe::CloneModule() const { return new FairPipe(*this); } -ClassImp(FairPipe) +ClassImp(FairPipe); diff --git a/examples/common/passive/FairPipe.h b/examples/common/passive/FairPipe.h index 5d0fc4677e..56eee05ef1 100644 --- a/examples/common/passive/FairPipe.h +++ b/examples/common/passive/FairPipe.h @@ -1,21 +1,21 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef PIPE_H #define PIPE_H -#include "FairModule.h" // for FairModule +#include "FairModule.h" // for FairModule -#include // for FairPipe::Class, ClassDef, etc +#include // for FairPipe::Class, ClassDef, etc class FairPipe : public FairModule { public: - FairPipe(const char* name, const char* Title="PND Pipe"); + FairPipe(const char* name, const char* Title = "PND Pipe"); FairPipe(); virtual ~FairPipe(); @@ -25,7 +25,7 @@ class FairPipe : public FairModule private: FairPipe(const FairPipe& rhs); - ClassDef(FairPipe,1) //PNDPIPE + ClassDef(FairPipe, 1) // PNDPIPE }; -#endif //PIPE_H +#endif // PIPE_H diff --git a/examples/common/passive/FairTarget.cxx b/examples/common/passive/FairTarget.cxx index 4080dd5ae1..35f18ab8bb 100644 --- a/examples/common/passive/FairTarget.cxx +++ b/examples/common/passive/FairTarget.cxx @@ -1,45 +1,37 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* Generated by Together */ #include "FairTarget.h" -#include "FairGeoPassivePar.h" // for FairGeoPassivePar -#include "FairGeoTarget.h" // for FairGeoTarget +#include "FairGeoPassivePar.h" // for FairGeoPassivePar +#include "FairGeoTarget.h" // for FairGeoTarget -FairTarget::~FairTarget() -{ -} +FairTarget::~FairTarget() {} FairTarget::FairTarget() - : FairModule("FairTarget", "") -{ -} + : FairModule("FairTarget", "") +{} FairTarget::FairTarget(const char* name, const char* title) - : FairModule(name, title) -{ -} + : FairModule(name, title) +{} FairTarget::FairTarget(const FairTarget& rhs) - : FairModule(rhs) -{ -} + : FairModule(rhs) +{} void FairTarget::ConstructGeometry() { - FairGeoTarget* MGeo = new FairGeoTarget(); + FairGeoTarget* MGeo = new FairGeoTarget(); - ConstructASCIIGeometry(MGeo, "FairGeoPassivePar"); + ConstructASCIIGeometry(MGeo, "FairGeoPassivePar"); } -FairModule* FairTarget::CloneModule() const -{ - return new FairTarget(*this); -} +FairModule* FairTarget::CloneModule() const { return new FairTarget(*this); } -ClassImp(FairTarget) +ClassImp(FairTarget); diff --git a/examples/common/passive/FairTarget.h b/examples/common/passive/FairTarget.h index 2caa17bae8..a7539be408 100644 --- a/examples/common/passive/FairTarget.h +++ b/examples/common/passive/FairTarget.h @@ -1,21 +1,21 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef Target_H #define Target_H -#include "FairModule.h" // for FairModule +#include "FairModule.h" // for FairModule -#include // for FairTarget::Class, ClassDef, etc +#include // for FairTarget::Class, ClassDef, etc class FairTarget : public FairModule { public: - FairTarget(const char* name, const char* Title="PND Target"); + FairTarget(const char* name, const char* Title = "PND Target"); FairTarget(); virtual ~FairTarget(); virtual void ConstructGeometry(); @@ -24,8 +24,7 @@ class FairTarget : public FairModule private: FairTarget(const FairTarget& rhs); - ClassDef(FairTarget,1) + ClassDef(FairTarget, 1) }; -#endif //Target_H - +#endif // Target_H diff --git a/examples/simulation/Tutorial1/macros/eventDisplay.C b/examples/simulation/Tutorial1/macros/eventDisplay.C index 402e81972a..339c3c9bbf 100644 --- a/examples/simulation/Tutorial1/macros/eventDisplay.C +++ b/examples/simulation/Tutorial1/macros/eventDisplay.C @@ -1,32 +1,29 @@ void eventDisplay() { - //-----User Settings:----------------------------------------------- - TString InputFile ="tutorial1_TGeant3_pions.mc_p2.000_t0_n10.root"; - TString ParFile ="tutorial1_TGeant3_pions.params_p2.000_t0_n10.root"; - TString OutFile ="tst.root"; + //-----User Settings:----------------------------------------------- + TString InputFile = "tutorial1_TGeant3_pions.mc_p2.000_t0_n10.root"; + TString ParFile = "tutorial1_TGeant3_pions.params_p2.000_t0_n10.root"; + TString OutFile = "tst.root"; + // ----- Reconstruction run ------------------------------------------- + FairRunAna *fRun = new FairRunAna(); + FairFileSource *fFileSource = new FairFileSource(InputFile); + fRun->SetSource(fFileSource); + fRun->SetSink(new FairRootFileSink(OutFile.Data())); - // ----- Reconstruction run ------------------------------------------- - FairRunAna *fRun= new FairRunAna(); - FairFileSource *fFileSource = new FairFileSource(InputFile); - fRun->SetSource(fFileSource); - fRun->SetSink(new FairRootFileSink(OutFile.Data())); + FairRuntimeDb *rtdb = fRun->GetRuntimeDb(); + FairParRootFileIo *parInput1 = new FairParRootFileIo(); + parInput1->open(ParFile.Data()); + rtdb->setFirstInput(parInput1); - FairRuntimeDb* rtdb = fRun->GetRuntimeDb(); - FairParRootFileIo* parInput1 = new FairParRootFileIo(); - parInput1->open(ParFile.Data()); - rtdb->setFirstInput(parInput1); + FairEventManager *fMan = new FairEventManager(); - FairEventManager *fMan= new FairEventManager(); + //----------------------Traks and points ------------------------------------- + FairMCTracks *Track = new FairMCTracks("Monte-Carlo Tracks"); + // FairMCPointDraw *TorinoDetectorPoints = new FairMCPointDraw("FairTestDetectorPoint", kRed, kFullSquare); - //----------------------Traks and points ------------------------------------- - FairMCTracks *Track = new FairMCTracks("Monte-Carlo Tracks"); -// FairMCPointDraw *TorinoDetectorPoints = new FairMCPointDraw("FairTestDetectorPoint", kRed, kFullSquare); - - fMan->AddTask(Track); -// fMan->AddTask(TorinoDetectorPoints); - - - fMan->Init(); + fMan->AddTask(Track); + // fMan->AddTask(TorinoDetectorPoints); + fMan->Init(); } diff --git a/examples/simulation/Tutorial1/macros/load_all_libs.C b/examples/simulation/Tutorial1/macros/load_all_libs.C index 3663edc030..02ca20afec 100644 --- a/examples/simulation/Tutorial1/macros/load_all_libs.C +++ b/examples/simulation/Tutorial1/macros/load_all_libs.C @@ -1,40 +1,40 @@ void load_all_libs() { - gSystem->Load("libBaseMQ"); - gSystem->Load("libBase"); - gSystem->Load("libEventDisplay"); - gSystem->Load("libFairDataMatch"); - gSystem->Load("libFairMQExample1"); - gSystem->Load("libFairMQExample2"); - gSystem->Load("libFairMQExample4"); - gSystem->Load("libFairMQExample5"); - gSystem->Load("libFairMQExample6"); - gSystem->Load("libFairMQExample7"); - gSystem->Load("libFairMQExample8"); - gSystem->Load("libFairMQExampleShm"); - gSystem->Load("libfairmq_logger"); - gSystem->Load("libFairMQ"); - gSystem->Load("libFairMQTest"); - gSystem->Load("libFairRutherford"); - gSystem->Load("libFairTestDetector"); - gSystem->Load("libFairTools"); - gSystem->Load("libGeane"); - gSystem->Load("libGenericMQTuto"); - gSystem->Load("libGen"); - gSystem->Load("libGeoBase"); - gSystem->Load("libLmdMQSampler"); - gSystem->Load("libMbsAPI"); - gSystem->Load("libMbsTutorial"); - gSystem->Load("libMCStack"); - gSystem->Load("libParBase"); - gSystem->Load("libParMQ"); - gSystem->Load("libPassive"); - gSystem->Load("libPixel"); - gSystem->Load("libTrkBase"); - gSystem->Load("libTutorial1"); - gSystem->Load("libTutorial2"); - gSystem->Load("libTutorial4"); + gSystem->Load("libBaseMQ"); + gSystem->Load("libBase"); + gSystem->Load("libEventDisplay"); + gSystem->Load("libFairDataMatch"); + gSystem->Load("libFairMQExample1"); + gSystem->Load("libFairMQExample2"); + gSystem->Load("libFairMQExample4"); + gSystem->Load("libFairMQExample5"); + gSystem->Load("libFairMQExample6"); + gSystem->Load("libFairMQExample7"); + gSystem->Load("libFairMQExample8"); + gSystem->Load("libFairMQExampleShm"); + gSystem->Load("libfairmq_logger"); + gSystem->Load("libFairMQ"); + gSystem->Load("libFairMQTest"); + gSystem->Load("libFairRutherford"); + gSystem->Load("libFairTestDetector"); + gSystem->Load("libFairTools"); + gSystem->Load("libGeane"); + gSystem->Load("libGenericMQTuto"); + gSystem->Load("libGen"); + gSystem->Load("libGeoBase"); + gSystem->Load("libLmdMQSampler"); + gSystem->Load("libMbsAPI"); + gSystem->Load("libMbsTutorial"); + gSystem->Load("libMCStack"); + gSystem->Load("libParBase"); + gSystem->Load("libParMQ"); + gSystem->Load("libPassive"); + gSystem->Load("libPixel"); + gSystem->Load("libTrkBase"); + gSystem->Load("libTutorial1"); + gSystem->Load("libTutorial2"); + gSystem->Load("libTutorial4"); - cout << endl << endl; - cout << "Macro finished succesfully." << endl; + cout << endl << endl; + cout << "Macro finished succesfully." << endl; } diff --git a/examples/simulation/Tutorial1/macros/run_tutorial1.C b/examples/simulation/Tutorial1/macros/run_tutorial1.C index e9876abd6f..4e131a9d45 100644 --- a/examples/simulation/Tutorial1/macros/run_tutorial1.C +++ b/examples/simulation/Tutorial1/macros/run_tutorial1.C @@ -5,149 +5,147 @@ * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ -void run_tutorial1(Int_t nEvents = 10, TString mcEngine = "TGeant3", Bool_t isMT=true) +void run_tutorial1(Int_t nEvents = 10, TString mcEngine = "TGeant3", Bool_t isMT = true) { - TString dir = getenv("VMCWORKDIR"); - TString tutdir = dir + "/simulation/Tutorial1"; + TString dir = getenv("VMCWORKDIR"); + TString tutdir = dir + "/simulation/Tutorial1"; - TString tut_geomdir = dir + "/common/geometry"; - gSystem->Setenv("GEOMPATH",tut_geomdir.Data()); + TString tut_geomdir = dir + "/common/geometry"; + gSystem->Setenv("GEOMPATH", tut_geomdir.Data()); - TString tut_configdir = dir + "/common/gconfig"; - gSystem->Setenv("CONFIG_DIR",tut_configdir.Data()); + TString tut_configdir = dir + "/common/gconfig"; + gSystem->Setenv("CONFIG_DIR", tut_configdir.Data()); - TString partName[] = {"pions","eplus","proton"}; - Int_t partPdgC[] = { 211, 11, 2212}; - Int_t chosenPart = 0; + TString partName[] = {"pions", "eplus", "proton"}; + Int_t partPdgC[] = {211, 11, 2212}; + Int_t chosenPart = 0; - Double_t momentum = 2.; + Double_t momentum = 2.; - Double_t theta = 0.; + Double_t theta = 0.; - TString outDir = "./"; + TString outDir = "./"; - // Output file name - TString outFile = Form("%s/tutorial1_%s_%s.mc_p%1.3f_t%1.0f_n%d.root", - outDir.Data(), - mcEngine.Data(), - partName[chosenPart].Data(), - momentum, - theta, - nEvents); + // Output file name + TString outFile = Form("%s/tutorial1_%s_%s.mc_p%1.3f_t%1.0f_n%d.root", + outDir.Data(), + mcEngine.Data(), + partName[chosenPart].Data(), + momentum, + theta, + nEvents); - // Parameter file name - TString parFile = Form("%s/tutorial1_%s_%s.params_p%1.3f_t%1.0f_n%d.root", - outDir.Data(), - mcEngine.Data(), - partName[chosenPart].Data(), - momentum, - theta, - nEvents); - - TString geoFile = "geofile_" + mcEngine + "_full.root"; - - // In general, the following parts need not be touched - // ======================================================================== - - // ---- Debug option ------------------------------------------------- - gDebug = 0; - // ------------------------------------------------------------------------ - - // ----- Timer -------------------------------------------------------- - TStopwatch timer; - timer.Start(); - // ------------------------------------------------------------------------ - - // ----- Create simulation run ---------------------------------------- - FairRunSim* run = new FairRunSim(); - run->SetName(mcEngine); // Transport engine - // run->SetSimulationConfig(new FairVMCConfig()); - run->SetIsMT(isMT); // Multi-threading mode (Geant4 only) - run->SetSink(new FairRootFileSink(outFile)); // Output file - FairRuntimeDb* rtdb = run->GetRuntimeDb(); - // ------------------------------------------------------------------------ - - // ----- Create media ------------------------------------------------- - run->SetMaterials("media.geo"); // Materials - // ------------------------------------------------------------------------ - - // ----- Create geometry ---------------------------------------------- - - FairModule* cave= new FairCave("CAVE"); - cave->SetGeometryFileName("cave_vacuum.geo"); - run->AddModule(cave); - - FairDetector* tutdet = new FairTutorialDet1("TUTDET", kTRUE); - tutdet->SetGeometryFileName("double_sector.geo"); - run->AddModule(tutdet); - // ------------------------------------------------------------------------ - - // ----- Create PrimaryGenerator -------------------------------------- - FairPrimaryGenerator* primGen = new FairPrimaryGenerator(); - FairBoxGenerator* boxGen = new FairBoxGenerator(partPdgC[chosenPart], 1); - - boxGen->SetThetaRange ( theta, theta+0.01); - boxGen->SetPRange (momentum,momentum+0.01); - boxGen->SetPhiRange (0.,360.); - boxGen->SetDebug(kTRUE); - - primGen->AddGenerator(boxGen); - - - run->SetGenerator(primGen); - // ------------------------------------------------------------------------ - - // ----- Initialize simulation run ------------------------------------ - UInt_t randomSeed = 123456; - TRandom3 random(randomSeed); - gRandom = &random; - - run->Init(); - // ------------------------------------------------------------------------ - - // ----- Runtime database --------------------------------------------- - - Bool_t kParameterMerged = kTRUE; - FairParRootFileIo* parOut = new FairParRootFileIo(kParameterMerged); - parOut->open(parFile.Data()); - rtdb->setOutput(parOut); - rtdb->saveOutput(); - rtdb->print(); - // ------------------------------------------------------------------------ - - // ----- Start run ---------------------------------------------------- - run->Run(nEvents); - run->CreateGeometryFile(geoFile); - // ------------------------------------------------------------------------ - - // ----- Finish ------------------------------------------------------- - - cout << endl << endl; - - // Extract the maximal used memory an add is as Dart measurement - // This line is filtered by CTest and the value send to CDash - FairSystemInfo sysInfo; - Float_t maxMemory=sysInfo.GetMaxMemory(); - cout << ""; - cout << maxMemory; - cout << "" << endl; - - timer.Stop(); - Double_t rtime = timer.RealTime(); - Double_t ctime = timer.CpuTime(); - - Float_t cpuUsage=ctime/rtime; - cout << ""; - cout << cpuUsage; - cout << "" << endl; - - cout << endl << endl; - cout << "Output file is " << outFile << endl; - cout << "Parameter file is " << parFile << endl; - cout << "Real time " << rtime << " s, CPU time " << ctime - << "s" << endl << endl; - cout << "Macro finished successfully." << endl; - - // ------------------------------------------------------------------------ + // Parameter file name + TString parFile = Form("%s/tutorial1_%s_%s.params_p%1.3f_t%1.0f_n%d.root", + outDir.Data(), + mcEngine.Data(), + partName[chosenPart].Data(), + momentum, + theta, + nEvents); + + TString geoFile = "geofile_" + mcEngine + "_full.root"; + + // In general, the following parts need not be touched + // ======================================================================== + + // ---- Debug option ------------------------------------------------- + gDebug = 0; + // ------------------------------------------------------------------------ + + // ----- Timer -------------------------------------------------------- + TStopwatch timer; + timer.Start(); + // ------------------------------------------------------------------------ + + // ----- Create simulation run ---------------------------------------- + FairRunSim* run = new FairRunSim(); + run->SetName(mcEngine); // Transport engine + // run->SetSimulationConfig(new FairVMCConfig()); + run->SetIsMT(isMT); // Multi-threading mode (Geant4 only) + run->SetSink(new FairRootFileSink(outFile)); // Output file + FairRuntimeDb* rtdb = run->GetRuntimeDb(); + // ------------------------------------------------------------------------ + + // ----- Create media ------------------------------------------------- + run->SetMaterials("media.geo"); // Materials + // ------------------------------------------------------------------------ + + // ----- Create geometry ---------------------------------------------- + + FairModule* cave = new FairCave("CAVE"); + cave->SetGeometryFileName("cave_vacuum.geo"); + run->AddModule(cave); + + FairDetector* tutdet = new FairTutorialDet1("TUTDET", kTRUE); + tutdet->SetGeometryFileName("double_sector.geo"); + run->AddModule(tutdet); + // ------------------------------------------------------------------------ + + // ----- Create PrimaryGenerator -------------------------------------- + FairPrimaryGenerator* primGen = new FairPrimaryGenerator(); + FairBoxGenerator* boxGen = new FairBoxGenerator(partPdgC[chosenPart], 1); + + boxGen->SetThetaRange(theta, theta + 0.01); + boxGen->SetPRange(momentum, momentum + 0.01); + boxGen->SetPhiRange(0., 360.); + boxGen->SetDebug(kTRUE); + + primGen->AddGenerator(boxGen); + + run->SetGenerator(primGen); + // ------------------------------------------------------------------------ + + // ----- Initialize simulation run ------------------------------------ + UInt_t randomSeed = 123456; + TRandom3 random(randomSeed); + gRandom = &random; + + run->Init(); + // ------------------------------------------------------------------------ + + // ----- Runtime database --------------------------------------------- + + Bool_t kParameterMerged = kTRUE; + FairParRootFileIo* parOut = new FairParRootFileIo(kParameterMerged); + parOut->open(parFile.Data()); + rtdb->setOutput(parOut); + rtdb->saveOutput(); + rtdb->print(); + // ------------------------------------------------------------------------ + + // ----- Start run ---------------------------------------------------- + run->Run(nEvents); + run->CreateGeometryFile(geoFile); + // ------------------------------------------------------------------------ + + // ----- Finish ------------------------------------------------------- + + cout << endl << endl; + + // Extract the maximal used memory an add is as Dart measurement + // This line is filtered by CTest and the value send to CDash + FairSystemInfo sysInfo; + Float_t maxMemory = sysInfo.GetMaxMemory(); + cout << ""; + cout << maxMemory; + cout << "" << endl; + + timer.Stop(); + Double_t rtime = timer.RealTime(); + Double_t ctime = timer.CpuTime(); + + Float_t cpuUsage = ctime / rtime; + cout << ""; + cout << cpuUsage; + cout << "" << endl; + + cout << endl << endl; + cout << "Output file is " << outFile << endl; + cout << "Parameter file is " << parFile << endl; + cout << "Real time " << rtime << " s, CPU time " << ctime << "s" << endl << endl; + cout << "Macro finished successfully." << endl; + + // ------------------------------------------------------------------------ } diff --git a/examples/simulation/Tutorial1/macros/run_tutorial1_binary.C b/examples/simulation/Tutorial1/macros/run_tutorial1_binary.C index a3ef132d5b..f6704c527f 100644 --- a/examples/simulation/Tutorial1/macros/run_tutorial1_binary.C +++ b/examples/simulation/Tutorial1/macros/run_tutorial1_binary.C @@ -9,16 +9,18 @@ #if !defined(__CLING__) || defined(__ROOTCLING__) #include using namespace std; -#include -#include -#include "FairRunSim.h" -#include "FairRootFileSink.h" -#include "FairTutorialDet1.h" -#include "FairCave.h" #include "FairBoxGenerator.h" -#include "FairPrimaryGenerator.h" +#include "FairCave.h" #include "FairParRootFileIo.h" +#include "FairPrimaryGenerator.h" +#include "FairRootFileSink.h" +#include "FairRunSim.h" +#include "FairSimConfig.h" #include "FairSystemInfo.h" +#include "FairTutorialDet1.h" + +#include +#include #endif void run_tutorial1_main(const FairSimConfig& config); @@ -43,8 +45,8 @@ void run_tutorial1_main(const FairSimConfig& config) TString tut_configdir = dir + "/common/gconfig"; gSystem->Setenv("CONFIG_DIR", tut_configdir.Data()); - TString partName[] = { "pions", "eplus", "proton" }; - Int_t partPdgC[] = { 211, 11, 2212 }; + TString partName[] = {"pions", "eplus", "proton"}; + Int_t partPdgC[] = {211, 11, 2212}; Int_t chosenPart = 0; Double_t momentum = 2.; @@ -73,14 +75,14 @@ void run_tutorial1_main(const FairSimConfig& config) // ----- Create simulation run ---------------------------------------- FairRunSim run; - run.SetName(config.GetEngine()); // Transport engine - run.SetIsMT(config.IsMultiThreaded()); // Multi-threading mode (Geant4 only) - run.SetSink(new FairRootFileSink(outFile)); // Output file + run.SetName(config.GetEngine()); // Transport engine + run.SetIsMT(config.IsMultiThreaded()); // Multi-threading mode (Geant4 only) + run.SetSink(new FairRootFileSink(outFile)); // Output file FairRuntimeDb* rtdb = run.GetRuntimeDb(); // ------------------------------------------------------------------------ // ----- Create media ------------------------------------------------- - run.SetMaterials("media.geo"); // Materials + run.SetMaterials("media.geo"); // Materials // ------------------------------------------------------------------------ // ----- Create geometry ---------------------------------------------- diff --git a/examples/simulation/Tutorial1/macros/run_tutorial1_fastsim.C b/examples/simulation/Tutorial1/macros/run_tutorial1_fastsim.C index 1d03b3ef21..a1564d518a 100644 --- a/examples/simulation/Tutorial1/macros/run_tutorial1_fastsim.C +++ b/examples/simulation/Tutorial1/macros/run_tutorial1_fastsim.C @@ -5,158 +5,156 @@ * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ -void run_tutorial1_fastsim(Int_t nEvents = 10, TString mcEngine = "TGeant3", Bool_t isMT=false) +void run_tutorial1_fastsim(Int_t nEvents = 10, TString mcEngine = "TGeant3", Bool_t isMT = false) { - TString dir = getenv("VMCWORKDIR"); - TString tutdir = dir + "/simulation/Tutorial1"; + TString dir = getenv("VMCWORKDIR"); + TString tutdir = dir + "/simulation/Tutorial1"; - TString tut_geomdir = dir + "/common/geometry"; - gSystem->Setenv("GEOMPATH",tut_geomdir.Data()); + TString tut_geomdir = dir + "/common/geometry"; + gSystem->Setenv("GEOMPATH", tut_geomdir.Data()); - TString tut_configdir = dir + "/common/gconfig"; - gSystem->Setenv("CONFIG_DIR",tut_configdir.Data()); + TString tut_configdir = dir + "/common/gconfig"; + gSystem->Setenv("CONFIG_DIR", tut_configdir.Data()); - TString partName[] = {"pions","eplus","proton"}; - Int_t partPdgC[] = { 211, 11, 2212}; - Int_t chosenPart = 0; + TString partName[] = {"pions", "eplus", "proton"}; + Int_t partPdgC[] = {211, 11, 2212}; + Int_t chosenPart = 0; - Double_t momentum = 2.; + Double_t momentum = 2.; - Double_t theta = 0.; + Double_t theta = 0.; - TString outDir = "./"; + TString outDir = "./"; - // Output file name - TString outFile = Form("%s/tutorial1_%s_%s.mc_p%1.3f_t%1.0f_n%d.root", - outDir.Data(), - mcEngine.Data(), - partName[chosenPart].Data(), - momentum, - theta, - nEvents); + // Output file name + TString outFile = Form("%s/tutorial1_%s_%s.mc_p%1.3f_t%1.0f_n%d.root", + outDir.Data(), + mcEngine.Data(), + partName[chosenPart].Data(), + momentum, + theta, + nEvents); - // Parameter file name - TString parFile = Form("%s/tutorial1_%s_%s.params_p%1.3f_t%1.0f_n%d.root", - outDir.Data(), - mcEngine.Data(), - partName[chosenPart].Data(), - momentum, - theta, - nEvents); + // Parameter file name + TString parFile = Form("%s/tutorial1_%s_%s.params_p%1.3f_t%1.0f_n%d.root", + outDir.Data(), + mcEngine.Data(), + partName[chosenPart].Data(), + momentum, + theta, + nEvents); - TString geoFile = "geofile_" + mcEngine + "_full.root"; + TString geoFile = "geofile_" + mcEngine + "_full.root"; - // In general, the following parts need not be touched - // ======================================================================== + // In general, the following parts need not be touched + // ======================================================================== - // ---- Debug option ------------------------------------------------- - gDebug = 0; - // ------------------------------------------------------------------------ + // ---- Debug option ------------------------------------------------- + gDebug = 0; + // ------------------------------------------------------------------------ - // ----- Timer -------------------------------------------------------- - TStopwatch timer; - timer.Start(); - // ------------------------------------------------------------------------ + // ----- Timer -------------------------------------------------------- + TStopwatch timer; + timer.Start(); + // ------------------------------------------------------------------------ - // ----- Create simulation run ---------------------------------------- - FairRunSim* run = new FairRunSim(); - run->SetName(mcEngine); // Transport engine - run->SetIsMT(isMT); // Multi-threading mode (Geant4 only) - run->SetSink(new FairRootFileSink(outFile)); // Output file - FairRuntimeDb* rtdb = run->GetRuntimeDb(); - // ------------------------------------------------------------------------ + // ----- Create simulation run ---------------------------------------- + FairRunSim* run = new FairRunSim(); + run->SetName(mcEngine); // Transport engine + run->SetIsMT(isMT); // Multi-threading mode (Geant4 only) + run->SetSink(new FairRootFileSink(outFile)); // Output file + FairRuntimeDb* rtdb = run->GetRuntimeDb(); + // ------------------------------------------------------------------------ - // ----- Create media ------------------------------------------------- - run->SetMaterials("media.geo"); // Materials - // ------------------------------------------------------------------------ + // ----- Create media ------------------------------------------------- + run->SetMaterials("media.geo"); // Materials + // ------------------------------------------------------------------------ - // ----- Create geometry ---------------------------------------------- + // ----- Create geometry ---------------------------------------------- - FairModule* cave= new FairCave("CAVE"); - cave->SetGeometryFileName("cave_vacuum.geo"); - run->AddModule(cave); + FairModule* cave = new FairCave("CAVE"); + cave->SetGeometryFileName("cave_vacuum.geo"); + run->AddModule(cave); - FairDetector* fastsim = new FairFastSimExample("FastSim"); - run->AddModule(fastsim); + FairDetector* fastsim = new FairFastSimExample("FastSim"); + run->AddModule(fastsim); - FairDetector* fastsim2 = new FairFastSimExample2("FastSim2"); - run->AddModule(fastsim2); + FairDetector* fastsim2 = new FairFastSimExample2("FastSim2"); + run->AddModule(fastsim2); - FairDetector* tutdet = new FairTutorialDet1("TUTDET", kTRUE); - tutdet->SetGeometryFileName("double_sector.geo"); - run->AddModule(tutdet); - // ------------------------------------------------------------------------ + FairDetector* tutdet = new FairTutorialDet1("TUTDET", kTRUE); + tutdet->SetGeometryFileName("double_sector.geo"); + run->AddModule(tutdet); + // ------------------------------------------------------------------------ - // ----- Create PrimaryGenerator -------------------------------------- - FairPrimaryGenerator* primGen = new FairPrimaryGenerator(); - FairBoxGenerator* boxGen = new FairBoxGenerator(partPdgC[chosenPart], 1); + // ----- Create PrimaryGenerator -------------------------------------- + FairPrimaryGenerator* primGen = new FairPrimaryGenerator(); + FairBoxGenerator* boxGen = new FairBoxGenerator(partPdgC[chosenPart], 1); - boxGen->SetThetaRange ( theta, theta+0.01); - boxGen->SetPRange (momentum,momentum+0.01); - boxGen->SetPhiRange (0.,360.); - boxGen->SetDebug(kTRUE); + boxGen->SetThetaRange(theta, theta + 0.01); + boxGen->SetPRange(momentum, momentum + 0.01); + boxGen->SetPhiRange(0., 360.); + boxGen->SetDebug(kTRUE); - primGen->AddGenerator(boxGen); + primGen->AddGenerator(boxGen); + run->SetGenerator(primGen); + // ------------------------------------------------------------------------ - run->SetGenerator(primGen); - // ------------------------------------------------------------------------ + // ----- Initialize simulation run ------------------------------------ + UInt_t randomSeed = 123456; + TRandom3 random(randomSeed); + gRandom = &random; - // ----- Initialize simulation run ------------------------------------ - UInt_t randomSeed = 123456; - TRandom3 random(randomSeed); - gRandom = &random; + run->SetStoreTraj(kTRUE); - run->SetStoreTraj(kTRUE); + gLogger->SetLogScreenLevel("info"); - gLogger->SetLogScreenLevel("info"); + run->Init(); + // ------------------------------------------------------------------------ - run->Init(); - // ------------------------------------------------------------------------ + // ----- Runtime database --------------------------------------------- - // ----- Runtime database --------------------------------------------- + Bool_t kParameterMerged = kTRUE; + FairParRootFileIo* parOut = new FairParRootFileIo(kParameterMerged); + parOut->open(parFile.Data()); + rtdb->setOutput(parOut); + rtdb->saveOutput(); + rtdb->print(); + // ------------------------------------------------------------------------ + + // ----- Start run ---------------------------------------------------- + run->Run(nEvents); + run->CreateGeometryFile(geoFile); + // ------------------------------------------------------------------------ + + // ----- Finish ------------------------------------------------------- + + cout << endl << endl; + + // Extract the maximal used memory an add is as Dart measurement + // This line is filtered by CTest and the value send to CDash + FairSystemInfo sysInfo; + Float_t maxMemory = sysInfo.GetMaxMemory(); + cout << ""; + cout << maxMemory; + cout << "" << endl; - Bool_t kParameterMerged = kTRUE; - FairParRootFileIo* parOut = new FairParRootFileIo(kParameterMerged); - parOut->open(parFile.Data()); - rtdb->setOutput(parOut); - rtdb->saveOutput(); - rtdb->print(); - // ------------------------------------------------------------------------ + timer.Stop(); + Double_t rtime = timer.RealTime(); + Double_t ctime = timer.CpuTime(); - // ----- Start run ---------------------------------------------------- - run->Run(nEvents); - run->CreateGeometryFile(geoFile); - // ------------------------------------------------------------------------ - - // ----- Finish ------------------------------------------------------- - - cout << endl << endl; + Float_t cpuUsage = ctime / rtime; + cout << ""; + cout << cpuUsage; + cout << "" << endl; - // Extract the maximal used memory an add is as Dart measurement - // This line is filtered by CTest and the value send to CDash - FairSystemInfo sysInfo; - Float_t maxMemory=sysInfo.GetMaxMemory(); - cout << ""; - cout << maxMemory; - cout << "" << endl; + cout << endl << endl; + cout << "Output file is " << outFile << endl; + cout << "Parameter file is " << parFile << endl; + cout << "Real time " << rtime << " s, CPU time " << ctime << "s" << endl << endl; + cout << "Macro finished successfully." << endl; - timer.Stop(); - Double_t rtime = timer.RealTime(); - Double_t ctime = timer.CpuTime(); - - Float_t cpuUsage=ctime/rtime; - cout << ""; - cout << cpuUsage; - cout << "" << endl; - - cout << endl << endl; - cout << "Output file is " << outFile << endl; - cout << "Parameter file is " << parFile << endl; - cout << "Real time " << rtime << " s, CPU time " << ctime - << "s" << endl << endl; - cout << "Macro finished successfully." << endl; - - // ------------------------------------------------------------------------ + // ------------------------------------------------------------------------ } diff --git a/examples/simulation/Tutorial1/macros/run_tutorial1_mesh.C b/examples/simulation/Tutorial1/macros/run_tutorial1_mesh.C index 19793f4907..ba40e573ce 100644 --- a/examples/simulation/Tutorial1/macros/run_tutorial1_mesh.C +++ b/examples/simulation/Tutorial1/macros/run_tutorial1_mesh.C @@ -1,170 +1,165 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ void run_tutorial1_mesh(Int_t nEvents = 10, TString mcEngine = "TGeant3") { - - TString dir = getenv("VMCWORKDIR"); - TString tutdir = dir + "/simulation/Tutorial1"; - - TString tut_geomdir = dir + "/common/geometry"; - gSystem->Setenv("GEOMPATH",tut_geomdir.Data()); - - TString tut_configdir = dir + "/common/gconfig"; - gSystem->Setenv("CONFIG_DIR",tut_configdir.Data()); - - TString partName[] = {"pions","eplus","proton"}; - Int_t partPdgC[] = { 211, 11, 2212}; - Int_t chosenPart = 0; - - Double_t momentum = 2.; - - Double_t theta = 0.; - - TString outDir = "./"; - - // Output file name - TString outFile = Form("%s/tutorial1_mesh%s_%s.mc_p%1.3f_t%1.0f_n%d.root", - outDir.Data(), - mcEngine.Data(), - partName[chosenPart].Data(), - momentum, - theta, - nEvents); - - // Parameter file name - TString parFile = Form("%s/tutorial1_mesh%s_%s.params_p%1.3f_t%1.0f_n%d.root", - outDir.Data(), - mcEngine.Data(), - partName[chosenPart].Data(), - momentum, - theta, - nEvents); - - // In general, the following parts need not be touched - // ======================================================================== - - // ---- Debug option ------------------------------------------------- - gDebug = 0; - // ------------------------------------------------------------------------ - - // ----- Timer -------------------------------------------------------- - TStopwatch timer; - timer.Start(); - // ------------------------------------------------------------------------ - - // ----- Create simulation run ---------------------------------------- - FairRunSim* run = new FairRunSim(); - run->SetName(mcEngine); // Transport engine - run->SetSink(new FairRootFileSink(outFile)); // Output file - FairRuntimeDb* rtdb = run->GetRuntimeDb(); - // ------------------------------------------------------------------------ - - // ----- Create media ------------------------------------------------- - run->SetMaterials("media.geo"); // Materials - // ------------------------------------------------------------------------ - - // ----- Create geometry ---------------------------------------------- - - FairModule* cave= new FairCave("CAVE"); - cave->SetGeometryFileName("cave_vacuum.geo"); - run->AddModule(cave); - - FairDetector* tutdet = new FairTutorialDet1("TUTDET", kTRUE); - tutdet->SetGeometryFileName("double_sector.geo"); - run->AddModule(tutdet); - // ------------------------------------------------------------------------ - - // ----- Create PrimaryGenerator -------------------------------------- - FairPrimaryGenerator* primGen = new FairPrimaryGenerator(); - FairBoxGenerator* boxGen = new FairBoxGenerator(partPdgC[chosenPart], 1); - - boxGen->SetThetaRange ( theta, theta+55.); - boxGen->SetPRange (momentum,momentum+0.01); - boxGen->SetPhiRange (0.,360.); - boxGen->SetCosTheta(); - boxGen->SetDebug(kTRUE); - - primGen->AddGenerator(boxGen); - - - run->SetGenerator(primGen); - // ------------------------------------------------------------------------ - - - run->SetStoreTraj(kFALSE); // to store particle trajectories - - run->SetRadGridRegister(kTRUE); // activate RadGridManager - - // define two example meshs for dosimetry - FairMesh* aMesh1 = new FairMesh("test1"); - aMesh1->SetX(-60,60,200); - aMesh1->SetY(-60,60,200); - aMesh1->SetZ(29.,31.,1); - - FairMesh* aMesh2 = new FairMesh("test2"); - aMesh2->SetX(-20,20,20); - aMesh2->SetY(-20,20,20); - aMesh2->SetZ(-5.0,5.0,1); - - aMesh1->print(); - aMesh2->print(); - - run->AddMesh( aMesh1 ); - run->AddMesh( aMesh2 ); - - // ----- Initialize simulation run ------------------------------------ - run->Init(); - FairRadGridManager::Instance()->SetOutputFileName("radGridResults.root"); - // ------------------------------------------------------------------------ - - // ----- Runtime database --------------------------------------------- - - Bool_t kParameterMerged = kTRUE; - FairParRootFileIo* parOut = new FairParRootFileIo(kParameterMerged); - parOut->open(parFile.Data()); - rtdb->setOutput(parOut); - rtdb->saveOutput(); - rtdb->print(); - // ------------------------------------------------------------------------ - - // ----- Start run ---------------------------------------------------- - run->Run(nEvents); - // ------------------------------------------------------------------------ - - // ----- Finish ------------------------------------------------------- - - cout << endl << endl; - - // Extract the maximal used memory an add is as Dart measurement - // This line is filtered by CTest and the value send to CDash - FairSystemInfo sysInfo; - Float_t maxMemory=sysInfo.GetMaxMemory(); - cout << ""; - cout << maxMemory; - cout << "" << endl; - - timer.Stop(); - Double_t rtime = timer.RealTime(); - Double_t ctime = timer.CpuTime(); - - Float_t cpuUsage=ctime/rtime; - cout << ""; - cout << cpuUsage; - cout << "" << endl; - - cout << endl << endl; - cout << "Output file is " << outFile << endl; - cout << "Parameter file is " << parFile << endl; - cout << "Real time " << rtime << " s, CPU time " << ctime - << "s" << endl << endl; - cout << "Macro finished successfully." << endl; - - // ------------------------------------------------------------------------ -} + TString dir = getenv("VMCWORKDIR"); + TString tutdir = dir + "/simulation/Tutorial1"; + + TString tut_geomdir = dir + "/common/geometry"; + gSystem->Setenv("GEOMPATH", tut_geomdir.Data()); + + TString tut_configdir = dir + "/common/gconfig"; + gSystem->Setenv("CONFIG_DIR", tut_configdir.Data()); + + TString partName[] = {"pions", "eplus", "proton"}; + Int_t partPdgC[] = {211, 11, 2212}; + Int_t chosenPart = 0; + + Double_t momentum = 2.; + + Double_t theta = 0.; + + TString outDir = "./"; + + // Output file name + TString outFile = Form("%s/tutorial1_mesh%s_%s.mc_p%1.3f_t%1.0f_n%d.root", + outDir.Data(), + mcEngine.Data(), + partName[chosenPart].Data(), + momentum, + theta, + nEvents); + + // Parameter file name + TString parFile = Form("%s/tutorial1_mesh%s_%s.params_p%1.3f_t%1.0f_n%d.root", + outDir.Data(), + mcEngine.Data(), + partName[chosenPart].Data(), + momentum, + theta, + nEvents); + + // In general, the following parts need not be touched + // ======================================================================== + + // ---- Debug option ------------------------------------------------- + gDebug = 0; + // ------------------------------------------------------------------------ + + // ----- Timer -------------------------------------------------------- + TStopwatch timer; + timer.Start(); + // ------------------------------------------------------------------------ + + // ----- Create simulation run ---------------------------------------- + FairRunSim* run = new FairRunSim(); + run->SetName(mcEngine); // Transport engine + run->SetSink(new FairRootFileSink(outFile)); // Output file + FairRuntimeDb* rtdb = run->GetRuntimeDb(); + // ------------------------------------------------------------------------ + // ----- Create media ------------------------------------------------- + run->SetMaterials("media.geo"); // Materials + // ------------------------------------------------------------------------ + + // ----- Create geometry ---------------------------------------------- + + FairModule* cave = new FairCave("CAVE"); + cave->SetGeometryFileName("cave_vacuum.geo"); + run->AddModule(cave); + + FairDetector* tutdet = new FairTutorialDet1("TUTDET", kTRUE); + tutdet->SetGeometryFileName("double_sector.geo"); + run->AddModule(tutdet); + // ------------------------------------------------------------------------ + + // ----- Create PrimaryGenerator -------------------------------------- + FairPrimaryGenerator* primGen = new FairPrimaryGenerator(); + FairBoxGenerator* boxGen = new FairBoxGenerator(partPdgC[chosenPart], 1); + + boxGen->SetThetaRange(theta, theta + 55.); + boxGen->SetPRange(momentum, momentum + 0.01); + boxGen->SetPhiRange(0., 360.); + boxGen->SetCosTheta(); + boxGen->SetDebug(kTRUE); + + primGen->AddGenerator(boxGen); + + run->SetGenerator(primGen); + // ------------------------------------------------------------------------ + + run->SetStoreTraj(kFALSE); // to store particle trajectories + + run->SetRadGridRegister(kTRUE); // activate RadGridManager + + // define two example meshs for dosimetry + FairMesh* aMesh1 = new FairMesh("test1"); + aMesh1->SetX(-60, 60, 200); + aMesh1->SetY(-60, 60, 200); + aMesh1->SetZ(29., 31., 1); + + FairMesh* aMesh2 = new FairMesh("test2"); + aMesh2->SetX(-20, 20, 20); + aMesh2->SetY(-20, 20, 20); + aMesh2->SetZ(-5.0, 5.0, 1); + + aMesh1->print(); + aMesh2->print(); + + run->AddMesh(aMesh1); + run->AddMesh(aMesh2); + + // ----- Initialize simulation run ------------------------------------ + run->Init(); + FairRadGridManager::Instance()->SetOutputFileName("radGridResults.root"); + // ------------------------------------------------------------------------ + + // ----- Runtime database --------------------------------------------- + + Bool_t kParameterMerged = kTRUE; + FairParRootFileIo* parOut = new FairParRootFileIo(kParameterMerged); + parOut->open(parFile.Data()); + rtdb->setOutput(parOut); + rtdb->saveOutput(); + rtdb->print(); + // ------------------------------------------------------------------------ + + // ----- Start run ---------------------------------------------------- + run->Run(nEvents); + // ------------------------------------------------------------------------ + + // ----- Finish ------------------------------------------------------- + + cout << endl << endl; + + // Extract the maximal used memory an add is as Dart measurement + // This line is filtered by CTest and the value send to CDash + FairSystemInfo sysInfo; + Float_t maxMemory = sysInfo.GetMaxMemory(); + cout << ""; + cout << maxMemory; + cout << "" << endl; + + timer.Stop(); + Double_t rtime = timer.RealTime(); + Double_t ctime = timer.CpuTime(); + + Float_t cpuUsage = ctime / rtime; + cout << ""; + cout << cpuUsage; + cout << "" << endl; + + cout << endl << endl; + cout << "Output file is " << outFile << endl; + cout << "Parameter file is " << parFile << endl; + cout << "Real time " << rtime << " s, CPU time " << ctime << "s" << endl << endl; + cout << "Macro finished successfully." << endl; + + // ------------------------------------------------------------------------ +} diff --git a/examples/simulation/Tutorial1/macros/run_tutorial1_pythia6.C b/examples/simulation/Tutorial1/macros/run_tutorial1_pythia6.C index 0442acccc8..029ca1fbcd 100644 --- a/examples/simulation/Tutorial1/macros/run_tutorial1_pythia6.C +++ b/examples/simulation/Tutorial1/macros/run_tutorial1_pythia6.C @@ -1,153 +1,149 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ void run_tutorial1_pythia6(Int_t nEvents = 10, TString mcEngine = "TGeant3") { - - TString dir = getenv("VMCWORKDIR"); - TString tutdir = dir + "/simulation/Tutorial1"; - - TString tut_geomdir = dir + "/common/geometry"; - gSystem->Setenv("GEOMPATH",tut_geomdir.Data()); - - TString tut_configdir = dir + "/common/gconfig"; - gSystem->Setenv("CONFIG_DIR",tut_configdir.Data()); - - TString pythia6Config(tut_configdir + "/DecayConfig.C"); - - TString partName[] = {"pions","eplus","proton"}; - Int_t partPdgC[] = { 211, 11, 2212}; - Int_t chosenPart = 0; - - Double_t momentum = 2.; - - Double_t theta = 0.; - - TString outDir = "./"; - - // Output file name - TString outFile = Form("%s/tutorial1_pythia6_%s_%s.mc_p%1.3f_t%1.0f_n%d.root", - outDir.Data(), - mcEngine.Data(), - partName[chosenPart].Data(), - momentum, - theta, - nEvents); - - // Parameter file name - TString parFile = Form("%s/tutorial1_pythia6_%s_%s.params_p%1.3f_t%1.0f_n%d.root", - outDir.Data(), - mcEngine.Data(), - partName[chosenPart].Data(), - momentum, - theta, - nEvents); - - TString geoFile = outDir + "geofile_pythia6_" + mcEngine + "_full.root"; - - // In general, the following parts need not be touched - // ======================================================================== - - // ---- Debug option ------------------------------------------------- - gDebug = 0; - // ------------------------------------------------------------------------ - - // ----- Timer -------------------------------------------------------- - TStopwatch timer; - timer.Start(); - // ------------------------------------------------------------------------ - - // ----- Create simulation run ---------------------------------------- - FairRunSim* run = new FairRunSim(); - run->SetName(mcEngine); // Transport engine - run->SetSink(new FairRootFileSink(outFile)); // Output file - run->SetPythiaDecayer(pythia6Config); // Define Pythia6 as decayer - - FairRuntimeDb* rtdb = run->GetRuntimeDb(); - // ------------------------------------------------------------------------ - - // ----- Create media ------------------------------------------------- - run->SetMaterials("media.geo"); // Materials - // ------------------------------------------------------------------------ - - // ----- Create geometry ---------------------------------------------- - - FairModule* cave= new FairCave("CAVE"); - cave->SetGeometryFileName("cave_vacuum.geo"); - run->AddModule(cave); - - FairDetector* tutdet = new FairTutorialDet1("TUTDET", kTRUE); - tutdet->SetGeometryFileName("double_sector.geo"); - run->AddModule(tutdet); - // ------------------------------------------------------------------------ - - // ----- Create PrimaryGenerator -------------------------------------- - FairPrimaryGenerator* primGen = new FairPrimaryGenerator(); - FairBoxGenerator* boxGen = new FairBoxGenerator(partPdgC[chosenPart], 1); - - boxGen->SetThetaRange ( theta, theta+0.01); - boxGen->SetPRange (momentum,momentum+0.01); - boxGen->SetPhiRange (0.,360.); - boxGen->SetDebug(kTRUE); - - primGen->AddGenerator(boxGen); - - - run->SetGenerator(primGen); - // ------------------------------------------------------------------------ - - // ----- Initialize simulation run ------------------------------------ - run->Init(); - // ------------------------------------------------------------------------ - - // ----- Runtime database --------------------------------------------- - - Bool_t kParameterMerged = kTRUE; - FairParRootFileIo* parOut = new FairParRootFileIo(kParameterMerged); - parOut->open(parFile.Data()); - rtdb->setOutput(parOut); - rtdb->saveOutput(); - rtdb->print(); - // ------------------------------------------------------------------------ - - // ----- Start run ---------------------------------------------------- - run->Run(nEvents); - run->CreateGeometryFile(geoFile); - // ------------------------------------------------------------------------ - - // ----- Finish ------------------------------------------------------- - - cout << endl << endl; - - // Extract the maximal used memory an add is as Dart measurement - // This line is filtered by CTest and the value send to CDash - FairSystemInfo sysInfo; - Float_t maxMemory=sysInfo.GetMaxMemory(); - cout << ""; - cout << maxMemory; - cout << "" << endl; - - timer.Stop(); - Double_t rtime = timer.RealTime(); - Double_t ctime = timer.CpuTime(); - - Float_t cpuUsage=ctime/rtime; - cout << ""; - cout << cpuUsage; - cout << "" << endl; - - cout << endl << endl; - cout << "Output file is " << outFile << endl; - cout << "Parameter file is " << parFile << endl; - cout << "Real time " << rtime << " s, CPU time " << ctime - << "s" << endl << endl; - cout << "Macro finished successfully." << endl; - - // ------------------------------------------------------------------------ -} + TString dir = getenv("VMCWORKDIR"); + TString tutdir = dir + "/simulation/Tutorial1"; + + TString tut_geomdir = dir + "/common/geometry"; + gSystem->Setenv("GEOMPATH", tut_geomdir.Data()); + + TString tut_configdir = dir + "/common/gconfig"; + gSystem->Setenv("CONFIG_DIR", tut_configdir.Data()); + + TString pythia6Config(tut_configdir + "/DecayConfig.C"); + + TString partName[] = {"pions", "eplus", "proton"}; + Int_t partPdgC[] = {211, 11, 2212}; + Int_t chosenPart = 0; + + Double_t momentum = 2.; + + Double_t theta = 0.; + + TString outDir = "./"; + + // Output file name + TString outFile = Form("%s/tutorial1_pythia6_%s_%s.mc_p%1.3f_t%1.0f_n%d.root", + outDir.Data(), + mcEngine.Data(), + partName[chosenPart].Data(), + momentum, + theta, + nEvents); + + // Parameter file name + TString parFile = Form("%s/tutorial1_pythia6_%s_%s.params_p%1.3f_t%1.0f_n%d.root", + outDir.Data(), + mcEngine.Data(), + partName[chosenPart].Data(), + momentum, + theta, + nEvents); + + TString geoFile = outDir + "geofile_pythia6_" + mcEngine + "_full.root"; + + // In general, the following parts need not be touched + // ======================================================================== + + // ---- Debug option ------------------------------------------------- + gDebug = 0; + // ------------------------------------------------------------------------ + + // ----- Timer -------------------------------------------------------- + TStopwatch timer; + timer.Start(); + // ------------------------------------------------------------------------ + + // ----- Create simulation run ---------------------------------------- + FairRunSim* run = new FairRunSim(); + run->SetName(mcEngine); // Transport engine + run->SetSink(new FairRootFileSink(outFile)); // Output file + run->SetPythiaDecayer(pythia6Config); // Define Pythia6 as decayer + FairRuntimeDb* rtdb = run->GetRuntimeDb(); + // ------------------------------------------------------------------------ + + // ----- Create media ------------------------------------------------- + run->SetMaterials("media.geo"); // Materials + // ------------------------------------------------------------------------ + + // ----- Create geometry ---------------------------------------------- + + FairModule* cave = new FairCave("CAVE"); + cave->SetGeometryFileName("cave_vacuum.geo"); + run->AddModule(cave); + + FairDetector* tutdet = new FairTutorialDet1("TUTDET", kTRUE); + tutdet->SetGeometryFileName("double_sector.geo"); + run->AddModule(tutdet); + // ------------------------------------------------------------------------ + + // ----- Create PrimaryGenerator -------------------------------------- + FairPrimaryGenerator* primGen = new FairPrimaryGenerator(); + FairBoxGenerator* boxGen = new FairBoxGenerator(partPdgC[chosenPart], 1); + + boxGen->SetThetaRange(theta, theta + 0.01); + boxGen->SetPRange(momentum, momentum + 0.01); + boxGen->SetPhiRange(0., 360.); + boxGen->SetDebug(kTRUE); + + primGen->AddGenerator(boxGen); + + run->SetGenerator(primGen); + // ------------------------------------------------------------------------ + + // ----- Initialize simulation run ------------------------------------ + run->Init(); + // ------------------------------------------------------------------------ + + // ----- Runtime database --------------------------------------------- + + Bool_t kParameterMerged = kTRUE; + FairParRootFileIo* parOut = new FairParRootFileIo(kParameterMerged); + parOut->open(parFile.Data()); + rtdb->setOutput(parOut); + rtdb->saveOutput(); + rtdb->print(); + // ------------------------------------------------------------------------ + + // ----- Start run ---------------------------------------------------- + run->Run(nEvents); + run->CreateGeometryFile(geoFile); + // ------------------------------------------------------------------------ + + // ----- Finish ------------------------------------------------------- + + cout << endl << endl; + + // Extract the maximal used memory an add is as Dart measurement + // This line is filtered by CTest and the value send to CDash + FairSystemInfo sysInfo; + Float_t maxMemory = sysInfo.GetMaxMemory(); + cout << ""; + cout << maxMemory; + cout << "" << endl; + + timer.Stop(); + Double_t rtime = timer.RealTime(); + Double_t ctime = timer.CpuTime(); + + Float_t cpuUsage = ctime / rtime; + cout << ""; + cout << cpuUsage; + cout << "" << endl; + + cout << endl << endl; + cout << "Output file is " << outFile << endl; + cout << "Parameter file is " << parFile << endl; + cout << "Real time " << rtime << " s, CPU time " << ctime << "s" << endl << endl; + cout << "Macro finished successfully." << endl; + + // ------------------------------------------------------------------------ +} diff --git a/examples/simulation/Tutorial1/macros/run_tutorial1_pythia8.C b/examples/simulation/Tutorial1/macros/run_tutorial1_pythia8.C index a14c4a7f1b..f7b741f56d 100644 --- a/examples/simulation/Tutorial1/macros/run_tutorial1_pythia8.C +++ b/examples/simulation/Tutorial1/macros/run_tutorial1_pythia8.C @@ -1,153 +1,149 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ void run_tutorial1_pythia8(Int_t nEvents = 10, TString mcEngine = "TGeant3") { - - TString dir = getenv("VMCWORKDIR"); - TString tutdir = dir + "/simulation/Tutorial1"; - - TString tut_geomdir = dir + "/common/geometry"; - gSystem->Setenv("GEOMPATH",tut_geomdir.Data()); - - TString tut_configdir = dir + "/common/gconfig"; - gSystem->Setenv("CONFIG_DIR",tut_configdir.Data()); - - TString pythia8Config(tut_configdir + "/DecayConfigPythia8.C"); - - TString partName[] = {"pions","eplus","proton"}; - Int_t partPdgC[] = { 211, 11, 2212}; - Int_t chosenPart = 0; - - Double_t momentum = 2.; - - Double_t theta = 0.; - - TString outDir = "./"; - - // Output file name - TString outFile = Form("%s/tutorial1_pythia8_%s_%s.mc_p%1.3f_t%1.0f_n%d.root", - outDir.Data(), - mcEngine.Data(), - partName[chosenPart].Data(), - momentum, - theta, - nEvents); - - // Parameter file name - TString parFile = Form("%s/tutorial1_pythia8_%s_%s.params_p%1.3f_t%1.0f_n%d.root", - outDir.Data(), - mcEngine.Data(), - partName[chosenPart].Data(), - momentum, - theta, - nEvents); - - TString geoFile = outDir + "geofile_pythia8_" + mcEngine + "_full.root"; - - // In general, the following parts need not be touched - // ======================================================================== - - // ---- Debug option ------------------------------------------------- - gDebug = 0; - // ------------------------------------------------------------------------ - - // ----- Timer -------------------------------------------------------- - TStopwatch timer; - timer.Start(); - // ------------------------------------------------------------------------ - - // ----- Create simulation run ---------------------------------------- - FairRunSim* run = new FairRunSim(); - run->SetName(mcEngine); // Transport engine - run->SetSink(new FairRootFileSink(outFile)); // Output file - run->SetPythiaDecayer(pythia8Config); // Define Pythia8 as decayer - - FairRuntimeDb* rtdb = run->GetRuntimeDb(); - // ------------------------------------------------------------------------ - - // ----- Create media ------------------------------------------------- - run->SetMaterials("media.geo"); // Materials - // ------------------------------------------------------------------------ - - // ----- Create geometry ---------------------------------------------- - - FairModule* cave= new FairCave("CAVE"); - cave->SetGeometryFileName("cave_vacuum.geo"); - run->AddModule(cave); - - FairDetector* tutdet = new FairTutorialDet1("TUTDET", kTRUE); - tutdet->SetGeometryFileName("double_sector.geo"); - run->AddModule(tutdet); - // ------------------------------------------------------------------------ - - // ----- Create PrimaryGenerator -------------------------------------- - FairPrimaryGenerator* primGen = new FairPrimaryGenerator(); - FairBoxGenerator* boxGen = new FairBoxGenerator(partPdgC[chosenPart], 1); - - boxGen->SetThetaRange ( theta, theta+0.01); - boxGen->SetPRange (momentum,momentum+0.01); - boxGen->SetPhiRange (0.,360.); - boxGen->SetDebug(kTRUE); - - primGen->AddGenerator(boxGen); - - - run->SetGenerator(primGen); - // ------------------------------------------------------------------------ - - // ----- Initialize simulation run ------------------------------------ - run->Init(); - // ------------------------------------------------------------------------ - - // ----- Runtime database --------------------------------------------- - - Bool_t kParameterMerged = kTRUE; - FairParRootFileIo* parOut = new FairParRootFileIo(kParameterMerged); - parOut->open(parFile.Data()); - rtdb->setOutput(parOut); - rtdb->saveOutput(); - rtdb->print(); - // ------------------------------------------------------------------------ - - // ----- Start run ---------------------------------------------------- - run->Run(nEvents); - run->CreateGeometryFile(geoFile); - // ------------------------------------------------------------------------ - - // ----- Finish ------------------------------------------------------- - - cout << endl << endl; - - // Extract the maximal used memory an add is as Dart measurement - // This line is filtered by CTest and the value send to CDash - FairSystemInfo sysInfo; - Float_t maxMemory=sysInfo.GetMaxMemory(); - cout << ""; - cout << maxMemory; - cout << "" << endl; - - timer.Stop(); - Double_t rtime = timer.RealTime(); - Double_t ctime = timer.CpuTime(); - - Float_t cpuUsage=ctime/rtime; - cout << ""; - cout << cpuUsage; - cout << "" << endl; - - cout << endl << endl; - cout << "Output file is " << outFile << endl; - cout << "Parameter file is " << parFile << endl; - cout << "Real time " << rtime << " s, CPU time " << ctime - << "s" << endl << endl; - cout << "Macro finished successfully." << endl; - - // ------------------------------------------------------------------------ -} + TString dir = getenv("VMCWORKDIR"); + TString tutdir = dir + "/simulation/Tutorial1"; + + TString tut_geomdir = dir + "/common/geometry"; + gSystem->Setenv("GEOMPATH", tut_geomdir.Data()); + + TString tut_configdir = dir + "/common/gconfig"; + gSystem->Setenv("CONFIG_DIR", tut_configdir.Data()); + + TString pythia8Config(tut_configdir + "/DecayConfigPythia8.C"); + + TString partName[] = {"pions", "eplus", "proton"}; + Int_t partPdgC[] = {211, 11, 2212}; + Int_t chosenPart = 0; + + Double_t momentum = 2.; + + Double_t theta = 0.; + + TString outDir = "./"; + + // Output file name + TString outFile = Form("%s/tutorial1_pythia8_%s_%s.mc_p%1.3f_t%1.0f_n%d.root", + outDir.Data(), + mcEngine.Data(), + partName[chosenPart].Data(), + momentum, + theta, + nEvents); + + // Parameter file name + TString parFile = Form("%s/tutorial1_pythia8_%s_%s.params_p%1.3f_t%1.0f_n%d.root", + outDir.Data(), + mcEngine.Data(), + partName[chosenPart].Data(), + momentum, + theta, + nEvents); + + TString geoFile = outDir + "geofile_pythia8_" + mcEngine + "_full.root"; + + // In general, the following parts need not be touched + // ======================================================================== + + // ---- Debug option ------------------------------------------------- + gDebug = 0; + // ------------------------------------------------------------------------ + + // ----- Timer -------------------------------------------------------- + TStopwatch timer; + timer.Start(); + // ------------------------------------------------------------------------ + + // ----- Create simulation run ---------------------------------------- + FairRunSim* run = new FairRunSim(); + run->SetName(mcEngine); // Transport engine + run->SetSink(new FairRootFileSink(outFile)); // Output file + run->SetPythiaDecayer(pythia8Config); // Define Pythia8 as decayer + FairRuntimeDb* rtdb = run->GetRuntimeDb(); + // ------------------------------------------------------------------------ + + // ----- Create media ------------------------------------------------- + run->SetMaterials("media.geo"); // Materials + // ------------------------------------------------------------------------ + + // ----- Create geometry ---------------------------------------------- + + FairModule* cave = new FairCave("CAVE"); + cave->SetGeometryFileName("cave_vacuum.geo"); + run->AddModule(cave); + + FairDetector* tutdet = new FairTutorialDet1("TUTDET", kTRUE); + tutdet->SetGeometryFileName("double_sector.geo"); + run->AddModule(tutdet); + // ------------------------------------------------------------------------ + + // ----- Create PrimaryGenerator -------------------------------------- + FairPrimaryGenerator* primGen = new FairPrimaryGenerator(); + FairBoxGenerator* boxGen = new FairBoxGenerator(partPdgC[chosenPart], 1); + + boxGen->SetThetaRange(theta, theta + 0.01); + boxGen->SetPRange(momentum, momentum + 0.01); + boxGen->SetPhiRange(0., 360.); + boxGen->SetDebug(kTRUE); + + primGen->AddGenerator(boxGen); + + run->SetGenerator(primGen); + // ------------------------------------------------------------------------ + + // ----- Initialize simulation run ------------------------------------ + run->Init(); + // ------------------------------------------------------------------------ + + // ----- Runtime database --------------------------------------------- + + Bool_t kParameterMerged = kTRUE; + FairParRootFileIo* parOut = new FairParRootFileIo(kParameterMerged); + parOut->open(parFile.Data()); + rtdb->setOutput(parOut); + rtdb->saveOutput(); + rtdb->print(); + // ------------------------------------------------------------------------ + + // ----- Start run ---------------------------------------------------- + run->Run(nEvents); + run->CreateGeometryFile(geoFile); + // ------------------------------------------------------------------------ + + // ----- Finish ------------------------------------------------------- + + cout << endl << endl; + + // Extract the maximal used memory an add is as Dart measurement + // This line is filtered by CTest and the value send to CDash + FairSystemInfo sysInfo; + Float_t maxMemory = sysInfo.GetMaxMemory(); + cout << ""; + cout << maxMemory; + cout << "" << endl; + + timer.Stop(); + Double_t rtime = timer.RealTime(); + Double_t ctime = timer.CpuTime(); + + Float_t cpuUsage = ctime / rtime; + cout << ""; + cout << cpuUsage; + cout << "" << endl; + + cout << endl << endl; + cout << "Output file is " << outFile << endl; + cout << "Parameter file is " << parFile << endl; + cout << "Real time " << rtime << " s, CPU time " << ctime << "s" << endl << endl; + cout << "Macro finished successfully." << endl; + + // ------------------------------------------------------------------------ +} diff --git a/examples/simulation/Tutorial1/macros/run_tutorial1_urqmd.C b/examples/simulation/Tutorial1/macros/run_tutorial1_urqmd.C index 39e78bce52..d7b978eedc 100644 --- a/examples/simulation/Tutorial1/macros/run_tutorial1_urqmd.C +++ b/examples/simulation/Tutorial1/macros/run_tutorial1_urqmd.C @@ -1,133 +1,124 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ void run_tutorial1_urqmd(Int_t nEvents = 2, TString mcEngine = "TGeant3") { - - TString dir = getenv("VMCWORKDIR"); - TString tutdir = dir + "/simulation//Tutorial1"; - - TString inFile = dir + "/common/input/urqmd.ftn14"; - - TString Urqmd_Conversion_table= dir + "/common/input/urqmd_pdg.dat"; - - TString tut_geomdir = dir + "/common/geometry"; - gSystem->Setenv("GEOMPATH",tut_geomdir.Data()); - - TString tut_configdir = dir + "/common/gconfig"; - gSystem->Setenv("CONFIG_DIR",tut_configdir.Data()); - - - TString outDir = "./"; - - // Output file name - TString outFile = Form("%s/tutorial1_urqmd_%s.mc.root", - outDir.Data(), - mcEngine.Data()); - - - // Parameter file name - TString parFile = Form("%s/tutorial1_urqmd_%s.params.root", - outDir.Data(), - mcEngine.Data()); - - TString geoFile = outDir + "geofile_urqmd_" + mcEngine + "_full.root"; - - // In general, the following parts need not be touched - // ======================================================================== - - // ---- Debug option ------------------------------------------------- - gDebug = 0; - // ------------------------------------------------------------------------ - - // ----- Timer -------------------------------------------------------- - TStopwatch timer; - timer.Start(); - // ------------------------------------------------------------------------ - - // ----- Create simulation run ---------------------------------------- - FairRunSim* run = new FairRunSim(); - run->SetName(mcEngine); // Transport engine - run->SetSink(new FairRootFileSink(outFile)); // Output file - FairRuntimeDb* rtdb = run->GetRuntimeDb(); - // ------------------------------------------------------------------------ - - // ----- Create media ------------------------------------------------- - run->SetMaterials("media.geo"); // Materials - // ------------------------------------------------------------------------ - - // ----- Create geometry ---------------------------------------------- - - FairModule* cave= new FairCave("CAVE"); - cave->SetGeometryFileName("cave_vacuum.geo"); - run->AddModule(cave); - - FairDetector* tutdet = new FairTutorialDet1("TUTDET", kTRUE); - tutdet->SetGeometryFileName("double_sector.geo"); - run->AddModule(tutdet); - // ------------------------------------------------------------------------ - - // ----- Create PrimaryGenerator -------------------------------------- - FairPrimaryGenerator* primGen = new FairPrimaryGenerator(); - - FairUrqmdGenerator* urqmdGen = new FairUrqmdGenerator(inFile.Data(),Urqmd_Conversion_table.Data()); - primGen->AddGenerator(urqmdGen); - - run->SetGenerator(primGen); - // ------------------------------------------------------------------------ - - // ----- Initialize simulation run ------------------------------------ - run->Init(); - // ------------------------------------------------------------------------ - - // ----- Runtime database --------------------------------------------- - - Bool_t kParameterMerged = kTRUE; - FairParRootFileIo* parOut = new FairParRootFileIo(kParameterMerged); - parOut->open(parFile.Data()); - rtdb->setOutput(parOut); - rtdb->saveOutput(); - rtdb->print(); - // ------------------------------------------------------------------------ - - // ----- Start run ---------------------------------------------------- - run->Run(nEvents); - run->CreateGeometryFile(geoFile); - // ------------------------------------------------------------------------ - - // ----- Finish ------------------------------------------------------- - - cout << endl << endl; - - // Extract the maximal used memory an add is as Dart measurement - // This line is filtered by CTest and the value send to CDash - FairSystemInfo sysInfo; - Float_t maxMemory=sysInfo.GetMaxMemory(); - cout << ""; - cout << maxMemory; - cout << "" << endl; - - timer.Stop(); - Double_t rtime = timer.RealTime(); - Double_t ctime = timer.CpuTime(); - - Float_t cpuUsage=ctime/rtime; - cout << ""; - cout << cpuUsage; - cout << "" << endl; - - cout << endl << endl; - cout << "Output file is " << outFile << endl; - cout << "Parameter file is " << parFile << endl; - cout << "Real time " << rtime << " s, CPU time " << ctime - << "s" << endl << endl; - cout << "Macro finished successfully." << endl; - - // ------------------------------------------------------------------------ -} + TString dir = getenv("VMCWORKDIR"); + TString tutdir = dir + "/simulation//Tutorial1"; + + TString inFile = dir + "/common/input/urqmd.ftn14"; + + TString Urqmd_Conversion_table = dir + "/common/input/urqmd_pdg.dat"; + + TString tut_geomdir = dir + "/common/geometry"; + gSystem->Setenv("GEOMPATH", tut_geomdir.Data()); + + TString tut_configdir = dir + "/common/gconfig"; + gSystem->Setenv("CONFIG_DIR", tut_configdir.Data()); + + TString outDir = "./"; + + // Output file name + TString outFile = Form("%s/tutorial1_urqmd_%s.mc.root", outDir.Data(), mcEngine.Data()); + + // Parameter file name + TString parFile = Form("%s/tutorial1_urqmd_%s.params.root", outDir.Data(), mcEngine.Data()); + + TString geoFile = outDir + "geofile_urqmd_" + mcEngine + "_full.root"; + + // In general, the following parts need not be touched + // ======================================================================== + + // ---- Debug option ------------------------------------------------- + gDebug = 0; + // ------------------------------------------------------------------------ + + // ----- Timer -------------------------------------------------------- + TStopwatch timer; + timer.Start(); + // ------------------------------------------------------------------------ + + // ----- Create simulation run ---------------------------------------- + FairRunSim* run = new FairRunSim(); + run->SetName(mcEngine); // Transport engine + run->SetSink(new FairRootFileSink(outFile)); // Output file + FairRuntimeDb* rtdb = run->GetRuntimeDb(); + // ------------------------------------------------------------------------ + + // ----- Create media ------------------------------------------------- + run->SetMaterials("media.geo"); // Materials + // ------------------------------------------------------------------------ + + // ----- Create geometry ---------------------------------------------- + + FairModule* cave = new FairCave("CAVE"); + cave->SetGeometryFileName("cave_vacuum.geo"); + run->AddModule(cave); + FairDetector* tutdet = new FairTutorialDet1("TUTDET", kTRUE); + tutdet->SetGeometryFileName("double_sector.geo"); + run->AddModule(tutdet); + // ------------------------------------------------------------------------ + + // ----- Create PrimaryGenerator -------------------------------------- + FairPrimaryGenerator* primGen = new FairPrimaryGenerator(); + + FairUrqmdGenerator* urqmdGen = new FairUrqmdGenerator(inFile.Data(), Urqmd_Conversion_table.Data()); + primGen->AddGenerator(urqmdGen); + + run->SetGenerator(primGen); + // ------------------------------------------------------------------------ + + // ----- Initialize simulation run ------------------------------------ + run->Init(); + // ------------------------------------------------------------------------ + + // ----- Runtime database --------------------------------------------- + + Bool_t kParameterMerged = kTRUE; + FairParRootFileIo* parOut = new FairParRootFileIo(kParameterMerged); + parOut->open(parFile.Data()); + rtdb->setOutput(parOut); + rtdb->saveOutput(); + rtdb->print(); + // ------------------------------------------------------------------------ + + // ----- Start run ---------------------------------------------------- + run->Run(nEvents); + run->CreateGeometryFile(geoFile); + // ------------------------------------------------------------------------ + + // ----- Finish ------------------------------------------------------- + + cout << endl << endl; + + // Extract the maximal used memory an add is as Dart measurement + // This line is filtered by CTest and the value send to CDash + FairSystemInfo sysInfo; + Float_t maxMemory = sysInfo.GetMaxMemory(); + cout << ""; + cout << maxMemory; + cout << "" << endl; + + timer.Stop(); + Double_t rtime = timer.RealTime(); + Double_t ctime = timer.CpuTime(); + + Float_t cpuUsage = ctime / rtime; + cout << ""; + cout << cpuUsage; + cout << "" << endl; + + cout << endl << endl; + cout << "Output file is " << outFile << endl; + cout << "Parameter file is " << parFile << endl; + cout << "Real time " << rtime << " s, CPU time " << ctime << "s" << endl << endl; + cout << "Macro finished successfully." << endl; + + // ------------------------------------------------------------------------ +} diff --git a/examples/simulation/Tutorial1/src/FairFastSimExample.cxx b/examples/simulation/Tutorial1/src/FairFastSimExample.cxx index 23e77f1d27..65f3b5b7d3 100644 --- a/examples/simulation/Tutorial1/src/FairFastSimExample.cxx +++ b/examples/simulation/Tutorial1/src/FairFastSimExample.cxx @@ -7,20 +7,20 @@ ********************************************************************************/ #include "FairFastSimExample.h" -#include "FairDetectorList.h" // for DetectorId::kTutDet -#include "FairRootManager.h" // for FairRootManager -#include "FairStack.h" // for FairStack -#include "FairTutorialDet1Point.h" // for FairTutorialDet1Point -#include "FairDetector.h" // for FairDetector +#include "FairDetector.h" // for FairDetector +#include "FairDetectorList.h" // for DetectorId::kTutDet +#include "FairRootManager.h" // for FairRootManager +#include "FairStack.h" // for FairStack +#include "FairTutorialDet1Point.h" // for FairTutorialDet1Point -#include // for TClonesArray +#include // for TClonesArray #include #include -#include // for TGeoCombiTrans, TGeoRotation -#include // for TGeoVolume -#include // for kPHadronic -#include // for TVirtualMC -#include // for TVirtualMCStack +#include // for TGeoCombiTrans, TGeoRotation +#include // for TGeoVolume +#include // for kPHadronic +#include // for TVirtualMC +#include // for TVirtualMCStack FairFastSimExample::FairFastSimExample() : FairFastSimDetector("TutorialDet", kTutDet) @@ -32,8 +32,7 @@ FairFastSimExample::FairFastSimExample() , fLength(-1.) , fELoss(-1) , fPointsArray(new TClonesArray("FairTutorialDet1Point")) -{ -} +{} FairFastSimExample::FairFastSimExample(const char* name) : FairFastSimDetector(name, kTutDet) @@ -45,8 +44,7 @@ FairFastSimExample::FairFastSimExample(const char* name) , fLength(-1.) , fELoss(-1) , fPointsArray(new TClonesArray("FairTutorialDet1Point")) -{ -} +{} FairFastSimExample::FairFastSimExample(const FairFastSimExample& rhs) : FairFastSimDetector(rhs) @@ -58,13 +56,11 @@ FairFastSimExample::FairFastSimExample(const FairFastSimExample& rhs) , fLength(-1.) , fELoss(-1) , fPointsArray(new TClonesArray("FairTutorialDet1Point")) -{ -} +{} FairFastSimExample::~FairFastSimExample() { - if (fPointsArray) - { + if (fPointsArray) { fPointsArray->Delete(); delete fPointsArray; } @@ -80,27 +76,27 @@ void FairFastSimExample::FastSimProcessParticle() FairStack* stack = static_cast(TVirtualMC::GetMC()->GetStack()); fTrackID = TVirtualMC::GetMC()->GetStack()->GetCurrentTrackNumber(); - if ( TVirtualMC::GetMC()->TrackPid() == 211 ) { // let only pion create secondaries - stack->FastSimPushSecondary(fTrackID,11,-12.5,-12.5,20.+5.+0.1,fPos.T(), - 0.1,0.1,1.0,1.0,0.,0.,0.,kPHadronic,1,0); - stack->FastSimPushSecondary(fTrackID,11,-12.5,-12.5,20.+5.+0.1,fPos.T(), - -0.1,-0.1,1.0,1.0,0.,0.,0.,kPHadronic,1,0); + if (TVirtualMC::GetMC()->TrackPid() == 211) { // let only pion create secondaries + stack->FastSimPushSecondary( + fTrackID, 11, -12.5, -12.5, 20. + 5. + 0.1, fPos.T(), 0.1, 0.1, 1.0, 1.0, 0., 0., 0., kPHadronic, 1, 0); + stack->FastSimPushSecondary( + fTrackID, 11, -12.5, -12.5, 20. + 5. + 0.1, fPos.T(), -0.1, -0.1, 1.0, 1.0, 0., 0., 0., kPHadronic, 1, 0); } stack->FastSimMoveParticleTo( - 12.5, 12.5, 20. + 5. + 0.1, TVirtualMC::GetMC()->TrackTime(), fMom.X(), fMom.Y(), fMom.Z(), 0.99*fMom.E()); + 12.5, 12.5, 20. + 5. + 0.1, TVirtualMC::GetMC()->TrackTime(), fMom.X(), fMom.Y(), fMom.Z(), 0.99 * fMom.E()); - if ( TVirtualMC::GetMC()->TrackPid() == 211 ) { // let only pion create secondaries - stack->FastSimPushSecondary(fTrackID,11,-12.5,-12.5,20.+5.+0.1,fPos.T(), - -0.1,0.1,1.0,1.0,0.,0.,0.,kPHadronic,1,0); - stack->FastSimPushSecondary(fTrackID,11,-12.5,-12.5,20.+5.+0.1,fPos.T(), - 0.1,-0.1,1.0,1.0,0.,0.,0.,kPHadronic,1,0); + if (TVirtualMC::GetMC()->TrackPid() == 211) { // let only pion create secondaries + stack->FastSimPushSecondary( + fTrackID, 11, -12.5, -12.5, 20. + 5. + 0.1, fPos.T(), -0.1, 0.1, 1.0, 1.0, 0., 0., 0., kPHadronic, 1, 0); + stack->FastSimPushSecondary( + fTrackID, 11, -12.5, -12.5, 20. + 5. + 0.1, fPos.T(), 0.1, -0.1, 1.0, 1.0, 0., 0., 0., kPHadronic, 1, 0); } -// stack->FastSimMoveParticleTo( -// 25., 25., 20. + 0.1, TVirtualMC::GetMC()->TrackTime(), fMom.X(), fMom.Y(), fMom.Z(), fMom.E()); + // stack->FastSimMoveParticleTo( + // 25., 25., 20. + 0.1, TVirtualMC::GetMC()->TrackTime(), fMom.X(), fMom.Y(), fMom.Z(), fMom.E()); -// stack->FastSimMoveParticleTo( -// 24., 24., 50. + 0.1, TVirtualMC::GetMC()->TrackTime(), fMom.X(), fMom.Y(), fMom.Z(), fMom.E()); + // stack->FastSimMoveParticleTo( + // 24., 24., 50. + 0.1, TVirtualMC::GetMC()->TrackTime(), fMom.X(), fMom.Y(), fMom.Z(), fMom.E()); fVolumeID = 0; fTime = TVirtualMC::GetMC()->TrackTime() * 1.0e09; @@ -133,12 +129,9 @@ void FairFastSimExample::Register() TClonesArray* FairFastSimExample::GetCollection(Int_t iColl) const { - if (iColl == 0) - { + if (iColl == 0) { return fPointsArray; - } - else - { + } else { return nullptr; } } @@ -169,23 +162,20 @@ void FairFastSimExample::ConstructGeometry() } FairTutorialDet1Point* FairFastSimExample::AddHit(Int_t trackID, - Int_t detID, - TVector3 pos, - TVector3 mom, - Double_t time, - Double_t length, - Double_t eLoss) + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t time, + Double_t length, + Double_t eLoss) { TClonesArray& clref = *fPointsArray; Int_t size = clref.GetEntriesFast(); return new (clref[size]) FairTutorialDet1Point(trackID, detID, pos, mom, time, length, eLoss); } -Bool_t FairFastSimExample::IsSensitive(const std::string& name) -{ - return name == "fast_sim_vol"; -} +Bool_t FairFastSimExample::IsSensitive(const std::string& name) { return name == "fast_sim_vol"; } FairModule* FairFastSimExample::CloneModule() const { return new FairFastSimExample(*this); } -ClassImp(FairFastSimExample) +ClassImp(FairFastSimExample); diff --git a/examples/simulation/Tutorial1/src/FairFastSimExample.h b/examples/simulation/Tutorial1/src/FairFastSimExample.h index 3261ae470f..6053a99a32 100644 --- a/examples/simulation/Tutorial1/src/FairFastSimExample.h +++ b/examples/simulation/Tutorial1/src/FairFastSimExample.h @@ -8,11 +8,11 @@ #ifndef FAIRFASTSIMEXAMPLE #define FAIRFASTSIMEXAMPLE -#include "FairFastSimDetector.h" // for FairFastSimDetector +#include "FairFastSimDetector.h" // for FairFastSimDetector -#include // for Int_t, Double32_t, Double_t, etc -#include // for TLorentzVector -#include // for TVector3 +#include // for Int_t, Double32_t, Double_t, etc +#include // for TLorentzVector +#include // for TVector3 class FairTutorialDet1Point; class TClonesArray; @@ -47,15 +47,16 @@ class FairFastSimExample : public FairFastSimDetector /** This method is an example of how to add your own point * of type FairTutorialDet1Point to the clones array - */ - FairTutorialDet1Point* AddHit(Int_t trackID, Int_t detID, TVector3 pos, TVector3 mom, Double_t time, Double_t length, Double_t eLoss); + */ + FairTutorialDet1Point* + AddHit(Int_t trackID, Int_t detID, TVector3 pos, TVector3 mom, Double_t time, Double_t length, Double_t eLoss); /** The following methods can be implemented if you need to make * any optional action in your detector during the transport. - */ + */ virtual void EndOfEvent(); - virtual Bool_t IsSensitive(const std::string& name); + virtual Bool_t IsSensitive(const std::string& name); virtual FairModule* CloneModule() const; @@ -66,13 +67,13 @@ class FairFastSimExample : public FairFastSimDetector /** 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* fPointsArray; @@ -83,4 +84,4 @@ class FairFastSimExample : public FairFastSimDetector ClassDef(FairFastSimExample, 2) }; -#endif // FAIRTUTORIALDET_H +#endif // FAIRTUTORIALDET_H diff --git a/examples/simulation/Tutorial1/src/FairFastSimExample2.cxx b/examples/simulation/Tutorial1/src/FairFastSimExample2.cxx index 8bd7bbeab5..a39acbd60e 100644 --- a/examples/simulation/Tutorial1/src/FairFastSimExample2.cxx +++ b/examples/simulation/Tutorial1/src/FairFastSimExample2.cxx @@ -7,20 +7,19 @@ ********************************************************************************/ #include "FairFastSimExample2.h" -#include "FairDetectorList.h" // for DetectorId::kTutDet -#include "FairRootManager.h" // for FairRootManager -#include "FairStack.h" // for FairStack -#include "FairTutorialDet1Point.h" // for FairTutorialDet1Point -#include "FairDetector.h" // for FairDetector - -#include // for TGeoCombiTrans, TGeoRotation -#include // for TGeoVolume -#include // for TClonesArray -#include // for TVirtualMC -#include // for TVirtualMCStack +#include "FairDetector.h" // for FairDetector +#include "FairDetectorList.h" // for DetectorId::kTutDet +#include "FairRootManager.h" // for FairRootManager +#include "FairStack.h" // for FairStack +#include "FairTutorialDet1Point.h" // for FairTutorialDet1Point -#include +#include // for TClonesArray #include +#include +#include // for TGeoCombiTrans, TGeoRotation +#include // for TGeoVolume +#include // for TVirtualMC +#include // for TVirtualMCStack FairFastSimExample2::FairFastSimExample2() : FairFastSimDetector("TutorialDet", kTutDet) @@ -32,8 +31,7 @@ FairFastSimExample2::FairFastSimExample2() , fLength(-1.) , fELoss(-1) , fPointsArray(new TClonesArray("FairTutorialDet1Point")) -{ -} +{} FairFastSimExample2::FairFastSimExample2(const char* name) : FairFastSimDetector(name, kTutDet) @@ -45,8 +43,7 @@ FairFastSimExample2::FairFastSimExample2(const char* name) , fLength(-1.) , fELoss(-1) , fPointsArray(new TClonesArray("FairTutorialDet1Point")) -{ -} +{} FairFastSimExample2::FairFastSimExample2(const FairFastSimExample2& rhs) : FairFastSimDetector(rhs) @@ -58,13 +55,11 @@ FairFastSimExample2::FairFastSimExample2(const FairFastSimExample2& rhs) , fLength(-1.) , fELoss(-1) , fPointsArray(new TClonesArray("FairTutorialDet1Point")) -{ -} +{} FairFastSimExample2::~FairFastSimExample2() { - if (fPointsArray) - { + if (fPointsArray) { fPointsArray->Delete(); delete fPointsArray; } @@ -80,7 +75,7 @@ void FairFastSimExample2::FastSimProcessParticle() FairStack* stack = static_cast(TVirtualMC::GetMC()->GetStack()); stack->FastSimMoveParticleTo( - 24., 24., 50. + 5. + 0.1, TVirtualMC::GetMC()->TrackTime(), fMom.X(), fMom.Y(), fMom.Z(), 0.99*fMom.E()); + 24., 24., 50. + 5. + 0.1, TVirtualMC::GetMC()->TrackTime(), fMom.X(), fMom.Y(), fMom.Z(), 0.99 * fMom.E()); fTrackID = TVirtualMC::GetMC()->GetStack()->GetCurrentTrackNumber(); fVolumeID = 0; @@ -114,12 +109,9 @@ void FairFastSimExample2::Register() TClonesArray* FairFastSimExample2::GetCollection(Int_t iColl) const { - if (iColl == 0) - { + if (iColl == 0) { return fPointsArray; - } - else - { + } else { return nullptr; } } @@ -150,23 +142,20 @@ void FairFastSimExample2::ConstructGeometry() } FairTutorialDet1Point* FairFastSimExample2::AddHit(Int_t trackID, - Int_t detID, - TVector3 pos, - TVector3 mom, - Double_t time, - Double_t length, - Double_t eLoss) + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t time, + Double_t length, + Double_t eLoss) { TClonesArray& clref = *fPointsArray; Int_t size = clref.GetEntriesFast(); return new (clref[size]) FairTutorialDet1Point(trackID, detID, pos, mom, time, length, eLoss); } -Bool_t FairFastSimExample2::IsSensitive(const std::string& name) -{ - return name == "fast_sim_vol_n2"; -} +Bool_t FairFastSimExample2::IsSensitive(const std::string& name) { return name == "fast_sim_vol_n2"; } FairModule* FairFastSimExample2::CloneModule() const { return new FairFastSimExample2(*this); } -ClassImp(FairFastSimExample2) +ClassImp(FairFastSimExample2); diff --git a/examples/simulation/Tutorial1/src/FairFastSimExample2.h b/examples/simulation/Tutorial1/src/FairFastSimExample2.h index 564d8e6de2..e440d309cd 100644 --- a/examples/simulation/Tutorial1/src/FairFastSimExample2.h +++ b/examples/simulation/Tutorial1/src/FairFastSimExample2.h @@ -8,11 +8,11 @@ #ifndef FAIRFASTSIMEXAMPLE2 #define FAIRFASTSIMEXAMPLE2 -#include "FairFastSimDetector.h" // for FairDetector +#include "FairFastSimDetector.h" // for FairDetector -#include // for Int_t, Double32_t, Double_t, etc -#include // for TLorentzVector -#include // for TVector3 +#include // for Int_t, Double32_t, Double_t, etc +#include // for TLorentzVector +#include // for TVector3 class FairTutorialDet1Point; class TClonesArray; @@ -47,16 +47,16 @@ class FairFastSimExample2 : public FairFastSimDetector /** This method is an example of how to add your own point * of type FairTutorialDet1Point to the clones array - */ + */ FairTutorialDet1Point* AddHit(Int_t trackID, Int_t detID, TVector3 pos, TVector3 mom, Double_t time, Double_t length, Double_t eLoss); /** The following methods can be implemented if you need to make * any optional action in your detector during the transport. - */ + */ virtual void EndOfEvent(); - virtual Bool_t IsSensitive(const std::string& name); + virtual Bool_t IsSensitive(const std::string& name); virtual FairModule* CloneModule() const; @@ -67,13 +67,13 @@ class FairFastSimExample2 : public FairFastSimDetector /** 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* fPointsArray; @@ -84,4 +84,4 @@ class FairFastSimExample2 : public FairFastSimDetector ClassDef(FairFastSimExample2, 2) }; -#endif // FAIRTUTORIALDET_H +#endif // FAIRTUTORIALDET_H diff --git a/examples/simulation/Tutorial1/src/FairSimConfig.cxx b/examples/simulation/Tutorial1/src/FairSimConfig.cxx index 23482b7f7c..32c740e65b 100644 --- a/examples/simulation/Tutorial1/src/FairSimConfig.cxx +++ b/examples/simulation/Tutorial1/src/FairSimConfig.cxx @@ -5,12 +5,13 @@ * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ -#include -#include - #include "FairSimConfig.h" + #include "FairLogger.h" +#include +#include + using namespace std; FairSimConfig::FairSimConfig() @@ -23,63 +24,57 @@ FairSimConfig::FairSimConfig() , fParameterFile("par.root") , fRandomSeed(0) { - fDescription.add_options()("help", "Print this message")( - "nevents", po::value(), "Number of events to simulate")( - "engine", po::value>(), "Monte Carlo engine")("multi-threaded", "Geant4 multi threaded")( - "output-file", po::value>(), "Output file")( - "parameter-file", po::value>(), "Parameter file")( - "random-seed", po::value(), "Seed for the random number generator"); + // clang-format off + fDescription.add_options() + ("help", "Print this message") + ("nevents", po::value(), "Number of events to simulate") + ("engine", po::value>(), "Monte Carlo engine") + ("multi-threaded", "Geant4 multi threaded") + ("output-file", po::value>(), "Output file") + ("parameter-file", po::value>(), "Parameter file") + ("random-seed", po::value(), "Seed for the random number generator"); + // clang-format on } FairSimConfig::~FairSimConfig() {} int FairSimConfig::ParseCommandLine(int argc, char* argv[]) { - try - { + try { po::store(po::parse_command_line(argc, argv, fDescription), fMap); po::notify(fMap); - } - catch (po::error& e) - { + } catch (po::error& e) { LOG(error) << e.what(); fHelp = true; return 0; } - if (fMap.count("help")) - { + if (fMap.count("help")) { fHelp = true; return 0; } - if (fMap.count("nevents")) - { + if (fMap.count("nevents")) { fnEvents = fMap["nevents"].as(); } - if (fMap.count("engine")) - { + if (fMap.count("engine")) { fEngine = fMap["engine"].as>().at(0); - if (!GetEngine().EqualTo("TGeant3") && !GetEngine().EqualTo("TGeant4")) - { + if (!GetEngine().EqualTo("TGeant3") && !GetEngine().EqualTo("TGeant4")) { LOG(error) << "Option engine can be either TGeant3 or TGeant4"; return 1; } } - if(fMap.count("output-file")) - { + if (fMap.count("output-file")) { fOutputFile = fMap["output-file"].as>().at(0); } - if(fMap.count("parameter-file")) - { + if (fMap.count("parameter-file")) { fParameterFile = fMap["parameter-file"].as>().at(0); } - if(fMap.count("random-seed")) - { + if (fMap.count("random-seed")) { fRandomSeed = fMap["random-seed"].as(); } - if(fMap.count("multi-threaded")) - { + if (fMap.count("multi-threaded")) { + LOG(info) << "YUPYUPYUP"; fMultiThreaded = true; } return 0; @@ -87,4 +82,4 @@ int FairSimConfig::ParseCommandLine(int argc, char* argv[]) void FairSimConfig::PrintHelpMessage() { cout << fDescription << endl; } -ClassImp(FairSimConfig) +ClassImp(FairSimConfig); diff --git a/examples/simulation/Tutorial1/src/FairSimConfig.h b/examples/simulation/Tutorial1/src/FairSimConfig.h index c1ed7a1b7a..b6f7059888 100644 --- a/examples/simulation/Tutorial1/src/FairSimConfig.h +++ b/examples/simulation/Tutorial1/src/FairSimConfig.h @@ -9,10 +9,10 @@ #define FAIRSIMCONFIG #include "boost/program_options.hpp" -#include #include #include +#include namespace po = boost::program_options; @@ -35,8 +35,8 @@ class FairSimConfig int GetRandomSeed() const { return fRandomSeed; } private: - po::options_description fDescription; //! - po::variables_map fMap; //! + po::options_description fDescription; //! + po::variables_map fMap; //! bool fHelp; int fnEvents; diff --git a/examples/simulation/Tutorial1/src/FairTutorialDet1.cxx b/examples/simulation/Tutorial1/src/FairTutorialDet1.cxx index e6556793b5..1884833f3f 100644 --- a/examples/simulation/Tutorial1/src/FairTutorialDet1.cxx +++ b/examples/simulation/Tutorial1/src/FairTutorialDet1.cxx @@ -1,152 +1,148 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "FairTutorialDet1.h" -#include "FairDetectorList.h" // for DetectorId::kTutDet -#include "FairRootManager.h" // for FairRootManager -#include "FairStack.h" // for FairStack -#include "FairTutorialDet1Geo.h" // for FairTutorialDet1Geo -#include "FairTutorialDet1GeoPar.h" // for FairTutorialDet1GeoPar -#include "FairTutorialDet1Point.h" // for FairTutorialDet1Point -#include "FairVolume.h" // for FairVolume -#include "FairLogger.h" // for logging +#include "FairDetectorList.h" // for DetectorId::kTutDet +#include "FairLogger.h" // for logging +#include "FairRootManager.h" // for FairRootManager +#include "FairStack.h" // for FairStack +#include "FairTutorialDet1Geo.h" // for FairTutorialDet1Geo +#include "FairTutorialDet1GeoPar.h" // for FairTutorialDet1GeoPar +#include "FairTutorialDet1Point.h" // for FairTutorialDet1Point +#include "FairVolume.h" // for FairVolume -#include // for TClonesArray -#include // for TVirtualMC -#include // for TVirtualMCStack +#include // for TClonesArray +#include // for TVirtualMC +#include // for TVirtualMCStack FairTutorialDet1Geo* FairTutorialDet1::fgGeo = nullptr; FairTutorialDet1::FairTutorialDet1() - : FairDetector("TutorialDet", kTRUE, kTutDet), - fTrackID(-1), - fVolumeID(-1), - fPos(), - fMom(), - fTime(-1.), - fLength(-1.), - fELoss(-1), - fFairTutorialDet1PointCollection(new TClonesArray("FairTutorialDet1Point")) -{ -} + : FairDetector("TutorialDet", kTRUE, kTutDet) + , fTrackID(-1) + , fVolumeID(-1) + , fPos() + , fMom() + , fTime(-1.) + , fLength(-1.) + , fELoss(-1) + , fFairTutorialDet1PointCollection(new TClonesArray("FairTutorialDet1Point")) +{} FairTutorialDet1::FairTutorialDet1(const char* name, Bool_t active) - : FairDetector(name, active, kTutDet), - fTrackID(-1), - fVolumeID(-1), - fPos(), - fMom(), - fTime(-1.), - fLength(-1.), - fELoss(-1), - fFairTutorialDet1PointCollection(new TClonesArray("FairTutorialDet1Point")) -{ -} + : FairDetector(name, active, kTutDet) + , fTrackID(-1) + , fVolumeID(-1) + , fPos() + , fMom() + , fTime(-1.) + , fLength(-1.) + , fELoss(-1) + , fFairTutorialDet1PointCollection(new TClonesArray("FairTutorialDet1Point")) +{} FairTutorialDet1::FairTutorialDet1(const FairTutorialDet1& rhs) - : FairDetector(rhs), - fTrackID(-1), - fVolumeID(-1), - fPos(), - fMom(), - fTime(-1.), - fLength(-1.), - fELoss(-1), - fFairTutorialDet1PointCollection(new TClonesArray("FairTutorialDet1Point")) -{ -} + : FairDetector(rhs) + , fTrackID(-1) + , fVolumeID(-1) + , fPos() + , fMom() + , fTime(-1.) + , fLength(-1.) + , fELoss(-1) + , fFairTutorialDet1PointCollection(new TClonesArray("FairTutorialDet1Point")) +{} FairTutorialDet1::~FairTutorialDet1() { - if (fFairTutorialDet1PointCollection) { - fFairTutorialDet1PointCollection->Delete(); - delete fFairTutorialDet1PointCollection; - } + if (fFairTutorialDet1PointCollection) { + fFairTutorialDet1PointCollection->Delete(); + delete fFairTutorialDet1PointCollection; + } } void FairTutorialDet1::Initialize() { - FairDetector::Initialize(); -/* + FairDetector::Initialize(); + /* FairRuntimeDb* rtdb= FairRun::Instance()->GetRuntimeDb(); FairTutorialDet1GeoPar* par=(FairTutorialDet1GeoPar*)(rtdb->getContainer("FairTutorialDet1GeoPar")); */ } -Bool_t FairTutorialDet1::ProcessHits(FairVolume* vol) -{ - /** This method is called from the MC stepping */ - - LOG(debug) << "In FairTutorialDet1::ProcessHits"; - //Set parameters at entrance of volume. Reset ELoss. - if ( TVirtualMC::GetMC()->IsTrackEntering() ) { - fELoss = 0.; - fTime = TVirtualMC::GetMC()->TrackTime() * 1.0e09; - fLength = TVirtualMC::GetMC()->TrackLength(); - TVirtualMC::GetMC()->TrackPosition(fPos); - TVirtualMC::GetMC()->TrackMomentum(fMom); - } - - // Sum energy loss for all steps in the active volume - fELoss += TVirtualMC::GetMC()->Edep(); - - // Create FairTutorialDet1Point at exit of active volume - if ( TVirtualMC::GetMC()->IsTrackExiting() || - TVirtualMC::GetMC()->IsTrackStop() || - TVirtualMC::GetMC()->IsTrackDisappeared() ) { - fTrackID = TVirtualMC::GetMC()->GetStack()->GetCurrentTrackNumber(); - fVolumeID = vol->getMCid(); - if (fELoss == 0. ) { return kFALSE; } - AddHit(fTrackID, fVolumeID, TVector3(fPos.X(), fPos.Y(), fPos.Z()), - TVector3(fMom.Px(), fMom.Py(), fMom.Pz()), fTime, fLength, - fELoss); - - // Increment number of tutorial det points in TParticle - FairStack* stack = static_cast(TVirtualMC::GetMC()->GetStack()); - stack->AddPoint(kTutDet); - } - - return kTRUE; -} - -void FairTutorialDet1::EndOfEvent() +Bool_t FairTutorialDet1::ProcessHits(FairVolume* vol) { + /** This method is called from the MC stepping */ + + LOG(debug) << "In FairTutorialDet1::ProcessHits"; + // Set parameters at entrance of volume. Reset ELoss. + if (TVirtualMC::GetMC()->IsTrackEntering()) { + fELoss = 0.; + fTime = TVirtualMC::GetMC()->TrackTime() * 1.0e09; + fLength = TVirtualMC::GetMC()->TrackLength(); + TVirtualMC::GetMC()->TrackPosition(fPos); + TVirtualMC::GetMC()->TrackMomentum(fMom); + } - fFairTutorialDet1PointCollection->Clear(); + // Sum energy loss for all steps in the active volume + fELoss += TVirtualMC::GetMC()->Edep(); + + // Create FairTutorialDet1Point at exit of active volume + if (TVirtualMC::GetMC()->IsTrackExiting() || TVirtualMC::GetMC()->IsTrackStop() + || TVirtualMC::GetMC()->IsTrackDisappeared()) { + fTrackID = TVirtualMC::GetMC()->GetStack()->GetCurrentTrackNumber(); + fVolumeID = vol->getMCid(); + if (fELoss == 0.) { + return kFALSE; + } + AddHit(fTrackID, + fVolumeID, + TVector3(fPos.X(), fPos.Y(), fPos.Z()), + TVector3(fMom.Px(), fMom.Py(), fMom.Pz()), + fTime, + fLength, + fELoss); + + // Increment number of tutorial det points in TParticle + FairStack* stack = static_cast(TVirtualMC::GetMC()->GetStack()); + stack->AddPoint(kTutDet); + } + return kTRUE; } +void FairTutorialDet1::EndOfEvent() { fFairTutorialDet1PointCollection->Clear(); } + void FairTutorialDet1::Register() { - /** This will create a branch in the output tree called + /** This will create a branch in the output tree called FairTutorialDet1Point, 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("TutorialDetPoint", "TutorialDet", - fFairTutorialDet1PointCollection, kTRUE); + FairRootManager::Instance()->Register("TutorialDetPoint", "TutorialDet", fFairTutorialDet1PointCollection, kTRUE); } TClonesArray* FairTutorialDet1::GetCollection(Int_t iColl) const { - if (iColl == 0) { return fFairTutorialDet1PointCollection; } - else { return nullptr; } + if (iColl == 0) { + return fFairTutorialDet1PointCollection; + } else { + return nullptr; + } } -void FairTutorialDet1::Reset() -{ - fFairTutorialDet1PointCollection->Clear(); -} +void FairTutorialDet1::Reset() { fFairTutorialDet1PointCollection->Clear(); } Bool_t FairTutorialDet1::IsSensitive(const std::string& name) { - if ( name.find("tutdet") != std::string::npos ) { + if (name.find("tutdet") != std::string::npos) { return kTRUE; } return kFALSE; @@ -154,27 +150,26 @@ Bool_t FairTutorialDet1::IsSensitive(const std::string& name) void FairTutorialDet1::ConstructGeometry() { - /** If you are using the standard ASCII input for 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. */ ConstructASCIIGeometry(fgGeo, "FairTutorialDet1GeoPar"); } -FairTutorialDet1Point* FairTutorialDet1::AddHit(Int_t trackID, Int_t detID, - TVector3 pos, TVector3 mom, - Double_t time, Double_t length, - Double_t eLoss) +FairTutorialDet1Point* FairTutorialDet1::AddHit(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t time, + Double_t length, + Double_t eLoss) { - TClonesArray& clref = *fFairTutorialDet1PointCollection; - Int_t size = clref.GetEntriesFast(); - return new(clref[size]) FairTutorialDet1Point(trackID, detID, pos, mom, - time, length, eLoss); + TClonesArray& clref = *fFairTutorialDet1PointCollection; + Int_t size = clref.GetEntriesFast(); + return new (clref[size]) FairTutorialDet1Point(trackID, detID, pos, mom, time, length, eLoss); } -FairModule* FairTutorialDet1::CloneModule() const -{ - return new FairTutorialDet1(*this); -} +FairModule* FairTutorialDet1::CloneModule() const { return new FairTutorialDet1(*this); } -ClassImp(FairTutorialDet1) +ClassImp(FairTutorialDet1); diff --git a/examples/simulation/Tutorial1/src/FairTutorialDet1.h b/examples/simulation/Tutorial1/src/FairTutorialDet1.h index e6b5c8f9a6..4d369fc3bf 100644 --- a/examples/simulation/Tutorial1/src/FairTutorialDet1.h +++ b/examples/simulation/Tutorial1/src/FairTutorialDet1.h @@ -1,18 +1,18 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRTUTORIALDET1_H #define FAIRTUTORIALDET1_H -#include "FairDetector.h" // for FairDetector +#include "FairDetector.h" // for FairDetector -#include // for Int_t, Double32_t, Double_t, etc -#include // for TLorentzVector -#include // for TVector3 +#include // for Int_t, Double32_t, Double_t, etc +#include // for TLorentzVector +#include // for TVector3 class FairTutorialDet1Point; class FairTutorialDet1Geo; @@ -20,15 +20,14 @@ class FairVolume; class TClonesArray; class FairModule; -class FairTutorialDet1: public FairDetector +class FairTutorialDet1 : public FairDetector { public: - /** Name : Detector Name * Active: kTRUE for active detectors (ProcessHits() will be called) * kFALSE for inactive detectors - */ + */ FairTutorialDet1(const char* Name, Bool_t Active); /** default constructor */ @@ -38,53 +37,49 @@ class FairTutorialDet1: public FairDetector virtual ~FairTutorialDet1(); /** 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(); - - /** This method is an example of how to add your own point * of type FairTutorialDet1Point to the clones array - */ - FairTutorialDet1Point* AddHit(Int_t trackID, Int_t detID, - TVector3 pos, TVector3 mom, - Double_t time, Double_t length, - Double_t eLoss); + */ + FairTutorialDet1Point* + AddHit(Int_t trackID, Int_t detID, TVector3 pos, TVector3 mom, Double_t time, Double_t length, Double_t eLoss); /** 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() { ; } virtual FairModule* CloneModule() const; - virtual Bool_t IsSensitive(const std::string& name); + virtual Bool_t IsSensitive(const std::string& name); private: static FairTutorialDet1Geo* fgGeo; //! @@ -92,22 +87,22 @@ class FairTutorialDet1: public FairDetector /** 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* fFairTutorialDet1PointCollection; + TClonesArray* fFairTutorialDet1PointCollection; FairTutorialDet1(const FairTutorialDet1&); FairTutorialDet1& operator=(const FairTutorialDet1&); - ClassDef(FairTutorialDet1,1) + ClassDef(FairTutorialDet1, 1) }; -#endif //FAIRTUTORIALDET_H +#endif // FAIRTUTORIALDET_H diff --git a/examples/simulation/Tutorial1/src/FairTutorialDet1ContFact.cxx b/examples/simulation/Tutorial1/src/FairTutorialDet1ContFact.cxx index f97b0905aa..433fd6c45b 100644 --- a/examples/simulation/Tutorial1/src/FairTutorialDet1ContFact.cxx +++ b/examples/simulation/Tutorial1/src/FairTutorialDet1ContFact.cxx @@ -1,62 +1,60 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "FairTutorialDet1ContFact.h" -#include "FairRuntimeDb.h" // for FairRuntimeDb -#include "FairTutorialDet1GeoPar.h" // for FairTutorialDet1GeoPar +#include "FairRuntimeDb.h" // for FairRuntimeDb +#include "FairTutorialDet1GeoPar.h" // for FairTutorialDet1GeoPar -#include // for TList -#include // for TString - -#include // for strcmp +#include // for TList +#include // for TString +#include // for strcmp class FairParSet; -ClassImp(FairTutorialDet1ContFact) +ClassImp(FairTutorialDet1ContFact); static FairTutorialDet1ContFact gFairTutorialDet1ContFact; FairTutorialDet1ContFact::FairTutorialDet1ContFact() - : FairContFact() + : FairContFact() { - /** Constructor (called when the library is loaded) */ - fName="FairTutorialDet1ContFact"; - fTitle="Factory for parameter containers in libTutorial1"; - setAllContainers(); - FairRuntimeDb::instance()->addContFactory(this); + /** Constructor (called when the library is loaded) */ + fName = "FairTutorialDet1ContFact"; + fTitle = "Factory for parameter containers in libTutorial1"; + setAllContainers(); + FairRuntimeDb::instance()->addContFactory(this); } void FairTutorialDet1ContFact::setAllContainers() { - /** Creates the Container objects with all accepted + /** Creates the Container objects with all accepted contexts and adds them to the list of containers for the Tutorial1 library. */ - FairContainer* p= new FairContainer("FairTutorialDet1GeoPar", - "FairTutorialDet1 Geometry Parameters", - "TestDefaultContext"); - p->addContext("TestNonDefaultContext"); + FairContainer* p = + new FairContainer("FairTutorialDet1GeoPar", "FairTutorialDet1 Geometry Parameters", "TestDefaultContext"); + p->addContext("TestNonDefaultContext"); - containers->Add(p); + containers->Add(p); } FairParSet* FairTutorialDet1ContFact::createContainer(FairContainer* c) { - /** Calls the constructor of the corresponding parameter container. + /** 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=nullptr; - if (strcmp(name,"FairTutorialDet1GeoPar")==0) { - p=new FairTutorialDet1GeoPar(c->getConcatName().Data(), c->GetTitle(), c->getContext()); - } - return p; + const char* name = c->GetName(); + FairParSet* p = nullptr; + if (strcmp(name, "FairTutorialDet1GeoPar") == 0) { + p = new FairTutorialDet1GeoPar(c->getConcatName().Data(), c->GetTitle(), c->getContext()); + } + return p; } diff --git a/examples/simulation/Tutorial1/src/FairTutorialDet1ContFact.h b/examples/simulation/Tutorial1/src/FairTutorialDet1ContFact.h index e70ef6c868..a12fd43d3e 100644 --- a/examples/simulation/Tutorial1/src/FairTutorialDet1ContFact.h +++ b/examples/simulation/Tutorial1/src/FairTutorialDet1ContFact.h @@ -1,14 +1,14 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRTUTORIALDET1CONTFACT_H #define FAIRTUTORIALDET1CONTFACT_H -#include "FairContFact.h" // for FairContFact, etc +#include "FairContFact.h" // for FairContFact, etc #include @@ -18,11 +18,12 @@ class FairTutorialDet1ContFact : public FairContFact { private: void setAllContainers(); + public: FairTutorialDet1ContFact(); ~FairTutorialDet1ContFact() {} FairParSet* createContainer(FairContainer*); - ClassDef( FairTutorialDet1ContFact,0) // Factory for all MyDet parameter containers + ClassDef(FairTutorialDet1ContFact, 0) // Factory for all MyDet parameter containers }; -#endif /* !FAIRTUTORIALDETCONTFACT_H */ +#endif /* !FAIRTUTORIALDETCONTFACT_H */ diff --git a/examples/simulation/Tutorial1/src/FairTutorialDet1Geo.cxx b/examples/simulation/Tutorial1/src/FairTutorialDet1Geo.cxx index 16b1945664..06db60f0b5 100644 --- a/examples/simulation/Tutorial1/src/FairTutorialDet1Geo.cxx +++ b/examples/simulation/Tutorial1/src/FairTutorialDet1Geo.cxx @@ -1,39 +1,39 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "FairTutorialDet1Geo.h" -#include // for sprintf +#include // for sprintf -ClassImp(FairTutorialDet1Geo) +ClassImp(FairTutorialDet1Geo); FairTutorialDet1Geo::FairTutorialDet1Geo() - : FairGeoSet() + : FairGeoSet() { - // Constructor - fName="tutdet"; - maxSectors=0; - maxModules=10; + // Constructor + fName = "tutdet"; + maxSectors = 0; + maxModules = 10; } const char* FairTutorialDet1Geo::getModuleName(Int_t m) { - /** Returns the module name of TutorialDet number m + /** Returns the module name of TutorialDet number m Setting MyDet here means that all modules names in the ASCII file should start with TutorialDet otherwise they will not be constructed */ - sprintf(modName,"tutdet%i",m+1); - return modName; + sprintf(modName, "tutdet%i", m + 1); + return modName; } const char* FairTutorialDet1Geo::getEleName(Int_t m) { - /** Returns the element name of Det number m */ - sprintf(eleName,"tutdet%i",m+1); - return eleName; + /** Returns the element name of Det number m */ + sprintf(eleName, "tutdet%i", m + 1); + return eleName; } diff --git a/examples/simulation/Tutorial1/src/FairTutorialDet1Geo.h b/examples/simulation/Tutorial1/src/FairTutorialDet1Geo.h index 456118375a..d7d7850695 100644 --- a/examples/simulation/Tutorial1/src/FairTutorialDet1Geo.h +++ b/examples/simulation/Tutorial1/src/FairTutorialDet1Geo.h @@ -1,24 +1,23 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRTUTORIALDET1GEO_H #define FAIRTUTORIALDET1GEO_H -#include "FairGeoSet.h" // for FairGeoSet +#include "FairGeoSet.h" // for FairGeoSet -#include // for Int_t, etc - -#include // for TString +#include // for Int_t, etc +#include // for TString class FairTutorialDet1Geo : public FairGeoSet { protected: - char modName[20]; // name of module - char eleName[20]; // substring for elements in module + char modName[20]; // name of module + char eleName[20]; // substring for elements in module public: FairTutorialDet1Geo(); @@ -26,17 +25,17 @@ class FairTutorialDet1Geo : public FairGeoSet const char* getModuleName(Int_t); const char* getEleName(Int_t); inline Int_t getModNumInMod(const TString&); - ClassDef(FairTutorialDet1Geo,1) + ClassDef(FairTutorialDet1Geo, 1) }; inline Int_t FairTutorialDet1Geo::getModNumInMod(const TString& name) { - /** returns the module index from module name + /** returns the module index from module name ?? in name[??] has to be the length of the detector name in the .geo file. For example if all nodes in this file starts with tutdet ?? has to be 6. */ - return static_cast((name[6]-'0')-1); // + return static_cast((name[6] - '0') - 1); // } -#endif /* FAIRTUTORIALDETGEO_H */ +#endif /* FAIRTUTORIALDETGEO_H */ diff --git a/examples/simulation/Tutorial1/src/FairTutorialDet1GeoPar.cxx b/examples/simulation/Tutorial1/src/FairTutorialDet1GeoPar.cxx index d2cc63cff8..b1ed46ffd6 100644 --- a/examples/simulation/Tutorial1/src/FairTutorialDet1GeoPar.cxx +++ b/examples/simulation/Tutorial1/src/FairTutorialDet1GeoPar.cxx @@ -1,48 +1,51 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "FairTutorialDet1GeoPar.h" -#include "FairParamList.h" // for FairParamList +#include "FairParamList.h" // for FairParamList -#include // for TObjArray +#include // for TObjArray -ClassImp(FairTutorialDet1GeoPar) +ClassImp(FairTutorialDet1GeoPar); -FairTutorialDet1GeoPar ::FairTutorialDet1GeoPar(const char* name, - const char* title, - const char* context) - : FairParGenericSet(name,title,context), - fGeoSensNodes(new TObjArray()), - fGeoPassNodes(new TObjArray()) -{ -} +FairTutorialDet1GeoPar ::FairTutorialDet1GeoPar(const char* name, const char* title, const char* context) + : FairParGenericSet(name, title, context) + , fGeoSensNodes(new TObjArray()) + , fGeoPassNodes(new TObjArray()) +{} -FairTutorialDet1GeoPar::~FairTutorialDet1GeoPar(void) -{ -} +FairTutorialDet1GeoPar::~FairTutorialDet1GeoPar(void) {} void FairTutorialDet1GeoPar::clear(void) { - delete fGeoSensNodes; - delete fGeoPassNodes; + delete fGeoSensNodes; + delete fGeoPassNodes; } void FairTutorialDet1GeoPar::putParams(FairParamList* l) { - if (!l) { return; } - l->addObject("FairGeoNodes Sensitive List", fGeoSensNodes); - l->addObject("FairGeoNodes Passive List", fGeoPassNodes); + if (!l) { + return; + } + l->addObject("FairGeoNodes Sensitive List", fGeoSensNodes); + l->addObject("FairGeoNodes Passive List", fGeoPassNodes); } Bool_t FairTutorialDet1GeoPar::getParams(FairParamList* l) { - if (!l) { return kFALSE; } - if (!l->fillObject("FairGeoNodes Sensitive List", fGeoSensNodes)) { return kFALSE; } - if (!l->fillObject("FairGeoNodes Passive List", fGeoPassNodes)) { return kFALSE; } - return kTRUE; + if (!l) { + return kFALSE; + } + if (!l->fillObject("FairGeoNodes Sensitive List", fGeoSensNodes)) { + return kFALSE; + } + if (!l->fillObject("FairGeoNodes Passive List", fGeoPassNodes)) { + return kFALSE; + } + return kTRUE; } diff --git a/examples/simulation/Tutorial1/src/FairTutorialDet1GeoPar.h b/examples/simulation/Tutorial1/src/FairTutorialDet1GeoPar.h index 1c43647c09..ac8c98d875 100644 --- a/examples/simulation/Tutorial1/src/FairTutorialDet1GeoPar.h +++ b/examples/simulation/Tutorial1/src/FairTutorialDet1GeoPar.h @@ -1,16 +1,16 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRTUTORIALDET1GEOPAR_H #define FAIRTUTORIALDET1GEOPAR_H -#include "FairParGenericSet.h" // for FairParGenericSet +#include "FairParGenericSet.h" // for FairParGenericSet -#include // for ClassDef +#include // for ClassDef class TObjArray; class FairParamList; @@ -24,21 +24,21 @@ class FairTutorialDet1GeoPar : public FairParGenericSet /** List of FairGeoNodes for sensitive volumes */ TObjArray* fGeoPassNodes; - FairTutorialDet1GeoPar(const char* name="FairTutorialDet1GeoPar", - const char* title="FairTutorialDet1 Geometry Parameters", - const char* context="TestDefaultContext"); + FairTutorialDet1GeoPar(const char* name = "FairTutorialDet1GeoPar", + const char* title = "FairTutorialDet1 Geometry Parameters", + const char* context = "TestDefaultContext"); ~FairTutorialDet1GeoPar(void); void clear(void); void putParams(FairParamList*); Bool_t getParams(FairParamList*); - TObjArray* GetGeoSensitiveNodes() {return fGeoSensNodes;} - TObjArray* GetGeoPassiveNodes() {return fGeoPassNodes;} + TObjArray* GetGeoSensitiveNodes() { return fGeoSensNodes; } + TObjArray* GetGeoPassiveNodes() { return fGeoPassNodes; } private: FairTutorialDet1GeoPar(const FairTutorialDet1GeoPar&); FairTutorialDet1GeoPar& operator=(const FairTutorialDet1GeoPar&); - ClassDef(FairTutorialDet1GeoPar,1) + ClassDef(FairTutorialDet1GeoPar, 1) }; #endif /* FAIRTUTORIALDETGEOPAR_H */ diff --git a/examples/simulation/Tutorial1/src/FairTutorialDet1Point.cxx b/examples/simulation/Tutorial1/src/FairTutorialDet1Point.cxx index 26f16f894b..1107209d52 100644 --- a/examples/simulation/Tutorial1/src/FairTutorialDet1Point.cxx +++ b/examples/simulation/Tutorial1/src/FairTutorialDet1Point.cxx @@ -10,26 +10,28 @@ #include "FairLogger.h" FairTutorialDet1Point::FairTutorialDet1Point() - : FairMCPoint() -{ -} + : FairMCPoint() +{} -FairTutorialDet1Point::FairTutorialDet1Point(Int_t trackID, Int_t detID, - TVector3 pos, TVector3 mom, - Double_t tof, Double_t length, - Double_t eLoss) - : FairMCPoint(trackID, detID, pos, mom, tof, length, eLoss) -{ -} +FairTutorialDet1Point::FairTutorialDet1Point(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t tof, + Double_t length, + Double_t eLoss) + : FairMCPoint(trackID, detID, pos, mom, tof, length, eLoss) +{} -FairTutorialDet1Point::~FairTutorialDet1Point() { } +FairTutorialDet1Point::~FairTutorialDet1Point() {} void FairTutorialDet1Point::Print(const Option_t* /*opt*/) const { - LOG(info) << "TutorialDet point for track " << fTrackID << " in detector " << fDetectorID; - LOG(info) << " Position (" << fX << ", " << fY << ", " << fZ << ") cm"; - LOG(info) << " Momentum (" << fPx << ", " << fPy << ", " << fPz << ") GeV"; - LOG(info) << " Time " << fTime << " ns, Length " << fLength << " cm, Energy loss " << fELoss*1.0e06 << " keV"; + LOG(info) << "TutorialDet point for track " << fTrackID << " in detector " << fDetectorID; + LOG(info) << " Position (" << fX << ", " << fY << ", " << fZ << ") cm"; + LOG(info) << " Momentum (" << fPx << ", " << fPy << ", " << fPz << ") GeV"; + LOG(info) << " Time " << fTime << " ns, Length " << fLength << " cm, Energy loss " << fELoss * 1.0e06 + << " keV"; } -ClassImp(FairTutorialDet1Point) +ClassImp(FairTutorialDet1Point); diff --git a/examples/simulation/Tutorial1/src/FairTutorialDet1Point.h b/examples/simulation/Tutorial1/src/FairTutorialDet1Point.h index baa33659cb..2d988bc334 100644 --- a/examples/simulation/Tutorial1/src/FairTutorialDet1Point.h +++ b/examples/simulation/Tutorial1/src/FairTutorialDet1Point.h @@ -1,17 +1,17 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRTUTORIALDET1POINT_H #define FAIRTUTORIALDET1POINT_H 1 -#include "FairMCPoint.h" // for FairMCPoint +#include "FairMCPoint.h" // for FairMCPoint -#include // for Double_t, etc -#include // for TVector3 +#include // for Double_t, etc +#include // for TVector3 class FairTutorialDet1Point : public FairMCPoint { @@ -28,8 +28,13 @@ class FairTutorialDet1Point : public FairMCPoint *@param length Track length since creation [cm] *@param eLoss Energy deposit [GeV] **/ - FairTutorialDet1Point(Int_t trackID, Int_t detID, TVector3 pos, TVector3 mom, - Double_t tof, Double_t length, Double_t eLoss); + FairTutorialDet1Point(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t tof, + Double_t length, + Double_t eLoss); /** Copy constructor **/ // FairTutorialDet1Point(const FairTutorialDet1Point& point) { *this = point; }; @@ -40,7 +45,7 @@ class FairTutorialDet1Point : public FairMCPoint /** Output to screen **/ virtual void Print(const Option_t* opt) const; - ClassDef(FairTutorialDet1Point,1) + ClassDef(FairTutorialDet1Point, 1) }; #endif diff --git a/examples/simulation/Tutorial1/src/runTutorial1.cxx b/examples/simulation/Tutorial1/src/runTutorial1.cxx index bc7655271b..6132aeacf3 100644 --- a/examples/simulation/Tutorial1/src/runTutorial1.cxx +++ b/examples/simulation/Tutorial1/src/runTutorial1.cxx @@ -5,24 +5,21 @@ * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ +#include "../macros/run_tutorial1_binary.C" #include "FairLogger.h" #include "FairSimConfig.h" -#include "../macros/run_tutorial1_binary.C" - int main(int argc, char* argv[]) { FairSimConfig simConfig; int value = simConfig.ParseCommandLine(argc, argv); - if (value) - { + if (value) { return 0; } - if (simConfig.IsHelp()) - { + if (simConfig.IsHelp()) { simConfig.PrintHelpMessage(); return 0; } diff --git a/examples/simulation/Tutorial2/macros/create_digis.C b/examples/simulation/Tutorial2/macros/create_digis.C index b3b2341787..ee3caefa61 100644 --- a/examples/simulation/Tutorial2/macros/create_digis.C +++ b/examples/simulation/Tutorial2/macros/create_digis.C @@ -5,12 +5,13 @@ * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ -void create_digis(){ +void create_digis() +{ TStopwatch timer; timer.Start(); - gDebug=0; + gDebug = 0; TString dir = getenv("VMCWORKDIR"); TString tutdir = dir + "/simulation/Tutorial2"; @@ -25,51 +26,48 @@ void create_digis(){ cout << "OutFile: " << outFile << endl; cout << "******************************" << endl; - FairRunAna *fRun= new FairRunAna(); - FairFileSource *fFileSource = new FairFileSource(inFile); + FairRunAna* fRun = new FairRunAna(); + FairFileSource* fFileSource = new FairFileSource(inFile); fRun->SetSource(fFileSource); fRun->SetSink(new FairRootFileSink(outFile)); - // Init Simulation Parameters from Root File - FairRuntimeDb* rtdb=fRun->GetRuntimeDb(); - FairParRootFileIo* io1=new FairParRootFileIo(); - io1->open(parFile.Data(),"UPDATE"); + FairRuntimeDb* rtdb = fRun->GetRuntimeDb(); + FairParRootFileIo* io1 = new FairParRootFileIo(); + io1->open(parFile.Data(), "UPDATE"); FairParAsciiFileIo* parInput2 = new FairParAsciiFileIo(); TString tutDetDigiFile = gSystem->Getenv("VMCWORKDIR"); tutDetDigiFile += "/simulation/Tutorial2/parameters/tutdet.digi.par"; - parInput2->open(tutDetDigiFile.Data(),"in"); + parInput2->open(tutDetDigiFile.Data(), "in"); rtdb->setFirstInput(io1); rtdb->setSecondInput(parInput2); - rtdb->print(); + rtdb->print(); //** TUt Det Digi Producer **// - FairTutorialDet2Digitizer *digi = new FairTutorialDet2Digitizer("tutdet","tut det task"); + FairTutorialDet2Digitizer* digi = new FairTutorialDet2Digitizer("tutdet", "tut det task"); // add the task - fRun->AddTask( digi ); + fRun->AddTask(digi); // add another task (to test reading data from in memory branches) - fRun->AddTask( new FairTutorialDet2CustomTask() ); + fRun->AddTask(new FairTutorialDet2CustomTask()); fRun->Init(); rtdb->getContainer("FairTutorialDet2DigiPar")->print(); - FairTutorialDet2DigiPar* DigiPar = (FairTutorialDet2DigiPar*) - rtdb->getContainer("FairTutorialDet2DigiPar"); + FairTutorialDet2DigiPar* DigiPar = (FairTutorialDet2DigiPar*)rtdb->getContainer("FairTutorialDet2DigiPar"); DigiPar->setChanged(); - DigiPar->setInputVersion(fRun->GetRunId(),1); + DigiPar->setInputVersion(fRun->GetRunId(), 1); rtdb->setOutput(io1); rtdb->saveOutput(); rtdb->print(); - fRun->Run(); // ----- Finish ------------------------------------------------------- @@ -79,7 +77,7 @@ void create_digis(){ // Extract the maximal used memory an add is as Dart measurement // This line is filtered by CTest and the value send to CDash FairSystemInfo sysInfo; - Float_t maxMemory=sysInfo.GetMaxMemory(); + Float_t maxMemory = sysInfo.GetMaxMemory(); cout << ""; cout << maxMemory; cout << "" << endl; @@ -88,16 +86,15 @@ void create_digis(){ Double_t rtime = timer.RealTime(); Double_t ctime = timer.CpuTime(); - Float_t cpuUsage=ctime/rtime; + Float_t cpuUsage = ctime / rtime; cout << ""; cout << cpuUsage; cout << "" << endl; cout << endl << endl; - cout << "Output file is " << outFile << endl; + cout << "Output file is " << outFile << endl; cout << "Parameter file is " << parFile << endl; - cout << "Real time " << rtime << " s, CPU time " << ctime - << "s" << endl << endl; + cout << "Real time " << rtime << " s, CPU time " << ctime << "s" << endl << endl; cout << "Macro finished successfully." << endl; // ------------------------------------------------------------------------ diff --git a/examples/simulation/Tutorial2/macros/create_digis_mixed.C b/examples/simulation/Tutorial2/macros/create_digis_mixed.C index fdbc3b3439..5a123d4d55 100644 --- a/examples/simulation/Tutorial2/macros/create_digis_mixed.C +++ b/examples/simulation/Tutorial2/macros/create_digis_mixed.C @@ -1,9 +1,10 @@ -void create_digis_mixed(){ +void create_digis_mixed() +{ TStopwatch timer; timer.Start(); - gDebug=0; + gDebug = 0; TString dir = getenv("VMCWORKDIR"); TString tutdir = dir + "/simulation/Tutorial2"; @@ -23,15 +24,15 @@ void create_digis_mixed(){ cout << "OutFile: " << outFile << endl; cout << "******************************" << endl; - FairRunAna *fRun= new FairRunAna(); + FairRunAna* fRun = new FairRunAna(); //** Create a mixed source and set BG file *// - FairMixedSource *fMixedSource = new FairMixedSource(BGinFile.Data(),0); + FairMixedSource* fMixedSource = new FairMixedSource(BGinFile.Data(), 0); //** Set first signal file */ - fMixedSource->AddSignalFile(SG1inFile,1); + fMixedSource->AddSignalFile(SG1inFile, 1); //** Set second signal file */ - fMixedSource->AddSignalFile(SG2inFile,2); + fMixedSource->AddSignalFile(SG2inFile, 2); fRun->SetSource(fMixedSource); @@ -40,9 +41,9 @@ void create_digis_mixed(){ //----- Mix using entries ---------------------------------------- /** for each ~20 entries background 1 entry from signal chain 1 will be read */ - //fRun->BGWindowWidthNo(20,1); + // fRun->BGWindowWidthNo(20,1); /** for each ~30 entries background 1 entry from signal chain 2 will be read */ - //fRun->BGWindowWidthNo(30,2); + // fRun->BGWindowWidthNo(30,2); //----- Mix using time ---------------------------------------- @@ -50,19 +51,19 @@ void create_digis_mixed(){ fRun->SetEventMeanTime(10); /** each ~100 ns background 1 entry from signal chain 1 will be read */ - fRun->BGWindowWidthTime(100,1); + fRun->BGWindowWidthTime(100, 1); /** each ~60 ns background 1 entry from signal chain 2 will be read */ - fRun->BGWindowWidthTime(60,2); + fRun->BGWindowWidthTime(60, 2); // Init Simulation Parameters from Root File - FairRuntimeDb* rtdb=fRun->GetRuntimeDb(); - FairParRootFileIo* io1=new FairParRootFileIo(); - io1->open(parFile.Data(),"UPDATE"); + FairRuntimeDb* rtdb = fRun->GetRuntimeDb(); + FairParRootFileIo* io1 = new FairParRootFileIo(); + io1->open(parFile.Data(), "UPDATE"); FairParAsciiFileIo* parInput2 = new FairParAsciiFileIo(); TString tutDetDigiFile = gSystem->Getenv("VMCWORKDIR"); tutDetDigiFile += "/simulation/Tutorial2/parameters/tutdet.digi.par"; - parInput2->open(tutDetDigiFile.Data(),"in"); + parInput2->open(tutDetDigiFile.Data(), "in"); rtdb->setFirstInput(io1); rtdb->setSecondInput(parInput2); @@ -71,25 +72,23 @@ void create_digis_mixed(){ //** TUt Det Digi Producer **// - FairTutorialDet2Digitizer *digi = new FairTutorialDet2Digitizer("tutdet","tut det task"); + FairTutorialDet2Digitizer* digi = new FairTutorialDet2Digitizer("tutdet", "tut det task"); // add the task - fRun->AddTask( digi ); + fRun->AddTask(digi); fRun->Init(); rtdb->getContainer("FairTutorialDet2DigiPar")->print(); - FairTutorialDet2DigiPar* DigiPar = (FairTutorialDet2DigiPar*) - rtdb->getContainer("FairTutorialDet2DigiPar"); + FairTutorialDet2DigiPar* DigiPar = (FairTutorialDet2DigiPar*)rtdb->getContainer("FairTutorialDet2DigiPar"); DigiPar->setChanged(); - DigiPar->setInputVersion(fRun->GetRunId(),1); + DigiPar->setInputVersion(fRun->GetRunId(), 1); rtdb->setOutput(io1); rtdb->saveOutput(); rtdb->print(); - fRun->Run(); // ----- Finish ------------------------------------------------------- @@ -99,7 +98,7 @@ void create_digis_mixed(){ // Extract the maximal used memory an add is as Dart measurement // This line is filtered by CTest and the value send to CDash FairSystemInfo sysInfo; - Float_t maxMemory=sysInfo.GetMaxMemory(); + Float_t maxMemory = sysInfo.GetMaxMemory(); cout << ""; cout << maxMemory; cout << "" << endl; @@ -108,15 +107,14 @@ void create_digis_mixed(){ Double_t rtime = timer.RealTime(); Double_t ctime = timer.CpuTime(); - Float_t cpuUsage=ctime/rtime; + Float_t cpuUsage = ctime / rtime; cout << ""; cout << cpuUsage; cout << "" << endl; cout << endl << endl; - cout << "Output file is " << outFile << endl; + cout << "Output file is " << outFile << endl; cout << "Parameter file is " << parFile << endl; - cout << "Real time " << rtime << " s, CPU time " << ctime - << "s" << endl << endl; + cout << "Real time " << rtime << " s, CPU time " << ctime << "s" << endl << endl; cout << "Macro finished successfully." << endl; } diff --git a/examples/simulation/Tutorial2/macros/read_digis.C b/examples/simulation/Tutorial2/macros/read_digis.C index 843d4c4ee9..49d6865b30 100644 --- a/examples/simulation/Tutorial2/macros/read_digis.C +++ b/examples/simulation/Tutorial2/macros/read_digis.C @@ -5,7 +5,8 @@ * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ -void read_digis(){ +void read_digis() +{ TStopwatch timer; timer.Start(); @@ -23,23 +24,21 @@ void read_digis(){ cout << "OutFile: " << outFile << endl; cout << "******************************" << endl; - FairRunAna *fRun= new FairRunAna(); - FairFileSource *fFileSource = new FairFileSource(inFile); + FairRunAna* fRun = new FairRunAna(); + FairFileSource* fFileSource = new FairFileSource(inFile); fRun->SetSource(fFileSource); fRun->SetSink(new FairRootFileSink(outFile)); - // Init Simulation Parameters from Root File - FairRuntimeDb* rtdb=fRun->GetRuntimeDb(); - FairParRootFileIo* io1=new FairParRootFileIo(); - io1->open(parFile.Data(),"UPDATE"); + FairRuntimeDb* rtdb = fRun->GetRuntimeDb(); + FairParRootFileIo* io1 = new FairParRootFileIo(); + io1->open(parFile.Data(), "UPDATE"); // Fallback solution if paramters are not found in database (ROOT file) FairParAsciiFileIo* parInput2 = new FairParAsciiFileIo(); TString tutDetDigiFile = gSystem->Getenv("VMCWORKDIR"); tutDetDigiFile += "/simulation/Tutorial2/parameters/tutdet.digi.par"; - parInput2->open(tutDetDigiFile.Data(),"in"); - + parInput2->open(tutDetDigiFile.Data(), "in"); // The parameter container is initialized from first input since it // is available from the ROOT parameter file. The second input is the @@ -73,20 +72,18 @@ void read_digis(){ rtdb->saveOutput(); // -- Print out the random seed from the simulation ---------------------- - FairBaseParSet* BasePar= (FairBaseParSet *) - rtdb->getContainer("FairBaseParSet"); - cout<<"RndSeed used in simulation was " << BasePar->GetRndSeed() << endl; + FairBaseParSet* BasePar = (FairBaseParSet*)rtdb->getContainer("FairBaseParSet"); + cout << "RndSeed used in simulation was " << BasePar->GetRndSeed() << endl; // ----------------------------------------------------------------------- // Second version to print the parameters // which also shows how to change and save them again - FairTutorialDet2DigiPar* DigiPar = (FairTutorialDet2DigiPar*) - rtdb->getContainer("FairTutorialDet2DigiPar"); + FairTutorialDet2DigiPar* DigiPar = (FairTutorialDet2DigiPar*)rtdb->getContainer("FairTutorialDet2DigiPar"); DigiPar->setChanged(); - DigiPar->setInputVersion(fRun->GetRunId(),1); + DigiPar->setInputVersion(fRun->GetRunId(), 1); // If you want to confirm that the parameters are really there you can // print them by disabling the following line DigiPar->printParams(); @@ -103,7 +100,7 @@ void read_digis(){ // Extract the maximal used memory an add is as Dart measurement // This line is filtered by CTest and the value send to CDash FairSystemInfo sysInfo; - Float_t maxMemory=sysInfo.GetMaxMemory(); + Float_t maxMemory = sysInfo.GetMaxMemory(); cout << ""; cout << maxMemory; cout << "" << endl; @@ -112,15 +109,14 @@ void read_digis(){ Double_t rtime = timer.RealTime(); Double_t ctime = timer.CpuTime(); - Float_t cpuUsage=ctime/rtime; + Float_t cpuUsage = ctime / rtime; cout << ""; cout << cpuUsage; cout << "" << endl; cout << endl << endl; - cout << "Output file is " << outFile << endl; + cout << "Output file is " << outFile << endl; cout << "Parameter file is " << parFile << endl; - cout << "Real time " << rtime << " s, CPU time " << ctime - << "s" << endl << endl; + cout << "Real time " << rtime << " s, CPU time " << ctime << "s" << endl << endl; cout << "Macro finished successfully." << endl; } diff --git a/examples/simulation/Tutorial2/macros/run_background.C b/examples/simulation/Tutorial2/macros/run_background.C old mode 100755 new mode 100644 index 4b51fbbbc2..6ed06e0f6f --- a/examples/simulation/Tutorial2/macros/run_background.C +++ b/examples/simulation/Tutorial2/macros/run_background.C @@ -1,130 +1,129 @@ void run_background(Int_t nEvents = 130) { - TString dir = getenv("VMCWORKDIR"); - TString tutdir = dir + "/simulation/Tutorial2"; + TString dir = getenv("VMCWORKDIR"); + TString tutdir = dir + "/simulation/Tutorial2"; - TString tut_geomdir = dir + "/common/geometry"; - gSystem->Setenv("GEOMPATH",tut_geomdir.Data()); - - TString tut_configdir = dir + "/common/gconfig"; - gSystem->Setenv("CONFIG_DIR",tut_configdir.Data()); - - TString partName[] = {"pions","eplus","proton"}; - Int_t partPdgC[] = { 211, 11, 2212}; - Int_t chosenPart = 0; - - Double_t momentum = 2.; - - Double_t theta = 0.; - - TString outDir = "./"; - - // Output file name - TString outFile = Form("%s/tutorial2_%s.mc_p%1.3f_t%1.0f_n%d.bg.root", - outDir.Data(), - partName[chosenPart].Data(), - momentum, - theta, - nEvents); - - // Parameter file name - TString parFile = Form("%s/tutorial2_%s.params_p%1.3f_t%1.0f_n%d.bg.root", - outDir.Data(), - partName[chosenPart].Data(), - momentum, - theta, - nEvents); - - // In general, the following parts need not be touched - // ======================================================================== - - // ---- Debug option ------------------------------------------------- - gDebug = 0; - // ------------------------------------------------------------------------ - - // ----- Timer -------------------------------------------------------- - TStopwatch timer; - timer.Start(); - // ------------------------------------------------------------------------ - - // ----- Create simulation run ---------------------------------------- - FairRunSim* run = new FairRunSim(); - run->SetName("TGeant3"); // Transport engine - run->SetSink(new FairRootFileSink(outFile)); // Output file - FairRuntimeDb* rtdb = run->GetRuntimeDb(); - // ------------------------------------------------------------------------ - - // ----- Create media ------------------------------------------------- - run->SetMaterials("media.geo"); // Materials - // ------------------------------------------------------------------------ - - // ----- Create geometry ---------------------------------------------- - FairModule* cave= new FairCave("CAVE"); - cave->SetGeometryFileName("cave_vacuum.geo"); - run->AddModule(cave); - - FairDetector* tutdet = new FairTutorialDet2("TUTDET", kTRUE); - tutdet->SetGeometryFileName("double_sector.geo"); - run->AddModule(tutdet); - // ------------------------------------------------------------------------ - - // ----- Create PrimaryGenerator -------------------------------------- - FairPrimaryGenerator* primGen = new FairPrimaryGenerator(); - FairBoxGenerator* boxGen = new FairBoxGenerator(partPdgC[chosenPart], 1); - - boxGen->SetThetaRange ( theta, theta+0.01); - boxGen->SetPRange (momentum,momentum+0.01); - boxGen->SetPhiRange (0.,360.); - - primGen->AddGenerator(boxGen); - - run->SetGenerator(primGen); - // ------------------------------------------------------------------------ - - // ----- Initialize simulation run ------------------------------------ - run->Init(); - // ------------------------------------------------------------------------ - - // ----- Runtime database --------------------------------------------- - Bool_t kParameterMerged = kTRUE; - FairParRootFileIo* parOut = new FairParRootFileIo(kParameterMerged); - parOut->open(parFile.Data()); - rtdb->setOutput(parOut); - rtdb->saveOutput(); - rtdb->print(); - // ------------------------------------------------------------------------ - - // ----- Start run ---------------------------------------------------- - run->Run(nEvents); - // ------------------------------------------------------------------------ - - // ----- Finish ------------------------------------------------------- - - cout << endl << endl; - - // Extract the maximal used memory an add is as Dart measurement - // This line is filtered by CTest and the value send to CDash - FairSystemInfo sysInfo; - Float_t maxMemory=sysInfo.GetMaxMemory(); - cout << ""; - cout << maxMemory; - cout << "" << endl; - - timer.Stop(); - Double_t rtime = timer.RealTime(); - Double_t ctime = timer.CpuTime(); - - Float_t cpuUsage=ctime/rtime; - cout << ""; - cout << cpuUsage; - cout << "" << endl; - - cout << endl << endl; - cout << "Output file is " << outFile << endl; - cout << "Parameter file is " << parFile << endl; - cout << "Real time " << rtime << " s, CPU time " << ctime - << "s" << endl << endl; - cout << "Macro finished successfully." << endl; - - // ------------------------------------------------------------------------ + TString tut_geomdir = dir + "/common/geometry"; + gSystem->Setenv("GEOMPATH", tut_geomdir.Data()); + + TString tut_configdir = dir + "/common/gconfig"; + gSystem->Setenv("CONFIG_DIR", tut_configdir.Data()); + + TString partName[] = {"pions", "eplus", "proton"}; + Int_t partPdgC[] = {211, 11, 2212}; + Int_t chosenPart = 0; + + Double_t momentum = 2.; + + Double_t theta = 0.; + + TString outDir = "./"; + + // Output file name + TString outFile = Form("%s/tutorial2_%s.mc_p%1.3f_t%1.0f_n%d.bg.root", + outDir.Data(), + partName[chosenPart].Data(), + momentum, + theta, + nEvents); + + // Parameter file name + TString parFile = Form("%s/tutorial2_%s.params_p%1.3f_t%1.0f_n%d.bg.root", + outDir.Data(), + partName[chosenPart].Data(), + momentum, + theta, + nEvents); + + // In general, the following parts need not be touched + // ======================================================================== + + // ---- Debug option ------------------------------------------------- + gDebug = 0; + // ------------------------------------------------------------------------ + + // ----- Timer -------------------------------------------------------- + TStopwatch timer; + timer.Start(); + // ------------------------------------------------------------------------ + + // ----- Create simulation run ---------------------------------------- + FairRunSim* run = new FairRunSim(); + run->SetName("TGeant3"); // Transport engine + run->SetSink(new FairRootFileSink(outFile)); // Output file + FairRuntimeDb* rtdb = run->GetRuntimeDb(); + // ------------------------------------------------------------------------ + + // ----- Create media ------------------------------------------------- + run->SetMaterials("media.geo"); // Materials + // ------------------------------------------------------------------------ + + // ----- Create geometry ---------------------------------------------- + FairModule* cave = new FairCave("CAVE"); + cave->SetGeometryFileName("cave_vacuum.geo"); + run->AddModule(cave); + + FairDetector* tutdet = new FairTutorialDet2("TUTDET", kTRUE); + tutdet->SetGeometryFileName("double_sector.geo"); + run->AddModule(tutdet); + // ------------------------------------------------------------------------ + + // ----- Create PrimaryGenerator -------------------------------------- + FairPrimaryGenerator* primGen = new FairPrimaryGenerator(); + FairBoxGenerator* boxGen = new FairBoxGenerator(partPdgC[chosenPart], 1); + + boxGen->SetThetaRange(theta, theta + 0.01); + boxGen->SetPRange(momentum, momentum + 0.01); + boxGen->SetPhiRange(0., 360.); + + primGen->AddGenerator(boxGen); + + run->SetGenerator(primGen); + // ------------------------------------------------------------------------ + + // ----- Initialize simulation run ------------------------------------ + run->Init(); + // ------------------------------------------------------------------------ + + // ----- Runtime database --------------------------------------------- + Bool_t kParameterMerged = kTRUE; + FairParRootFileIo* parOut = new FairParRootFileIo(kParameterMerged); + parOut->open(parFile.Data()); + rtdb->setOutput(parOut); + rtdb->saveOutput(); + rtdb->print(); + // ------------------------------------------------------------------------ + + // ----- Start run ---------------------------------------------------- + run->Run(nEvents); + // ------------------------------------------------------------------------ + + // ----- Finish ------------------------------------------------------- + + cout << endl << endl; + + // Extract the maximal used memory an add is as Dart measurement + // This line is filtered by CTest and the value send to CDash + FairSystemInfo sysInfo; + Float_t maxMemory = sysInfo.GetMaxMemory(); + cout << ""; + cout << maxMemory; + cout << "" << endl; + + timer.Stop(); + Double_t rtime = timer.RealTime(); + Double_t ctime = timer.CpuTime(); + + Float_t cpuUsage = ctime / rtime; + cout << ""; + cout << cpuUsage; + cout << "" << endl; + + cout << endl << endl; + cout << "Output file is " << outFile << endl; + cout << "Parameter file is " << parFile << endl; + cout << "Real time " << rtime << " s, CPU time " << ctime << "s" << endl << endl; + cout << "Macro finished successfully." << endl; + + // ------------------------------------------------------------------------ } diff --git a/examples/simulation/Tutorial2/macros/run_signal.C b/examples/simulation/Tutorial2/macros/run_signal.C old mode 100755 new mode 100644 index 2fc715f250..d55ff3076b --- a/examples/simulation/Tutorial2/macros/run_signal.C +++ b/examples/simulation/Tutorial2/macros/run_signal.C @@ -1,132 +1,131 @@ void run_signal(Int_t fileNr, Int_t nEvents = 10) { - TString dir = getenv("VMCWORKDIR"); - TString tutdir = dir + "/simulation/Tutorial2"; - - TString tut_geomdir = dir + "/common/geometry"; - gSystem->Setenv("GEOMPATH",tut_geomdir.Data()); - - TString tut_configdir = dir + "/common/gconfig"; - gSystem->Setenv("CONFIG_DIR",tut_configdir.Data()); - - TString partName[] = {"pions","eplus","proton"}; - Int_t partPdgC[] = { 211, 11, 2212}; - Int_t chosenPart = 0; - - Double_t momentum = 2.; - - Double_t theta = 0.; - - TString outDir = "./"; - - // Output file name - TString outFile = Form("%s/tutorial2_%s.mc_p%1.3f_t%1.0f_n%d.sg%d.root", - outDir.Data(), - partName[chosenPart].Data(), - momentum, - theta, - nEvents, - fileNr); - - // Parameter file name - TString parFile = Form("%s/tutorial2_%s.params_p%1.3f_t%1.0f_n%d.sg%d.root", - outDir.Data(), - partName[chosenPart].Data(), - momentum, - theta, - nEvents, - fileNr); - - // In general, the following parts need not be touched - // ======================================================================== - - // ---- Debug option ------------------------------------------------- - gDebug = 0; - // ------------------------------------------------------------------------ - - // ----- Timer -------------------------------------------------------- - TStopwatch timer; - timer.Start(); - // ------------------------------------------------------------------------ - - // ----- Create simulation run ---------------------------------------- - FairRunSim* run = new FairRunSim(); - run->SetName("TGeant3"); // Transport engine - run->SetSink(new FairRootFileSink(outFile)); // Output file - FairRuntimeDb* rtdb = run->GetRuntimeDb(); - // ------------------------------------------------------------------------ - - // ----- Create media ------------------------------------------------- - run->SetMaterials("media.geo"); // Materials - // ------------------------------------------------------------------------ - - // ----- Create geometry ---------------------------------------------- - FairModule* cave= new FairCave("CAVE"); - cave->SetGeometryFileName("cave_vacuum.geo"); - run->AddModule(cave); - - FairDetector* tutdet = new FairTutorialDet2("TUTDET", kTRUE); - tutdet->SetGeometryFileName("double_sector.geo"); - run->AddModule(tutdet); - // ------------------------------------------------------------------------ - - // ----- Create PrimaryGenerator -------------------------------------- - FairPrimaryGenerator* primGen = new FairPrimaryGenerator(); - FairBoxGenerator* boxGen = new FairBoxGenerator(partPdgC[chosenPart], 1); - - boxGen->SetThetaRange ( theta, theta+0.01); - boxGen->SetPRange (momentum,momentum+0.01); - boxGen->SetPhiRange (0.,360.); - - primGen->AddGenerator(boxGen); - - run->SetGenerator(primGen); - // ------------------------------------------------------------------------ - - // ----- Initialize simulation run ------------------------------------ - run->Init(); - // ------------------------------------------------------------------------ - - // ----- Runtime database --------------------------------------------- - Bool_t kParameterMerged = kTRUE; - FairParRootFileIo* parOut = new FairParRootFileIo(kParameterMerged); - parOut->open(parFile.Data()); - rtdb->setOutput(parOut); - rtdb->saveOutput(); - rtdb->print(); - // ------------------------------------------------------------------------ - - // ----- Start run ---------------------------------------------------- - run->Run(nEvents); - // ------------------------------------------------------------------------ - - // ----- Finish ------------------------------------------------------- - - cout << endl << endl; - - // Extract the maximal used memory an add is as Dart measurement - // This line is filtered by CTest and the value send to CDash - FairSystemInfo sysInfo; - Float_t maxMemory=sysInfo.GetMaxMemory(); - cout << ""; - cout << maxMemory; - cout << "" << endl; - - timer.Stop(); - Double_t rtime = timer.RealTime(); - Double_t ctime = timer.CpuTime(); - - Float_t cpuUsage=ctime/rtime; - cout << ""; - cout << cpuUsage; - cout << "" << endl; - - cout << endl << endl; - cout << "Output file is " << outFile << endl; - cout << "Parameter file is " << parFile << endl; - cout << "Real time " << rtime << " s, CPU time " << ctime - << "s" << endl << endl; - cout << "Macro finished successfully." << endl; - - // ------------------------------------------------------------------------ + TString dir = getenv("VMCWORKDIR"); + TString tutdir = dir + "/simulation/Tutorial2"; + + TString tut_geomdir = dir + "/common/geometry"; + gSystem->Setenv("GEOMPATH", tut_geomdir.Data()); + + TString tut_configdir = dir + "/common/gconfig"; + gSystem->Setenv("CONFIG_DIR", tut_configdir.Data()); + + TString partName[] = {"pions", "eplus", "proton"}; + Int_t partPdgC[] = {211, 11, 2212}; + Int_t chosenPart = 0; + + Double_t momentum = 2.; + + Double_t theta = 0.; + + TString outDir = "./"; + + // Output file name + TString outFile = Form("%s/tutorial2_%s.mc_p%1.3f_t%1.0f_n%d.sg%d.root", + outDir.Data(), + partName[chosenPart].Data(), + momentum, + theta, + nEvents, + fileNr); + + // Parameter file name + TString parFile = Form("%s/tutorial2_%s.params_p%1.3f_t%1.0f_n%d.sg%d.root", + outDir.Data(), + partName[chosenPart].Data(), + momentum, + theta, + nEvents, + fileNr); + + // In general, the following parts need not be touched + // ======================================================================== + + // ---- Debug option ------------------------------------------------- + gDebug = 0; + // ------------------------------------------------------------------------ + + // ----- Timer -------------------------------------------------------- + TStopwatch timer; + timer.Start(); + // ------------------------------------------------------------------------ + + // ----- Create simulation run ---------------------------------------- + FairRunSim* run = new FairRunSim(); + run->SetName("TGeant3"); // Transport engine + run->SetSink(new FairRootFileSink(outFile)); // Output file + FairRuntimeDb* rtdb = run->GetRuntimeDb(); + // ------------------------------------------------------------------------ + + // ----- Create media ------------------------------------------------- + run->SetMaterials("media.geo"); // Materials + // ------------------------------------------------------------------------ + + // ----- Create geometry ---------------------------------------------- + FairModule* cave = new FairCave("CAVE"); + cave->SetGeometryFileName("cave_vacuum.geo"); + run->AddModule(cave); + + FairDetector* tutdet = new FairTutorialDet2("TUTDET", kTRUE); + tutdet->SetGeometryFileName("double_sector.geo"); + run->AddModule(tutdet); + // ------------------------------------------------------------------------ + + // ----- Create PrimaryGenerator -------------------------------------- + FairPrimaryGenerator* primGen = new FairPrimaryGenerator(); + FairBoxGenerator* boxGen = new FairBoxGenerator(partPdgC[chosenPart], 1); + + boxGen->SetThetaRange(theta, theta + 0.01); + boxGen->SetPRange(momentum, momentum + 0.01); + boxGen->SetPhiRange(0., 360.); + + primGen->AddGenerator(boxGen); + + run->SetGenerator(primGen); + // ------------------------------------------------------------------------ + + // ----- Initialize simulation run ------------------------------------ + run->Init(); + // ------------------------------------------------------------------------ + + // ----- Runtime database --------------------------------------------- + Bool_t kParameterMerged = kTRUE; + FairParRootFileIo* parOut = new FairParRootFileIo(kParameterMerged); + parOut->open(parFile.Data()); + rtdb->setOutput(parOut); + rtdb->saveOutput(); + rtdb->print(); + // ------------------------------------------------------------------------ + + // ----- Start run ---------------------------------------------------- + run->Run(nEvents); + // ------------------------------------------------------------------------ + + // ----- Finish ------------------------------------------------------- + + cout << endl << endl; + + // Extract the maximal used memory an add is as Dart measurement + // This line is filtered by CTest and the value send to CDash + FairSystemInfo sysInfo; + Float_t maxMemory = sysInfo.GetMaxMemory(); + cout << ""; + cout << maxMemory; + cout << "" << endl; + + timer.Stop(); + Double_t rtime = timer.RealTime(); + Double_t ctime = timer.CpuTime(); + + Float_t cpuUsage = ctime / rtime; + cout << ""; + cout << cpuUsage; + cout << "" << endl; + + cout << endl << endl; + cout << "Output file is " << outFile << endl; + cout << "Parameter file is " << parFile << endl; + cout << "Real time " << rtime << " s, CPU time " << ctime << "s" << endl << endl; + cout << "Macro finished successfully." << endl; + + // ------------------------------------------------------------------------ } diff --git a/examples/simulation/Tutorial2/macros/run_tutorial2.C b/examples/simulation/Tutorial2/macros/run_tutorial2.C index 4ffa5dfdbd..b5155648e2 100644 --- a/examples/simulation/Tutorial2/macros/run_tutorial2.C +++ b/examples/simulation/Tutorial2/macros/run_tutorial2.C @@ -5,138 +5,137 @@ * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ -void run_tutorial2(Int_t nEvents = 10, TString mcEngine = "TGeant3", Bool_t isMT=true) +void run_tutorial2(Int_t nEvents = 10, TString mcEngine = "TGeant3", Bool_t isMT = true) { - TString dir = getenv("VMCWORKDIR"); - TString tutdir = dir + "/simulation/Tutorial2"; - - TString tut_geomdir = dir + "/common/geometry"; - gSystem->Setenv("GEOMPATH",tut_geomdir.Data()); + TString dir = getenv("VMCWORKDIR"); + TString tutdir = dir + "/simulation/Tutorial2"; + + TString tut_geomdir = dir + "/common/geometry"; + gSystem->Setenv("GEOMPATH", tut_geomdir.Data()); - TString tut_configdir = dir + "/common/gconfig"; - gSystem->Setenv("CONFIG_DIR",tut_configdir.Data()); + TString tut_configdir = dir + "/common/gconfig"; + gSystem->Setenv("CONFIG_DIR", tut_configdir.Data()); - TString partName[] = {"pions","eplus","proton"}; - Int_t partPdgC[] = { 211, 11, 2212}; - Int_t chosenPart = 0; - - Double_t momentum = 2.; - - Double_t theta = 0.; - - TString outDir = "./"; - - // Output file name - TString outFile = Form("%s/tutorial2_%s.mc_p%1.3f_t%1.0f_n%d.root", - outDir.Data(), - partName[chosenPart].Data(), - momentum, - theta, - nEvents); - - // Parameter file name - TString parFile = Form("%s/tutorial2_%s.params_p%1.3f_t%1.0f_n%d.root", - outDir.Data(), - partName[chosenPart].Data(), - momentum, - theta, - nEvents); - - // Set the random seed - gRandom->SetSeed(98989); - - // In general, the following parts need not be touched - // ======================================================================== - - // ---- Debug option ------------------------------------------------- - gDebug = 0; - // ------------------------------------------------------------------------ - - // ----- Timer -------------------------------------------------------- - TStopwatch timer; - timer.Start(); - // ------------------------------------------------------------------------ - - // ----- Create simulation run ---------------------------------------- - FairRunSim* run = new FairRunSim(); - run->SetName(mcEngine); // Transport engine - run->SetIsMT(isMT); // Multi-threading mode (Geant4 only) - run->SetSink(new FairRootFileSink(outFile)); // Output file - FairRuntimeDb* rtdb = run->GetRuntimeDb(); - // ------------------------------------------------------------------------ - - // ----- Create media ------------------------------------------------- - run->SetMaterials("media.geo"); // Materials - // ------------------------------------------------------------------------ - - // ----- Create geometry ---------------------------------------------- - FairModule* cave= new FairCave("CAVE"); - cave->SetGeometryFileName("cave_vacuum.geo"); - run->AddModule(cave); - - FairDetector* tutdet = new FairTutorialDet2("TUTDET", kTRUE); - tutdet->SetGeometryFileName("double_sector.geo"); - run->AddModule(tutdet); - // ------------------------------------------------------------------------ - - // ----- Create PrimaryGenerator -------------------------------------- - FairPrimaryGenerator* primGen = new FairPrimaryGenerator(); - FairBoxGenerator* boxGen = new FairBoxGenerator(partPdgC[chosenPart], 1); - - boxGen->SetThetaRange ( theta, theta+0.01); - boxGen->SetPRange (momentum,momentum+0.01); - boxGen->SetPhiRange (0.,360.); - - primGen->AddGenerator(boxGen); - - run->SetGenerator(primGen); - // ------------------------------------------------------------------------ - - // ----- Initialize simulation run ------------------------------------ - run->Init(); - // ------------------------------------------------------------------------ - - // ----- Runtime database --------------------------------------------- - Bool_t kParameterMerged = kTRUE; - FairParRootFileIo* parOut = new FairParRootFileIo(kParameterMerged); - parOut->open(parFile.Data()); - rtdb->setOutput(parOut); - rtdb->saveOutput(); - rtdb->print(); - // ------------------------------------------------------------------------ - - // ----- Start run ---------------------------------------------------- - run->Run(nEvents); - // ------------------------------------------------------------------------ - - // ----- Finish ------------------------------------------------------- - - cout << endl << endl; - - // Extract the maximal used memory an add is as Dart measurement - // This line is filtered by CTest and the value send to CDash - FairSystemInfo sysInfo; - Float_t maxMemory=sysInfo.GetMaxMemory(); - cout << ""; - cout << maxMemory; - cout << "" << endl; - - timer.Stop(); - Double_t rtime = timer.RealTime(); - Double_t ctime = timer.CpuTime(); - - Float_t cpuUsage=ctime/rtime; - cout << ""; - cout << cpuUsage; - cout << "" << endl; - - cout << endl << endl; - cout << "Output file is " << outFile << endl; - cout << "Parameter file is " << parFile << endl; - cout << "Real time " << rtime << " s, CPU time " << ctime - << "s" << endl << endl; - cout << "Macro finished successfully." << endl; - - // ------------------------------------------------------------------------ + TString partName[] = {"pions", "eplus", "proton"}; + Int_t partPdgC[] = {211, 11, 2212}; + Int_t chosenPart = 0; + + Double_t momentum = 2.; + + Double_t theta = 0.; + + TString outDir = "./"; + + // Output file name + TString outFile = Form("%s/tutorial2_%s.mc_p%1.3f_t%1.0f_n%d.root", + outDir.Data(), + partName[chosenPart].Data(), + momentum, + theta, + nEvents); + + // Parameter file name + TString parFile = Form("%s/tutorial2_%s.params_p%1.3f_t%1.0f_n%d.root", + outDir.Data(), + partName[chosenPart].Data(), + momentum, + theta, + nEvents); + + // Set the random seed + gRandom->SetSeed(98989); + + // In general, the following parts need not be touched + // ======================================================================== + + // ---- Debug option ------------------------------------------------- + gDebug = 0; + // ------------------------------------------------------------------------ + + // ----- Timer -------------------------------------------------------- + TStopwatch timer; + timer.Start(); + // ------------------------------------------------------------------------ + + // ----- Create simulation run ---------------------------------------- + FairRunSim* run = new FairRunSim(); + run->SetName(mcEngine); // Transport engine + run->SetIsMT(isMT); // Multi-threading mode (Geant4 only) + run->SetSink(new FairRootFileSink(outFile)); // Output file + FairRuntimeDb* rtdb = run->GetRuntimeDb(); + // ------------------------------------------------------------------------ + + // ----- Create media ------------------------------------------------- + run->SetMaterials("media.geo"); // Materials + // ------------------------------------------------------------------------ + + // ----- Create geometry ---------------------------------------------- + FairModule* cave = new FairCave("CAVE"); + cave->SetGeometryFileName("cave_vacuum.geo"); + run->AddModule(cave); + + FairDetector* tutdet = new FairTutorialDet2("TUTDET", kTRUE); + tutdet->SetGeometryFileName("double_sector.geo"); + run->AddModule(tutdet); + // ------------------------------------------------------------------------ + + // ----- Create PrimaryGenerator -------------------------------------- + FairPrimaryGenerator* primGen = new FairPrimaryGenerator(); + FairBoxGenerator* boxGen = new FairBoxGenerator(partPdgC[chosenPart], 1); + + boxGen->SetThetaRange(theta, theta + 0.01); + boxGen->SetPRange(momentum, momentum + 0.01); + boxGen->SetPhiRange(0., 360.); + + primGen->AddGenerator(boxGen); + + run->SetGenerator(primGen); + // ------------------------------------------------------------------------ + + // ----- Initialize simulation run ------------------------------------ + run->Init(); + // ------------------------------------------------------------------------ + + // ----- Runtime database --------------------------------------------- + Bool_t kParameterMerged = kTRUE; + FairParRootFileIo* parOut = new FairParRootFileIo(kParameterMerged); + parOut->open(parFile.Data()); + rtdb->setOutput(parOut); + rtdb->saveOutput(); + rtdb->print(); + // ------------------------------------------------------------------------ + + // ----- Start run ---------------------------------------------------- + run->Run(nEvents); + // ------------------------------------------------------------------------ + + // ----- Finish ------------------------------------------------------- + + cout << endl << endl; + + // Extract the maximal used memory an add is as Dart measurement + // This line is filtered by CTest and the value send to CDash + FairSystemInfo sysInfo; + Float_t maxMemory = sysInfo.GetMaxMemory(); + cout << ""; + cout << maxMemory; + cout << "" << endl; + + timer.Stop(); + Double_t rtime = timer.RealTime(); + Double_t ctime = timer.CpuTime(); + + Float_t cpuUsage = ctime / rtime; + cout << ""; + cout << cpuUsage; + cout << "" << endl; + + cout << endl << endl; + cout << "Output file is " << outFile << endl; + cout << "Parameter file is " << parFile << endl; + cout << "Real time " << rtime << " s, CPU time " << ctime << "s" << endl << endl; + cout << "Macro finished successfully." << endl; + + // ------------------------------------------------------------------------ } diff --git a/examples/simulation/Tutorial2/src/FairTutorialDet2.cxx b/examples/simulation/Tutorial2/src/FairTutorialDet2.cxx index a40c31caa7..6afc36f1d9 100644 --- a/examples/simulation/Tutorial2/src/FairTutorialDet2.cxx +++ b/examples/simulation/Tutorial2/src/FairTutorialDet2.cxx @@ -1,19 +1,18 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "FairTutorialDet2.h" -#include "FairTutorialDet2Geo.h" -#include "FairTutorialDet2GeoPar.h" -#include "FairTutorialDet2Point.h" - #include "FairDetectorList.h" #include "FairRootManager.h" #include "FairStack.h" +#include "FairTutorialDet2Geo.h" +#include "FairTutorialDet2GeoPar.h" +#include "FairTutorialDet2Point.h" #include "FairVolume.h" #include @@ -27,157 +26,159 @@ FairTutorialDet2Geo* FairTutorialDet2::fgGeo; //! FairTutorialDet2::FairTutorialDet2() - : FairDetector("TutorialDet", kTRUE, kTutDet), - fTrackID(-1), - fVolumeID(-1), - fPos(), - fMom(), - fTime(-1.), - fLength(-1.), - fELoss(-1), - fFairTutorialDet2PointCollection(new TClonesArray("FairTutorialDet2Point")), - fCustomData(new Det2PointContainer()) -{ -} + : FairDetector("TutorialDet", kTRUE, kTutDet) + , fTrackID(-1) + , fVolumeID(-1) + , fPos() + , fMom() + , fTime(-1.) + , fLength(-1.) + , fELoss(-1) + , fFairTutorialDet2PointCollection(new TClonesArray("FairTutorialDet2Point")) + , fCustomData(new Det2PointContainer()) +{} FairTutorialDet2::FairTutorialDet2(const char* name, Bool_t active) - : FairDetector(name, active, kTutDet), - fTrackID(-1), - fVolumeID(-1), - fPos(), - fMom(), - fTime(-1.), - fLength(-1.), - fELoss(-1), - fFairTutorialDet2PointCollection(new TClonesArray("FairTutorialDet2Point")), - fCustomData(new Det2PointContainer()) -{ -} + : FairDetector(name, active, kTutDet) + , fTrackID(-1) + , fVolumeID(-1) + , fPos() + , fMom() + , fTime(-1.) + , fLength(-1.) + , fELoss(-1) + , fFairTutorialDet2PointCollection(new TClonesArray("FairTutorialDet2Point")) + , fCustomData(new Det2PointContainer()) +{} FairTutorialDet2::FairTutorialDet2(const FairTutorialDet2& rhs) - : FairDetector(rhs), - fTrackID(-1), - fVolumeID(-1), - fPos(), - fMom(), - fTime(-1.), - fLength(-1.), - fELoss(-1), - fFairTutorialDet2PointCollection(new TClonesArray("FairTutorialDet2Point")), - fCustomData(new Det2PointContainer()) -{ -} + : FairDetector(rhs) + , fTrackID(-1) + , fVolumeID(-1) + , fPos() + , fMom() + , fTime(-1.) + , fLength(-1.) + , fELoss(-1) + , fFairTutorialDet2PointCollection(new TClonesArray("FairTutorialDet2Point")) + , fCustomData(new Det2PointContainer()) +{} FairTutorialDet2::~FairTutorialDet2() { - if (fFairTutorialDet2PointCollection) { - fFairTutorialDet2PointCollection->Delete(); - delete fFairTutorialDet2PointCollection; - } + if (fFairTutorialDet2PointCollection) { + fFairTutorialDet2PointCollection->Delete(); + delete fFairTutorialDet2PointCollection; + } } void FairTutorialDet2::Initialize() { - FairDetector::Initialize(); -/* + FairDetector::Initialize(); + /* FairRuntimeDb* rtdb= FairRun::Instance()->GetRuntimeDb(); FairTutorialDet2GeoPar* par=(FairTutorialDet2GeoPar*)(rtdb->getContainer("FairTutorialDet2GeoPar")); */ } -Bool_t FairTutorialDet2::ProcessHits(FairVolume* vol) +Bool_t FairTutorialDet2::ProcessHits(FairVolume* vol) { - /** This method is called from the MC stepping */ - - //Set parameters at entrance of volume. Reset ELoss. - if (TVirtualMC::GetMC()->IsTrackEntering()) { - fELoss = 0.; - fTime = TVirtualMC::GetMC()->TrackTime() * 1.0e09; - fLength = TVirtualMC::GetMC()->TrackLength(); - TVirtualMC::GetMC()->TrackPosition(fPos); - TVirtualMC::GetMC()->TrackMomentum(fMom); - } - - // Sum energy loss for all steps in the active volume - fELoss += TVirtualMC::GetMC()->Edep(); - - // Create FairTutorialDet2Point at exit of active volume - if (TVirtualMC::GetMC()->IsTrackExiting() || - TVirtualMC::GetMC()->IsTrackStop() || - TVirtualMC::GetMC()->IsTrackDisappeared()) { - fTrackID = TVirtualMC::GetMC()->GetStack()->GetCurrentTrackNumber(); - fVolumeID = vol->getMCid(); - if (fELoss == 0.) { return kFALSE; } - AddHit(fTrackID, fVolumeID, TVector3(fPos.X(), fPos.Y(), fPos.Z()), - TVector3(fMom.Px(), fMom.Py(), fMom.Pz()), fTime, fLength, fELoss); - - // Increment number of tutorial det points in TParticle - FairStack* stack = static_cast(TVirtualMC::GetMC()->GetStack()); - stack->AddPoint(kTutDet); - } - - return kTRUE; + /** This method is called from the MC stepping */ + + // Set parameters at entrance of volume. Reset ELoss. + if (TVirtualMC::GetMC()->IsTrackEntering()) { + fELoss = 0.; + fTime = TVirtualMC::GetMC()->TrackTime() * 1.0e09; + fLength = TVirtualMC::GetMC()->TrackLength(); + TVirtualMC::GetMC()->TrackPosition(fPos); + TVirtualMC::GetMC()->TrackMomentum(fMom); + } + + // Sum energy loss for all steps in the active volume + fELoss += TVirtualMC::GetMC()->Edep(); + + // Create FairTutorialDet2Point at exit of active volume + if (TVirtualMC::GetMC()->IsTrackExiting() || TVirtualMC::GetMC()->IsTrackStop() + || TVirtualMC::GetMC()->IsTrackDisappeared()) { + fTrackID = TVirtualMC::GetMC()->GetStack()->GetCurrentTrackNumber(); + fVolumeID = vol->getMCid(); + if (fELoss == 0.) { + return kFALSE; + } + AddHit(fTrackID, + fVolumeID, + TVector3(fPos.X(), fPos.Y(), fPos.Z()), + TVector3(fMom.Px(), fMom.Py(), fMom.Pz()), + fTime, + fLength, + fELoss); + + // Increment number of tutorial det points in TParticle + FairStack* stack = static_cast(TVirtualMC::GetMC()->GetStack()); + stack->AddPoint(kTutDet); + } + + return kTRUE; } -void FairTutorialDet2::EndOfEvent() -{ - Reset(); -} +void FairTutorialDet2::EndOfEvent() { Reset(); } void FairTutorialDet2::Register() { - /** This will create a branch in the output tree called + /** This will create a branch in the output tree called FairTutorialDet2Point, setting the last parameter to kFALSE means: this collection will not be written to the file, it will exist only during the simulation. */ - auto mgr = FairRootManager::Instance(); + auto mgr = FairRootManager::Instance(); - mgr->Register("TutorialDetPoint", "TutorialDet", - fFairTutorialDet2PointCollection, kTRUE); + mgr->Register("TutorialDetPoint", "TutorialDet", fFairTutorialDet2PointCollection, kTRUE); - // example how to register any type T - mgr->RegisterAny("TutorialCustomData", fCustomData, kTRUE); + // example how to register any type T + mgr->RegisterAny("TutorialCustomData", fCustomData, kTRUE); } TClonesArray* FairTutorialDet2::GetCollection(Int_t iColl) const { - if (iColl == 0) { return fFairTutorialDet2PointCollection; } - else { return nullptr; } + if (iColl == 0) { + return fFairTutorialDet2PointCollection; + } else { + return nullptr; + } } void FairTutorialDet2::Reset() { - fFairTutorialDet2PointCollection->Clear(); - fCustomData->clear(); + fFairTutorialDet2PointCollection->Clear(); + fCustomData->clear(); } void FairTutorialDet2::ConstructGeometry() { - /** If you are using the standard ASCII input for 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. */ ConstructASCIIGeometry(fgGeo, "FairTutorialDet2GeoPar"); } -FairTutorialDet2Point* FairTutorialDet2::AddHit(Int_t trackID, Int_t detID, - TVector3 pos, TVector3 mom, - Double_t time, Double_t length, - Double_t eLoss) +FairTutorialDet2Point* FairTutorialDet2::AddHit(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t time, + Double_t length, + Double_t eLoss) { - TClonesArray& clref = *fFairTutorialDet2PointCollection; - Int_t size = clref.GetEntriesFast(); + TClonesArray& clref = *fFairTutorialDet2PointCollection; + Int_t size = clref.GetEntriesFast(); - // fill this with some (meaningless) data - fCustomData->emplace_back(pos.X(), size); + // fill this with some (meaningless) data + fCustomData->emplace_back(pos.X(), size); - return new(clref[size]) FairTutorialDet2Point(trackID, detID, pos, mom, time, length, eLoss); + return new (clref[size]) FairTutorialDet2Point(trackID, detID, pos, mom, time, length, eLoss); } -FairModule* FairTutorialDet2::CloneModule() const -{ - return new FairTutorialDet2(*this); -} +FairModule* FairTutorialDet2::CloneModule() const { return new FairTutorialDet2(*this); } -ClassImp(FairTutorialDet2) +ClassImp(FairTutorialDet2); diff --git a/examples/simulation/Tutorial2/src/FairTutorialDet2.h b/examples/simulation/Tutorial2/src/FairTutorialDet2.h index 2f8d60a60d..aa6cdbbe42 100644 --- a/examples/simulation/Tutorial2/src/FairTutorialDet2.h +++ b/examples/simulation/Tutorial2/src/FairTutorialDet2.h @@ -9,13 +9,11 @@ #define FAIRTUTORIALDET2_H #include "FairDetector.h" - #include "FairTutorialDet2Point.h" #include -#include #include - +#include #include class FairModule; @@ -23,13 +21,13 @@ class FairTutorialDet2Geo; class FairVolume; class TClonesArray; -class FairTutorialDet2: public FairDetector +class FairTutorialDet2 : public FairDetector { public: /** Name : Detector Name * Active: kTRUE for active detectors (ProcessHits() will be called) * kFALSE for inactive detectors - */ + */ FairTutorialDet2(const char* Name, Bool_t Active); /** default constructor */ @@ -39,47 +37,45 @@ class FairTutorialDet2: public FairDetector virtual ~FairTutorialDet2(); /** 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(); /** This method is an example of how to add your own point * of type FairTutorialDet2Point to the clones array - */ - FairTutorialDet2Point* AddHit(Int_t trackID, Int_t detID, - TVector3 pos, TVector3 mom, - Double_t time, Double_t length, - Double_t eLoss); + */ + FairTutorialDet2Point* + AddHit(Int_t trackID, Int_t detID, TVector3 pos, TVector3 mom, Double_t time, Double_t length, Double_t eLoss); /** 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() { ; } virtual FairModule* CloneModule() const; @@ -89,28 +85,28 @@ class FairTutorialDet2: public FairDetector /** 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* fFairTutorialDet2PointCollection; + TClonesArray* fFairTutorialDet2PointCollection; /** alternative output based on standard containers just to demonstrate that we can pass non TClonesArray/TObject data */ using Det2PointContainer = std::vector; - Det2PointContainer *fCustomData; + Det2PointContainer* fCustomData; FairTutorialDet2(const FairTutorialDet2&); FairTutorialDet2& operator=(const FairTutorialDet2&); - ClassDef(FairTutorialDet2,1) + ClassDef(FairTutorialDet2, 1) }; -#endif //FAIRTUTORIALDET_H +#endif // FAIRTUTORIALDET_H diff --git a/examples/simulation/Tutorial2/src/FairTutorialDet2ContFact.cxx b/examples/simulation/Tutorial2/src/FairTutorialDet2ContFact.cxx index e13d0bf073..d684c2340f 100644 --- a/examples/simulation/Tutorial2/src/FairTutorialDet2ContFact.cxx +++ b/examples/simulation/Tutorial2/src/FairTutorialDet2ContFact.cxx @@ -1,71 +1,66 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "FairTutorialDet2ContFact.h" -#include "FairTutorialDet2GeoPar.h" -#include "FairTutorialDet2DigiPar.h" - #include "FairRuntimeDb.h" +#include "FairTutorialDet2DigiPar.h" +#include "FairTutorialDet2GeoPar.h" -#include // strcmp +#include // strcmp -ClassImp(FairTutorialDet2ContFact) +ClassImp(FairTutorialDet2ContFact); static FairTutorialDet2ContFact gFairTutorialDet2ContFact; FairTutorialDet2ContFact::FairTutorialDet2ContFact() { - /** Constructor (called when the library is loaded) */ - fName="FairTutorialDet2ContFact"; - fTitle="Factory for parameter containers in libTutorial1"; - setAllContainers(); - FairRuntimeDb::instance()->addContFactory(this); + /** Constructor (called when the library is loaded) */ + fName = "FairTutorialDet2ContFact"; + fTitle = "Factory for parameter containers in libTutorial1"; + setAllContainers(); + FairRuntimeDb::instance()->addContFactory(this); } void FairTutorialDet2ContFact::setAllContainers() { - /** Creates the Container objects with all accepted + /** Creates the Container objects with all accepted contexts and adds them to the list of containers for the Tutorial1 library. */ - FairContainer* p1= new FairContainer("FairTutorialDet2GeoPar", - "FairTutorialDet2 Geometry Parameters", - "TestDefaultContext"); - p1->addContext("TestNonDefaultContext"); + FairContainer* p1 = + new FairContainer("FairTutorialDet2GeoPar", "FairTutorialDet2 Geometry Parameters", "TestDefaultContext"); + p1->addContext("TestNonDefaultContext"); - containers->Add(p1); + containers->Add(p1); - FairContainer* p2= new FairContainer("FairTutorialDet2DigiPar", - "Tutorial Det Digi Parameters", - "TestDefaultContext"); - p2->addContext("TestNonDefaultContext"); + FairContainer* p2 = + new FairContainer("FairTutorialDet2DigiPar", "Tutorial Det Digi Parameters", "TestDefaultContext"); + p2->addContext("TestNonDefaultContext"); - containers->Add(p2); + containers->Add(p2); } FairParSet* FairTutorialDet2ContFact::createContainer(FairContainer* c) { - /** Calls the constructor of the corresponding parameter container. + /** 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 = nullptr; - if (strcmp(name,"FairTutorialDet2GeoPar") == 0) { - p = new FairTutorialDet2GeoPar(c->getConcatName().Data(), - c->GetTitle(),c->getContext()); - } - if (strcmp(name,"FairTutorialDet2DigiPar") == 0) { - p = new FairTutorialDet2DigiPar(c->getConcatName().Data(), - c->GetTitle(),c->getContext()); - } + const char* name = c->GetName(); + FairParSet* p = nullptr; + if (strcmp(name, "FairTutorialDet2GeoPar") == 0) { + p = new FairTutorialDet2GeoPar(c->getConcatName().Data(), c->GetTitle(), c->getContext()); + } + if (strcmp(name, "FairTutorialDet2DigiPar") == 0) { + p = new FairTutorialDet2DigiPar(c->getConcatName().Data(), c->GetTitle(), c->getContext()); + } - return p; + return p; } diff --git a/examples/simulation/Tutorial2/src/FairTutorialDet2ContFact.h b/examples/simulation/Tutorial2/src/FairTutorialDet2ContFact.h index b3a8b61009..5eac8037cd 100644 --- a/examples/simulation/Tutorial2/src/FairTutorialDet2ContFact.h +++ b/examples/simulation/Tutorial2/src/FairTutorialDet2ContFact.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRTUTORIALDET2CONTFACT_H @@ -23,7 +23,7 @@ class FairTutorialDet2ContFact : public FairContFact FairTutorialDet2ContFact(); ~FairTutorialDet2ContFact() {} FairParSet* createContainer(FairContainer*); - ClassDef( FairTutorialDet2ContFact,0) // Factory for all MyDet parameter containers + ClassDef(FairTutorialDet2ContFact, 0) // Factory for all MyDet parameter containers }; -#endif /* !FAIRTUTORIALDETCONTFACT_H */ +#endif /* !FAIRTUTORIALDETCONTFACT_H */ diff --git a/examples/simulation/Tutorial2/src/FairTutorialDet2CustomTask.cxx b/examples/simulation/Tutorial2/src/FairTutorialDet2CustomTask.cxx index 2de9805230..cdbe9f3915 100644 --- a/examples/simulation/Tutorial2/src/FairTutorialDet2CustomTask.cxx +++ b/examples/simulation/Tutorial2/src/FairTutorialDet2CustomTask.cxx @@ -6,9 +6,10 @@ * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "FairTutorialDet2CustomTask.h" -#include "FairTutorialDet2Point.h" -#include "FairRootManager.h" + #include "FairLogger.h" +#include "FairRootManager.h" +#include "FairTutorialDet2Point.h" // we include some unit testing here #ifdef NDEBUG @@ -17,62 +18,57 @@ #include FairTutorialDet2CustomTask::FairTutorialDet2CustomTask() - : FairTask("TutorialDetCustomTask", 0) -{ -} + : FairTask("TutorialDetCustomTask", 0) +{} FairTutorialDet2CustomTask::FairTutorialDet2CustomTask(const char* name, const char* /*title*/) - : FairTask(name, 0) -{ -} + : FairTask(name, 0) +{} -FairTutorialDet2CustomTask::~FairTutorialDet2CustomTask() -{ -} +FairTutorialDet2CustomTask::~FairTutorialDet2CustomTask() {} InitStatus FairTutorialDet2CustomTask::Init() { - LOG(info) << " FairTutorialDet2CustomTask :: Init() "; + LOG(info) << " FairTutorialDet2CustomTask :: Init() "; - FairRootManager* ioman = FairRootManager::Instance(); - if (!ioman) { - LOG(fatal) << "No FairRootManager"; - return kERROR; - } else { - fCustomData = ioman->InitObjectAs const*>("TutorialCustomData"); - if (!fCustomData) { - LOG(error) << "No input data found!"; - LOG(error) << "Task will be inactive"; - return kERROR; - } + FairRootManager* ioman = FairRootManager::Instance(); + if (!ioman) { + LOG(fatal) << "No FairRootManager"; + return kERROR; + } else { + fCustomData = ioman->InitObjectAs const*>("TutorialCustomData"); + if (!fCustomData) { + LOG(error) << "No input data found!"; + LOG(error) << "Task will be inactive"; + return kERROR; + } - // assert that some other queries are null: - // querying existing data under wrong type - assert(ioman->InitObjectAs("TutorialCustomData") == nullptr); - // querying non-existing branch - assert(ioman->InitObjectAs("WrongName") == nullptr); - fCustomData2=ioman->InitObjectAs const*>("InMemory1"); - assert(fCustomData2); - } - return kSUCCESS; + // assert that some other queries are null: + // querying existing data under wrong type + assert(ioman->InitObjectAs("TutorialCustomData") == nullptr); + // querying non-existing branch + assert(ioman->InitObjectAs("WrongName") == nullptr); + fCustomData2 = ioman->InitObjectAs const*>("InMemory1"); + assert(fCustomData2); + } + return kSUCCESS; } void FairTutorialDet2CustomTask::Exec(Option_t* /*option*/) { - // Here we print something - LOG(info) <<" I am in FairTutorialDet2CustomTask::Exec"; - - LOG(info) << " The custom data input vector has size" << fCustomData->size(); - for (auto& entry : *fCustomData) { - LOG(info) << " Got entry " << entry.GetX() << " " << entry.GetQ(); - } + // Here we print something + LOG(info) << " I am in FairTutorialDet2CustomTask::Exec"; - // process data that we got from DigitizerTask - LOG(info) << " The input vector from DigitizerTask has size" << fCustomData2->size(); - for (auto& entry : *fCustomData2) { - LOG(info) << " Got entry " << entry.GetX() << " " << entry.GetQ(); - } + LOG(info) << " The custom data input vector has size" << fCustomData->size(); + for (auto& entry : *fCustomData) { + LOG(info) << " Got entry " << entry.GetX() << " " << entry.GetQ(); + } + // process data that we got from DigitizerTask + LOG(info) << " The input vector from DigitizerTask has size" << fCustomData2->size(); + for (auto& entry : *fCustomData2) { + LOG(info) << " Got entry " << entry.GetX() << " " << entry.GetQ(); + } } ClassImp(FairTutorialDet2CustomTask); diff --git a/examples/simulation/Tutorial2/src/FairTutorialDet2CustomTask.h b/examples/simulation/Tutorial2/src/FairTutorialDet2CustomTask.h index 0902fc9448..cfad3f322d 100644 --- a/examples/simulation/Tutorial2/src/FairTutorialDet2CustomTask.h +++ b/examples/simulation/Tutorial2/src/FairTutorialDet2CustomTask.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // -------------------------------------------------------------------------- @@ -16,7 +16,6 @@ #include "FairTask.h" #include - #include class CustomClass; @@ -28,7 +27,7 @@ class FairTutorialDet2CustomTask : public FairTask FairTutorialDet2CustomTask(); /** Standard constructor **/ - FairTutorialDet2CustomTask(const char* name, const char* title="FAIR Task"); + FairTutorialDet2CustomTask(const char* name, const char* title = "FAIR Task"); /** Destructor **/ virtual ~FairTutorialDet2CustomTask(); @@ -42,8 +41,8 @@ class FairTutorialDet2CustomTask : public FairTask private: // This task just has input data to be retrieved with InitObjectAs function // note that we are forced to put const on data that we are consuming - std::vector const* fCustomData = nullptr; //! - std::vector const* fCustomData2 = nullptr; //! - ClassDef(FairTutorialDet2CustomTask,1) + std::vector const* fCustomData = nullptr; //! + std::vector const* fCustomData2 = nullptr; //! + ClassDef(FairTutorialDet2CustomTask, 1) }; -#endif //FAIRTUTORIALDETCUSTOMTASK_H +#endif // FAIRTUTORIALDETCUSTOMTASK_H diff --git a/examples/simulation/Tutorial2/src/FairTutorialDet2DigiPar.cxx b/examples/simulation/Tutorial2/src/FairTutorialDet2DigiPar.cxx index 3ee4e62be5..0840d07835 100644 --- a/examples/simulation/Tutorial2/src/FairTutorialDet2DigiPar.cxx +++ b/examples/simulation/Tutorial2/src/FairTutorialDet2DigiPar.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -12,102 +12,105 @@ #include "FairTutorialDet2DigiPar.h" -#include "FairParamList.h" #include "FairLogger.h" +#include "FairParamList.h" #include #include -FairTutorialDet2DigiPar::FairTutorialDet2DigiPar(const char* name, - const char* title, - const char* context) - : FairParGenericSet(name, title, context), - ftutdetdigipar(new TArrayF(10)), - ftutdetdigiparsector(), - ftutdetdigiparstation(-1) +FairTutorialDet2DigiPar::FairTutorialDet2DigiPar(const char* name, const char* title, const char* context) + : FairParGenericSet(name, title, context) + , ftutdetdigipar(new TArrayF(10)) + , ftutdetdigiparsector() + , ftutdetdigiparstation(-1) { - detName = "TutorialDet"; - // ftutdetdigipar = new TArrayF(10); - // ftutdetdigipar = new TArrayF(10); + detName = "TutorialDet"; + // ftutdetdigipar = new TArrayF(10); + // ftutdetdigipar = new TArrayF(10); } -FairTutorialDet2DigiPar::~FairTutorialDet2DigiPar() -{ - clear(); -} +FairTutorialDet2DigiPar::~FairTutorialDet2DigiPar() { clear(); } void FairTutorialDet2DigiPar::clear() { - status = kFALSE; - resetInputVersions(); + status = kFALSE; + resetInputVersions(); } void FairTutorialDet2DigiPar::printparams() { - LOG(info) <<"Print"; - LOG(info) << "ftutdetdigiparstation: " << ftutdetdigiparstation; - Int_t size = ftutdetdigiparsector.GetSize(); - LOG(info) <<"size: " << size; - for (Int_t i=0; i< size; i++) { - LOG(info) << i <<" :" << ftutdetdigiparsector.GetAt(i); - } - size = ftutdetdigipar->GetSize(); - LOG(info) <<"size: " << size; - for (Int_t i=0; i< size; i++) { - LOG(info) << i <<" :" << ftutdetdigipar->GetAt(i); - } + LOG(info) << "Print"; + LOG(info) << "ftutdetdigiparstation: " << ftutdetdigiparstation; + Int_t size = ftutdetdigiparsector.GetSize(); + LOG(info) << "size: " << size; + for (Int_t i = 0; i < size; i++) { + LOG(info) << i << " :" << ftutdetdigiparsector.GetAt(i); + } + size = ftutdetdigipar->GetSize(); + LOG(info) << "size: " << size; + for (Int_t i = 0; i < size; i++) { + LOG(info) << i << " :" << ftutdetdigipar->GetAt(i); + } } void FairTutorialDet2DigiPar::putParams(FairParamList* l) { - // print(); - LOG(info) << "I am in FairTutorialDet2DigiPar::putParams "; - if (!l) { return; } - l->add("FairTutorialDet2DigiStations", ftutdetdigiparstation); - l->add("FairTutorialDet2DigiSectorsPerStation", ftutdetdigiparsector); - Int_t count_sectors = 0; - for (Int_t i=0; i< ftutdetdigiparstation; i++) { - count_sectors+=ftutdetdigiparsector[i]; - } - Int_t array_size = (count_sectors * 10 + ftutdetdigiparstation * 3); - LOG(info) << "Array Size: " << array_size; - /* Float_t zwischen[array_size]; + // print(); + LOG(info) << "I am in FairTutorialDet2DigiPar::putParams "; + if (!l) { + return; + } + l->add("FairTutorialDet2DigiStations", ftutdetdigiparstation); + l->add("FairTutorialDet2DigiSectorsPerStation", ftutdetdigiparsector); + Int_t count_sectors = 0; + for (Int_t i = 0; i < ftutdetdigiparstation; i++) { + count_sectors += ftutdetdigiparsector[i]; + } + Int_t array_size = (count_sectors * 10 + ftutdetdigiparstation * 3); + LOG(info) << "Array Size: " << array_size; + /* Float_t zwischen[array_size]; for (Int_t i=0; i< array_size; i++) { zwischen[i] = ftutdetdigipar.GetAt(i); } */ - ftutdetdigipar->Set(array_size); - l->add("FairTutorialDet2DigiPar",*ftutdetdigipar); + ftutdetdigipar->Set(array_size); + l->add("FairTutorialDet2DigiPar", *ftutdetdigipar); } Bool_t FairTutorialDet2DigiPar::getParams(FairParamList* l) { - // print(); + // print(); - LOG(info) << "I am in FairTutorialDet2DigiPar::getParams "; + LOG(info) << "I am in FairTutorialDet2DigiPar::getParams "; - if (!l) { return kFALSE; } - if (! l->fill("FairTutorialDet2DigiStations", &ftutdetdigiparstation)) { return kFALSE; } - ftutdetdigiparsector.Set(ftutdetdigiparstation); + if (!l) { + return kFALSE; + } + if (!l->fill("FairTutorialDet2DigiStations", &ftutdetdigiparstation)) { + return kFALSE; + } + ftutdetdigiparsector.Set(ftutdetdigiparstation); - if (! l->fill("FairTutorialDet2DigiSectorsPerStation", &ftutdetdigiparsector)) { return kFALSE; } + if (!l->fill("FairTutorialDet2DigiSectorsPerStation", &ftutdetdigiparsector)) { + return kFALSE; + } - Int_t count_sectors = 0; - for (Int_t i=0; i< ftutdetdigiparstation; i++) { - count_sectors+=ftutdetdigiparsector[i]; - } - LOG(info) << "Total number of sectors: " << count_sectors; + Int_t count_sectors = 0; + for (Int_t i = 0; i < ftutdetdigiparstation; i++) { + count_sectors += ftutdetdigiparsector[i]; + } + LOG(info) << "Total number of sectors: " << count_sectors; - Int_t array_size = (count_sectors * 10 + ftutdetdigiparstation * 3); - LOG(info) << "Array Size: " << array_size; - ftutdetdigipar->Set(array_size); - // Float_t zwischen[array_size]; - if (!(l->fill("FairTutorialDet2DigiPar",ftutdetdigipar))) { - LOG(warn) << "Could not initialize FairTutorialDet2DigiPar"; - return kFALSE; - } - // ftutdetdigipar.Set(array_size, zwischen); - return kTRUE; + Int_t array_size = (count_sectors * 10 + ftutdetdigiparstation * 3); + LOG(info) << "Array Size: " << array_size; + ftutdetdigipar->Set(array_size); + // Float_t zwischen[array_size]; + if (!(l->fill("FairTutorialDet2DigiPar", ftutdetdigipar))) { + LOG(warn) << "Could not initialize FairTutorialDet2DigiPar"; + return kFALSE; + } + // ftutdetdigipar.Set(array_size, zwischen); + return kTRUE; } -ClassImp(FairTutorialDet2DigiPar) +ClassImp(FairTutorialDet2DigiPar); diff --git a/examples/simulation/Tutorial2/src/FairTutorialDet2DigiPar.h b/examples/simulation/Tutorial2/src/FairTutorialDet2DigiPar.h index 9b599560dd..136d932613 100644 --- a/examples/simulation/Tutorial2/src/FairTutorialDet2DigiPar.h +++ b/examples/simulation/Tutorial2/src/FairTutorialDet2DigiPar.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -25,8 +25,8 @@ class FairTutorialDet2DigiPar : public FairParGenericSet { public: /** Standard constructor **/ - FairTutorialDet2DigiPar(const char* name = "FairTutorialDet2DigiPar", - const char* title = "Tutorial Det digi parameters", + FairTutorialDet2DigiPar(const char* name = "FairTutorialDet2DigiPar", + const char* title = "Tutorial Det digi parameters", const char* context = "Default"); /** Destructor **/ @@ -48,14 +48,14 @@ class FairTutorialDet2DigiPar : public FairParGenericSet Bool_t getParams(FairParamList*); private: - TArrayF* ftutdetdigipar; // - TArrayI ftutdetdigiparsector; // - Int_t ftutdetdigiparstation; // + TArrayF* ftutdetdigipar; // + TArrayI ftutdetdigiparsector; // + Int_t ftutdetdigiparstation; // FairTutorialDet2DigiPar(const FairTutorialDet2DigiPar&); FairTutorialDet2DigiPar& operator=(const FairTutorialDet2DigiPar&); - ClassDef(FairTutorialDet2DigiPar,1); + ClassDef(FairTutorialDet2DigiPar, 1); }; #endif diff --git a/examples/simulation/Tutorial2/src/FairTutorialDet2Digitizer.cxx b/examples/simulation/Tutorial2/src/FairTutorialDet2Digitizer.cxx index fbceb08ad1..64a4165c82 100644 --- a/examples/simulation/Tutorial2/src/FairTutorialDet2Digitizer.cxx +++ b/examples/simulation/Tutorial2/src/FairTutorialDet2Digitizer.cxx @@ -7,112 +7,109 @@ ********************************************************************************/ #include "FairTutorialDet2Digitizer.h" -#include "FairTutorialDet2DigiPar.h" -#include "FairTutorialDet2Point.h" - +#include "FairLogger.h" #include "FairRootManager.h" #include "FairRunAna.h" #include "FairRuntimeDb.h" -#include "FairLogger.h" +#include "FairTutorialDet2DigiPar.h" +#include "FairTutorialDet2Point.h" #include FairTutorialDet2Digitizer::FairTutorialDet2Digitizer() - : FairTask("TutorialDetDigitizer", 0), - fTutorialDetPoints(nullptr), - fCustomData2(new std::vector), - fDigiPar(nullptr) -{ -} + : FairTask("TutorialDetDigitizer", 0) + , fTutorialDetPoints(nullptr) + , fCustomData2(new std::vector) + , fDigiPar(nullptr) +{} FairTutorialDet2Digitizer::FairTutorialDet2Digitizer(const char* name, const char* /*title*/) - : FairTask(name, 0), - fTutorialDetPoints(nullptr), - fCustomData2(new std::vector), - fDigiPar(nullptr) -{ -} + : FairTask(name, 0) + , fTutorialDetPoints(nullptr) + , fCustomData2(new std::vector) + , fDigiPar(nullptr) +{} FairTutorialDet2Digitizer::~FairTutorialDet2Digitizer() { - // FairRootManager *ioman =FairRootManager::Instance(); - // ioman->Write(); - // fDigiCollection->Clear("C"); - // delete fDigiCollection; + // FairRootManager *ioman =FairRootManager::Instance(); + // ioman->Write(); + // fDigiCollection->Clear("C"); + // delete fDigiCollection; } void FairTutorialDet2Digitizer::SetParContainers() { - LOG(info) << "FairTutorialDet2Digitizer :: SetParContainers() "; + LOG(info) << "FairTutorialDet2Digitizer :: SetParContainers() "; - // Get Base Container - FairRunAna* ana = FairRunAna::Instance(); - FairRuntimeDb* rtdb=ana->GetRuntimeDb(); + // Get Base Container + FairRunAna* ana = FairRunAna::Instance(); + FairRuntimeDb* rtdb = ana->GetRuntimeDb(); - fDigiPar = static_cast(rtdb->getContainer("FairTutorialDet2DigiPar")); + fDigiPar = static_cast(rtdb->getContainer("FairTutorialDet2DigiPar")); - // parameters are not filled yet - fDigiPar->printparams(); + // parameters are not filled yet + fDigiPar->printparams(); } InitStatus FairTutorialDet2Digitizer::ReInit() { - LOG(info) << " FairTutorialDet2Digitizer :: ReInit() "; + LOG(info) << " FairTutorialDet2Digitizer :: ReInit() "; - FairRunAna* ana = FairRunAna::Instance(); - FairRuntimeDb* rtdb=ana->GetRuntimeDb(); + FairRunAna* ana = FairRunAna::Instance(); + FairRuntimeDb* rtdb = ana->GetRuntimeDb(); - fDigiPar = static_cast(rtdb->getContainer("FairTutorialDet2DigiPar")); + fDigiPar = static_cast(rtdb->getContainer("FairTutorialDet2DigiPar")); - return kSUCCESS; + return kSUCCESS; } InitStatus FairTutorialDet2Digitizer::Init() { - LOG(info) << " FairTutorialDet2Digitizer :: Init() "; + LOG(info) << " FairTutorialDet2Digitizer :: Init() "; - FairRootManager* ioman = FairRootManager::Instance(); - if (! ioman) { - LOG(fatal) << "No FairRootManager"; - return kERROR; - } else { - fTutorialDetPoints = static_cast(ioman->GetObject("TutorialDetPoint")); + FairRootManager* ioman = FairRootManager::Instance(); + if (!ioman) { + LOG(fatal) << "No FairRootManager"; + return kERROR; + } else { + fTutorialDetPoints = static_cast(ioman->GetObject("TutorialDetPoint")); - fCustomData = ioman->InitObjectAs const*>("TutorialCustomData"); - if (! fTutorialDetPoints) { - LOG(error) << "No TutorialDetPoints array!"; - LOG(error) << "Task will be inactive"; - return kERROR; - } + fCustomData = ioman->InitObjectAs const*>("TutorialCustomData"); + if (!fTutorialDetPoints) { + LOG(error) << "No TutorialDetPoints array!"; + LOG(error) << "Task will be inactive"; + return kERROR; + } - //fListStack = (TClonesArray*)ioman->GetObject("MCTrack"); - //fDigiCollection = new TClonesArray("FairTrdDigi", 100); - //ioman->Register("TRDDigi","TRD Digis",fDigiCollection,kTRUE); + // fListStack = (TClonesArray*)ioman->GetObject("MCTrack"); + // fDigiCollection = new TClonesArray("FairTrdDigi", 100); + // ioman->Register("TRDDigi","TRD Digis",fDigiCollection,kTRUE); - // now parameters are filled - fDigiPar->printparams(); + // now parameters are filled + fDigiPar->printparams(); - // register data output of this task - Register(); + // register data output of this task + Register(); - return kSUCCESS; - } + return kSUCCESS; + } } void FairTutorialDet2Digitizer::Exec(Option_t* /*option*/) { - // Here we print something + // Here we print something - LOG(info) <<" I am in FairTutorialDet2Digitizer::Exec"; + LOG(info) << " I am in FairTutorialDet2Digitizer::Exec"; - LOG(info) << " The custom data input vector has size" << fCustomData->size() << "\n"; - for(auto& entry : *fCustomData) { - LOG(info) << " Got entry " << entry.GetX() << " " << entry.GetQ() << "\n"; - // process data and fill a structure here, which can be consumed by the next task - fCustomData2->emplace_back(entry.GetX()*2, entry.GetQ()*10); - } + LOG(info) << " The custom data input vector has size" << fCustomData->size() << "\n"; + for (auto& entry : *fCustomData) { + LOG(info) << " Got entry " << entry.GetX() << " " << entry.GetQ() << "\n"; + // process data and fill a structure here, which can be consumed by the next task + fCustomData2->emplace_back(entry.GetX() * 2, entry.GetQ() * 10); + } - /* + /* fNHits = 0; FairTutorialDet2Point *pt=nullptr; @@ -177,15 +174,13 @@ void FairTutorialDet2Digitizer::Exec(Option_t* /*option*/) */ } -void FairTutorialDet2Digitizer::Finish() -{ -} +void FairTutorialDet2Digitizer::Finish() {} void FairTutorialDet2Digitizer::Register() { - // testing to transfer a variable to another task via a memory branch - LOG(info) << "Digitizer::Register\n"; - FairRootManager::Instance()->RegisterAny("InMemory1", fCustomData2, false); + // testing to transfer a variable to another task via a memory branch + LOG(info) << "Digitizer::Register\n"; + FairRootManager::Instance()->RegisterAny("InMemory1", fCustomData2, false); } -ClassImp(FairTutorialDet2Digitizer) +ClassImp(FairTutorialDet2Digitizer); diff --git a/examples/simulation/Tutorial2/src/FairTutorialDet2Digitizer.h b/examples/simulation/Tutorial2/src/FairTutorialDet2Digitizer.h index a6a9ffd979..7f79cdc852 100644 --- a/examples/simulation/Tutorial2/src/FairTutorialDet2Digitizer.h +++ b/examples/simulation/Tutorial2/src/FairTutorialDet2Digitizer.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // -------------------------------------------------------------------------- @@ -16,7 +16,6 @@ #include "FairTask.h" #include - #include class TClonesArray; @@ -30,7 +29,7 @@ class FairTutorialDet2Digitizer : public FairTask FairTutorialDet2Digitizer(); /** Standard constructor **/ - FairTutorialDet2Digitizer(const char* name, const char* title="FAIR Task"); + FairTutorialDet2Digitizer(const char* name, const char* title = "FAIR Task"); /** Destructor **/ virtual ~FairTutorialDet2Digitizer(); @@ -54,23 +53,23 @@ class FairTutorialDet2Digitizer : public FairTask void Register(); private: - TClonesArray* fTutorialDetPoints; //! Tutorial Det MC points - std::vector const* fCustomData = nullptr; //! - std::vector* fCustomData2 = nullptr; //! + TClonesArray* fTutorialDetPoints; //! Tutorial Det MC points + std::vector const* fCustomData = nullptr; //! + std::vector* fCustomData2 = nullptr; //! // TClonesArray *fDigiCollection; //! TRD hits - //TClonesArray *fListStack; //Tracks + // TClonesArray *fListStack; //Tracks FairTutorialDet2DigiPar* fDigiPar; // Double_t fDx; //! - //Double_t fDy; //! - //Int_t fNHits; + // Double_t fDy; //! + // Int_t fNHits; FairTutorialDet2Digitizer(const FairTutorialDet2Digitizer&); FairTutorialDet2Digitizer& operator=(const FairTutorialDet2Digitizer&); - ClassDef(FairTutorialDet2Digitizer,1) + ClassDef(FairTutorialDet2Digitizer, 1) }; -#endif //FAIRTUTORIALDETDIGITIZER_H +#endif // FAIRTUTORIALDETDIGITIZER_H diff --git a/examples/simulation/Tutorial2/src/FairTutorialDet2Geo.cxx b/examples/simulation/Tutorial2/src/FairTutorialDet2Geo.cxx index 7e1053c4e4..f00335d4d3 100644 --- a/examples/simulation/Tutorial2/src/FairTutorialDet2Geo.cxx +++ b/examples/simulation/Tutorial2/src/FairTutorialDet2Geo.cxx @@ -9,31 +9,31 @@ #include -ClassImp(FairTutorialDet2Geo) +ClassImp(FairTutorialDet2Geo); FairTutorialDet2Geo::FairTutorialDet2Geo() - : FairGeoSet() + : FairGeoSet() { - // Constructor - fName = "tutdet"; - maxSectors = 0; - maxModules = 10; + // Constructor + fName = "tutdet"; + maxSectors = 0; + maxModules = 10; } const char* FairTutorialDet2Geo::getModuleName(Int_t m) { - /** Returns the module name of TutorialDet number m + /** Returns the module name of TutorialDet number m Setting MyDet here means that all modules names in the ASCII file should start with TutorialDet otherwise they will not be constructed */ - sprintf(modName, "tutdet%i", m + 1); - return modName; + sprintf(modName, "tutdet%i", m + 1); + return modName; } const char* FairTutorialDet2Geo::getEleName(Int_t m) { - /** Returns the element name of Det number m */ - sprintf(eleName, "tutdet%i", m + 1); - return eleName; + /** Returns the element name of Det number m */ + sprintf(eleName, "tutdet%i", m + 1); + return eleName; } diff --git a/examples/simulation/Tutorial2/src/FairTutorialDet2Geo.h b/examples/simulation/Tutorial2/src/FairTutorialDet2Geo.h index d19231d551..9dc49e9dc0 100644 --- a/examples/simulation/Tutorial2/src/FairTutorialDet2Geo.h +++ b/examples/simulation/Tutorial2/src/FairTutorialDet2Geo.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRTUTORIALDET2GEO_H @@ -15,8 +15,8 @@ class FairTutorialDet2Geo : public FairGeoSet { protected: - char modName[20]; // name of module - char eleName[20]; // substring for elements in module + char modName[20]; // name of module + char eleName[20]; // substring for elements in module public: FairTutorialDet2Geo(); @@ -24,17 +24,17 @@ class FairTutorialDet2Geo : public FairGeoSet const char* getModuleName(Int_t); const char* getEleName(Int_t); inline Int_t getModNumInMod(const TString&); - ClassDef(FairTutorialDet2Geo,1) + ClassDef(FairTutorialDet2Geo, 1) }; inline Int_t FairTutorialDet2Geo::getModNumInMod(const TString& name) { - /** returns the module index from module name + /** returns the module index from module name ?? in name[??] has to be the length of the detector name in the .geo file. For example if all nodes in this file starts with tutdet ?? has to be 6. */ - return static_cast((name[6]-'0')-1); // + return static_cast((name[6] - '0') - 1); // } -#endif /* FAIRTUTORIALDETGEO_H */ +#endif /* FAIRTUTORIALDETGEO_H */ diff --git a/examples/simulation/Tutorial2/src/FairTutorialDet2GeoPar.cxx b/examples/simulation/Tutorial2/src/FairTutorialDet2GeoPar.cxx index dcf4b2f5a2..35f6b568c7 100644 --- a/examples/simulation/Tutorial2/src/FairTutorialDet2GeoPar.cxx +++ b/examples/simulation/Tutorial2/src/FairTutorialDet2GeoPar.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "FairTutorialDet2GeoPar.h" @@ -11,38 +11,41 @@ #include -ClassImp(FairTutorialDet2GeoPar) +ClassImp(FairTutorialDet2GeoPar); -FairTutorialDet2GeoPar ::FairTutorialDet2GeoPar(const char* name, - const char* title, - const char* context) - : FairParGenericSet(name,title,context), - fGeoSensNodes(new TObjArray()), - fGeoPassNodes(new TObjArray()) -{ -} +FairTutorialDet2GeoPar ::FairTutorialDet2GeoPar(const char* name, const char* title, const char* context) + : FairParGenericSet(name, title, context) + , fGeoSensNodes(new TObjArray()) + , fGeoPassNodes(new TObjArray()) +{} -FairTutorialDet2GeoPar::~FairTutorialDet2GeoPar(void) -{ -} +FairTutorialDet2GeoPar::~FairTutorialDet2GeoPar(void) {} void FairTutorialDet2GeoPar::clear(void) { - delete fGeoSensNodes; - delete fGeoPassNodes; + delete fGeoSensNodes; + delete fGeoPassNodes; } void FairTutorialDet2GeoPar::putParams(FairParamList* l) { - if (!l) { return; } - l->addObject("FairGeoNodes Sensitive List", fGeoSensNodes); - l->addObject("FairGeoNodes Passive List", fGeoPassNodes); + if (!l) { + return; + } + l->addObject("FairGeoNodes Sensitive List", fGeoSensNodes); + l->addObject("FairGeoNodes Passive List", fGeoPassNodes); } Bool_t FairTutorialDet2GeoPar::getParams(FairParamList* l) { - if (!l) { return kFALSE; } - if (!l->fillObject("FairGeoNodes Sensitive List", fGeoSensNodes)) { return kFALSE; } - if (!l->fillObject("FairGeoNodes Passive List", fGeoPassNodes)) { return kFALSE; } - return kTRUE; + if (!l) { + return kFALSE; + } + if (!l->fillObject("FairGeoNodes Sensitive List", fGeoSensNodes)) { + return kFALSE; + } + if (!l->fillObject("FairGeoNodes Passive List", fGeoPassNodes)) { + return kFALSE; + } + return kTRUE; } diff --git a/examples/simulation/Tutorial2/src/FairTutorialDet2GeoPar.h b/examples/simulation/Tutorial2/src/FairTutorialDet2GeoPar.h index 02486b7685..fa71ebf2ff 100644 --- a/examples/simulation/Tutorial2/src/FairTutorialDet2GeoPar.h +++ b/examples/simulation/Tutorial2/src/FairTutorialDet2GeoPar.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRTUTORIALDET2GEOPAR_H @@ -32,13 +32,13 @@ class FairTutorialDet2GeoPar : public FairParGenericSet void putParams(FairParamList*); Bool_t getParams(FairParamList*); TObjArray* GetGeoSensitiveNodes() { return fGeoSensNodes; } - TObjArray* GetGeoPassiveNodes() { return fGeoPassNodes; } + TObjArray* GetGeoPassiveNodes() { return fGeoPassNodes; } private: FairTutorialDet2GeoPar(const FairTutorialDet2GeoPar&); FairTutorialDet2GeoPar& operator=(const FairTutorialDet2GeoPar&); - ClassDef(FairTutorialDet2GeoPar,1) + ClassDef(FairTutorialDet2GeoPar, 1) }; #endif /* FAIRTUTORIALDETGEOPAR_H */ diff --git a/examples/simulation/Tutorial2/src/FairTutorialDet2Point.cxx b/examples/simulation/Tutorial2/src/FairTutorialDet2Point.cxx index 3fe9f54897..972f48a524 100644 --- a/examples/simulation/Tutorial2/src/FairTutorialDet2Point.cxx +++ b/examples/simulation/Tutorial2/src/FairTutorialDet2Point.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "FairTutorialDet2Point.h" @@ -10,26 +10,26 @@ #include "FairLogger.h" FairTutorialDet2Point::FairTutorialDet2Point() - : FairMCPoint() -{ -} + : FairMCPoint() +{} -FairTutorialDet2Point::FairTutorialDet2Point(Int_t trackID, Int_t detID, - TVector3 pos, TVector3 mom, - Double_t tof, Double_t length, - Double_t eLoss) - : FairMCPoint(trackID, detID, pos, mom, tof, length, eLoss) -{ -} +FairTutorialDet2Point::FairTutorialDet2Point(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t tof, + Double_t length, + Double_t eLoss) + : FairMCPoint(trackID, detID, pos, mom, tof, length, eLoss) +{} void FairTutorialDet2Point::Print(const Option_t* /*opt*/) const { - LOG(info) << "FairTutorialDet2Point: TutorialDet point for track " - << fTrackID << " in detector " << fDetectorID; - LOG(info) << " Position (" << fX << ", " << fY << ", " << fZ << ") cm"; - LOG(info) << " Momentum (" << fPx << ", " << fPy << ", " << fPz << ") GeV"; - LOG(info) << " Time " << fTime << " ns, Length " << fLength - << " cm, Energy loss " << fELoss*1.0e06 << " keV"; + LOG(info) << "FairTutorialDet2Point: TutorialDet point for track " << fTrackID << " in detector " << fDetectorID; + LOG(info) << " Position (" << fX << ", " << fY << ", " << fZ << ") cm"; + LOG(info) << " Momentum (" << fPx << ", " << fPy << ", " << fPz << ") GeV"; + LOG(info) << " Time " << fTime << " ns, Length " << fLength << " cm, Energy loss " << fELoss * 1.0e06 + << " keV"; } -ClassImp(FairTutorialDet2Point) +ClassImp(FairTutorialDet2Point); diff --git a/examples/simulation/Tutorial2/src/FairTutorialDet2Point.h b/examples/simulation/Tutorial2/src/FairTutorialDet2Point.h index 8a319c0bf6..7e66c76d32 100644 --- a/examples/simulation/Tutorial2/src/FairTutorialDet2Point.h +++ b/examples/simulation/Tutorial2/src/FairTutorialDet2Point.h @@ -10,8 +10,8 @@ #include "FairMCPoint.h" -#include #include +#include class FairTutorialDet2Point : public FairMCPoint { @@ -28,8 +28,13 @@ class FairTutorialDet2Point : public FairMCPoint *@param length Track length since creation [cm] *@param eLoss Energy deposit [GeV] **/ - FairTutorialDet2Point(Int_t trackID, Int_t detID, TVector3 pos, TVector3 mom, - Double_t tof, Double_t length, Double_t eLoss); + FairTutorialDet2Point(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t tof, + Double_t length, + Double_t eLoss); /** Copy constructor **/ // FairTutorialDet2Point(const FairTutorialDet2Point& point) { *this = point; }; @@ -40,7 +45,7 @@ class FairTutorialDet2Point : public FairMCPoint /** Output to screen **/ virtual void Print(const Option_t* opt) const; - ClassDef(FairTutorialDet2Point,1) + ClassDef(FairTutorialDet2Point, 1) }; // a custom class holding some data @@ -49,13 +54,16 @@ class CustomClass { public: CustomClass() {} - CustomClass(double x, int q) : fX(x), fQ(q) {} - double GetX() const {return fX;} - int GetQ() const {return fQ;} + CustomClass(double x, int q) + : fX(x) + , fQ(q) + {} + double GetX() const { return fX; } + int GetQ() const { return fQ; } private: - double fX = 0.; // x position - int fQ = 0; // charge + double fX = 0.; // x position + int fQ = 0; // charge ClassDefNV(CustomClass, 1); }; diff --git a/examples/simulation/Tutorial4/gconfig/DecayConfig.C b/examples/simulation/Tutorial4/gconfig/DecayConfig.C index b357532373..bfdda43ec5 100644 --- a/examples/simulation/Tutorial4/gconfig/DecayConfig.C +++ b/examples/simulation/Tutorial4/gconfig/DecayConfig.C @@ -5,92 +5,94 @@ * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ -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/examples/simulation/Tutorial4/gconfig/Geane.C b/examples/simulation/Tutorial4/gconfig/Geane.C index 73336c993f..84ba16895a 100644 --- a/examples/simulation/Tutorial4/gconfig/Geane.C +++ b/examples/simulation/Tutorial4/gconfig/Geane.C @@ -11,74 +11,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/examples/simulation/Tutorial4/gconfig/SetCuts.C b/examples/simulation/Tutorial4/gconfig/SetCuts.C index 095498f4c7..65ed486782 100644 --- a/examples/simulation/Tutorial4/gconfig/SetCuts.C +++ b/examples/simulation/Tutorial4/gconfig/SetCuts.C @@ -13,47 +13,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",0); /**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", 0); /**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/examples/simulation/Tutorial4/gconfig/UserDecay.C b/examples/simulation/Tutorial4/gconfig/UserDecay.C index 68e77763c1..28494cceab 100644 --- a/examples/simulation/Tutorial4/gconfig/UserDecay.C +++ b/examples/simulation/Tutorial4/gconfig/UserDecay.C @@ -5,34 +5,37 @@ * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ -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"); + 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 ; + 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.; + /* bratio[1] = 50.; mode[1][0] =2212 ; mode[1][1] =AlphaPDG ; */ - gMC->SetDecayMode(He5PDG,bratio,mode); + gMC->SetDecayMode(He5PDG, bratio, mode); } diff --git a/examples/simulation/Tutorial4/gconfig/basiclibs.C b/examples/simulation/Tutorial4/gconfig/basiclibs.C index 4a3bbdd209..85c3e0d4fb 100644 --- a/examples/simulation/Tutorial4/gconfig/basiclibs.C +++ b/examples/simulation/Tutorial4/gconfig/basiclibs.C @@ -11,7 +11,7 @@ void basiclibs() { - /* gSystem->Load("libGeom"); + /* gSystem->Load("libGeom"); gSystem->Load("libGeomPainter"); @@ -23,21 +23,21 @@ void basiclibs() gSystem->Load("libMinuit"); gSystem->Load("libTree"); */ - 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("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("libProof"); - gSystem->Load("libProofPlayer"); - gSystem->Load("libGX11TTF"); - gSystem->Load("libGX11"); + gSystem->Load("libProof"); + gSystem->Load("libProofPlayer"); + gSystem->Load("libGX11TTF"); + gSystem->Load("libGX11"); } diff --git a/examples/simulation/Tutorial4/gconfig/flConfig.C b/examples/simulation/Tutorial4/gconfig/flConfig.C index 99c2de787f..bc3ed7481b 100644 --- a/examples/simulation/Tutorial4/gconfig/flConfig.C +++ b/examples/simulation/Tutorial4/gconfig/flConfig.C @@ -10,19 +10,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; FairStack *st = new FairStack(); 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/examples/simulation/Tutorial4/gconfig/fllibs.C b/examples/simulation/Tutorial4/gconfig/fllibs.C index 7bb0f907c6..89f2b45894 100644 --- a/examples/simulation/Tutorial4/gconfig/fllibs.C +++ b/examples/simulation/Tutorial4/gconfig/fllibs.C @@ -23,11 +23,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/examples/simulation/Tutorial4/gconfig/g3Config.C b/examples/simulation/Tutorial4/gconfig/g3Config.C index e775d1f5ea..ccab5bb1bf 100644 --- a/examples/simulation/Tutorial4/gconfig/g3Config.C +++ b/examples/simulation/Tutorial4/gconfig/g3Config.C @@ -11,36 +11,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 - FairStack *st = new FairStack(); - 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 + FairStack* st = new FairStack(); + 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(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->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(1); // cerenkov photons + geant3->SetCKOV(1); // cerenkov photons } diff --git a/examples/simulation/Tutorial4/gconfig/g3Config_new.C b/examples/simulation/Tutorial4/gconfig/g3Config_new.C index ed861022d2..8a8d201ea3 100644 --- a/examples/simulation/Tutorial4/gconfig/g3Config_new.C +++ b/examples/simulation/Tutorial4/gconfig/g3Config_new.C @@ -11,65 +11,56 @@ 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 - FairStack *st = new FairStack(); - st->SetMinPoints(0); - 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 + FairStack* st = new FairStack(); + st->SetMinPoints(0); + geant3->SetStack(st); - // ******* Geant3 configuration for simulated Runs ******* - geant3->SetTRIG(1); //Number of events to be processed + // ******* Geant3 configuration for simulated Runs ******* + geant3->SetTRIG(1); // Number of events to be processed geant3->SetSWIT(4, 100); geant3->SetDEBU(0, 0, 1); geant3->SetDCAY(1); geant3->SetPAIR(1); geant3->SetCOMP(1); geant3->SetPHOT(1); - geant3->SetPFIS(0); // + geant3->SetPFIS(0); // geant3->SetDRAY(1); geant3->SetANNI(1); geant3->SetBREM(1); geant3->SetMUNU(1); geant3->SetCKOV(1); - geant3->SetHADR(3); //Select pure GEANH (HADR 1) or GEANH/NUCRIN (HADR 3) //5==GCALOR + geant3->SetHADR(3); // Select pure GEANH (HADR 1) or GEANH/NUCRIN (HADR 3) //5==GCALOR geant3->SetLOSS(1); geant3->SetMULS(1); geant3->SetRAYL(1); 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->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); - - Float_t cut = 1. e-3; // 1MeV cut by default + Float_t cut = 1. e - 3; // 1MeV cut by default Float_t tofmax = 1.e10; // Float_t cut2 = 1.e-10; // 1 keV? Float_t cut2 = cut; - Float_t cut3 =50.e-6 ; // Threshold for delta electrons + Float_t cut3 = 50.e-6; // Threshold for delta electrons - Float_t cut5[5] ={0,0,0,0,0}; + Float_t cut5[5] = {0, 0, 0, 0, 0}; // set cuts here // GAM ELEC NHAD CHAD MUON EBREM MUHAB EDEL MUDEL MUPA TOFMAX -// geant3->SetCUTS(cut2, cut2, cut2, cut2, cut, cut2, cut2, cut3, cut2, cut2, -// tofmax); - geant3->SetCUTS(cut2, cut2, cut2, cut2, cut, cut2, cut2, cut2, cut2, cut2, - tofmax,cut5); - - + // geant3->SetCUTS(cut2, cut2, cut2, cut2, cut, cut2, cut2, cut3, cut2, cut2, + // tofmax); + geant3->SetCUTS(cut2, cut2, cut2, cut2, cut, cut2, cut2, cut2, cut2, cut2, tofmax, cut5); } diff --git a/examples/simulation/Tutorial4/gconfig/g3libs.C b/examples/simulation/Tutorial4/gconfig/g3libs.C index 83b3ab34c6..c729474b10 100644 --- a/examples/simulation/Tutorial4/gconfig/g3libs.C +++ b/examples/simulation/Tutorial4/gconfig/g3libs.C @@ -9,11 +9,11 @@ void g3libs() { - cout << "Loading Geant3 libraries ..." << endl; + cout << "Loading Geant3 libraries ..." << endl; - gSystem->Load("libPythia6"); - gSystem->Load("libEGPythia6"); - gSystem->Load("libgeant321"); + gSystem->Load("libPythia6"); + gSystem->Load("libEGPythia6"); + gSystem->Load("libgeant321"); - cout << "Loading Geant3 libraries ... finished" << endl; + cout << "Loading Geant3 libraries ... finished" << endl; } diff --git a/examples/simulation/Tutorial4/gconfig/g4Config.C b/examples/simulation/Tutorial4/gconfig/g4Config.C index 7f40b87824..b52f0c0cde 100644 --- a/examples/simulation/Tutorial4/gconfig/g4Config.C +++ b/examples/simulation/Tutorial4/gconfig/g4Config.C @@ -8,60 +8,58 @@ // 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. + /// 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. - Bool_t mtMode = FairRunSim::Instance()->IsMT(); - Bool_t specialStacking = false; - TG4RunConfiguration* runConfiguration - = new TG4RunConfiguration("geomRoot", "QGSP_BERT_EMV", "stepLimiter+specialCuts+specialControls", - specialStacking, mtMode); + Bool_t mtMode = FairRunSim::Instance()->IsMT(); + Bool_t specialStacking = false; + TG4RunConfiguration* runConfiguration = new TG4RunConfiguration( + "geomRoot", "QGSP_BERT_EMV", "stepLimiter+specialCuts+specialControls", specialStacking, mtMode); -/// Create the G4 VMC - TGeant4* geant4 = new TGeant4("TGeant4", "The Geant4 Monte Carlo", runConfiguration); - cout << "Geant4 has been created." << endl; + /// Create the G4 VMC + TGeant4* geant4 = new TGeant4("TGeant4", "The Geant4 Monte Carlo", runConfiguration); + cout << "Geant4 has been created." << endl; -/// create the Specific stack - FairStack *stack = new FairStack(1000); - stack->StoreSecondaries(kTRUE); - stack->SetMinPoints(0); - geant4->SetStack(stack); + /// create the Specific stack + FairStack* stack = new FairStack(1000); + stack->StoreSecondaries(kTRUE); + stack->SetMinPoints(0); + geant4->SetStack(stack); - if(FairRunSim::Instance()->IsExtDecayer()){ - TVirtualMCDecayer* decayer = TPythia6Decayer::Instance(); - geant4->SetExternalDecayer(decayer); - } + if (FairRunSim::Instance()->IsExtDecayer()) { + TVirtualMCDecayer* decayer = TPythia6Decayer::Instance(); + geant4->SetExternalDecayer(decayer); + } -/// Customise Geant4 setting -/// (verbose level, global range cut, ..) + /// Customise Geant4 setting + /// (verbose level, global range cut, ..) - TString configm(gSystem->Getenv("CONFIG_DIR")); - TString configm1 = configm + "/g4config.in"; - cout << " -I g4Config() using g4conf macro: " << configm1 << endl; - - //set geant4 specific stuff - geant4->SetMaxNStep(10000); // default is 30000 - geant4->ProcessGeantMacro(configm1.Data()); + TString configm(gSystem->Getenv("CONFIG_DIR")); + TString configm1 = configm + "/g4config.in"; + cout << " -I g4Config() using g4conf macro: " << configm1 << endl; + // set geant4 specific stuff + geant4->SetMaxNStep(10000); // default is 30000 + geant4->ProcessGeantMacro(configm1.Data()); } diff --git a/examples/simulation/Tutorial4/gconfig/rootlogon.C b/examples/simulation/Tutorial4/gconfig/rootlogon.C index 707f2ec1df..8d401a1ea4 100644 --- a/examples/simulation/Tutorial4/gconfig/rootlogon.C +++ b/examples/simulation/Tutorial4/gconfig/rootlogon.C @@ -7,18 +7,18 @@ ********************************************************************************/ 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/examples/simulation/Tutorial4/macros/Create_Tutorial4_Geometry.C b/examples/simulation/Tutorial4/macros/Create_Tutorial4_Geometry.C index e0b43eb311..d8cf614995 100644 --- a/examples/simulation/Tutorial4/macros/Create_Tutorial4_Geometry.C +++ b/examples/simulation/Tutorial4/macros/Create_Tutorial4_Geometry.C @@ -7,28 +7,20 @@ ********************************************************************************/ // in root all sizes are given in cm - - - -#include +#include +#include #include -#include #include +#include #include #include -#include -#include -#include -#include +#include #include #include - - - +#include +#include #include - - // Name of geometry version and output file const TString geoVersion = "tutorial4"; const TString FileName = geoVersion + ".root"; @@ -36,8 +28,8 @@ const TString FileName1 = geoVersion + "_geomanager.root"; // Names of the different used materials which are used to build the modules // The materials are defined in the global media.geo file -const TString KeepingVolumeMedium = "air"; -const TString BoxVolumeMedium = "silicon"; +const TString KeepingVolumeMedium = "air"; +const TString BoxVolumeMedium = "silicon"; // Distance of the center of the first detector layer [cm]; const Float_t First_Z_Position = 10; @@ -49,8 +41,8 @@ const Float_t Module_Size_Y = 80.; const Float_t Module_Size_Z = .04; // some global variables -TGeoManager* gGeoMan = NULL; // Pointer to TGeoManager instance -TGeoVolume* gModules; // Global storage for module types +TGeoManager* gGeoMan = NULL; // Pointer to TGeoManager instance +TGeoVolume* gModules; // Global storage for module types // Forward declarations void create_materials_from_media_file(); @@ -58,135 +50,127 @@ TGeoVolume* create_detector(); void position_detector(); void add_alignable_volumes(); -void Create_Tutorial4_Geometry() { - // Load the necessary FairRoot libraries -// gROOT->LoadMacro("$VMCWORKDIR/gconfig/basiclibs.C"); -// basiclibs(); -// gSystem->Load("libGeoBase"); -// gSystem->Load("libParBase"); -// gSystem->Load("libBase"); - - // Load needed material definition from media.geo file - create_materials_from_media_file(); - - // Get the GeoManager for later usage - gGeoMan = (TGeoManager*) gROOT->FindObject("FAIRGeom"); - gGeoMan->SetVisLevel(7); +void Create_Tutorial4_Geometry() +{ + // Load the necessary FairRoot libraries + // gROOT->LoadMacro("$VMCWORKDIR/gconfig/basiclibs.C"); + // basiclibs(); + // gSystem->Load("libGeoBase"); + // gSystem->Load("libParBase"); + // gSystem->Load("libBase"); - // Create the top volume + // Load needed material definition from media.geo file + create_materials_from_media_file(); - TGeoVolume* top = new TGeoVolumeAssembly("TOP"); - gGeoMan->SetTopVolume(top); + // Get the GeoManager for later usage + gGeoMan = (TGeoManager*)gROOT->FindObject("FAIRGeom"); + gGeoMan->SetVisLevel(7); - TGeoVolume* tut4 = new TGeoVolumeAssembly(geoVersion); - top->AddNode(tut4, 1); + // Create the top volume - gModules = create_detector(); + TGeoVolume* top = new TGeoVolumeAssembly("TOP"); + gGeoMan->SetTopVolume(top); - position_detector(); + TGeoVolume* tut4 = new TGeoVolumeAssembly(geoVersion); + top->AddNode(tut4, 1); - cout<<"Voxelizing."<Voxelize(""); - gGeoMan->CloseGeometry(); + gModules = create_detector(); - add_alignable_volumes(); + position_detector(); - gGeoMan->CheckOverlaps(0.001); - gGeoMan->PrintOverlaps(); - gGeoMan->Test(); + cout << "Voxelizing." << endl; + top->Voxelize(""); + gGeoMan->CloseGeometry(); - TFile* outfile = TFile::Open(FileName,"RECREATE"); - top->Write(); - outfile->Close(); + add_alignable_volumes(); - TFile* outfile1 = TFile::Open(FileName1,"RECREATE"); - gGeoMan->Write(); - outfile1->Close(); + gGeoMan->CheckOverlaps(0.001); + gGeoMan->PrintOverlaps(); + gGeoMan->Test(); + TFile* outfile = TFile::Open(FileName, "RECREATE"); + top->Write(); + outfile->Close(); + TFile* outfile1 = TFile::Open(FileName1, "RECREATE"); + gGeoMan->Write(); + outfile1->Close(); - // ------------------------------------------------------------------------ + // ------------------------------------------------------------------------ } void create_materials_from_media_file() { - // Use the FairRoot geometry interface to load the media which are already defined - FairGeoLoader* geoLoad = new FairGeoLoader("TGeo", "FairGeoLoader"); - FairGeoInterface* geoFace = geoLoad->getGeoInterface(); - TString geoPath = gSystem->Getenv("VMCWORKDIR"); - TString geoFile = geoPath + "/common/geometry/media.geo"; - geoFace->setMediaFile(geoFile); - geoFace->readMedia(); + // Use the FairRoot geometry interface to load the media which are already defined + FairGeoLoader* geoLoad = new FairGeoLoader("TGeo", "FairGeoLoader"); + FairGeoInterface* geoFace = geoLoad->getGeoInterface(); + TString geoPath = gSystem->Getenv("VMCWORKDIR"); + TString geoFile = geoPath + "/common/geometry/media.geo"; + geoFace->setMediaFile(geoFile); + geoFace->readMedia(); - // Read the required media and create them in the GeoManager - FairGeoMedia* geoMedia = geoFace->getMedia(); - FairGeoBuilder* geoBuild = geoLoad->getGeoBuilder(); + // Read the required media and create them in the GeoManager + FairGeoMedia* geoMedia = geoFace->getMedia(); + FairGeoBuilder* geoBuild = geoLoad->getGeoBuilder(); - FairGeoMedium* air = geoMedia->getMedium("air"); - FairGeoMedium* silicon = geoMedia->getMedium("silicon"); + FairGeoMedium* air = geoMedia->getMedium("air"); + FairGeoMedium* silicon = geoMedia->getMedium("silicon"); - // include check if all media are found + // include check if all media are found - geoBuild->createMedium(air); - geoBuild->createMedium(silicon); + geoBuild->createMedium(air); + geoBuild->createMedium(silicon); } TGeoVolume* create_detector() { - // needed materials - TGeoMedium* SiliconVolMed = gGeoMan->GetMedium(BoxVolumeMedium); - - // Single detector_layer - TGeoBBox* det_plane = new TGeoBBox("", Module_Size_X/2., Module_Size_Y/2., Module_Size_Z/2.); - TGeoVolume* det_plane_vol = - new TGeoVolume("tut4_det", det_plane, SiliconVolMed); - det_plane_vol->SetLineColor(kBlue); // set line color - det_plane_vol->SetTransparency(70); // set transparency - TGeoTranslation* det_plane_trans - = new TGeoTranslation("", 0., 0., 0.); + // needed materials + TGeoMedium* SiliconVolMed = gGeoMan->GetMedium(BoxVolumeMedium); - return det_plane_vol; + // Single detector_layer + TGeoBBox* det_plane = new TGeoBBox("", Module_Size_X / 2., Module_Size_Y / 2., Module_Size_Z / 2.); + TGeoVolume* det_plane_vol = new TGeoVolume("tut4_det", det_plane, SiliconVolMed); + det_plane_vol->SetLineColor(kBlue); // set line color + det_plane_vol->SetTransparency(70); // set transparency + TGeoTranslation* det_plane_trans = new TGeoTranslation("", 0., 0., 0.); + return det_plane_vol; } void position_detector() { - TGeoTranslation* det_trans=NULL; + TGeoTranslation* det_trans = NULL; - Int_t numDets=0; - for (Int_t detectorPlanes = 0; detectorPlanes < 40; detectorPlanes++) { - det_trans - = new TGeoTranslation("", 0., 0., First_Z_Position+(numDets*Z_Distance)); - gGeoMan->GetVolume(geoVersion)->AddNode(gModules, numDets, det_trans); - numDets++; - - } + Int_t numDets = 0; + for (Int_t detectorPlanes = 0; detectorPlanes < 40; detectorPlanes++) { + det_trans = new TGeoTranslation("", 0., 0., First_Z_Position + (numDets * Z_Distance)); + gGeoMan->GetVolume(geoVersion)->AddNode(gModules, numDets, det_trans); + numDets++; + } } void add_alignable_volumes() { - TString volPath; - TString symName; - TString detStr = "Tutorial4/det"; - TString volStr = "/TOP_1/tutorial4_1/tut4_det_"; - - for (Int_t detectorPlanes = 0; detectorPlanes < 40; detectorPlanes++) { - - volPath = volStr; - volPath += detectorPlanes; + TString volPath; + TString symName; + TString detStr = "Tutorial4/det"; + TString volStr = "/TOP_1/tutorial4_1/tut4_det_"; - symName = detStr; - symName += Form("%02d",detectorPlanes); + for (Int_t detectorPlanes = 0; detectorPlanes < 40; detectorPlanes++) { - cout<<"Path: "<cd(volPath); + volPath = volStr; + volPath += detectorPlanes; - gGeoMan->SetAlignableEntry(symName.Data(),volPath.Data()); + symName = detStr; + symName += Form("%02d", detectorPlanes); - } - cout<<"Nr of alignable objects: "<GetNAlignable()<cd(volPath); + gGeoMan->SetAlignableEntry(symName.Data(), volPath.Data()); + } + cout << "Nr of alignable objects: " << gGeoMan->GetNAlignable() << endl; } diff --git a/examples/simulation/Tutorial4/macros/analysis/compare.cxx b/examples/simulation/Tutorial4/macros/analysis/compare.cxx index ea80d0ce3c..785684e983 100644 --- a/examples/simulation/Tutorial4/macros/analysis/compare.cxx +++ b/examples/simulation/Tutorial4/macros/analysis/compare.cxx @@ -5,153 +5,159 @@ * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ -#include -#include -#include #include #include +#include +#include +#include -using std::ifstream; -using std::vector; using std::cout; using std::endl; using std::fabs; +using std::ifstream; +using std::vector; int main(int argc, char* argv[]) { - // No good solution - // TODO - bool isFortranFile; - if ( 2 == argc ) { - isFortranFile = argv[1]; - } - - // Read the milepede output and the file with shifts created by - // TestMillePede to compare if the correction have been correctly calculated - - int label; - float value; - float value2; - vector labelVector; - vector valueVector; - - if (!isFortranFile) { - - cout<<"Read file created by TestMillePede."<> label >> value; - if (!vInput.good()) { break; } - labelVector.push_back(label); - valueVector.push_back(value); + + // Read the milepede output and the file with shifts created by + // TestMillePede to compare if the correction have been correctly calculated + + int label; + float value; + float value2; + vector labelVector; + vector valueVector; + + if (!isFortranFile) { + + cout << "Read file created by TestMillePede." << endl; + + ifstream vInput; + vInput.open("shifts.txt"); + if (!vInput.is_open()) { + cout << "Could not open the input file." << endl; + exit(1); + } + while (1) { + vInput >> label >> value; + if (!vInput.good()) { + break; + } + labelVector.push_back(label); + valueVector.push_back(value); + } + vInput.close(); + + } else { + + cout << "Read file created by pede." << endl; + + ifstream vInput; + vInput.open("shifts.txt"); + if (!vInput.is_open()) { + cout << "Could not open the input file." << endl; + exit(1); + } + while (1) { + vInput >> label >> value >> value2; + if (!vInput.good()) { + break; + } + int label1 = 10 + label * 2; + labelVector.push_back(label1); + valueVector.push_back(value); + label1 = 500 + label; + labelVector.push_back(label1); + valueVector.push_back(value2); + } + vInput.close(); } - vInput.close(); - } else { + for (int c = 0; c < (int)labelVector.size(); ++c) { + cout << "c, label,value:" << c << ", " << labelVector[c] << ", " << valueVector[c] << endl; + } - cout<<"Read file created by pede."<::iterator result; - ifstream vInput; - vInput.open("shifts.txt"); - if (!vInput.is_open()) { - cout<<"Could not open the input file."<> label >> value >> value2; - if (!vInput.good()) { break; } - int label1=10+label*2; - labelVector.push_back(label1); - valueVector.push_back(value); - label1=500+label; - labelVector.push_back(label1); - valueVector.push_back(value2); + vInput1 >> label >> value >> dummy1 >> dummy2 >> dummy3; + if (!vInput1.good()) { + break; + } + labelVector.push_back(label); + valueVector.push_back(value); + cout << label << ", " << value << endl; } - vInput.close(); - } - - for(int c=0; c < (int)labelVector.size(); ++c) { - cout <<"c, label,value:" << c <<", "<::iterator result; - - result = std::max_element(labelVector.begin(), labelVector.end()); - - int maxValue = *result; - - float origShifts[maxValue+1]; - float recoShifts[maxValue+1]; - - for (int i=0; i> label >> value >> dummy1 >> dummy2 >> dummy3; - if (!vInput1.good()) { break; } - labelVector.push_back(label); - valueVector.push_back(value); - cout << label<<", "< 1.) { - cout< 2.) { - percent2++; + + for (int i = 0; i < labelVector.size(); ++i) { + recoShifts[labelVector[i]] = valueVector[i]; } - if ( percent > 3.) { - percent3++; + + for (int i = 0; i < labelVector.size(); ++i) { + recoShifts[labelVector[i]] = valueVector[i]; } - if ( percent > 4.) { - percent4++; + + int numBadValues = 0; + int percent2 = 0; + int percent3 = 0; + int percent4 = 0; + for (int i = 0; i < maxValue + 1; ++i) { + float diff = recoShifts[i] + origShifts[i]; + float percent = fabs(diff / origShifts[i]) * 100; + if (percent > 1.) { + cout << i << " : " << recoShifts[i] << ", " << origShifts[i] << ", " << diff << ", " << percent << endl; + numBadValues++; + } + if (percent > 2.) { + percent2++; + } + if (percent > 3.) { + percent3++; + } + if (percent > 4.) { + percent4++; + } } - } - cout< 1%"< 2%"< 3%"< 4%"< 1%" << endl; + cout << percent2 << " corrections with a deviation > 2%" << endl; + cout << percent3 << " corrections with a deviation > 3%" << endl; + cout << percent4 << " corrections with a deviation > 4%" << endl; } diff --git a/examples/simulation/Tutorial4/macros/eventDisplay.C b/examples/simulation/Tutorial4/macros/eventDisplay.C index 046280e637..9685a1ca17 100644 --- a/examples/simulation/Tutorial4/macros/eventDisplay.C +++ b/examples/simulation/Tutorial4/macros/eventDisplay.C @@ -5,35 +5,34 @@ * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ -void eventDisplay(TString mcEngine="TGeant3") +void eventDisplay(TString mcEngine = "TGeant3") { - //-----User Settings:----------------------------------------------- - TString InputFile ="testrun_" + mcEngine + ".root"; - TString ParFile ="testparams_" + mcEngine + ".root"; - TString OutFile ="tst.root"; - //------------------------------------------------------------------ - - - // ----- Reconstruction run ------------------------------------------- - FairRunAna *fRun= new FairRunAna(); - FairFileSource *fFileSource = new FairFileSource(InputFile); - fRun->SetSource(fFileSource); - fRun->SetSink(new FairRootFileSink(OutFile.Data())); - - FairRuntimeDb* rtdb = fRun->GetRuntimeDb(); - FairParRootFileIo* parInput1 = new FairParRootFileIo(); - parInput1->open(ParFile.Data()); - rtdb->setFirstInput(parInput1); - - FairEventManager *fMan= new FairEventManager(); - - //----------------------Traks and points ------------------------------------- - FairMCTracks *Track = new FairMCTracks("Monte-Carlo Tracks"); - FairTutorialDet4PointDraw *TutorialDetectorPoints = new FairTutorialDet4PointDraw("TutorialDetPoint", kRed, kFullSquare); - - fMan->AddTask(Track); - fMan->AddTask(TutorialDetectorPoints); - - fMan->Init(); - + //-----User Settings:----------------------------------------------- + TString InputFile = "testrun_" + mcEngine + ".root"; + TString ParFile = "testparams_" + mcEngine + ".root"; + TString OutFile = "tst.root"; + //------------------------------------------------------------------ + + // ----- Reconstruction run ------------------------------------------- + FairRunAna *fRun = new FairRunAna(); + FairFileSource *fFileSource = new FairFileSource(InputFile); + fRun->SetSource(fFileSource); + fRun->SetSink(new FairRootFileSink(OutFile.Data())); + + FairRuntimeDb *rtdb = fRun->GetRuntimeDb(); + FairParRootFileIo *parInput1 = new FairParRootFileIo(); + parInput1->open(ParFile.Data()); + rtdb->setFirstInput(parInput1); + + FairEventManager *fMan = new FairEventManager(); + + //----------------------Traks and points ------------------------------------- + FairMCTracks *Track = new FairMCTracks("Monte-Carlo Tracks"); + FairTutorialDet4PointDraw *TutorialDetectorPoints = + new FairTutorialDet4PointDraw("TutorialDetPoint", kRed, kFullSquare); + + fMan->AddTask(Track); + fMan->AddTask(TutorialDetectorPoints); + + fMan->Init(); } diff --git a/examples/simulation/Tutorial4/macros/plots.C b/examples/simulation/Tutorial4/macros/plots.C index 0751b00823..f7e563641d 100644 --- a/examples/simulation/Tutorial4/macros/plots.C +++ b/examples/simulation/Tutorial4/macros/plots.C @@ -5,175 +5,173 @@ * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ -plots(Int_t nEvents = 1000, Int_t iout=1, TString mcEngine="TGeant3") +plots(Int_t nEvents = 1000, Int_t iout = 1, TString mcEngine = "TGeant3") { - // Input data definitions - //-----User Settings:----------------------------------------------- - TString MCFile ="testrun_" + mcEngine + ".root"; - TString ParFile ="testparams_" + mcEngine + ".root"; - TString RecoFile ="testreco_"+ mcEngine + ".root";; - - - // ----- Reconstruction run ------------------------------------------- - FairRunAna *fRun= new FairRunAna(); - FairFileSource *fFileSource = new FairFileSource(MCFile); - fRun->SetSource(fFileSource); - fRun->AddFriend(RecoFile.Data()); - - FairRuntimeDb* rtdb = fRun->GetRuntimeDb(); - FairParRootFileIo* parInput1 = new FairParRootFileIo(); - parInput1->open(ParFile.Data()); - rtdb->setFirstInput(parInput1); - - TFile *f1 = TFile::Open(MCFile); - TFile *f2 = TFile::Open(RecoFile); - - TTree *t1 = f1->Get("cbmsim"); - TTree *t2 = f2->Get("cbmsim"); - - FairMCEventHeader *MCEventHeader = new FairMCEventHeader(); - TClonesArray *MCTracks = new TClonesArray("FairMCTrack"); - TClonesArray *TutorialDetPoints = new TClonesArray("FairTutorialDet4Point"); - TClonesArray *TutorialDetHits = new TClonesArray("FairTutorialDet4Hit"); - - t1->SetBranchAddress("MCEventHeader.",&MCEventHeader); - t1->SetBranchAddress("MCTrack", &MCTracks); - t1->SetBranchAddress("TutorialDetPoint", &TutorialDetPoints); - t2->SetBranchAddress("TutorialDetHit", &TutorialDetHits); - - FairMCTrack *MCTrack; - FairTutorialDet4Point *Point; - FairTutorialDet4Hit *Hit; - - //histograms - fRun->SetSink(new FairRootFileSink("test.ana.root")); - TFile *fHist = fRun->GetOutputFile(); - - Float_t xrange=80.; - Float_t yrange=80.; - - TH2F* dxx = new TH2F("dxx","Hit; x; Delta x;",100,-xrange,xrange,50.,-10.,10.); - TH2F* dyy = new TH2F("dyy","Hit; y; Delta y;",100,-yrange,yrange,50.,-10.,10.); - TH1F* pullx = new TH1F("pullx","Hit; pullx;",100.,-5.,5.); - TH1F* pully = new TH1F("pully","Hit; pully;",100.,-5.,5.); - TH1F* pullz = new TH1F("pullz","Hit; pullz;",50.,-10.,10.); - TH1F* pointx = new TH1F("pointx","Hit; posx;",200.,-80.,80.); - TH1F* pointy = new TH1F("pointy","Hit; posy;",200.,-80.,80.); - - Int_t nMCTracks, nPoints, nHits; - Float_t x_point, y_point, z_point, tof_point, SMtype_point, mod_point, cel_point, gap_point; - Float_t x_poi, y_poi, z_poi; - Float_t SMtype_poi, mod_poi, cel_poi, gap_poi; - Float_t p_MC, px_MC, py_MC, pz_MC; - Float_t x_hit, y_hit, z_hit, dy_hit; - - Int_t nevent = t1->GetEntries(); - - if (nevent > nEvents) nevent=nEvents; - - cout << "total number of events to process: " << nevent - <GetEntry(iev); - t2->GetEntry(iev); - - nMCTracks = MCTracks->GetEntriesFast(); - nPoints = TutorialDetPoints->GetEntriesFast(); - nHits = TutorialDetHits->GetEntriesFast(); - - cout << " Event" << iev << ":"; - cout << nMCTracks << " MC tracks "; - cout << nPoints << " points "; - cout << nHits << " Hits "<At(j); - Int_t l = Hit->GetRefIndex(); - Point = (FairTutorialDet4Point*) TutorialDetPoints->At(l); - - // Point info - x_poi = Point -> GetX(); - y_poi = Point -> GetY(); - z_poi = Point -> GetZ(); - - // Hit info - x_hit = Hit->GetX(); - y_hit = Hit->GetY(); - z_hit = Hit->GetZ(); - dy_hit = Hit->GetDy(); -// Int_t flg_hit = Hit->GetFlag(); - - Float_t delta_x = x_poi - x_hit; - Float_t delta_y = y_poi - y_hit; - Float_t delta_z = z_poi - z_hit; - - dxx ->Fill(x_poi,delta_x); - dyy ->Fill(y_poi,delta_y); - pullx ->Fill(delta_x); - pully ->Fill(delta_y); - pullz ->Fill(delta_z); - pointx ->Fill(x_hit); - pointy ->Fill(y_hit); - - } // Hit loop end - -} // event loop end - - -// save histos to file -// TFile *fHist = TFile::Open("data/auaumbias.hst.root","RECREATE"); - cout << "Processing done, outflag =" <Write(); - if(0){ // explicit writing - TIter next(gDirectory->GetList()); - TH1 *h; - TObject* obj; - while(obj= (TObject*)next()){ - if(obj->InheritsFrom(TH1::Class())){ - h = (TH1*)obj; - cout << "Write histo " << h->GetTitle() << endl; - h->Write(); - } - } - } - fHist->ls(); - fHist->Close(); - } - - // ----- Finish ------------------------------------------------------- - - cout << endl << endl; - - // Extract the maximal used memory an add is as Dart measurement - // This line is filtered by CTest and the value send to CDash - FairSystemInfo sysInfo; - Float_t maxMemory=sysInfo.GetMaxMemory(); - cout << ""; - cout << maxMemory; - cout << "" << endl; - - timer.Stop(); - Double_t rtime = timer.RealTime(); - Double_t ctime = timer.CpuTime(); - - Float_t cpuUsage=ctime/rtime; - cout << ""; - cout << cpuUsage; - cout << "" << endl; - - cout << endl << endl; - cout << "Output file is " << outFile << endl; - cout << "Parameter file is " << parFile << endl; - cout << "Real time " << rtime << " s, CPU time " << ctime - << "s" << endl << endl; - cout << "Macro finished successfully." << endl; - - // ------------------------------------------------------------------------ + // Input data definitions + //-----User Settings:----------------------------------------------- + TString MCFile = "testrun_" + mcEngine + ".root"; + TString ParFile = "testparams_" + mcEngine + ".root"; + TString RecoFile = "testreco_" + mcEngine + ".root"; + ; + + // ----- Reconstruction run ------------------------------------------- + FairRunAna *fRun = new FairRunAna(); + FairFileSource *fFileSource = new FairFileSource(MCFile); + fRun->SetSource(fFileSource); + fRun->AddFriend(RecoFile.Data()); + + FairRuntimeDb *rtdb = fRun->GetRuntimeDb(); + FairParRootFileIo *parInput1 = new FairParRootFileIo(); + parInput1->open(ParFile.Data()); + rtdb->setFirstInput(parInput1); + + TFile *f1 = TFile::Open(MCFile); + TFile *f2 = TFile::Open(RecoFile); + + TTree *t1 = f1->Get("cbmsim"); + TTree *t2 = f2->Get("cbmsim"); + + FairMCEventHeader *MCEventHeader = new FairMCEventHeader(); + TClonesArray *MCTracks = new TClonesArray("FairMCTrack"); + TClonesArray *TutorialDetPoints = new TClonesArray("FairTutorialDet4Point"); + TClonesArray *TutorialDetHits = new TClonesArray("FairTutorialDet4Hit"); + + t1->SetBranchAddress("MCEventHeader.", &MCEventHeader); + t1->SetBranchAddress("MCTrack", &MCTracks); + t1->SetBranchAddress("TutorialDetPoint", &TutorialDetPoints); + t2->SetBranchAddress("TutorialDetHit", &TutorialDetHits); + + FairMCTrack *MCTrack; + FairTutorialDet4Point *Point; + FairTutorialDet4Hit *Hit; + + // histograms + fRun->SetSink(new FairRootFileSink("test.ana.root")); + TFile *fHist = fRun->GetOutputFile(); + + Float_t xrange = 80.; + Float_t yrange = 80.; + + TH2F *dxx = new TH2F("dxx", "Hit; x; Delta x;", 100, -xrange, xrange, 50., -10., 10.); + TH2F *dyy = new TH2F("dyy", "Hit; y; Delta y;", 100, -yrange, yrange, 50., -10., 10.); + TH1F *pullx = new TH1F("pullx", "Hit; pullx;", 100., -5., 5.); + TH1F *pully = new TH1F("pully", "Hit; pully;", 100., -5., 5.); + TH1F *pullz = new TH1F("pullz", "Hit; pullz;", 50., -10., 10.); + TH1F *pointx = new TH1F("pointx", "Hit; posx;", 200., -80., 80.); + TH1F *pointy = new TH1F("pointy", "Hit; posy;", 200., -80., 80.); + + Int_t nMCTracks, nPoints, nHits; + Float_t x_point, y_point, z_point, tof_point, SMtype_point, mod_point, cel_point, gap_point; + Float_t x_poi, y_poi, z_poi; + Float_t SMtype_poi, mod_poi, cel_poi, gap_poi; + Float_t p_MC, px_MC, py_MC, pz_MC; + Float_t x_hit, y_hit, z_hit, dy_hit; + + Int_t nevent = t1->GetEntries(); + + if (nevent > nEvents) + nevent = nEvents; + + cout << "total number of events to process: " << nevent << endl; + + // Event loop + + for (Int_t iev = 0; iev < nevent; iev++) { + // get entry + t1->GetEntry(iev); + t2->GetEntry(iev); + + nMCTracks = MCTracks->GetEntriesFast(); + nPoints = TutorialDetPoints->GetEntriesFast(); + nHits = TutorialDetHits->GetEntriesFast(); + + cout << " Event" << iev << ":"; + cout << nMCTracks << " MC tracks "; + cout << nPoints << " points "; + cout << nHits << " Hits " << endl; + + // Hit loop + for (Int_t j = 0; j < nHits; j++) { + Hit = (FairTutorialDet4Hit *)TutorialDetHits->At(j); + Int_t l = Hit->GetRefIndex(); + Point = (FairTutorialDet4Point *)TutorialDetPoints->At(l); + + // Point info + x_poi = Point->GetX(); + y_poi = Point->GetY(); + z_poi = Point->GetZ(); + + // Hit info + x_hit = Hit->GetX(); + y_hit = Hit->GetY(); + z_hit = Hit->GetZ(); + dy_hit = Hit->GetDy(); + // Int_t flg_hit = Hit->GetFlag(); + + Float_t delta_x = x_poi - x_hit; + Float_t delta_y = y_poi - y_hit; + Float_t delta_z = z_poi - z_hit; + + dxx->Fill(x_poi, delta_x); + dyy->Fill(y_poi, delta_y); + pullx->Fill(delta_x); + pully->Fill(delta_y); + pullz->Fill(delta_z); + pointx->Fill(x_hit); + pointy->Fill(y_hit); + + } // Hit loop end + + } // event loop end + + // save histos to file + // TFile *fHist = TFile::Open("data/auaumbias.hst.root","RECREATE"); + cout << "Processing done, outflag =" << iout << endl; + if (iout == 1) { + fHist->Write(); + if (0) { // explicit writing + TIter next(gDirectory->GetList()); + TH1 *h; + TObject *obj; + while (obj = (TObject *)next()) { + if (obj->InheritsFrom(TH1::Class())) { + h = (TH1 *)obj; + cout << "Write histo " << h->GetTitle() << endl; + h->Write(); + } + } + } + fHist->ls(); + fHist->Close(); + } + + // ----- Finish ------------------------------------------------------- + + cout << endl << endl; + + // Extract the maximal used memory an add is as Dart measurement + // This line is filtered by CTest and the value send to CDash + FairSystemInfo sysInfo; + Float_t maxMemory = sysInfo.GetMaxMemory(); + cout << ""; + cout << maxMemory; + cout << "" << endl; + + timer.Stop(); + Double_t rtime = timer.RealTime(); + Double_t ctime = timer.CpuTime(); + + Float_t cpuUsage = ctime / rtime; + cout << ""; + cout << cpuUsage; + cout << "" << endl; + + cout << endl << endl; + cout << "Output file is " << outFile << endl; + cout << "Parameter file is " << parFile << endl; + cout << "Real time " << rtime << " s, CPU time " << ctime << "s" << endl << endl; + cout << "Macro finished successfully." << endl; + + // ------------------------------------------------------------------------ } diff --git a/examples/simulation/Tutorial4/macros/run_reco.C b/examples/simulation/Tutorial4/macros/run_reco.C index ef3dbb8be3..631af91887 100644 --- a/examples/simulation/Tutorial4/macros/run_reco.C +++ b/examples/simulation/Tutorial4/macros/run_reco.C @@ -5,118 +5,116 @@ * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ -void run_reco( TString mcEngine="TGeant3", Bool_t AlignDone=true ) +void run_reco(TString mcEngine = "TGeant3", Bool_t AlignDone = true) { - // ---- Load libraries ------------------------------------------------- - FairLogger *logger = FairLogger::GetLogger(); -// logger->SetLogFileName("MyLog.log"); - logger->SetLogToScreen(kTRUE); -// logger->SetLogToFile(kTRUE); -// logger->SetLogVerbosityLevel("HIGH"); -// logger->SetLogFileLevel("DEBUG4"); - logger->SetLogScreenLevel("INFO"); - - // Verbosity level (0=quiet, 1=event level, 2=track level, 3=debug) - Int_t iVerbose = 0; // just forget about it, for the moment - - TString Align= ""; - if (AlignDone) { - Align= "align_"; - } - TString InDir = "./data/"; - // Input file (MC Events) - TString inFile ="testrun_"; - inFile = InDir +inFile + Align + mcEngine + ".root"; - - // Output file name - TString outFile ="testreco_"; - outFile = InDir + outFile + Align + mcEngine + ".root"; - - // Parameter file - TString parFile ="testparams_"; - parFile = InDir + parFile + Align + mcEngine + ".root"; - - // Millepede file name - TString milleFile ="testmille_"; - milleFile = InDir + milleFile + Align + mcEngine; - - TList *parFileList = new TList(); - - TString workDir = gSystem->Getenv("VMCWORKDIR"); - TString paramDir = workDir + "/simulation/Tutorial4/parameters/"; - TString paramFile = paramDir + "example.par"; - - TObjString tutDetDigiFile; - tutDetDigiFile.SetString(paramFile); - parFileList->Add(&tutDetDigiFile); - - // ----- Timer -------------------------------------------------------- - TStopwatch timer; - - // ----- Reconstruction run ------------------------------------------- - FairRunAna *fRun= new FairRunAna(); - FairFileSource *fFileSource = new FairFileSource(inFile); - fRun->SetSource(fFileSource); - fRun->SetSink(new FairRootFileSink(outFile)); - - FairRuntimeDb* rtdb = fRun->GetRuntimeDb(); - FairParRootFileIo* parInput1 = new FairParRootFileIo(); - FairParAsciiFileIo* parIo2 = new FairParAsciiFileIo(); - parIo2->open(parFileList, "in"); - parInput1->open(parFile.Data()); - parIo2->open(parFileList, "in"); - rtdb->setFirstInput(parInput1); - rtdb->setSecondInput(parIo2); - rtdb->setOutput(parInput1); - rtdb->saveOutput(); - - // ----- TorinoDetector hit producers --------------------------------- - FairTutorialDet4HitProducerIdealMisalign* hitProducer = new FairTutorialDet4HitProducerIdealMisalign(); - hitProducer->DoMisalignment(kFALSE); - fRun->AddTask(hitProducer); - - FairTutorialDet4StraightLineFitter* fitter = new FairTutorialDet4StraightLineFitter(); - fitter->SetVersion(2); - fRun->AddTask(fitter); - - FairTutorialDet4MilleWriter* writer = new FairTutorialDet4MilleWriter(); -// writer->SetWriteAscii(kTRUE); - writer->SetVersion(2); - writer->SetFileName(milleFile); - fRun->AddTask(writer); - - - fRun->Init(); - - timer.Start(); - fRun->Run(); - - // ----- Finish ------------------------------------------------------- - - cout << endl << endl; - - // Extract the maximal used memory an add is as Dart measurement - // This line is filtered by CTest and the value send to CDash - FairSystemInfo sysInfo; - Float_t maxMemory=sysInfo.GetMaxMemory(); - cout << ""; - cout << maxMemory; - cout << "" << endl; - - timer.Stop(); - Double_t rtime = timer.RealTime(); - Double_t ctime = timer.CpuTime(); - - Float_t cpuUsage=ctime/rtime; - cout << ""; - cout << cpuUsage; - cout << "" << endl; - - cout << endl << endl; - cout << "Output file is " << outFile << endl; - cout << "Parameter file is " << parFile << endl; - cout << "Real time " << rtime << " s, CPU time " << ctime - << "s" << endl << endl; - cout << "Macro finished successfully." << endl; - // ------------------------------------------------------------------------ + // ---- Load libraries ------------------------------------------------- + FairLogger* logger = FairLogger::GetLogger(); + // logger->SetLogFileName("MyLog.log"); + logger->SetLogToScreen(kTRUE); + // logger->SetLogToFile(kTRUE); + // logger->SetLogVerbosityLevel("HIGH"); + // logger->SetLogFileLevel("DEBUG4"); + logger->SetLogScreenLevel("INFO"); + + // Verbosity level (0=quiet, 1=event level, 2=track level, 3=debug) + Int_t iVerbose = 0; // just forget about it, for the moment + + TString Align = ""; + if (AlignDone) { + Align = "align_"; + } + TString InDir = "./data/"; + // Input file (MC Events) + TString inFile = "testrun_"; + inFile = InDir + inFile + Align + mcEngine + ".root"; + + // Output file name + TString outFile = "testreco_"; + outFile = InDir + outFile + Align + mcEngine + ".root"; + + // Parameter file + TString parFile = "testparams_"; + parFile = InDir + parFile + Align + mcEngine + ".root"; + + // Millepede file name + TString milleFile = "testmille_"; + milleFile = InDir + milleFile + Align + mcEngine; + + TList* parFileList = new TList(); + + TString workDir = gSystem->Getenv("VMCWORKDIR"); + TString paramDir = workDir + "/simulation/Tutorial4/parameters/"; + TString paramFile = paramDir + "example.par"; + + TObjString tutDetDigiFile; + tutDetDigiFile.SetString(paramFile); + parFileList->Add(&tutDetDigiFile); + + // ----- Timer -------------------------------------------------------- + TStopwatch timer; + + // ----- Reconstruction run ------------------------------------------- + FairRunAna* fRun = new FairRunAna(); + FairFileSource* fFileSource = new FairFileSource(inFile); + fRun->SetSource(fFileSource); + fRun->SetSink(new FairRootFileSink(outFile)); + + FairRuntimeDb* rtdb = fRun->GetRuntimeDb(); + FairParRootFileIo* parInput1 = new FairParRootFileIo(); + FairParAsciiFileIo* parIo2 = new FairParAsciiFileIo(); + parIo2->open(parFileList, "in"); + parInput1->open(parFile.Data()); + parIo2->open(parFileList, "in"); + rtdb->setFirstInput(parInput1); + rtdb->setSecondInput(parIo2); + rtdb->setOutput(parInput1); + rtdb->saveOutput(); + + // ----- TorinoDetector hit producers --------------------------------- + FairTutorialDet4HitProducerIdealMisalign* hitProducer = new FairTutorialDet4HitProducerIdealMisalign(); + hitProducer->DoMisalignment(kFALSE); + fRun->AddTask(hitProducer); + + FairTutorialDet4StraightLineFitter* fitter = new FairTutorialDet4StraightLineFitter(); + fitter->SetVersion(2); + fRun->AddTask(fitter); + + FairTutorialDet4MilleWriter* writer = new FairTutorialDet4MilleWriter(); + // writer->SetWriteAscii(kTRUE); + writer->SetVersion(2); + writer->SetFileName(milleFile); + fRun->AddTask(writer); + + fRun->Init(); + + timer.Start(); + fRun->Run(); + + // ----- Finish ------------------------------------------------------- + + cout << endl << endl; + + // Extract the maximal used memory an add is as Dart measurement + // This line is filtered by CTest and the value send to CDash + FairSystemInfo sysInfo; + Float_t maxMemory = sysInfo.GetMaxMemory(); + cout << ""; + cout << maxMemory; + cout << "" << endl; + + timer.Stop(); + Double_t rtime = timer.RealTime(); + Double_t ctime = timer.CpuTime(); + + Float_t cpuUsage = ctime / rtime; + cout << ""; + cout << cpuUsage; + cout << "" << endl; + + cout << endl << endl; + cout << "Output file is " << outFile << endl; + cout << "Parameter file is " << parFile << endl; + cout << "Real time " << rtime << " s, CPU time " << ctime << "s" << endl << endl; + cout << "Macro finished successfully." << endl; + // ------------------------------------------------------------------------ } diff --git a/examples/simulation/Tutorial4/macros/run_tutorial4.C b/examples/simulation/Tutorial4/macros/run_tutorial4.C index de2bbfdafe..d24fb7d38f 100644 --- a/examples/simulation/Tutorial4/macros/run_tutorial4.C +++ b/examples/simulation/Tutorial4/macros/run_tutorial4.C @@ -5,128 +5,126 @@ * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ -void run_tutorial4(Int_t nEvents = 10, TString mcEngine="TGeant3", - Bool_t doAlign=true, Bool_t isMT=false) +void run_tutorial4(Int_t nEvents = 10, TString mcEngine = "TGeant3", Bool_t doAlign = true, Bool_t isMT = false) { - TString dir = getenv("VMCWORKDIR"); + TString dir = getenv("VMCWORKDIR"); - TString tut_configdir = dir + "/simulation/Tutorial4/gconfig"; - gSystem->Setenv("CONFIG_DIR",tut_configdir.Data()); + TString tut_configdir = dir + "/simulation/Tutorial4/gconfig"; + gSystem->Setenv("CONFIG_DIR", tut_configdir.Data()); - TString tut_geomdir = dir + "/common/geometry"; - gSystem->Setenv("GEOMPATH",tut_geomdir.Data()); + TString tut_geomdir = dir + "/common/geometry"; + gSystem->Setenv("GEOMPATH", tut_geomdir.Data()); - Double_t momentum = 2.; + Double_t momentum = 2.; - Double_t theta = 2.; + Double_t theta = 2.; - TString outDir = "./data/"; + TString outDir = "./data/"; - // Output file name - TString outFile{""}; - TString geoFile{""}; - TString parFile{""}; - if (doAlign) { - outFile = "testrun_align_"; - geoFile = "geoFile_align_"; - parFile = "testparams_align_"; - } else { - outFile = "testrun_"; - geoFile = "geoFile"; - parFile = "testparams_"; - } - outFile = outDir + outFile + mcEngine + ".root"; - geoFile = outDir + geoFile + mcEngine + ".root"; - parFile = outDir + parFile + mcEngine + ".root"; + // Output file name + TString outFile{""}; + TString geoFile{""}; + TString parFile{""}; + if (doAlign) { + outFile = "testrun_align_"; + geoFile = "geoFile_align_"; + parFile = "testparams_align_"; + } else { + outFile = "testrun_"; + geoFile = "geoFile"; + parFile = "testparams_"; + } + outFile = outDir + outFile + mcEngine + ".root"; + geoFile = outDir + geoFile + mcEngine + ".root"; + parFile = outDir + parFile + mcEngine + ".root"; - TList *parFileList = new TList(); + TList* parFileList = new TList(); - TString paramDir = dir + "/simulation/Tutorial4/parameters/"; - TString paramFile = paramDir + "example.par"; + TString paramDir = dir + "/simulation/Tutorial4/parameters/"; + TString paramFile = paramDir + "example.par"; - TObjString* tutDetDigiFile = new TObjString(paramFile); - parFileList->Add(tutDetDigiFile); + TObjString* tutDetDigiFile = new TObjString(paramFile); + parFileList->Add(tutDetDigiFile); - // In general, the following parts need not be touched - // ======================================================================== + // In general, the following parts need not be touched + // ======================================================================== - // ---- Debug option ------------------------------------------------- - gDebug = 0; - // ------------------------------------------------------------------------ + // ---- Debug option ------------------------------------------------- + gDebug = 0; + // ------------------------------------------------------------------------ - // ----- Timer -------------------------------------------------------- - TStopwatch timer; - timer.Start(); - // ------------------------------------------------------------------------ + // ----- Timer -------------------------------------------------------- + TStopwatch timer; + timer.Start(); + // ------------------------------------------------------------------------ - //Does not work with automatic loading pf libraries. The info is not in the rootmap file -// gLogger->SetLogScreenLevel("INFO"); + // Does not work with automatic loading pf libraries. The info is not in the rootmap file + // gLogger->SetLogScreenLevel("INFO"); - // ----- Create simulation run ---------------------------------------- - FairRunSim* run = new FairRunSim(); - run->SetName(mcEngine); // Transport engine - run->SetIsMT(isMT); // Multi-threading mode (Geant4 only) - run->SetSink(new FairRootFileSink(outFile)); // Output file - FairRuntimeDb* rtdb = run->GetRuntimeDb(); - // ------------------------------------------------------------------------ + // ----- Create simulation run ---------------------------------------- + FairRunSim* run = new FairRunSim(); + run->SetName(mcEngine); // Transport engine + run->SetIsMT(isMT); // Multi-threading mode (Geant4 only) + run->SetSink(new FairRootFileSink(outFile)); // Output file + FairRuntimeDb* rtdb = run->GetRuntimeDb(); + // ------------------------------------------------------------------------ - // ----- Create media ------------------------------------------------- - run->SetMaterials("media.geo"); // Materials - // ------------------------------------------------------------------------ + // ----- Create media ------------------------------------------------- + run->SetMaterials("media.geo"); // Materials + // ------------------------------------------------------------------------ - // ----- Create geometry ---------------------------------------------- - FairModule* cave= new FairCave("CAVE"); - cave->SetGeometryFileName("cave_vacuum.geo"); - run->AddModule(cave); + // ----- Create geometry ---------------------------------------------- + FairModule* cave = new FairCave("CAVE"); + cave->SetGeometryFileName("cave_vacuum.geo"); + run->AddModule(cave); - FairTutorialDet4* tutdet = new FairTutorialDet4("TUTDET", kTRUE); - tutdet->SetGeometryFileName("tutorial4.root"); - tutdet->SetModifyGeometry(doAlign); + FairTutorialDet4* tutdet = new FairTutorialDet4("TUTDET", kTRUE); + tutdet->SetGeometryFileName("tutorial4.root"); + tutdet->SetModifyGeometry(doAlign); - run->AddModule(tutdet); - // ------------------------------------------------------------------------ + run->AddModule(tutdet); + // ------------------------------------------------------------------------ - // ----- Create PrimaryGenerator -------------------------------------- - FairPrimaryGenerator* primGen = new FairPrimaryGenerator(); - FairBoxGenerator* boxGen = new FairBoxGenerator(2212, 1); + // ----- Create PrimaryGenerator -------------------------------------- + FairPrimaryGenerator* primGen = new FairPrimaryGenerator(); + FairBoxGenerator* boxGen = new FairBoxGenerator(2212, 1); - boxGen->SetThetaRange ( theta, theta+0.1); -// boxGen->SetThetaRange ( 0., 0.); - boxGen->SetPRange (momentum,momentum+0.01); - boxGen->SetPhiRange (0.,360.); - boxGen->SetBoxXYZ (-20.,-20.,20.,20., 0.); -// boxGen->SetBoxXYZ (0.,0.,0.,0., 0.); + boxGen->SetThetaRange(theta, theta + 0.1); + // boxGen->SetThetaRange ( 0., 0.); + boxGen->SetPRange(momentum, momentum + 0.01); + boxGen->SetPhiRange(0., 360.); + boxGen->SetBoxXYZ(-20., -20., 20., 20., 0.); + // boxGen->SetBoxXYZ (0.,0.,0.,0., 0.); -// boxGen->SetDebug(kTRUE); + // boxGen->SetDebug(kTRUE); - primGen->AddGenerator(boxGen); + primGen->AddGenerator(boxGen); + run->SetGenerator(primGen); - run->SetGenerator(primGen); + // ----- Store information about particle trajectories ------------------ + run->SetStoreTraj(kTRUE); - // ----- Store information about particle trajectories ------------------ - run->SetStoreTraj(kTRUE); + // ----- Runtime database --------------------------------------------- - // ----- Runtime database --------------------------------------------- - - Bool_t kParameterMerged = kTRUE; - FairParRootFileIo* parOut = new FairParRootFileIo(kParameterMerged); - FairParAsciiFileIo* parIn = new FairParAsciiFileIo(); - parOut->open(parFile.Data()); - parIn->open(parFileList, "in"); - rtdb->setFirstInput(parIn); - rtdb->setOutput(parOut); - // ------------------------------------------------------------------------ - - // ----- Initialize simulation run ------------------------------------ - run->Init(); - - // -Trajectories Visualization (TGeoManager Only ) - // ----------------------------------------------- - - // Set cuts for storing the trajectories - /* FairTrajFilter* trajFilter = FairTrajFilter::Instance(); + Bool_t kParameterMerged = kTRUE; + FairParRootFileIo* parOut = new FairParRootFileIo(kParameterMerged); + FairParAsciiFileIo* parIn = new FairParAsciiFileIo(); + parOut->open(parFile.Data()); + parIn->open(parFileList, "in"); + rtdb->setFirstInput(parIn); + rtdb->setOutput(parOut); + // ------------------------------------------------------------------------ + + // ----- Initialize simulation run ------------------------------------ + run->Init(); + + // -Trajectories Visualization (TGeoManager Only ) + // ----------------------------------------------- + + // Set cuts for storing the trajectories + /* FairTrajFilter* trajFilter = FairTrajFilter::Instance(); trajFilter->SetStepSizeCut(0.01); // 1 cm trajFilter->SetVertexCut(-2000., -2000., 4., 2000., 2000., 100.); trajFilter->SetMomentumCutP(10e-3); // p_lab > 10 MeV @@ -135,47 +133,45 @@ void run_tutorial4(Int_t nEvents = 10, TString mcEngine="TGeant3", trajFilter->SetStoreSecondaries(kTRUE); */ - // ------------------------------------------------------------------------ - + // ------------------------------------------------------------------------ - // ----- Start run ---------------------------------------------------- - //run->CreateGeometryFile(geoFile); //misaligned geometry - run->Run(nEvents); - //run->CreateGeometryFile(geoFile); // original geometry - // ------------------------------------------------------------------------ + // ----- Start run ---------------------------------------------------- + // run->CreateGeometryFile(geoFile); //misaligned geometry + run->Run(nEvents); + // run->CreateGeometryFile(geoFile); // original geometry + // ------------------------------------------------------------------------ - rtdb->saveOutput(); - rtdb->print(); + rtdb->saveOutput(); + rtdb->print(); - delete run; + delete run; - // ----- Finish ------------------------------------------------------- + // ----- Finish ------------------------------------------------------- - cout << endl << endl; + cout << endl << endl; - // Extract the maximal used memory an add is as Dart measurement - // This line is filtered by CTest and the value send to CDash - FairSystemInfo sysInfo; - Float_t maxMemory=sysInfo.GetMaxMemory(); - cout << ""; - cout << maxMemory; - cout << "" << endl; + // Extract the maximal used memory an add is as Dart measurement + // This line is filtered by CTest and the value send to CDash + FairSystemInfo sysInfo; + Float_t maxMemory = sysInfo.GetMaxMemory(); + cout << ""; + cout << maxMemory; + cout << "" << endl; - timer.Stop(); - Double_t rtime = timer.RealTime(); - Double_t ctime = timer.CpuTime(); + timer.Stop(); + Double_t rtime = timer.RealTime(); + Double_t ctime = timer.CpuTime(); - Float_t cpuUsage=ctime/rtime; - cout << ""; - cout << cpuUsage; - cout << "" << endl; + Float_t cpuUsage = ctime / rtime; + cout << ""; + cout << cpuUsage; + cout << "" << endl; - cout << endl << endl; - cout << "Output file is " << outFile << endl; - cout << "Parameter file is " << parFile << endl; - cout << "Real time " << rtime << " s, CPU time " << ctime - << "s" << endl << endl; - cout << "Macro finished successfully." << endl; + cout << endl << endl; + cout << "Output file is " << outFile << endl; + cout << "Parameter file is " << parFile << endl; + cout << "Real time " << rtime << " s, CPU time " << ctime << "s" << endl << endl; + cout << "Macro finished successfully." << endl; - // ------------------------------------------------------------------------ + // ------------------------------------------------------------------------ } diff --git a/examples/simulation/Tutorial4/macros/run_tutorial4_createGeometryFile.C b/examples/simulation/Tutorial4/macros/run_tutorial4_createGeometryFile.C index 8c092b69ad..13d0b89be9 100644 --- a/examples/simulation/Tutorial4/macros/run_tutorial4_createGeometryFile.C +++ b/examples/simulation/Tutorial4/macros/run_tutorial4_createGeometryFile.C @@ -1,41 +1,40 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ -void run_tutorial4_createGeometryFile(Int_t nEvents = 1, TString mcEngine="TGeant3", Bool_t isMT=false) +void run_tutorial4_createGeometryFile(Int_t nEvents = 1, TString mcEngine = "TGeant3", Bool_t isMT = false) { - - TString dir = getenv("VMCWORKDIR"); - TString tut_configdir = dir + "/simulation/Tutorial4/gconfig"; - gSystem->Setenv("CONFIG_DIR",tut_configdir.Data()); + TString dir = getenv("VMCWORKDIR"); - TString tut_geomdir = dir + "/common/geometry"; - gSystem->Setenv("GEOMPATH",tut_geomdir.Data()); - - Double_t momentum = 2.; + TString tut_configdir = dir + "/simulation/Tutorial4/gconfig"; + gSystem->Setenv("CONFIG_DIR", tut_configdir.Data()); - Double_t theta = 2.; + TString tut_geomdir = dir + "/common/geometry"; + gSystem->Setenv("GEOMPATH", tut_geomdir.Data()); - TString outDir = "./data/"; + Double_t momentum = 2.; - // Output file name - TString outFile ="makeGeo_"; - outFile = outDir + outFile + mcEngine + ".root"; + Double_t theta = 2.; - TString geoFile ="makeGeoFile_"; - geoFile = outDir + geoFile + mcEngine + "_full.root"; + TString outDir = "./data/"; + // Output file name + TString outFile = "makeGeo_"; + outFile = outDir + outFile + mcEngine + ".root"; - TString parFile ="makeGeoParams_"; - parFile = outDir + parFile + mcEngine + ".root"; - - TList *parFileList = new TList(); + TString geoFile = "makeGeoFile_"; + geoFile = outDir + geoFile + mcEngine + "_full.root"; -/* + TString parFile = "makeGeoParams_"; + parFile = outDir + parFile + mcEngine + ".root"; + + TList* parFileList = new TList(); + + /* TString paramDir = dir + "/simulation/Tutorial4/parameters/"; TString paramFile = paramDir + "example.par"; @@ -43,118 +42,113 @@ void run_tutorial4_createGeometryFile(Int_t nEvents = 1, TString mcEngine="TGean parFileList->Add(tutDetDigiFile); */ - // In general, the following parts need not be touched - // ======================================================================== - - // ---- Debug option ------------------------------------------------- - gDebug = 0; - // ------------------------------------------------------------------------ - - // ----- Timer -------------------------------------------------------- - TStopwatch timer; - timer.Start(); - // ------------------------------------------------------------------------ - - //Does not work with automatic loading pf libraries. The info is not in the rootmap file -// gLogger->SetLogScreenLevel("INFO"); - - // ----- Create simulation run ---------------------------------------- - FairRunSim* run = new FairRunSim(); - run->SetName(mcEngine); // Transport engine - run->SetIsMT(isMT); // Multi-threading mode (Geant4 only) - run->SetSink(new FairRootFileSink(outFile)); // Output file - FairRuntimeDb* rtdb = run->GetRuntimeDb(); - // ------------------------------------------------------------------------ - - // ----- Create media ------------------------------------------------- - run->SetMaterials("media.geo"); // Materials - // ------------------------------------------------------------------------ - - // ----- Create geometry ---------------------------------------------- - FairModule* cave= new FairCave("CAVE"); - cave->SetGeometryFileName("cave_vacuum.geo"); - run->AddModule(cave); - - FairTutorialDet4* tutdet = new FairTutorialDet4("TUTDET", kTRUE); - tutdet->SetGeometryFileName("tutorial4.root"); - - run->AddModule(tutdet); - // ------------------------------------------------------------------------ - - // ----- Create PrimaryGenerator -------------------------------------- - FairPrimaryGenerator* primGen = new FairPrimaryGenerator(); - FairBoxGenerator* boxGen = new FairBoxGenerator(2212, 1); - - boxGen->SetThetaRange ( theta, theta+0.1); -// boxGen->SetThetaRange ( 0., 0.); - boxGen->SetPRange (momentum,momentum+0.01); - boxGen->SetPhiRange (0.,360.); - boxGen->SetBoxXYZ (-20.,-20.,20.,20., 0.); -// boxGen->SetBoxXYZ (0.,0.,0.,0., 0.); - -// boxGen->SetDebug(kTRUE); - - primGen->AddGenerator(boxGen); - - - run->SetGenerator(primGen); - // ------------------------------------------------------------------------ - - // ----- Runtime database --------------------------------------------- - - Bool_t kParameterMerged = kTRUE; - FairParRootFileIo* parOut = new FairParRootFileIo(kParameterMerged); - FairParAsciiFileIo* parIn = new FairParAsciiFileIo(); - parOut->open(parFile.Data()); - parIn->open(parFileList, "in"); - rtdb->setFirstInput(parIn); - rtdb->setOutput(parOut); - // ------------------------------------------------------------------------ - - run->Init(); - - // ------------------------------------------------------------------------ - - - // ----- Start run ---------------------------------------------------- - run->Run(nEvents); - run->CreateGeometryFile(geoFile); - // ------------------------------------------------------------------------ - - rtdb->saveOutput(); - rtdb->print(); - - delete run; - - // ----- Finish ------------------------------------------------------- - - cout << endl << endl; - - // Extract the maximal used memory an add is as Dart measurement - // This line is filtered by CTest and the value send to CDash - FairSystemInfo sysInfo; - Float_t maxMemory=sysInfo.GetMaxMemory(); - cout << ""; - cout << maxMemory; - cout << "" << endl; - - timer.Stop(); - Double_t rtime = timer.RealTime(); - Double_t ctime = timer.CpuTime(); - - Float_t cpuUsage=ctime/rtime; - cout << ""; - cout << cpuUsage; - cout << "" << endl; - - cout << endl << endl; - cout << "Output file is " << outFile << endl; - cout << "Parameter file is " << parFile << endl; - cout << "Real time " << rtime << " s, CPU time " << ctime - << "s" << endl << endl; - cout << "Macro finished successfully." << endl; - - // ------------------------------------------------------------------------ -} + // In general, the following parts need not be touched + // ======================================================================== + + // ---- Debug option ------------------------------------------------- + gDebug = 0; + // ------------------------------------------------------------------------ + + // ----- Timer -------------------------------------------------------- + TStopwatch timer; + timer.Start(); + // ------------------------------------------------------------------------ + + // Does not work with automatic loading pf libraries. The info is not in the rootmap file + // gLogger->SetLogScreenLevel("INFO"); + + // ----- Create simulation run ---------------------------------------- + FairRunSim* run = new FairRunSim(); + run->SetName(mcEngine); // Transport engine + run->SetIsMT(isMT); // Multi-threading mode (Geant4 only) + run->SetSink(new FairRootFileSink(outFile)); // Output file + FairRuntimeDb* rtdb = run->GetRuntimeDb(); + // ------------------------------------------------------------------------ + + // ----- Create media ------------------------------------------------- + run->SetMaterials("media.geo"); // Materials + // ------------------------------------------------------------------------ + + // ----- Create geometry ---------------------------------------------- + FairModule* cave = new FairCave("CAVE"); + cave->SetGeometryFileName("cave_vacuum.geo"); + run->AddModule(cave); + + FairTutorialDet4* tutdet = new FairTutorialDet4("TUTDET", kTRUE); + tutdet->SetGeometryFileName("tutorial4.root"); + + run->AddModule(tutdet); + // ------------------------------------------------------------------------ + + // ----- Create PrimaryGenerator -------------------------------------- + FairPrimaryGenerator* primGen = new FairPrimaryGenerator(); + FairBoxGenerator* boxGen = new FairBoxGenerator(2212, 1); + + boxGen->SetThetaRange(theta, theta + 0.1); + // boxGen->SetThetaRange ( 0., 0.); + boxGen->SetPRange(momentum, momentum + 0.01); + boxGen->SetPhiRange(0., 360.); + boxGen->SetBoxXYZ(-20., -20., 20., 20., 0.); + // boxGen->SetBoxXYZ (0.,0.,0.,0., 0.); + + // boxGen->SetDebug(kTRUE); + + primGen->AddGenerator(boxGen); + run->SetGenerator(primGen); + // ------------------------------------------------------------------------ + // ----- Runtime database --------------------------------------------- + + Bool_t kParameterMerged = kTRUE; + FairParRootFileIo* parOut = new FairParRootFileIo(kParameterMerged); + FairParAsciiFileIo* parIn = new FairParAsciiFileIo(); + parOut->open(parFile.Data()); + parIn->open(parFileList, "in"); + rtdb->setFirstInput(parIn); + rtdb->setOutput(parOut); + // ------------------------------------------------------------------------ + + run->Init(); + + // ------------------------------------------------------------------------ + + // ----- Start run ---------------------------------------------------- + run->Run(nEvents); + run->CreateGeometryFile(geoFile); + // ------------------------------------------------------------------------ + + rtdb->saveOutput(); + rtdb->print(); + + delete run; + + // ----- Finish ------------------------------------------------------- + + cout << endl << endl; + + // Extract the maximal used memory an add is as Dart measurement + // This line is filtered by CTest and the value send to CDash + FairSystemInfo sysInfo; + Float_t maxMemory = sysInfo.GetMaxMemory(); + cout << ""; + cout << maxMemory; + cout << "" << endl; + + timer.Stop(); + Double_t rtime = timer.RealTime(); + Double_t ctime = timer.CpuTime(); + + Float_t cpuUsage = ctime / rtime; + cout << ""; + cout << cpuUsage; + cout << "" << endl; + + cout << endl << endl; + cout << "Output file is " << outFile << endl; + cout << "Parameter file is " << parFile << endl; + cout << "Real time " << rtime << " s, CPU time " << ctime << "s" << endl << endl; + cout << "Macro finished successfully." << endl; + + // ------------------------------------------------------------------------ +} diff --git a/examples/simulation/Tutorial4/macros/run_tutorial4_createMatrices.C b/examples/simulation/Tutorial4/macros/run_tutorial4_createMatrices.C index db51a4aafb..58b9158367 100644 --- a/examples/simulation/Tutorial4/macros/run_tutorial4_createMatrices.C +++ b/examples/simulation/Tutorial4/macros/run_tutorial4_createMatrices.C @@ -1,147 +1,145 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ -void run_tutorial4_createMatrices(Int_t nEvents = 10, TString mcEngine="TGeant3", Bool_t isMT=false) +void run_tutorial4_createMatrices(Int_t nEvents = 10, TString mcEngine = "TGeant3", Bool_t isMT = false) { - - TString dir = getenv("VMCWORKDIR"); - - TString tut_configdir = dir + "/simulation/Tutorial4/gconfig"; - gSystem->Setenv("CONFIG_DIR",tut_configdir.Data()); - - TString tut_geomdir = dir + "/common/geometry"; - gSystem->Setenv("GEOMPATH",tut_geomdir.Data()); - - Double_t momentum = 2.; - - Double_t theta = 2.; - - TString outDir = "./"; - // Output file name - TString outFile ="testrun_"; - outFile = outFile + mcEngine + ".root"; + TString dir = getenv("VMCWORKDIR"); - TString geoFile ="data/geoFile_" + mcEngine + "_full.root"; - TString geoFileMisaligned ="data/geoFile_" + mcEngine + "_full_misaligned.root"; - - TString parFile ="testparams_"; - parFile = parFile + mcEngine + ".root"; - - TList *parFileList = new TList(); - - TString paramDir = dir + "/simulation/Tutorial4/parameters/"; - TString paramFile = paramDir + "example.par"; - - TObjString* tutDetDigiFile = new TObjString(paramFile); - parFileList->Add(tutDetDigiFile); + TString tut_configdir = dir + "/simulation/Tutorial4/gconfig"; + gSystem->Setenv("CONFIG_DIR", tut_configdir.Data()); + TString tut_geomdir = dir + "/common/geometry"; + gSystem->Setenv("GEOMPATH", tut_geomdir.Data()); - // In general, the following parts need not be touched - // ======================================================================== + Double_t momentum = 2.; - // ---- Debug option ------------------------------------------------- - gDebug = 0; - // ------------------------------------------------------------------------ + Double_t theta = 2.; - // ----- Timer -------------------------------------------------------- - TStopwatch timer; - timer.Start(); - // ------------------------------------------------------------------------ + TString outDir = "./"; - //Does not work with automatic loading pf libraries. The info is not in the rootmap file -// gLogger->SetLogScreenLevel("INFO"); - - // ----- Create simulation run ---------------------------------------- - FairRunSim* run = new FairRunSim(); - run->SetName(mcEngine); // Transport engine - run->SetIsMT(isMT); // Multi-threading mode (Geant4 only) - run->SetSink(new FairRootFileSink(outFile)); // Output file - FairRuntimeDb* rtdb = run->GetRuntimeDb(); - // ------------------------------------------------------------------------ - - // ----- Create media ------------------------------------------------- - run->SetMaterials("media.geo"); // Materials - // ------------------------------------------------------------------------ - - // ----- Create geometry ---------------------------------------------- - FairModule* cave= new FairCave("CAVE"); - cave->SetGeometryFileName("cave_vacuum.geo"); - run->AddModule(cave); + // Output file name + TString outFile = "testrun_"; + outFile = outFile + mcEngine + ".root"; - FairTutorialDet4* tutdet = new FairTutorialDet4("TUTDET", kTRUE); - tutdet->SetGeometryFileName("tutorial4.root"); - - run->AddModule(tutdet); - // ------------------------------------------------------------------------ + TString geoFile = "data/geoFile_" + mcEngine + "_full.root"; + TString geoFileMisaligned = "data/geoFile_" + mcEngine + "_full_misaligned.root"; - // ----- Create PrimaryGenerator -------------------------------------- - FairPrimaryGenerator* primGen = new FairPrimaryGenerator(); - FairBoxGenerator* boxGen = new FairBoxGenerator(2212, 1); + TString parFile = "testparams_"; + parFile = parFile + mcEngine + ".root"; - boxGen->SetThetaRange ( theta, theta+0.1); -// boxGen->SetThetaRange ( 0., 0.); - boxGen->SetPRange (momentum,momentum+0.01); - boxGen->SetPhiRange (0.,360.); - boxGen->SetBoxXYZ (-20.,-20.,20.,20., 0.); -// boxGen->SetBoxXYZ (0.,0.,0.,0., 0.); + TList* parFileList = new TList(); -// boxGen->SetDebug(kTRUE); + TString paramDir = dir + "/simulation/Tutorial4/parameters/"; + TString paramFile = paramDir + "example.par"; - primGen->AddGenerator(boxGen); + TObjString* tutDetDigiFile = new TObjString(paramFile); + parFileList->Add(tutDetDigiFile); - - run->SetGenerator(primGen); - // ------------------------------------------------------------------------ + // In general, the following parts need not be touched + // ======================================================================== - // ----- Initialize simulation run ------------------------------------ - run->SetStoreTraj(kTRUE); + // ---- Debug option ------------------------------------------------- + gDebug = 0; + // ------------------------------------------------------------------------ - // ----- Runtime database --------------------------------------------- + // ----- Timer -------------------------------------------------------- + TStopwatch timer; + timer.Start(); + // ------------------------------------------------------------------------ - Bool_t kParameterMerged = kTRUE; - FairParRootFileIo* parOut = new FairParRootFileIo(kParameterMerged); - FairParAsciiFileIo* parIn = new FairParAsciiFileIo(); - parOut->open(parFile.Data()); - parIn->open(parFileList, "in"); - rtdb->setFirstInput(parIn); - rtdb->setOutput(parOut); - // ------------------------------------------------------------------------ + // Does not work with automatic loading pf libraries. The info is not in the rootmap file + // gLogger->SetLogScreenLevel("INFO"); - run->Init(); - - //sadly, the align parameters are only available AFTER we called fRun->Init() + // ----- Create simulation run ---------------------------------------- + FairRunSim* run = new FairRunSim(); + run->SetName(mcEngine); // Transport engine + run->SetIsMT(isMT); // Multi-threading mode (Geant4 only) + run->SetSink(new FairRootFileSink(outFile)); // Output file + FairRuntimeDb* rtdb = run->GetRuntimeDb(); + // ------------------------------------------------------------------------ - // We fill a std::map map with all misalignment matrices - // how you get those in your geometry is up to you - - auto matrices = tutdet->getMisalignmentMatrices(); - - ofstream myfile; - myfile.open ("misalignmentMatrices.txt"); - - double *rot; - double *trans; - - // this can probably be done more elegantly - for(auto &mat : matrices){ - myfile << mat.first << "\n"; - rot = mat.second.GetRotationMatrix(); - trans = mat.second.GetTranslation(); - for(int i=0; i<9; i++) myfile << rot[i] << "\n"; - for(int i=0; i<3; i++) myfile << trans[i] << "\n"; - } - myfile.close(); - - LOG(info) << "AlignHandler: all matrices added!"; - - LOG(info) << "SUCCESS! All matrices created and saved!"; - - return; -} + // ----- Create media ------------------------------------------------- + run->SetMaterials("media.geo"); // Materials + // ------------------------------------------------------------------------ + + // ----- Create geometry ---------------------------------------------- + FairModule* cave = new FairCave("CAVE"); + cave->SetGeometryFileName("cave_vacuum.geo"); + run->AddModule(cave); + + FairTutorialDet4* tutdet = new FairTutorialDet4("TUTDET", kTRUE); + tutdet->SetGeometryFileName("tutorial4.root"); + + run->AddModule(tutdet); + // ------------------------------------------------------------------------ + + // ----- Create PrimaryGenerator -------------------------------------- + FairPrimaryGenerator* primGen = new FairPrimaryGenerator(); + FairBoxGenerator* boxGen = new FairBoxGenerator(2212, 1); + + boxGen->SetThetaRange(theta, theta + 0.1); + // boxGen->SetThetaRange ( 0., 0.); + boxGen->SetPRange(momentum, momentum + 0.01); + boxGen->SetPhiRange(0., 360.); + boxGen->SetBoxXYZ(-20., -20., 20., 20., 0.); + // boxGen->SetBoxXYZ (0.,0.,0.,0., 0.); + + // boxGen->SetDebug(kTRUE); + + primGen->AddGenerator(boxGen); + + run->SetGenerator(primGen); + // ------------------------------------------------------------------------ + + // ----- Initialize simulation run ------------------------------------ + run->SetStoreTraj(kTRUE); + + // ----- Runtime database --------------------------------------------- + Bool_t kParameterMerged = kTRUE; + FairParRootFileIo* parOut = new FairParRootFileIo(kParameterMerged); + FairParAsciiFileIo* parIn = new FairParAsciiFileIo(); + parOut->open(parFile.Data()); + parIn->open(parFileList, "in"); + rtdb->setFirstInput(parIn); + rtdb->setOutput(parOut); + // ------------------------------------------------------------------------ + run->Init(); + + // sadly, the align parameters are only available AFTER we called fRun->Init() + + // We fill a std::map map with all misalignment matrices + // how you get those in your geometry is up to you + + auto matrices = tutdet->getMisalignmentMatrices(); + + ofstream myfile; + myfile.open("misalignmentMatrices.txt"); + + double* rot; + double* trans; + + // this can probably be done more elegantly + for (auto& mat : matrices) { + myfile << mat.first << "\n"; + rot = mat.second.GetRotationMatrix(); + trans = mat.second.GetTranslation(); + for (int i = 0; i < 9; i++) + myfile << rot[i] << "\n"; + for (int i = 0; i < 3; i++) + myfile << trans[i] << "\n"; + } + myfile.close(); + + LOG(info) << "AlignHandler: all matrices added!"; + + LOG(info) << "SUCCESS! All matrices created and saved!"; + + return; +} diff --git a/examples/simulation/Tutorial4/macros/run_tutorial4_createParameterFile.C b/examples/simulation/Tutorial4/macros/run_tutorial4_createParameterFile.C index 291718d1bb..8044620350 100644 --- a/examples/simulation/Tutorial4/macros/run_tutorial4_createParameterFile.C +++ b/examples/simulation/Tutorial4/macros/run_tutorial4_createParameterFile.C @@ -6,244 +6,239 @@ * copied verbatim in the file "LICENSE" * ********************************************************************************/ - // forward declaration void writeVectorToFile(std::vector& vec, ofstream* myfile); void run_tutorial4_createParameterFile() { - // Create shift in x, y, z when true - Bool_t ShiftX = kTRUE; - Bool_t ShiftY = kTRUE; - Bool_t ShiftZ = kFALSE; - - // Create a rotation around x, y, z when true - Bool_t RotX = kFALSE; - Bool_t RotY = kFALSE; - Bool_t RotZ = kFALSE; + // Create shift in x, y, z when true + Bool_t ShiftX = kTRUE; + Bool_t ShiftY = kTRUE; + Bool_t ShiftZ = kFALSE; - // main container to store all relevant alignment informatio - std::map> misalignInfo; + // Create a rotation around x, y, z when true + Bool_t RotX = kFALSE; + Bool_t RotY = kFALSE; + Bool_t RotZ = kFALSE; + // main container to store all relevant alignment informatio + std::map> misalignInfo; - //Open file and get the stired TGeoManager - TString mcEngine="TGeant3"; - TString dir = getenv("VMCWORKDIR"); + // Open file and get the stired TGeoManager + TString mcEngine = "TGeant3"; + TString dir = getenv("VMCWORKDIR"); - TString outDir = "./data/"; + TString outDir = "./data/"; - TString geoFile ="makeGeoFile_"; - geoFile = outDir + geoFile + mcEngine + "_full.root"; + TString geoFile = "makeGeoFile_"; + geoFile = outDir + geoFile + mcEngine + "_full.root"; - TFile* f = new TFile(geoFile, "READ"); - if (!f) { - std::cout << "Could not open the file" << std::endl; - exit(1); - } + TFile* f = new TFile(geoFile, "READ"); + if (!f) { + std::cout << "Could not open the file" << std::endl; + exit(1); + } - TList* l = f->GetListOfKeys(); + TList* l = f->GetListOfKeys(); - TKey* key; - TIter next( l); + TKey* key; + TIter next(l); - TGeoManager* geoMan{nullptr}; + TGeoManager* geoMan{nullptr}; - while ((key = (TKey*)next())) { - if ( key->ReadObj()->InheritsFrom("TGeoManager") ) { - geoMan = static_cast(key->ReadObj()); - break; + while ((key = (TKey*)next())) { + if (key->ReadObj()->InheritsFrom("TGeoManager")) { + geoMan = static_cast(key->ReadObj()); + break; + } } - } - if (! geoMan) { - f->Close(); - std::cout << "Could not find TGeoManager inside the file" << std::endl; - exit(1); - } - - Float_t shiftx{0.}; - Float_t shifty{0.}; - Float_t shiftz{0.}; - Float_t rotx{0.}; - Float_t roty{0.}; - Float_t rotz{0.}; - - TGeoNode* topNode = gGeoManager->GetTopNode(); - TObjArray* nodes = topNode->GetNodes(); - for (Int_t iNode = 0; iNode < nodes->GetEntriesFast(); iNode++) { - TGeoNode* node = static_cast(nodes->At(iNode)); - if (!TString(node->GetName()).Contains("tutorial4")) continue; // trd_vXXy top node, e.g. trd_v13a, trd_v14b - TGeoNode* station = node; - TObjArray* layers = station->GetNodes(); - for (Int_t iLayer = 0; iLayer < layers->GetEntriesFast(); iLayer++) { - TGeoNode* layer = static_cast(layers->At(iLayer)); - TString path = TString("/") + topNode->GetName() + "/" + station->GetName() + "/" - + layer->GetName(); - - UInt_t hash = path.Hash(); - if (ShiftX) { - shiftx = gRandom->Uniform(-1.,1.); - } - if (ShiftY) { - shifty = gRandom->Uniform(-1.,1.); - } - if (ShiftZ) { - shiftz = gRandom->Uniform(-1.,1.); - } - - TGeoTranslation* trans{nullptr}; - TGeoRotation* rot{nullptr}; - if ( iLayer > 0 & iLayer < layers->GetEntriesFast()-1 ) { - trans = new TGeoTranslation(shiftx, shifty, shiftz); - rot = new TGeoRotation("temp",rotx, roty, rotz); - } else { - trans = new TGeoTranslation(0., 0., 0.); - rot = new TGeoRotation("temp",0.,0., 0.); - } - TGeoCombiTrans* combi= new TGeoCombiTrans(*trans, *rot); - - if (misalignInfo.find(hash) != misalignInfo.end()) { - cerr << "[ERROR ] Hash collision" << endl; - cerr << "[ERROR ] Hash value " << hash << " already exist." << endl; - auto it = misalignInfo.find(hash); - cerr << "[ERROR ] TGeoNode: " << it->second.first << " and " << path - << " both have hash " << hash << endl; - cerr << "[FATAL ] This should never happen. Stop execution." << endl; - exit(1); - } - - misalignInfo[hash] = make_pair(path, combi); + if (!geoMan) { + f->Close(); + std::cout << "Could not find TGeoManager inside the file" << std::endl; + exit(1); } - } - // Close the file with the TGeoManager after all information was extracted - f->Close(); + Float_t shiftx{0.}; + Float_t shifty{0.}; + Float_t shiftz{0.}; + Float_t rotx{0.}; + Float_t roty{0.}; + Float_t rotz{0.}; + + TGeoNode* topNode = gGeoManager->GetTopNode(); + TObjArray* nodes = topNode->GetNodes(); + for (Int_t iNode = 0; iNode < nodes->GetEntriesFast(); iNode++) { + TGeoNode* node = static_cast(nodes->At(iNode)); + if (!TString(node->GetName()).Contains("tutorial4")) + continue; // trd_vXXy top node, e.g. trd_v13a, trd_v14b + TGeoNode* station = node; + TObjArray* layers = station->GetNodes(); + for (Int_t iLayer = 0; iLayer < layers->GetEntriesFast(); iLayer++) { + TGeoNode* layer = static_cast(layers->At(iLayer)); + TString path = TString("/") + topNode->GetName() + "/" + station->GetName() + "/" + layer->GetName(); + + UInt_t hash = path.Hash(); + if (ShiftX) { + shiftx = gRandom->Uniform(-1., 1.); + } + if (ShiftY) { + shifty = gRandom->Uniform(-1., 1.); + } + if (ShiftZ) { + shiftz = gRandom->Uniform(-1., 1.); + } + + TGeoTranslation* trans{nullptr}; + TGeoRotation* rot{nullptr}; + if (iLayer > 0 & iLayer < layers->GetEntriesFast() - 1) { + trans = new TGeoTranslation(shiftx, shifty, shiftz); + rot = new TGeoRotation("temp", rotx, roty, rotz); + } else { + trans = new TGeoTranslation(0., 0., 0.); + rot = new TGeoRotation("temp", 0., 0., 0.); + } + TGeoCombiTrans* combi = new TGeoCombiTrans(*trans, *rot); + + if (misalignInfo.find(hash) != misalignInfo.end()) { + cerr << "[ERROR ] Hash collision" << endl; + cerr << "[ERROR ] Hash value " << hash << " already exist." << endl; + auto it = misalignInfo.find(hash); + cerr << "[ERROR ] TGeoNode: " << it->second.first << " and " << path << " both have hash " << hash + << endl; + cerr << "[FATAL ] This should never happen. Stop execution." << endl; + exit(1); + } - cout << "There are in total " << misalignInfo.size() << " misalligned nodes" << endl; + misalignInfo[hash] = make_pair(path, combi); + } + } - for (auto& elem: misalignInfo) { - cout << "Module "<< elem.first << " " << elem.second.first << " " - << elem.second.second << endl; - } + // Close the file with the TGeoManager after all information was extracted + f->Close(); + cout << "There are in total " << misalignInfo.size() << " misalligned nodes" << endl; - // Write the paramter file - ofstream myfile; - myfile.open ("example.par"); - - myfile << "##############################################################################" << endl; - myfile << "# Class: FairTutorialDetMissallignPar" << endl; - myfile << "# Context: TestDefaultContext" << endl; - myfile << "##############################################################################" << endl; - myfile << "[FairTutorialDetMissallignPar]" << endl; - myfile << "//----------------------------------------------------------------------------" << endl; - myfile << "NrOfDetectors: Int_t "<< misalignInfo.size() << endl; - - // vectors for the different components of the rotation matrix and - // the translation vector. - std::vector r11; - std::vector r12; - std::vector r13; - std::vector r21; - std::vector r22; - std::vector r23; - std::vector r31; - std::vector r32; - std::vector r33; - std::vector tx; - std::vector ty; - std::vector tz; - std::vector path; - std::vector hash; - - Int_t counter = 0; - - myfile << "DetectorId: UInt_t \\ "<< endl; - myfile <<" "; - for (auto& elem: misalignInfo) { - const Double_t* rotation = elem.second.second->GetRotationMatrix(); - const Double_t* translation = elem.second.second->GetTranslation(); - r11.push_back(rotation[0]); - r12.push_back(rotation[1]); - r13.push_back(rotation[2]); - r21.push_back(rotation[3]); - r22.push_back(rotation[4]); - r23.push_back(rotation[5]); - r31.push_back(rotation[6]); - r32.push_back(rotation[7]); - r33.push_back(rotation[8]); - tx.push_back(translation[0]); - ty.push_back(translation[1]); - tz.push_back(translation[2]); - hash.push_back(elem.first); - path.push_back(elem.second.first); - - if ( (8 == counter) ) { - myfile << elem.first <<" \\"< r11; + std::vector r12; + std::vector r13; + std::vector r21; + std::vector r22; + std::vector r23; + std::vector r31; + std::vector r32; + std::vector r33; + std::vector tx; + std::vector ty; + std::vector tz; + std::vector path; + std::vector hash; + + Int_t counter = 0; + + myfile << "DetectorId: UInt_t \\ " << endl; + myfile << " "; + for (auto& elem : misalignInfo) { + const Double_t* rotation = elem.second.second->GetRotationMatrix(); + const Double_t* translation = elem.second.second->GetTranslation(); + r11.push_back(rotation[0]); + r12.push_back(rotation[1]); + r13.push_back(rotation[2]); + r21.push_back(rotation[3]); + r22.push_back(rotation[4]); + r23.push_back(rotation[5]); + r31.push_back(rotation[6]); + r32.push_back(rotation[7]); + r33.push_back(rotation[8]); + tx.push_back(translation[0]); + ty.push_back(translation[1]); + tz.push_back(translation[2]); + hash.push_back(elem.first); + path.push_back(elem.second.first); + + if ((8 == counter)) { + myfile << elem.first << " \\" << endl; + myfile << " "; + counter = 0; + } else { + myfile << elem.first << " "; + ++counter; + } + } + myfile << endl; + + // Due to performance issues when reading the parameters it is not possible + // to store the information about rotation and translation for each + // misaligned node. Instead store the values for one component of rotation + // or translation for all nodes in one array. This reduces the number of + // parameters from a (possible) very large number to 12 (9 components for + // the rotation matrix and 3 for the translation matrix. The proper + // matrices will be created when reading the parameter container. + + myfile << "R11: Double_t \\ " << endl; + myfile << " "; + writeVectorToFile(r11, &myfile); + myfile << "R12: Double_t \\ " << endl; + myfile << " "; + writeVectorToFile(r12, &myfile); + myfile << "R13: Double_t \\ " << endl; + myfile << " "; + writeVectorToFile(r13, &myfile); + + myfile << "R21: Double_t \\ " << endl; + myfile << " "; + writeVectorToFile(r21, &myfile); + myfile << "R22: Double_t \\ " << endl; + myfile << " "; + writeVectorToFile(r22, &myfile); + myfile << "23: Double_t \\ " << endl; + myfile << " "; + writeVectorToFile(r23, &myfile); + + myfile << "R31: Double_t \\ " << endl; + myfile << " "; + writeVectorToFile(r31, &myfile); + myfile << "R32: Double_t \\ " << endl; + myfile << " "; + writeVectorToFile(r32, &myfile); + myfile << "33: Double_t \\ " << endl; + myfile << " "; + writeVectorToFile(r33, &myfile); + + myfile << "TX: Double_t \\ " << endl; + myfile << " "; + writeVectorToFile(tx, &myfile); + myfile << "TY: Double_t \\ " << endl; + myfile << " "; + writeVectorToFile(ty, &myfile); + myfile << "TZ: Double_t \\ " << endl; + myfile << " "; + writeVectorToFile(tz, &myfile); + + myfile << "##############################################################################" << endl; + + myfile.close(); + + /* // To check if the vector sorting works and one gets in the end the same // results as when using the map myfile.open ("test1.txt"); @@ -266,32 +261,30 @@ void run_tutorial4_createParameterFile() myfile.close(); */ - myfile.open ("misalignment.txt"); - for (auto& elem: misalignInfo) { - const Double_t* rotation = elem.second.second->GetRotationMatrix(); - const Double_t* translation = elem.second.second->GetTranslation(); - myfile << "Module " << elem.first << " " << elem.second.first << " " - << rotation[0] << " " << rotation[1] << " " << rotation[2] <<" " - << rotation[3] << " " << rotation[4] << " " << rotation[5] <<" " - << rotation[6] << " " << rotation[7] << " " << rotation[8] <<" " - << translation[0] << " " << translation[1] << " " << translation[2] <GetRotationMatrix(); + const Double_t* translation = elem.second.second->GetTranslation(); + myfile << "Module " << elem.first << " " << elem.second.first << " " << rotation[0] << " " << rotation[1] << " " + << rotation[2] << " " << rotation[3] << " " << rotation[4] << " " << rotation[5] << " " << rotation[6] + << " " << rotation[7] << " " << rotation[8] << " " << translation[0] << " " << translation[1] << " " + << translation[2] << endl; + } + myfile.close(); } void writeVectorToFile(std::vector& vec, ofstream* myfile) { - Int_t counter = 0; - for (auto& elem: vec) { - if ( (8 == counter) ) { - *myfile << elem <<" \\"<Uniform(-1.,1.); - Float_t shifty = gRandom->Uniform(-1.,1.); - Float_t shiftz = gRandom->Uniform(-1.,1.); - Float_t rotx = gRandom->Uniform(-1.,1.); - Float_t roty = gRandom->Uniform(-1.,1.); - Float_t rotz = gRandom->Uniform(-1.,1.); - - if (misalignX) ShiftX[iLayer] = shiftx; - if (misalignY) ShiftY[iLayer] = shifty; - if (misalignZ) ShiftZ[iLayer] = shiftz; - if (rotX) RotX[iLayer] = rotx; - if (rotY) RotY[iLayer] = roty; - if (rotZ) RotZ[iLayer] = rotz; - - } - - ofstream myfile; - myfile.open ("example.par"); - - myfile << "##############################################################################" << endl; - myfile << "# Class: FairTutorialDetMissallignPar" << endl; - myfile << "# Context: TestDefaultContext" << endl; - myfile << "##############################################################################" << endl; - myfile << "[FairTutorialDetMissallignPar]" << endl; - myfile << "//----------------------------------------------------------------------------" << endl; - myfile << "NrOfDetectors: Int_t "<< nrOfDetLayers << endl; - myfile << "ShiftX: Double_t \\ "<< endl; - - Int_t counter = 0; - - myfile <<" "; - for (Int_t iLayer = 0; iLayerUniform(-1., 1.); + Float_t shifty = gRandom->Uniform(-1., 1.); + Float_t shiftz = gRandom->Uniform(-1., 1.); + Float_t rotx = gRandom->Uniform(-1., 1.); + Float_t roty = gRandom->Uniform(-1., 1.); + Float_t rotz = gRandom->Uniform(-1., 1.); + + if (misalignX) + ShiftX[iLayer] = shiftx; + if (misalignY) + ShiftY[iLayer] = shifty; + if (misalignZ) + ShiftZ[iLayer] = shiftz; + if (rotX) + RotX[iLayer] = rotx; + if (rotY) + RotY[iLayer] = roty; + if (rotZ) + RotZ[iLayer] = rotz; } - } - myfile< // for FairTutorialDet4Hit::Class, etc +#include // for FairTutorialDet4Hit::Class, etc class TVector3; @@ -28,7 +28,7 @@ class FairTutorialDet4Hit : public FairHit FairTutorialDet4Hit(const FairTutorialDet4Hit&); FairTutorialDet4Hit operator=(const FairTutorialDet4Hit&); - ClassDef(FairTutorialDet4Hit,1); + ClassDef(FairTutorialDet4Hit, 1); }; #endif diff --git a/examples/simulation/Tutorial4/src/data/FairTutorialDet4Point.cxx b/examples/simulation/Tutorial4/src/data/FairTutorialDet4Point.cxx index bd8ef87021..52754a1a0c 100644 --- a/examples/simulation/Tutorial4/src/data/FairTutorialDet4Point.cxx +++ b/examples/simulation/Tutorial4/src/data/FairTutorialDet4Point.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "FairTutorialDet4Point.h" @@ -10,27 +10,27 @@ #include "FairLogger.h" FairTutorialDet4Point::FairTutorialDet4Point() - : FairMCPoint() -{ -} + : FairMCPoint() +{} -FairTutorialDet4Point::FairTutorialDet4Point(Int_t trackID, Int_t detID, - TVector3 pos, TVector3 mom, - Double_t tof, Double_t length, - Double_t eLoss) - : FairMCPoint(trackID, detID, pos, mom, tof, length, eLoss) -{ -} +FairTutorialDet4Point::FairTutorialDet4Point(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t tof, + Double_t length, + Double_t eLoss) + : FairMCPoint(trackID, detID, pos, mom, tof, length, eLoss) +{} void FairTutorialDet4Point::Print(const Option_t* /*opt*/) const { - LOG(info) << "-I- FairTutorialDet4Point: TutorialDet point for track " - << fTrackID - << " in detector " << fDetectorID; - LOG(info) << " Position (" << fX << ", " << fY << ", " << fZ << ") cm"; - LOG(info) << " Momentum (" << fPx << ", " << fPy << ", " << fPz << ") GeV"; - LOG(info) << " Time " << fTime << " ns, Length " << fLength - << " cm, Energy loss " << fELoss*1.0e06 << " keV"; + LOG(info) << "-I- FairTutorialDet4Point: TutorialDet point for track " << fTrackID << " in detector " + << fDetectorID; + LOG(info) << " Position (" << fX << ", " << fY << ", " << fZ << ") cm"; + LOG(info) << " Momentum (" << fPx << ", " << fPy << ", " << fPz << ") GeV"; + LOG(info) << " Time " << fTime << " ns, Length " << fLength << " cm, Energy loss " << fELoss * 1.0e06 + << " keV"; } -ClassImp(FairTutorialDet4Point) +ClassImp(FairTutorialDet4Point); diff --git a/examples/simulation/Tutorial4/src/data/FairTutorialDet4Point.h b/examples/simulation/Tutorial4/src/data/FairTutorialDet4Point.h index 9addcc576e..bf049d0284 100644 --- a/examples/simulation/Tutorial4/src/data/FairTutorialDet4Point.h +++ b/examples/simulation/Tutorial4/src/data/FairTutorialDet4Point.h @@ -1,17 +1,17 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRTUTORIALDET4POINT_H #define FAIRTUTORIALDET4POINT_H 1 -#include "FairMCPoint.h" // for FairMCPoint +#include "FairMCPoint.h" // for FairMCPoint -#include // for Double_t, etc -#include // for TVector3 +#include // for Double_t, etc +#include // for TVector3 class FairTutorialDet4Point : public FairMCPoint { @@ -28,8 +28,13 @@ class FairTutorialDet4Point : public FairMCPoint *@param length Track length since creation [cm] *@param eLoss Energy deposit [GeV] **/ - FairTutorialDet4Point(Int_t trackID, Int_t detID, TVector3 pos, TVector3 mom, - Double_t tof, Double_t length, Double_t eLoss); + FairTutorialDet4Point(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t tof, + Double_t length, + Double_t eLoss); /** Copy constructor **/ // FairTutorialDet4Point(const FairTutorialDet4Point& point) { *this = point; }; @@ -40,7 +45,7 @@ class FairTutorialDet4Point : public FairMCPoint /** Output to screen **/ virtual void Print(const Option_t* opt) const; - ClassDef(FairTutorialDet4Point,1) + ClassDef(FairTutorialDet4Point, 1) }; #endif diff --git a/examples/simulation/Tutorial4/src/display/FairTutorialDet4PointDraw.cxx b/examples/simulation/Tutorial4/src/display/FairTutorialDet4PointDraw.cxx index 85c7f98388..0158fa5649 100644 --- a/examples/simulation/Tutorial4/src/display/FairTutorialDet4PointDraw.cxx +++ b/examples/simulation/Tutorial4/src/display/FairTutorialDet4PointDraw.cxx @@ -5,124 +5,124 @@ #include "FairTutorialDet4PointDraw.h" +#include "FairEventManager.h" // for FairEventManager +#include "FairLogger.h" +#include "FairRootManager.h" // for FairRootManager +#include "FairRun.h" // for FairRunAna +#include "FairRuntimeDb.h" // for FairRuntimeDb +#include "FairTutorialDet4GeoHandler.h" #include "FairTutorialDet4GeoPar.h" #include "FairTutorialDet4Point.h" -#include "FairTutorialDet4GeoHandler.h" - -#include "FairEventManager.h" // for FairEventManager -#include "FairRootManager.h" // for FairRootManager -#include "FairRun.h" // for FairRunAna -#include "FairRuntimeDb.h" // for FairRuntimeDb -#include "FairLogger.h" -#include // for TClonesArray -#include // for TEveBoxSet, etc -#include // for TEveManager, gEve +#include // for TClonesArray +#include // for TEveManager, gEve +#include // for TEveBoxSet, etc FairTutorialDet4PointDraw::FairTutorialDet4PointDraw() - : FairTask("FairTutorialDet4PointDraw"), - fPointList(nullptr), - fGeoPar(nullptr), - fEventManager(nullptr), - fq(nullptr), - fColor(), - fStyle(), - fGlobalCoordinates(kTRUE), - fGeoHandler(new FairTutorialDet4GeoHandler) -{ -} + : FairTask("FairTutorialDet4PointDraw") + , fPointList(nullptr) + , fGeoPar(nullptr) + , fEventManager(nullptr) + , fq(nullptr) + , fColor() + , fStyle() + , fGlobalCoordinates(kTRUE) + , fGeoHandler(new FairTutorialDet4GeoHandler) +{} FairTutorialDet4PointDraw::FairTutorialDet4PointDraw(const char* name, Color_t color, Style_t mystyle) - : FairTask(name), - fPointList(nullptr), - fGeoPar(nullptr), - fEventManager(nullptr), - fq(nullptr), - fColor(color), - fStyle(mystyle), - fGlobalCoordinates(kTRUE), - fGeoHandler(new FairTutorialDet4GeoHandler) -{ -} + : FairTask(name) + , fPointList(nullptr) + , fGeoPar(nullptr) + , fEventManager(nullptr) + , fq(nullptr) + , fColor(color) + , fStyle(mystyle) + , fGlobalCoordinates(kTRUE) + , fGeoHandler(new FairTutorialDet4GeoHandler) +{} void FairTutorialDet4PointDraw::SetParContainers() { - // Get Base Container - FairRun* run = FairRun::Instance(); - FairRuntimeDb* rtdb=run->GetRuntimeDb(); + // Get Base Container + FairRun* run = FairRun::Instance(); + FairRuntimeDb* rtdb = run->GetRuntimeDb(); - fGeoPar = static_cast(rtdb->getContainer("FairTutorialDet4GeoPar")); + fGeoPar = static_cast(rtdb->getContainer("FairTutorialDet4GeoPar")); } InitStatus FairTutorialDet4PointDraw::Init() { - FairRootManager* fManager = FairRootManager::Instance(); - fPointList = static_cast(fManager->GetObject(GetName())); - if (nullptr==fPointList) { - LOG(error) << "FairTutorialDet4PointDraw::Init() branch " << GetName() << " not found! Task will be deactivated."; - return kERROR; - } - fEventManager = FairEventManager::Instance(); - fq = 0; - - fGlobalCoordinates = fGeoPar->IsGlobalCoordinateSystem(); - - return kSUCCESS; + FairRootManager* fManager = FairRootManager::Instance(); + fPointList = static_cast(fManager->GetObject(GetName())); + if (nullptr == fPointList) { + LOG(error) << "FairTutorialDet4PointDraw::Init() branch " << GetName() + << " not found! Task will be deactivated."; + return kERROR; + } + fEventManager = FairEventManager::Instance(); + fq = 0; + + fGlobalCoordinates = fGeoPar->IsGlobalCoordinateSystem(); + + return kSUCCESS; } void FairTutorialDet4PointDraw::Exec(Option_t* /*option*/) { - if (IsActive()) { - FairTutorialDet4Point *point=0; + if (IsActive()) { + FairTutorialDet4Point* point = 0; - Int_t npoints=fPointList->GetEntriesFast(); - Reset(); + Int_t npoints = fPointList->GetEntriesFast(); + Reset(); - TEvePointSet* q = new TEvePointSet(GetName(), npoints, TEvePointSelectorConsumer::kTVT_XYZ); - q->SetOwnIds(kTRUE); - q->SetMarkerColor(fColor); - q->SetMarkerSize(1.5); - q->SetMarkerStyle(fStyle); + TEvePointSet* q = new TEvePointSet(GetName(), npoints, TEvePointSelectorConsumer::kTVT_XYZ); + q->SetOwnIds(kTRUE); + q->SetMarkerColor(fColor); + q->SetMarkerSize(1.5); + q->SetMarkerStyle(fStyle); - // Int_t refCounter=0; + // Int_t refCounter=0; - for (Int_t i=0; i(fPointList->At(i)); + for (Int_t i = 0; i < npoints; ++i) { + point = static_cast(fPointList->At(i)); - if (!point) { continue; } + if (!point) { + continue; + } - // Detector ID - Int_t detID = point->GetDetectorID(); + // Detector ID + Int_t detID = point->GetDetectorID(); - // Determine hit position - Double_t x = point->GetX(); - Double_t y = point->GetY(); - Double_t z = point->GetZ(); + // Determine hit position + Double_t x = point->GetX(); + Double_t y = point->GetY(); + Double_t z = point->GetZ(); - if (!fGlobalCoordinates) { - Double_t local[3] = {x, y, z}; - Double_t global[3]; + if (!fGlobalCoordinates) { + Double_t local[3] = {x, y, z}; + Double_t global[3]; - fGeoHandler->LocalToGlobal(local, global, detID); + fGeoHandler->LocalToGlobal(local, global, detID); - x = global[0]; - y = global[1]; - z = global[2]; - } - q->SetNextPoint(x, y, z); - // q->SetPointId(GetValue(p, i)); - } + x = global[0]; + y = global[1]; + z = global[2]; + } + q->SetNextPoint(x, y, z); + // q->SetPointId(GetValue(p, i)); + } - gEve->AddElement(q); - gEve->Redraw3D(kFALSE); - fq = q; - } + gEve->AddElement(q); + gEve->Redraw3D(kFALSE); + fq = q; + } } void FairTutorialDet4PointDraw::Reset() { - if (fq) { - fq->Reset(); - gEve->RemoveElement(fq, fEventManager); - } + if (fq) { + fq->Reset(); + gEve->RemoveElement(fq, fEventManager); + } } diff --git a/examples/simulation/Tutorial4/src/display/FairTutorialDet4PointDraw.h b/examples/simulation/Tutorial4/src/display/FairTutorialDet4PointDraw.h index 21fb0f0857..4b42a3ff2e 100644 --- a/examples/simulation/Tutorial4/src/display/FairTutorialDet4PointDraw.h +++ b/examples/simulation/Tutorial4/src/display/FairTutorialDet4PointDraw.h @@ -14,8 +14,9 @@ #ifndef FAIRTUTORIALDET4POINTDRAW_H #define FAIRTUTORIALDET4POINTDRAW_H -#include "FairTask.h" // for FairTask, InitStatus -#include // for Bool_t, Int_t, etc +#include "FairTask.h" // for FairTask, InitStatus + +#include // for Bool_t, Int_t, etc class FairTutorialDet4GeoPar; class FairTutorialDet4DigiPar; @@ -32,9 +33,9 @@ class FairTutorialDet4PointDraw : public FairTask FairTutorialDet4PointDraw(); /** Standard constructor - *@param name Name of task - *@param iVerbose Verbosity level - **/ + *@param name Name of task + *@param iVerbose Verbosity level + **/ FairTutorialDet4PointDraw(const char* name, Color_t color, Style_t mstyle); /** Destructor **/ @@ -51,19 +52,19 @@ class FairTutorialDet4PointDraw : public FairTask virtual void Finish() {} private: - TClonesArray *fPointList; //! - FairTutorialDet4GeoPar *fGeoPar; //! - FairEventManager *fEventManager; //! - TEvePointSet* fq; //! - Color_t fColor; //! - Style_t fStyle; //! - Bool_t fGlobalCoordinates; //! - FairTutorialDet4GeoHandler* fGeoHandler; //! + TClonesArray* fPointList; //! + FairTutorialDet4GeoPar* fGeoPar; //! + FairEventManager* fEventManager; //! + TEvePointSet* fq; //! + Color_t fColor; //! + Style_t fStyle; //! + Bool_t fGlobalCoordinates; //! + FairTutorialDet4GeoHandler* fGeoHandler; //! FairTutorialDet4PointDraw(const FairTutorialDet4PointDraw&); FairTutorialDet4PointDraw& operator=(const FairTutorialDet4PointDraw&); - ClassDef(FairTutorialDet4PointDraw,1); + ClassDef(FairTutorialDet4PointDraw, 1); }; #endif diff --git a/examples/simulation/Tutorial4/src/mc/FairTutorialDet4.cxx b/examples/simulation/Tutorial4/src/mc/FairTutorialDet4.cxx index 0513e4bbd5..029f1937e1 100644 --- a/examples/simulation/Tutorial4/src/mc/FairTutorialDet4.cxx +++ b/examples/simulation/Tutorial4/src/mc/FairTutorialDet4.cxx @@ -7,249 +7,252 @@ ********************************************************************************/ #include "FairTutorialDet4.h" -#include "FairDetectorList.h" // for DetectorId::kTutDet -#include "FairLogger.h" // for FairLogger, etc -#include "FairRootManager.h" // for FairRootManager -#include "FairRun.h" // for FairRun -#include "FairRuntimeDb.h" // for FairRuntimeDb -#include "FairStack.h" // for FairStack -#include "FairTutorialDet4Geo.h" // for FairTutorialDet4Geo -#include "FairTutorialDet4GeoHandler.h" // for FairTutorialDet4GeoHandler -#include "FairTutorialDet4GeoPar.h" // for FairTutorialDet4GeoPar +#include "FairDetectorList.h" // for DetectorId::kTutDet +#include "FairLogger.h" // for FairLogger, etc +#include "FairModule.h" // for FairModule +#include "FairRootManager.h" // for FairRootManager +#include "FairRun.h" // for FairRun +#include "FairRuntimeDb.h" // for FairRuntimeDb +#include "FairStack.h" // for FairStack +#include "FairTutorialDet4Geo.h" // for FairTutorialDet4Geo +#include "FairTutorialDet4GeoHandler.h" // for FairTutorialDet4GeoHandler +#include "FairTutorialDet4GeoPar.h" // for FairTutorialDet4GeoPar #include "FairTutorialDet4MisalignPar.h" -#include "FairTutorialDet4Point.h" // for FairTutorialDet4Point -#include "FairModule.h" // for FairModule +#include "FairTutorialDet4Point.h" // for FairTutorialDet4Point -#include // for TGeoHMatrix, TGeoCombiTrans, etc +#include // for TGeoHMatrix, TGeoCombiTrans, etc +#include // for TString, operator<<, Form +#include // for TVirtualMC +#include // for TVirtualMCStack -#include // for TString, operator<<, Form -#include // for TVirtualMC -#include // for TVirtualMCStack - -FairTutorialDet4Geo* FairTutorialDet4::fgGeo; //! +FairTutorialDet4Geo* FairTutorialDet4::fgGeo; //! FairTutorialDet4::FairTutorialDet4() - : FairDetector("TutorialDet", kTRUE, kTutDet), - fTrackID(-1), - fVolumeID(-1), - fPos(), - fMom(), - fTime(-1.), - fLength(-1.), - fELoss(-1), - fFairTutorialDet4PointCollection(new TClonesArray("FairTutorialDet4Point")), - fGeoHandler(new FairTutorialDet4GeoHandler()), - fMisalignPar(nullptr), - fNrOfDetectors(-1), - fShiftX(), - fShiftY(), - fShiftZ(), - fRotX(), - fRotY(), - fRotZ(), - fModifyGeometry(kFALSE), - fGlobalCoordinates(kFALSE) -{ -} + : FairDetector("TutorialDet", kTRUE, kTutDet) + , fTrackID(-1) + , fVolumeID(-1) + , fPos() + , fMom() + , fTime(-1.) + , fLength(-1.) + , fELoss(-1) + , fFairTutorialDet4PointCollection(new TClonesArray("FairTutorialDet4Point")) + , fGeoHandler(new FairTutorialDet4GeoHandler()) + , fMisalignPar(nullptr) + , fNrOfDetectors(-1) + , fShiftX() + , fShiftY() + , fShiftZ() + , fRotX() + , fRotY() + , fRotZ() + , fModifyGeometry(kFALSE) + , fGlobalCoordinates(kFALSE) +{} FairTutorialDet4::FairTutorialDet4(const char* name, Bool_t active) - : FairDetector(name, active, kTutDet), - fTrackID(-1), - fVolumeID(-1), - fPos(), - fMom(), - fTime(-1.), - fLength(-1.), - fELoss(-1), - fFairTutorialDet4PointCollection(new TClonesArray("FairTutorialDet4Point")), - fGeoHandler(new FairTutorialDet4GeoHandler()), - fMisalignPar(nullptr), - fNrOfDetectors(-1), - fShiftX(), - fShiftY(), - fShiftZ(), - fRotX(), - fRotY(), - fRotZ(), - fModifyGeometry(kFALSE), - fGlobalCoordinates(kFALSE) -{ -} + : FairDetector(name, active, kTutDet) + , fTrackID(-1) + , fVolumeID(-1) + , fPos() + , fMom() + , fTime(-1.) + , fLength(-1.) + , fELoss(-1) + , fFairTutorialDet4PointCollection(new TClonesArray("FairTutorialDet4Point")) + , fGeoHandler(new FairTutorialDet4GeoHandler()) + , fMisalignPar(nullptr) + , fNrOfDetectors(-1) + , fShiftX() + , fShiftY() + , fShiftZ() + , fRotX() + , fRotY() + , fRotZ() + , fModifyGeometry(kFALSE) + , fGlobalCoordinates(kFALSE) +{} FairTutorialDet4::FairTutorialDet4(const FairTutorialDet4& rhs) - : FairDetector(rhs), - fTrackID(-1), - fVolumeID(-1), - fPos(), - fMom(), - fTime(-1.), - fLength(-1.), - fELoss(-1), - fFairTutorialDet4PointCollection(new TClonesArray("FairTutorialDet4Point")), - fGeoHandler(new FairTutorialDet4GeoHandler()), - fMisalignPar(nullptr), - fNrOfDetectors(-1), - fShiftX(), - fShiftY(), - fShiftZ(), - fRotX(), - fRotY(), - fRotZ(), - fModifyGeometry(kFALSE), - fGlobalCoordinates(kFALSE) -{ -} + : FairDetector(rhs) + , fTrackID(-1) + , fVolumeID(-1) + , fPos() + , fMom() + , fTime(-1.) + , fLength(-1.) + , fELoss(-1) + , fFairTutorialDet4PointCollection(new TClonesArray("FairTutorialDet4Point")) + , fGeoHandler(new FairTutorialDet4GeoHandler()) + , fMisalignPar(nullptr) + , fNrOfDetectors(-1) + , fShiftX() + , fShiftY() + , fShiftZ() + , fRotX() + , fRotY() + , fRotZ() + , fModifyGeometry(kFALSE) + , fGlobalCoordinates(kFALSE) +{} FairTutorialDet4::~FairTutorialDet4() { - LOG(debug4)<<"Entering Destructor of FairTutorialDet4"; - if (fFairTutorialDet4PointCollection) { - fFairTutorialDet4PointCollection->Delete(); - delete fFairTutorialDet4PointCollection; - } - LOG(debug4)<<"Leaving Destructor of FairTutorialDet4"; + LOG(debug4) << "Entering Destructor of FairTutorialDet4"; + if (fFairTutorialDet4PointCollection) { + fFairTutorialDet4PointCollection->Delete(); + delete fFairTutorialDet4PointCollection; + } + LOG(debug4) << "Leaving Destructor of FairTutorialDet4"; } void FairTutorialDet4::SetParContainers() { - LOG(info)<< "Set tutdet missallign parameters"; - // Get Base Container - FairRun* sim = FairRun::Instance(); - LOG_IF (FATAL, !sim) << "No run object"; - FairRuntimeDb* rtdb=sim->GetRuntimeDb(); - LOG_IF (FATAL, !rtdb) << "No runtime database"; + LOG(info) << "Set tutdet missallign parameters"; + // Get Base Container + FairRun* sim = FairRun::Instance(); + LOG_IF(FATAL, !sim) << "No run object"; + FairRuntimeDb* rtdb = sim->GetRuntimeDb(); + LOG_IF(FATAL, !rtdb) << "No runtime database"; - fMisalignPar = static_cast(rtdb->getContainer("FairTutorialDet4MissallignPar")); + fMisalignPar = static_cast(rtdb->getContainer("FairTutorialDet4MissallignPar")); } void FairTutorialDet4::Initialize() { - FairDetector::Initialize(); - FairRuntimeDb* rtdb= FairRun::Instance()->GetRuntimeDb(); - FairTutorialDet4GeoPar* par=static_cast(rtdb->getContainer("FairTutorialDet4GeoPar")); - - if (fModifyGeometry) { - if (fGlobalCoordinates) { - LOG(warn) << "Storing MCPoints in global coordinates and modifying the geometry was set."; - LOG(warn) << "When modifying the geometry is set the MCPoints has to be stored in local coordinates."; - LOG(warn) << "Store MCPoints in local coordinate system."; - fGlobalCoordinates=kFALSE; + FairDetector::Initialize(); + FairRuntimeDb* rtdb = FairRun::Instance()->GetRuntimeDb(); + FairTutorialDet4GeoPar* par = static_cast(rtdb->getContainer("FairTutorialDet4GeoPar")); + + if (fModifyGeometry) { + if (fGlobalCoordinates) { + LOG(warn) << "Storing MCPoints in global coordinates and modifying the geometry was set."; + LOG(warn) << "When modifying the geometry is set the MCPoints has to be stored in local coordinates."; + LOG(warn) << "Store MCPoints in local coordinate system."; + fGlobalCoordinates = kFALSE; + } } - } - par->SetGlobalCoordinates(fGlobalCoordinates); - par->setChanged(); - par->setInputVersion(FairRun::Instance()->GetRunId(),1); + par->SetGlobalCoordinates(fGlobalCoordinates); + par->setChanged(); + par->setInputVersion(FairRun::Instance()->GetRunId(), 1); - Bool_t isSimulation = kTRUE; - fGeoHandler->Init(isSimulation); + Bool_t isSimulation = kTRUE; + fGeoHandler->Init(isSimulation); } void FairTutorialDet4::InitParContainers() { - LOG(info)<< "Initialize tutdet missallign parameters"; - fNrOfDetectors=fMisalignPar->GetNrOfDetectors(); - fShiftX=fMisalignPar->GetShiftX(); - fShiftY=fMisalignPar->GetShiftY(); - fShiftZ=fMisalignPar->GetShiftZ(); - fRotX=fMisalignPar->GetRotX(); - fRotY=fMisalignPar->GetRotY(); - fRotZ=fMisalignPar->GetRotZ(); + LOG(info) << "Initialize tutdet missallign parameters"; + fNrOfDetectors = fMisalignPar->GetNrOfDetectors(); + fShiftX = fMisalignPar->GetShiftX(); + fShiftY = fMisalignPar->GetShiftY(); + fShiftZ = fMisalignPar->GetShiftZ(); + fRotX = fMisalignPar->GetRotX(); + fRotY = fMisalignPar->GetRotY(); + fRotZ = fMisalignPar->GetRotZ(); } -Bool_t FairTutorialDet4::ProcessHits(FairVolume* /*vol*/) +Bool_t FairTutorialDet4::ProcessHits(FairVolume* /*vol*/) { - /** This method is called from the MC stepping */ - - //Set parameters at entrance of volume. Reset ELoss. - if (TVirtualMC::GetMC()->IsTrackEntering()) { - fELoss = 0.; - fTime = TVirtualMC::GetMC()->TrackTime() * 1.0e09; - fLength = TVirtualMC::GetMC()->TrackLength(); - TVirtualMC::GetMC()->TrackPosition(fPos); - TVirtualMC::GetMC()->TrackMomentum(fMom); - } - - // Sum energy loss for all steps in the active volume - fELoss += TVirtualMC::GetMC()->Edep(); - - // Create FairTutorialDet4Point at exit of active volume - if (TVirtualMC::GetMC()->IsTrackExiting() || - TVirtualMC::GetMC()->IsTrackStop() || - TVirtualMC::GetMC()->IsTrackDisappeared() ) { - fTrackID = TVirtualMC::GetMC()->GetStack()->GetCurrentTrackNumber(); - // fVolumeID = vol->getMCid(); - fVolumeID = fGeoHandler->GetUniqueDetectorId(); - if (fELoss == 0.) { return kFALSE; } - - if (!fGlobalCoordinates) { - // Save positions in local coordinate system, so transform the - // global coordinates into local ones. - Double_t master[3] = {fPos.X(), fPos.Y(), fPos.Z()}; - Double_t local[3]; - - TVirtualMC::GetMC()->Gmtod(master, local, 1); - AddHit(fTrackID, fVolumeID, TVector3(local[0], local[1], local[2]), - TVector3(fMom.Px(), fMom.Py(), fMom.Pz()), fTime, fLength, fELoss); - } else { - AddHit(fTrackID, fVolumeID, TVector3(fPos.X(), fPos.Y(), fPos.Z()), - TVector3(fMom.Px(), fMom.Py(), fMom.Pz()), fTime, fLength, fELoss); + /** This method is called from the MC stepping */ + + // Set parameters at entrance of volume. Reset ELoss. + if (TVirtualMC::GetMC()->IsTrackEntering()) { + fELoss = 0.; + fTime = TVirtualMC::GetMC()->TrackTime() * 1.0e09; + fLength = TVirtualMC::GetMC()->TrackLength(); + TVirtualMC::GetMC()->TrackPosition(fPos); + TVirtualMC::GetMC()->TrackMomentum(fMom); } - // Increment number of tutorial det points in TParticle - FairStack* stack = static_cast(TVirtualMC::GetMC()->GetStack()); - stack->AddPoint(kTutDet); - } + // Sum energy loss for all steps in the active volume + fELoss += TVirtualMC::GetMC()->Edep(); + + // Create FairTutorialDet4Point at exit of active volume + if (TVirtualMC::GetMC()->IsTrackExiting() || TVirtualMC::GetMC()->IsTrackStop() + || TVirtualMC::GetMC()->IsTrackDisappeared()) { + fTrackID = TVirtualMC::GetMC()->GetStack()->GetCurrentTrackNumber(); + // fVolumeID = vol->getMCid(); + fVolumeID = fGeoHandler->GetUniqueDetectorId(); + if (fELoss == 0.) { + return kFALSE; + } + + if (!fGlobalCoordinates) { + // Save positions in local coordinate system, so transform the + // global coordinates into local ones. + Double_t master[3] = {fPos.X(), fPos.Y(), fPos.Z()}; + Double_t local[3]; + + TVirtualMC::GetMC()->Gmtod(master, local, 1); + AddHit(fTrackID, + fVolumeID, + TVector3(local[0], local[1], local[2]), + TVector3(fMom.Px(), fMom.Py(), fMom.Pz()), + fTime, + fLength, + fELoss); + } else { + AddHit(fTrackID, + fVolumeID, + TVector3(fPos.X(), fPos.Y(), fPos.Z()), + TVector3(fMom.Px(), fMom.Py(), fMom.Pz()), + fTime, + fLength, + fELoss); + } + + // Increment number of tutorial det points in TParticle + FairStack* stack = static_cast(TVirtualMC::GetMC()->GetStack()); + stack->AddPoint(kTutDet); + } - return kTRUE; + return kTRUE; } -void FairTutorialDet4::EndOfEvent() -{ - fFairTutorialDet4PointCollection->Clear(); -} +void FairTutorialDet4::EndOfEvent() { fFairTutorialDet4PointCollection->Clear(); } void FairTutorialDet4::Register() { - /** This will create a branch in the output tree called + /** This will create a branch in the output tree called FairTutorialDet4Point, 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("TutorialDetPoint", "TutorialDet", - fFairTutorialDet4PointCollection, kTRUE); + FairRootManager::Instance()->Register("TutorialDetPoint", "TutorialDet", fFairTutorialDet4PointCollection, kTRUE); } TClonesArray* FairTutorialDet4::GetCollection(Int_t iColl) const { - if (iColl == 0) { return fFairTutorialDet4PointCollection; } - else { return nullptr; } + if (iColl == 0) { + return fFairTutorialDet4PointCollection; + } else { + return nullptr; + } } -void FairTutorialDet4::Reset() -{ - fFairTutorialDet4PointCollection->Clear(); -} +void FairTutorialDet4::Reset() { fFairTutorialDet4PointCollection->Clear(); } void FairTutorialDet4::ConstructGeometry() { - TString fileName=GetGeometryFileName(); - if (fileName.EndsWith(".geo")) { - LOG(info)<<"Constructing Tutorial4 geometry from ASCII file "< FairTutorialDet4::getMisalignmentMatrices() { - TString volPath; - TString volStr = "/cave_1/tutorial4_0/tut4_det_"; + TString volPath; + TString volStr = "/cave_1/tutorial4_0/tut4_det_"; - std::map matrices; + std::map matrices; - for (Int_t iDet = 0; iDet < fNrOfDetectors; ++iDet) { - LOG(debug)<<"Create Matrix for detector nr "< matrices; - LOG(info) << fNrOfDetectors << " misalignment matrices created!"; + for (Int_t iDet = 0; iDet < fNrOfDetectors; ++iDet) { + LOG(debug) << "Create Matrix for detector nr " << iDet; + volPath = volStr; + volPath += iDet; - return matrices; -} + LOG(debug) << "Path: " << volPath; -void FairTutorialDet4::RegisterAlignmentMatrices() -{ - if (fModifyGeometry) { - TString volPath; - TString volStr = "/cave_1/tutorial4_0/tut4_det_"; + // we have to express the displacements as regards the old local RS (non misaligned BTOF) + Double_t dx = fShiftX[iDet]; + Double_t dy = fShiftY[iDet]; + Double_t dz = fShiftZ[iDet]; + Double_t dphi = fRotX[iDet]; + Double_t dtheta = fRotY[iDet]; + Double_t dpsi = fRotZ[iDet]; - std::map matrices; + TGeoRotation* rrot = new TGeoRotation("rot", dphi, dtheta, dpsi); + TGeoCombiTrans localdelta = *(new TGeoCombiTrans(dx, dy, dz, rrot)); + TGeoHMatrix ldm = TGeoHMatrix(localdelta); - for (Int_t iDet = 0; iDet < fNrOfDetectors; ++iDet) { - LOG(debug)<<"Create Matrix for detector nr "<AddAlignmentMatrices(matrices); - } + FairRun* run = FairRun::Instance(); + run->AddAlignmentMatrices(matrices); + } } -FairTutorialDet4Point* FairTutorialDet4::AddHit(Int_t trackID, Int_t detID, - TVector3 pos, TVector3 mom, - Double_t time, Double_t length, - Double_t eLoss) +FairTutorialDet4Point* FairTutorialDet4::AddHit(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t time, + Double_t length, + Double_t eLoss) { - TClonesArray& clref = *fFairTutorialDet4PointCollection; - Int_t size = clref.GetEntriesFast(); - return new(clref[size]) FairTutorialDet4Point(trackID, detID, pos, mom, time, length, eLoss); + TClonesArray& clref = *fFairTutorialDet4PointCollection; + Int_t size = clref.GetEntriesFast(); + return new (clref[size]) FairTutorialDet4Point(trackID, detID, pos, mom, time, length, eLoss); } -FairModule* FairTutorialDet4::CloneModule() const -{ - return new FairTutorialDet4(*this); -} +FairModule* FairTutorialDet4::CloneModule() const { return new FairTutorialDet4(*this); } -ClassImp(FairTutorialDet4) +ClassImp(FairTutorialDet4); diff --git a/examples/simulation/Tutorial4/src/mc/FairTutorialDet4.h b/examples/simulation/Tutorial4/src/mc/FairTutorialDet4.h index e9180205ab..74889c59a5 100644 --- a/examples/simulation/Tutorial4/src/mc/FairTutorialDet4.h +++ b/examples/simulation/Tutorial4/src/mc/FairTutorialDet4.h @@ -8,16 +8,15 @@ #ifndef FAIRTUTORIALDET4_H #define FAIRTUTORIALDET4_H -#include "FairDetector.h" // for FairDetector +#include "FairDetector.h" // for FairDetector -#include // for Int_t, Bool_t, Double32_t, etc -#include // for TArrayD -#include // for TLorentzVector -#include // for TVector3 +#include // for Int_t, Bool_t, Double32_t, etc +#include // for TArrayD #include - -#include +#include // for TLorentzVector +#include // for TVector3 #include +#include class FairTutorialDet4Point; class FairTutorialDet4GeoHandler; @@ -33,7 +32,7 @@ class FairTutorialDet4 : public FairDetector /** Name : Detector Name * Active: kTRUE for active detectors (ProcessHits() will be called) * kFALSE for inactive detectors - */ + */ FairTutorialDet4(const char* Name, Bool_t Active); /** default constructor */ @@ -43,24 +42,24 @@ class FairTutorialDet4 : public FairDetector virtual ~FairTutorialDet4(); /** Initialization of the detector is done here */ - virtual void Initialize(); + virtual void Initialize(); /** Init parameter containers */ - virtual void InitParContainers(); + virtual void InitParContainers(); /** 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(); @@ -69,15 +68,13 @@ class FairTutorialDet4 : public FairDetector /** This method is an example of how to add your own point * of type FairTutorialDet4Point to the clones array - */ - FairTutorialDet4Point* AddHit(Int_t trackID, Int_t detID, - TVector3 pos, TVector3 mom, - Double_t time, Double_t length, - Double_t eLoss); + */ + FairTutorialDet4Point* + AddHit(Int_t trackID, Int_t detID, TVector3 pos, TVector3 mom, Double_t time, Double_t length, Double_t eLoss); /** 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() {} @@ -89,8 +86,8 @@ class FairTutorialDet4 : public FairDetector virtual void PreTrack() {} virtual void BeginEvent() {} - void SetModifyGeometry(Bool_t val) { fModifyGeometry=val; } - void SetGlobalCoordinates(Bool_t val) { fGlobalCoordinates=val; } + void SetModifyGeometry(Bool_t val) { fModifyGeometry = val; } + void SetGlobalCoordinates(Bool_t val) { fGlobalCoordinates = val; } virtual FairModule* CloneModule() const; @@ -106,17 +103,17 @@ class FairTutorialDet4 : public FairDetector /** 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* fFairTutorialDet4PointCollection; + TClonesArray* fFairTutorialDet4PointCollection; FairTutorialDet4GeoHandler* fGeoHandler; @@ -141,7 +138,7 @@ class FairTutorialDet4 : public FairDetector FairTutorialDet4(const FairTutorialDet4&); FairTutorialDet4& operator=(const FairTutorialDet4&); - ClassDef(FairTutorialDet4,3) + ClassDef(FairTutorialDet4, 3) }; -#endif //FAIRTUTORIALDET_H +#endif // FAIRTUTORIALDET_H diff --git a/examples/simulation/Tutorial4/src/mc/FairTutorialDet4Geo.cxx b/examples/simulation/Tutorial4/src/mc/FairTutorialDet4Geo.cxx index f5702a1487..8bdc391502 100644 --- a/examples/simulation/Tutorial4/src/mc/FairTutorialDet4Geo.cxx +++ b/examples/simulation/Tutorial4/src/mc/FairTutorialDet4Geo.cxx @@ -1,39 +1,39 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "FairTutorialDet4Geo.h" -#include // for sprintf +#include // for sprintf -ClassImp(FairTutorialDet4Geo) +ClassImp(FairTutorialDet4Geo); FairTutorialDet4Geo::FairTutorialDet4Geo() - : FairGeoSet() + : FairGeoSet() { - // Constructor - fName="tutdet"; - maxSectors=0; - maxModules=100; + // Constructor + fName = "tutdet"; + maxSectors = 0; + maxModules = 100; } const char* FairTutorialDet4Geo::getModuleName(Int_t m) { - /** Returns the module name of TutorialDet number m + /** Returns the module name of TutorialDet number m Setting MyDet here means that all modules names in the ASCII file should start with TutorialDet otherwise they will not be constructed */ - sprintf(modName,"tutdet%i",m+1); - return modName; + sprintf(modName, "tutdet%i", m + 1); + return modName; } const char* FairTutorialDet4Geo::getEleName(Int_t m) { - /** Returns the element name of Det number m */ - sprintf(eleName,"tutdet%i",m+1); - return eleName; + /** Returns the element name of Det number m */ + sprintf(eleName, "tutdet%i", m + 1); + return eleName; } diff --git a/examples/simulation/Tutorial4/src/mc/FairTutorialDet4Geo.h b/examples/simulation/Tutorial4/src/mc/FairTutorialDet4Geo.h index 867a6c102b..a35645bc8e 100644 --- a/examples/simulation/Tutorial4/src/mc/FairTutorialDet4Geo.h +++ b/examples/simulation/Tutorial4/src/mc/FairTutorialDet4Geo.h @@ -1,23 +1,23 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRTUTORIALDET4GEO_H #define FAIRTUTORIALDET4GEO_H -#include "FairGeoSet.h" // for FairGeoSet +#include "FairGeoSet.h" // for FairGeoSet -#include // for Int_t, etc -#include // for TString +#include // for Int_t, etc +#include // for TString class FairTutorialDet4Geo : public FairGeoSet { protected: - char modName[20]; // name of module - char eleName[20]; // substring for elements in module + char modName[20]; // name of module + char eleName[20]; // substring for elements in module public: FairTutorialDet4Geo(); @@ -25,17 +25,17 @@ class FairTutorialDet4Geo : public FairGeoSet const char* getModuleName(Int_t); const char* getEleName(Int_t); inline Int_t getModNumInMod(const TString&); - ClassDef(FairTutorialDet4Geo,1) + ClassDef(FairTutorialDet4Geo, 1) }; inline Int_t FairTutorialDet4Geo::getModNumInMod(const TString& name) { - /** returns the module index from module name + /** returns the module index from module name ?? in name[??] has to be the length of the detector name in the .geo file. For example if all nodes in this file starts with tutdet ?? has to be 6. */ - return static_cast((name[6]-'0')-1); // + return static_cast((name[6] - '0') - 1); // } -#endif /* FAIRTUTORIALDETGEO_H */ +#endif /* FAIRTUTORIALDETGEO_H */ diff --git a/examples/simulation/Tutorial4/src/param/FairTutorialDet4ContFact.cxx b/examples/simulation/Tutorial4/src/param/FairTutorialDet4ContFact.cxx index 1a9e60234b..18accb5c9c 100644 --- a/examples/simulation/Tutorial4/src/param/FairTutorialDet4ContFact.cxx +++ b/examples/simulation/Tutorial4/src/param/FairTutorialDet4ContFact.cxx @@ -1,73 +1,70 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "FairTutorialDet4ContFact.h" -#include "FairRuntimeDb.h" // for FairRuntimeDb -#include "FairTutorialDet4GeoPar.h" // for FairTutorialDet4GeoPar +#include "FairRuntimeDb.h" // for FairRuntimeDb +#include "FairTutorialDet4GeoPar.h" // for FairTutorialDet4GeoPar #include "FairTutorialDet4MisalignPar.h" -#include // for TList -#include // for TString - -#include // for strcmp +#include // for TList +#include // for TString +#include // for strcmp class FairParSet; -ClassImp(FairTutorialDet4ContFact) +ClassImp(FairTutorialDet4ContFact); static FairTutorialDet4ContFact gFairTutorialDet4ContFact; FairTutorialDet4ContFact::FairTutorialDet4ContFact() - : FairContFact() + : FairContFact() { - /** Constructor (called when the library is loaded) */ - fName="FairTutorialDet4ContFact"; - fTitle="Factory for parameter containers in libTutorial1"; - setAllContainers(); - FairRuntimeDb::instance()->addContFactory(this); + /** Constructor (called when the library is loaded) */ + fName = "FairTutorialDet4ContFact"; + fTitle = "Factory for parameter containers in libTutorial1"; + setAllContainers(); + FairRuntimeDb::instance()->addContFactory(this); } void FairTutorialDet4ContFact::setAllContainers() { - /** Creates the Container objects with all accepted + /** Creates the Container objects with all accepted contexts and adds them to the list of containers for the Tutorial1 library. */ - FairContainer* p= new FairContainer("FairTutorialDet4GeoPar", - "FairTutorialDet4 Geometry Parameters", - "TestDefaultContext"); - p->addContext("TestNonDefaultContext"); + FairContainer* p = + new FairContainer("FairTutorialDet4GeoPar", "FairTutorialDet4 Geometry Parameters", "TestDefaultContext"); + p->addContext("TestNonDefaultContext"); - containers->Add(p); + containers->Add(p); - FairContainer* p1= new FairContainer("FairTutorialDet4MissallignPar", - "FairTutorialDet4 Missallignment Parameters", - "TestDefaultContext"); - p1->addContext("TestNonDefaultContext"); + FairContainer* p1 = new FairContainer( + "FairTutorialDet4MissallignPar", "FairTutorialDet4 Missallignment Parameters", "TestDefaultContext"); + p1->addContext("TestNonDefaultContext"); - containers->Add(p1); + containers->Add(p1); } FairParSet* FairTutorialDet4ContFact::createContainer(FairContainer* c) { - /** Calls the constructor of the corresponding parameter container. + /** 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 = nullptr; - if (strcmp(name,"FairTutorialDet4GeoPar")==0) { - p = new FairTutorialDet4GeoPar(c->getConcatName().Data(), c->GetTitle(),c->getContext()); - } - if (strcmp(name,"FairTutorialDet4MissallignPar")==0) { - p = new FairTutorialDet4MisalignPar(c->getConcatName().Data(), c->GetTitle(),c->getContext()); - } - return p; + const char* name = c->GetName(); + FairParSet* p = nullptr; + if (strcmp(name, "FairTutorialDet4GeoPar") == 0) { + p = new FairTutorialDet4GeoPar(c->getConcatName().Data(), c->GetTitle(), c->getContext()); + } + if (strcmp(name, "FairTutorialDet4MissallignPar") == 0) { + p = new FairTutorialDet4MisalignPar(c->getConcatName().Data(), c->GetTitle(), c->getContext()); + } + return p; } diff --git a/examples/simulation/Tutorial4/src/param/FairTutorialDet4ContFact.h b/examples/simulation/Tutorial4/src/param/FairTutorialDet4ContFact.h index 6eb04dfedd..ab5f3b819c 100644 --- a/examples/simulation/Tutorial4/src/param/FairTutorialDet4ContFact.h +++ b/examples/simulation/Tutorial4/src/param/FairTutorialDet4ContFact.h @@ -1,16 +1,16 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRTUTORIALDET4CONTFACT_H #define FAIRTUTORIALDET4CONTFACT_H -#include "FairContFact.h" // for FairContFact, etc +#include "FairContFact.h" // for FairContFact, etc -#include // for ClassDef +#include // for ClassDef class FairParSet; @@ -23,7 +23,7 @@ class FairTutorialDet4ContFact : public FairContFact FairTutorialDet4ContFact(); ~FairTutorialDet4ContFact() {} FairParSet* createContainer(FairContainer*); - ClassDef( FairTutorialDet4ContFact,0) // Factory for all MyDet parameter containers + ClassDef(FairTutorialDet4ContFact, 0) // Factory for all MyDet parameter containers }; -#endif /* !FAIRTUTORIALDETCONTFACT_H */ +#endif /* !FAIRTUTORIALDETCONTFACT_H */ diff --git a/examples/simulation/Tutorial4/src/param/FairTutorialDet4GeoPar.cxx b/examples/simulation/Tutorial4/src/param/FairTutorialDet4GeoPar.cxx index 1227cec733..c6669a862e 100644 --- a/examples/simulation/Tutorial4/src/param/FairTutorialDet4GeoPar.cxx +++ b/examples/simulation/Tutorial4/src/param/FairTutorialDet4GeoPar.cxx @@ -7,39 +7,48 @@ ********************************************************************************/ #include "FairTutorialDet4GeoPar.h" -#include "FairParamList.h" // for FairParamList +#include "FairParamList.h" // for FairParamList -#include // for TObjArray +#include // for TObjArray -ClassImp(FairTutorialDet4GeoPar) +ClassImp(FairTutorialDet4GeoPar); FairTutorialDet4GeoPar ::FairTutorialDet4GeoPar(const char* name, const char* title, const char* context) -: FairParGenericSet(name,title,context), - fGeoSensNodes(new TObjArray()), - fGeoPassNodes(new TObjArray()), - fGlobalCoordinates(kFALSE) -{ -} + : FairParGenericSet(name, title, context) + , fGeoSensNodes(new TObjArray()) + , fGeoPassNodes(new TObjArray()) + , fGlobalCoordinates(kFALSE) +{} void FairTutorialDet4GeoPar::clear(void) { - delete fGeoSensNodes; - delete fGeoPassNodes; + delete fGeoSensNodes; + delete fGeoPassNodes; } void FairTutorialDet4GeoPar::putParams(FairParamList* l) { - if (!l) { return; } - l->addObject("FairGeoNodes Sensitive List", fGeoSensNodes); - l->addObject("FairGeoNodes Passive List", fGeoPassNodes); - l->add("GlobalCoordinates", fGlobalCoordinates); + if (!l) { + return; + } + l->addObject("FairGeoNodes Sensitive List", fGeoSensNodes); + l->addObject("FairGeoNodes Passive List", fGeoPassNodes); + l->add("GlobalCoordinates", fGlobalCoordinates); } Bool_t FairTutorialDet4GeoPar::getParams(FairParamList* l) { - if (!l) { return kFALSE; } - if (!l->fillObject("FairGeoNodes Sensitive List", fGeoSensNodes)) { return kFALSE; } - if (!l->fillObject("FairGeoNodes Passive List", fGeoPassNodes)) { return kFALSE; } - if (!l->fill("GlobalCoordinates", &fGlobalCoordinates) ) { return kFALSE; } - return kTRUE; + if (!l) { + return kFALSE; + } + if (!l->fillObject("FairGeoNodes Sensitive List", fGeoSensNodes)) { + return kFALSE; + } + if (!l->fillObject("FairGeoNodes Passive List", fGeoPassNodes)) { + return kFALSE; + } + if (!l->fill("GlobalCoordinates", &fGlobalCoordinates)) { + return kFALSE; + } + return kTRUE; } diff --git a/examples/simulation/Tutorial4/src/param/FairTutorialDet4GeoPar.h b/examples/simulation/Tutorial4/src/param/FairTutorialDet4GeoPar.h index 310b2a0e8d..bdcc1932bf 100644 --- a/examples/simulation/Tutorial4/src/param/FairTutorialDet4GeoPar.h +++ b/examples/simulation/Tutorial4/src/param/FairTutorialDet4GeoPar.h @@ -8,9 +8,9 @@ #ifndef FAIRTUTORIALDET4GEOPAR_H #define FAIRTUTORIALDET4GEOPAR_H -#include "FairParGenericSet.h" // for FairParGenericSet +#include "FairParGenericSet.h" // for FairParGenericSet -#include // for ClassDef +#include // for ClassDef class TObjArray; class FairParamList; @@ -18,34 +18,32 @@ class FairParamList; class FairTutorialDet4GeoPar : public FairParGenericSet { public: - FairTutorialDet4GeoPar(const char* name="FairTutorialDet4GeoPar", - const char* title="FairTutorialDet4 Geometry Parameters", - const char* context="TestDefaultContext"); + FairTutorialDet4GeoPar(const char* name = "FairTutorialDet4GeoPar", + const char* title = "FairTutorialDet4 Geometry Parameters", + const char* context = "TestDefaultContext"); ~FairTutorialDet4GeoPar(void) {} void clear(void); void putParams(FairParamList*); Bool_t getParams(FairParamList*); - TObjArray* GetGeoSensitiveNodes() {return fGeoSensNodes;} - TObjArray* GetGeoPassiveNodes() {return fGeoPassNodes;} - Bool_t IsGlobalCoordinateSystem() {return fGlobalCoordinates;} - void SetGlobalCoordinates(Bool_t globalCoordinates) { - fGlobalCoordinates = globalCoordinates; - } + TObjArray* GetGeoSensitiveNodes() { return fGeoSensNodes; } + TObjArray* GetGeoPassiveNodes() { return fGeoPassNodes; } + Bool_t IsGlobalCoordinateSystem() { return fGlobalCoordinates; } + void SetGlobalCoordinates(Bool_t globalCoordinates) { fGlobalCoordinates = globalCoordinates; } private: /** List of FairGeoNodes for sensitive volumes */ - TObjArray* fGeoSensNodes; + TObjArray* fGeoSensNodes; /** List of FairGeoNodes for sensitive volumes */ - TObjArray* fGeoPassNodes; + TObjArray* fGeoPassNodes; - Bool_t fGlobalCoordinates; + Bool_t fGlobalCoordinates; FairTutorialDet4GeoPar(const FairTutorialDet4GeoPar&); FairTutorialDet4GeoPar& operator=(const FairTutorialDet4GeoPar&); - ClassDef(FairTutorialDet4GeoPar,2) + ClassDef(FairTutorialDet4GeoPar, 2) }; #endif /* FAIRTUTORIALDETGEOPAR_H */ diff --git a/examples/simulation/Tutorial4/src/param/FairTutorialDet4MisalignPar.cxx b/examples/simulation/Tutorial4/src/param/FairTutorialDet4MisalignPar.cxx index 9a85acc3a1..f278f0bcf8 100644 --- a/examples/simulation/Tutorial4/src/param/FairTutorialDet4MisalignPar.cxx +++ b/examples/simulation/Tutorial4/src/param/FairTutorialDet4MisalignPar.cxx @@ -1,75 +1,85 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "FairTutorialDet4MisalignPar.h" #include "FairParamList.h" -ClassImp(FairTutorialDet4MisalignPar) - -FairTutorialDet4MisalignPar ::FairTutorialDet4MisalignPar(const char* name, - const char* title, - const char* context) - : FairParGenericSet(name,title,context), - fShiftX(), - fShiftY(), - fShiftZ(), - fRotX(), - fRotY(), - fRotZ(), - fNrOfDetectors(0) -{ -} +ClassImp(FairTutorialDet4MisalignPar); -FairTutorialDet4MisalignPar::~FairTutorialDet4MisalignPar(void) -{ -} +FairTutorialDet4MisalignPar ::FairTutorialDet4MisalignPar(const char* name, const char* title, const char* context) + : FairParGenericSet(name, title, context) + , fShiftX() + , fShiftY() + , fShiftZ() + , fRotX() + , fRotY() + , fRotZ() + , fNrOfDetectors(0) +{} -void FairTutorialDet4MisalignPar::clear(void) -{ -} +FairTutorialDet4MisalignPar::~FairTutorialDet4MisalignPar(void) {} + +void FairTutorialDet4MisalignPar::clear(void) {} void FairTutorialDet4MisalignPar::putParams(FairParamList* l) { - if (!l) { return; } - - l->add("NrOfDetectors", fNrOfDetectors); - l->add("ShiftX", fShiftX); - l->add("ShiftY", fShiftY); - l->add("ShiftZ", fShiftZ); - l->add("RotationX", fRotX); - l->add("RotationY", fRotY); - l->add("RotationZ", fRotZ); - + if (!l) { + return; + } + + l->add("NrOfDetectors", fNrOfDetectors); + l->add("ShiftX", fShiftX); + l->add("ShiftY", fShiftY); + l->add("ShiftZ", fShiftZ); + l->add("RotationX", fRotX); + l->add("RotationY", fRotY); + l->add("RotationZ", fRotZ); } Bool_t FairTutorialDet4MisalignPar::getParams(FairParamList* l) { - if (!l) { return kFALSE; } - - if ( ! l->fill("NrOfDetectors", &fNrOfDetectors) ) { return kFALSE; } - - fShiftX.Set(fNrOfDetectors); - if ( ! l->fill("ShiftX", &fShiftX )) { return kFALSE; } - - fShiftY.Set(fNrOfDetectors); - if ( ! l->fill("ShiftY", &fShiftY )) { return kFALSE; } - - fShiftZ.Set(fNrOfDetectors); - if ( ! l->fill("ShiftZ", &fShiftZ )) { return kFALSE; } - - fRotX.Set(fNrOfDetectors); - if ( ! l->fill("RotationX", &fRotX )) { return kFALSE; } - - fRotY.Set(fNrOfDetectors); - if ( ! l->fill("RotationY", &fRotY )) { return kFALSE; } - - fRotZ.Set(fNrOfDetectors); - if ( ! l->fill("RotationZ", &fRotZ )) { return kFALSE; } - - return kTRUE; + if (!l) { + return kFALSE; + } + + if (!l->fill("NrOfDetectors", &fNrOfDetectors)) { + return kFALSE; + } + + fShiftX.Set(fNrOfDetectors); + if (!l->fill("ShiftX", &fShiftX)) { + return kFALSE; + } + + fShiftY.Set(fNrOfDetectors); + if (!l->fill("ShiftY", &fShiftY)) { + return kFALSE; + } + + fShiftZ.Set(fNrOfDetectors); + if (!l->fill("ShiftZ", &fShiftZ)) { + return kFALSE; + } + + fRotX.Set(fNrOfDetectors); + if (!l->fill("RotationX", &fRotX)) { + return kFALSE; + } + + fRotY.Set(fNrOfDetectors); + if (!l->fill("RotationY", &fRotY)) { + return kFALSE; + } + + fRotZ.Set(fNrOfDetectors); + if (!l->fill("RotationZ", &fRotZ)) { + return kFALSE; + } + + return kTRUE; } diff --git a/examples/simulation/Tutorial4/src/param/FairTutorialDet4MisalignPar.h b/examples/simulation/Tutorial4/src/param/FairTutorialDet4MisalignPar.h index 035239b1e6..161cdc3c11 100644 --- a/examples/simulation/Tutorial4/src/param/FairTutorialDet4MisalignPar.h +++ b/examples/simulation/Tutorial4/src/param/FairTutorialDet4MisalignPar.h @@ -1,52 +1,53 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRTUTORIALDET4MISSALLIGNPAR_H #define FAIRTUTORIALDET4MISSALLIGNPAR_H -#include "FairParGenericSet.h" // for FairParGenericSet +#include "FairParGenericSet.h" // for FairParGenericSet -#include // for ClassDef -#include // for TArrayD +#include // for ClassDef +#include // for TArrayD class FairParamList; class FairTutorialDet4MisalignPar : public FairParGenericSet { public: - FairTutorialDet4MisalignPar(const char* name="FairTutorialDet4MissallignPar", - const char* title="Missalignment parameter for FairTutorialDet4HitProducerIdealMissallign Parameters", - const char* context="TestDefaultContext"); + FairTutorialDet4MisalignPar( + const char* name = "FairTutorialDet4MissallignPar", + const char* title = "Missalignment parameter for FairTutorialDet4HitProducerIdealMissallign Parameters", + const char* context = "TestDefaultContext"); ~FairTutorialDet4MisalignPar(void); void clear(void); void putParams(FairParamList*); Bool_t getParams(FairParamList*); - TArrayD GetShiftX() {return fShiftX;} - TArrayD GetShiftY() {return fShiftY;} - TArrayD GetShiftZ() {return fShiftZ;} - TArrayD GetRotX() {return fRotX;} - TArrayD GetRotY() {return fRotY;} - TArrayD GetRotZ() {return fRotZ;} - Int_t GetNrOfDetectors() {return fNrOfDetectors;} + TArrayD GetShiftX() { return fShiftX; } + TArrayD GetShiftY() { return fShiftY; } + TArrayD GetShiftZ() { return fShiftZ; } + TArrayD GetRotX() { return fRotX; } + TArrayD GetRotY() { return fRotY; } + TArrayD GetRotZ() { return fRotZ; } + Int_t GetNrOfDetectors() { return fNrOfDetectors; } private: - TArrayD fShiftX; // Array to hold the misalignment in x-direction - TArrayD fShiftY; // Array to hold the misalignment in y-direction - TArrayD fShiftZ; // Array to hold the misalignment in z-direction - TArrayD fRotX; // Array to hold the rotation in x-direction - TArrayD fRotY; // Array to hold the rotation in y-direction - TArrayD fRotZ; // Array to hold the rotation in z-direction - Int_t fNrOfDetectors; // Total number of detectors + TArrayD fShiftX; // Array to hold the misalignment in x-direction + TArrayD fShiftY; // Array to hold the misalignment in y-direction + TArrayD fShiftZ; // Array to hold the misalignment in z-direction + TArrayD fRotX; // Array to hold the rotation in x-direction + TArrayD fRotY; // Array to hold the rotation in y-direction + TArrayD fRotZ; // Array to hold the rotation in z-direction + Int_t fNrOfDetectors; // Total number of detectors FairTutorialDet4MisalignPar(const FairTutorialDet4MisalignPar&); FairTutorialDet4MisalignPar& operator=(const FairTutorialDet4MisalignPar&); - ClassDef(FairTutorialDet4MisalignPar,1) + ClassDef(FairTutorialDet4MisalignPar, 1) }; #endif diff --git a/examples/simulation/Tutorial4/src/reco/FairTutorialDet4HitProducerIdealMisalign.cxx b/examples/simulation/Tutorial4/src/reco/FairTutorialDet4HitProducerIdealMisalign.cxx index fcad37d593..5c040bae19 100644 --- a/examples/simulation/Tutorial4/src/reco/FairTutorialDet4HitProducerIdealMisalign.cxx +++ b/examples/simulation/Tutorial4/src/reco/FairTutorialDet4HitProducerIdealMisalign.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -11,104 +11,102 @@ // ------------------------------------------------------------------------- #include "FairTutorialDet4HitProducerIdealMisalign.h" -#include "FairLogger.h" // for FairLogger, etc -#include "FairRootManager.h" // for FairRootManager -#include "FairRunAna.h" // for FairRunAna -#include "FairRuntimeDb.h" // for FairRuntimeDb -#include "FairTutorialDet4GeoHandler.h" // for FairTutorialDet4GeoHandler -#include "FairTutorialDet4Hit.h" // for FairTutorialDet4Hit -#include "FairTutorialDet4MisalignPar.h" +#include "FairLogger.h" // for FairLogger, etc +#include "FairRootManager.h" // for FairRootManager +#include "FairRunAna.h" // for FairRunAna +#include "FairRuntimeDb.h" // for FairRuntimeDb +#include "FairTutorialDet4GeoHandler.h" // for FairTutorialDet4GeoHandler #include "FairTutorialDet4GeoPar.h" -#include "FairTutorialDet4Point.h" // for FairTutorialDet4Point +#include "FairTutorialDet4Hit.h" // for FairTutorialDet4Hit +#include "FairTutorialDet4MisalignPar.h" +#include "FairTutorialDet4Point.h" // for FairTutorialDet4Point -#include // for TClonesArray -#include // for Cos, Sin -#include // for Abs -#include // for TRandom, gRandom -#include // for TVector3 +#include // for TClonesArray +#include // for Cos, Sin +#include // for Abs +#include // for TRandom, gRandom +#include // for TVector3 FairTutorialDet4HitProducerIdealMisalign::FairTutorialDet4HitProducerIdealMisalign() - : FairTask("Missallign Hit Producer for the TutorialDet"), - fPointArray(nullptr), - fHitArray(nullptr), - fShiftX(), - fShiftY(), - fShiftZ(), - fRotX(), - fRotY(), - fRotZ(), - fDigiPar(nullptr), - fGeoHandler(new FairTutorialDet4GeoHandler), - fGeoPar(nullptr), - fDoMisalignment(kFALSE) -{ -} + : FairTask("Missallign Hit Producer for the TutorialDet") + , fPointArray(nullptr) + , fHitArray(nullptr) + , fShiftX() + , fShiftY() + , fShiftZ() + , fRotX() + , fRotY() + , fRotZ() + , fDigiPar(nullptr) + , fGeoHandler(new FairTutorialDet4GeoHandler) + , fGeoPar(nullptr) + , fDoMisalignment(kFALSE) +{} void FairTutorialDet4HitProducerIdealMisalign::SetParContainers() { - LOG(info)<< "Set tutdet missallign parameters"; - // Get Base Container - FairRunAna* ana = FairRunAna::Instance(); - FairRuntimeDb* rtdb=ana->GetRuntimeDb(); + LOG(info) << "Set tutdet missallign parameters"; + // Get Base Container + FairRunAna* ana = FairRunAna::Instance(); + FairRuntimeDb* rtdb = ana->GetRuntimeDb(); - fDigiPar = static_cast(rtdb->getContainer("FairTutorialDet4MissallignPar")); - fGeoPar = static_cast(rtdb->getContainer("FairTutorialDet4GeoPar")); + fDigiPar = static_cast(rtdb->getContainer("FairTutorialDet4MissallignPar")); + fGeoPar = static_cast(rtdb->getContainer("FairTutorialDet4GeoPar")); } InitStatus FairTutorialDet4HitProducerIdealMisalign::ReInit() { - // Get Base Container - FairRunAna* ana = FairRunAna::Instance(); - FairRuntimeDb* rtdb=ana->GetRuntimeDb(); + // Get Base Container + FairRunAna* ana = FairRunAna::Instance(); + FairRuntimeDb* rtdb = ana->GetRuntimeDb(); - fDigiPar = static_cast - (rtdb->getContainer("FairTutorialDet4MissallignPar")); + fDigiPar = static_cast(rtdb->getContainer("FairTutorialDet4MissallignPar")); - fShiftX=fDigiPar->GetShiftX(); - fShiftY=fDigiPar->GetShiftY(); - fShiftZ=fDigiPar->GetShiftZ(); - fRotX=fDigiPar->GetRotX(); - fRotY=fDigiPar->GetRotY(); - fRotZ=fDigiPar->GetRotZ(); + fShiftX = fDigiPar->GetShiftX(); + fShiftY = fDigiPar->GetShiftY(); + fShiftZ = fDigiPar->GetShiftZ(); + fRotX = fDigiPar->GetRotX(); + fRotY = fDigiPar->GetRotY(); + fRotZ = fDigiPar->GetRotZ(); - return kSUCCESS; + return kSUCCESS; } InitStatus FairTutorialDet4HitProducerIdealMisalign::Init() { - // Get RootManager - FairRootManager* ioman = FairRootManager::Instance(); - if (!ioman) { - LOG(fatal) << "RootManager not instantised!"; - return kFATAL; - } - - // Get input array - fPointArray = static_cast(ioman->GetObject("TutorialDetPoint")); - if (!fPointArray) { - LOG(fatal)<<"No TutorialDetPoint array!"; - return kFATAL; - } - - // Create and register output array - fHitArray = new TClonesArray("FairTutorialDet4Hit"); - ioman->Register("TutorialDetHit", "TutorialDet", fHitArray, kTRUE); - - LOG(info)<< "HitProducerIdealMissallign: Initialisation successfull"; - - fShiftX=fDigiPar->GetShiftX(); - fShiftY=fDigiPar->GetShiftY(); - fShiftZ=fDigiPar->GetShiftZ(); - fRotX=fDigiPar->GetRotX(); - fRotY=fDigiPar->GetRotY(); - fRotZ=fDigiPar->GetRotZ(); - - Bool_t isGlobalCoordinateSystem=fGeoPar->IsGlobalCoordinateSystem(); - if (isGlobalCoordinateSystem) { - LOG(fatal) << "Task can only work with local coordinates."; - } - /* + // Get RootManager + FairRootManager* ioman = FairRootManager::Instance(); + if (!ioman) { + LOG(fatal) << "RootManager not instantised!"; + return kFATAL; + } + + // Get input array + fPointArray = static_cast(ioman->GetObject("TutorialDetPoint")); + if (!fPointArray) { + LOG(fatal) << "No TutorialDetPoint array!"; + return kFATAL; + } + + // Create and register output array + fHitArray = new TClonesArray("FairTutorialDet4Hit"); + ioman->Register("TutorialDetHit", "TutorialDet", fHitArray, kTRUE); + + LOG(info) << "HitProducerIdealMissallign: Initialisation successfull"; + + fShiftX = fDigiPar->GetShiftX(); + fShiftY = fDigiPar->GetShiftY(); + fShiftZ = fDigiPar->GetShiftZ(); + fRotX = fDigiPar->GetRotX(); + fRotY = fDigiPar->GetRotY(); + fRotZ = fDigiPar->GetRotZ(); + + Bool_t isGlobalCoordinateSystem = fGeoPar->IsGlobalCoordinateSystem(); + if (isGlobalCoordinateSystem) { + LOG(fatal) << "Task can only work with local coordinates."; + } + /* Int_t num = fDigiPar->GetNrOfDetectors(); Int_t size = fShiftX.GetSize(); LOG(info)<<"Array has a size of "<< size << "elements"; @@ -116,102 +114,102 @@ InitStatus FairTutorialDet4HitProducerIdealMisalign::Init() LOG(info)<< i <<": "<Clear(); - - // Declare some variables - FairTutorialDet4Point* point = nullptr; - Int_t detID = 0; // Detector ID - // Int_t trackID = 0; // Track index - Double_t x, y, z; // Position - Double_t dx = 0.1; // Position error - // Double_t tof = 0.; // Time of flight - TVector3 pos, dpos; // Position and error vectors - - // Loop over TofPoints - Int_t nHits = 0; - Int_t nPoints = fPointArray->GetEntriesFast(); - for (Int_t iPoint=0; iPoint(fPointArray->At(iPoint)); - if (!point) { continue; } - - // Detector ID - detID = point->GetDetectorID(); - - // MCTrack ID - // trackID = point->GetTrackID(); - - if (fDoMisalignment) { - - Float_t cosAlpha = TMath::Cos(fRotZ.At(detID)); - Float_t sinAlpha = TMath::Sin(fRotZ.At(detID)); - - // Determine hit position - x = (point->GetX()*cosAlpha + point->GetY()*sinAlpha)-fShiftX.At(detID); - y = (-point->GetX()*sinAlpha + point->GetY()*cosAlpha)-fShiftY.At(detID); - z = point->GetZ(); - - LOG(debug)<<"Pos before misalignment: "<< point->GetX() <<", " - << point->GetY() <<", "<< point->GetZ(); - LOG(debug)<<"Pos after misalignment: "<< x <<", " - << y <<", "<< z; - - x = x + GetHitErr(0.1); - y = y + GetHitErr(0.1); - - LOG(debug2)<<"Missallign hit by "<GetTime(); - - // Create new hit - pos.SetXYZ(x,y,z); - dpos.SetXYZ(dx, dx, 0.); - new ((*fHitArray)[nHits]) FairTutorialDet4Hit(detID, iPoint, pos, dpos); - nHits++; - } else { - // Determine hit position - x = point->GetX(); - y = point->GetY(); - z = point->GetZ(); - - LOG(info)<<"Position: "<LocalToGlobal(local, global, detID); - - x = global[0] + GetHitErr(0.1); - y = global[1] + GetHitErr(0.1); - z = global[2]; - - LOG(info)<<"Position: "<GetTime(); - - // Create new hit - pos.SetXYZ(x,y,z); - dpos.SetXYZ(dx, dx, 0.); - new ((*fHitArray)[nHits]) FairTutorialDet4Hit(detID, iPoint, pos, dpos); - nHits++; + fHitArray->Clear(); + + // Declare some variables + FairTutorialDet4Point* point = nullptr; + Int_t detID = 0; // Detector ID + // Int_t trackID = 0; // Track index + Double_t x, y, z; // Position + Double_t dx = 0.1; // Position error + // Double_t tof = 0.; // Time of flight + TVector3 pos, dpos; // Position and error vectors + + // Loop over TofPoints + Int_t nHits = 0; + Int_t nPoints = fPointArray->GetEntriesFast(); + for (Int_t iPoint = 0; iPoint < nPoints; iPoint++) { + point = static_cast(fPointArray->At(iPoint)); + if (!point) { + continue; + } + + // Detector ID + detID = point->GetDetectorID(); + + // MCTrack ID + // trackID = point->GetTrackID(); + + if (fDoMisalignment) { + + Float_t cosAlpha = TMath::Cos(fRotZ.At(detID)); + Float_t sinAlpha = TMath::Sin(fRotZ.At(detID)); + + // Determine hit position + x = (point->GetX() * cosAlpha + point->GetY() * sinAlpha) - fShiftX.At(detID); + y = (-point->GetX() * sinAlpha + point->GetY() * cosAlpha) - fShiftY.At(detID); + z = point->GetZ(); + + LOG(debug) << "Pos before misalignment: " << point->GetX() << ", " << point->GetY() << ", " + << point->GetZ(); + LOG(debug) << "Pos after misalignment: " << x << ", " << y << ", " << z; + + x = x + GetHitErr(0.1); + y = y + GetHitErr(0.1); + + LOG(debug2) << "Missallign hit by " << fShiftX.At(detID) << " cm in x- and " << fShiftY.At(detID) + << " cm in y-direction."; + + // Time of flight + // tof = point->GetTime(); + + // Create new hit + pos.SetXYZ(x, y, z); + dpos.SetXYZ(dx, dx, 0.); + new ((*fHitArray)[nHits]) FairTutorialDet4Hit(detID, iPoint, pos, dpos); + nHits++; + } else { + // Determine hit position + x = point->GetX(); + y = point->GetY(); + z = point->GetZ(); + + LOG(info) << "Position: " << x << ", " << y << ", " << z; + + Double_t local[3] = {x, y, z}; + Double_t global[3]; + + fGeoHandler->LocalToGlobal(local, global, detID); + + x = global[0] + GetHitErr(0.1); + y = global[1] + GetHitErr(0.1); + z = global[2]; + + LOG(info) << "Position: " << x << ", " << y << ", " << z; + LOG(info) << "****"; + // Time of flight + // tof = point->GetTime(); + + // Create new hit + pos.SetXYZ(x, y, z); + dpos.SetXYZ(dx, dx, 0.); + new ((*fHitArray)[nHits]) FairTutorialDet4Hit(detID, iPoint, pos, dpos); + nHits++; + } } - } - // Event summary - LOG(debug) << "Create " << nHits << " TutorialDetHits out of " << nPoints << " TutorilaDetPoints created."; + // Event summary + LOG(debug) << "Create " << nHits << " TutorialDetHits out of " << nPoints << " TutorilaDetPoints created."; } Double_t FairTutorialDet4HitProducerIdealMisalign::GetHitErr(Double_t sigma) { - Double_t err = gRandom->Gaus(0, sigma); - return (TMath::Abs(err) < 3 * sigma) ? err : (err > 0) ? 3 * sigma : -3 * sigma; + Double_t err = gRandom->Gaus(0, sigma); + return (TMath::Abs(err) < 3 * sigma) ? err : (err > 0) ? 3 * sigma : -3 * sigma; } -ClassImp(FairTutorialDet4HitProducerIdealMisalign) +ClassImp(FairTutorialDet4HitProducerIdealMisalign); diff --git a/examples/simulation/Tutorial4/src/reco/FairTutorialDet4HitProducerIdealMisalign.h b/examples/simulation/Tutorial4/src/reco/FairTutorialDet4HitProducerIdealMisalign.h index e88a0aa55d..48a01636ec 100644 --- a/examples/simulation/Tutorial4/src/reco/FairTutorialDet4HitProducerIdealMisalign.h +++ b/examples/simulation/Tutorial4/src/reco/FairTutorialDet4HitProducerIdealMisalign.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -10,7 +10,6 @@ // ----- Created 11.02.13 by F. Uhlig ----- // ------------------------------------------------------------------------- - /** FairTutorialDet4HitProducerIdealMissallign.h *@author Florian Uhlig ** @@ -22,14 +21,13 @@ ** The position error is set to 1 mm. **/ - #ifndef FAIRTUTORIALDET4HITPRODUCERIDEALMISSALLIGN_H #define FAIRTUTORIALDET4HITPRODUCERIDEALMISSALLIGN_H 1 -#include "FairTask.h" // for InitStatus, FairTask +#include "FairTask.h" // for InitStatus, FairTask -#include // for Bool_t, Double_t, etc -#include // for TArrayD +#include // for Bool_t, Double_t, etc +#include // for TArrayD class FairTutorialDet4MisalignPar; class FairTutorialDet4GeoPar; @@ -56,14 +54,14 @@ class FairTutorialDet4HitProducerIdealMisalign : public FairTask /** Virtual method Exec **/ virtual void Exec(Option_t* opt); - void DoMisalignment(Bool_t val) {fDoMisalignment=val;} + void DoMisalignment(Bool_t val) { fDoMisalignment = val; } private: /** Input array of CbmTofPoints **/ - TClonesArray* fPointArray; //! + TClonesArray* fPointArray; //! /** Output array of CbmTofHits **/ - TClonesArray* fHitArray; //! + TClonesArray* fHitArray; //! TArrayD fShiftX; TArrayD fShiftY; @@ -84,8 +82,7 @@ class FairTutorialDet4HitProducerIdealMisalign : public FairTask FairTutorialDet4HitProducerIdealMisalign(const FairTutorialDet4HitProducerIdealMisalign&); FairTutorialDet4HitProducerIdealMisalign& operator=(const FairTutorialDet4HitProducerIdealMisalign&); - ClassDef(FairTutorialDet4HitProducerIdealMisalign,1); - + ClassDef(FairTutorialDet4HitProducerIdealMisalign, 1); }; #endif diff --git a/examples/simulation/Tutorial4/src/reco/FairTutorialDet4MilleWriter.cxx b/examples/simulation/Tutorial4/src/reco/FairTutorialDet4MilleWriter.cxx index dc6ba2e5f7..df10f77da4 100644 --- a/examples/simulation/Tutorial4/src/reco/FairTutorialDet4MilleWriter.cxx +++ b/examples/simulation/Tutorial4/src/reco/FairTutorialDet4MilleWriter.cxx @@ -1,45 +1,43 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "FairTutorialDet4MilleWriter.h" -#include "FairLogger.h" // for FairLogger, etc -#include "FairRootManager.h" // for FairRootManager -#include "FairTrackParam.h" // for FairTrackParam -#include "FairTutorialDet4Hit.h" // for FairTutorialDet4Hit +#include "FairLogger.h" // for FairLogger, etc +#include "FairRootManager.h" // for FairRootManager +#include "FairTrackParam.h" // for FairTrackParam +#include "FairTutorialDet4Hit.h" // for FairTutorialDet4Hit +#include "Mille.h" // for Mille -#include "Mille.h" // for Mille - -#include // for TClonesArray - -#include // for set, set<>::iterator, etc +#include // for TClonesArray +#include // for set, set<>::iterator, etc FairTutorialDet4MilleWriter::FairTutorialDet4MilleWriter() - :FairTask("FairTutorialDet4MilleWriter"), - fTracks(), - fHits(), - fMille(nullptr), - fWriteAscii(kFALSE), - fVersion(1), - fFileName("mp2tst") + : FairTask("FairTutorialDet4MilleWriter") + , fTracks() + , fHits() + , fMille(nullptr) + , fWriteAscii(kFALSE) + , fVersion(1) + , fFileName("mp2tst") { - LOG(debug) << "Default Constructor of FairTutorialDet4MilleWriter"; + LOG(debug) << "Default Constructor of FairTutorialDet4MilleWriter"; } FairTutorialDet4MilleWriter::~FairTutorialDet4MilleWriter() { - LOG(debug) << "Destructor of FairTutorialDet4MilleWriter"; + LOG(debug) << "Destructor of FairTutorialDet4MilleWriter"; } void FairTutorialDet4MilleWriter::SetParContainers() { - LOG(debug) << "SetParContainers of FairTutorialDet4MilleWriter"; - // Load all necessary parameter containers from the runtime data base - /* + LOG(debug) << "SetParContainers of FairTutorialDet4MilleWriter"; + // Load all necessary parameter containers from the runtime data base + /* FairRunAna* ana = FairRunAna::Instance(); FairRuntimeDb* rtdb=ana->GetRuntimeDb(); @@ -50,234 +48,231 @@ void FairTutorialDet4MilleWriter::SetParContainers() InitStatus FairTutorialDet4MilleWriter::Init() { - LOG(debug) << "Initilization of FairTutorialDet4MilleWriter"; - - // Get a handle from the IO manager - FairRootManager* ioman = FairRootManager::Instance(); - - // Get a pointer to the previous already existing data level - fTracks = static_cast(ioman->GetObject("TutorialDetTrack")); - if (!fTracks) { - LOG(error) << "No InputDataLevelName array!\n FairTutorialDet4MilleWriter will be inactive"; - return kERROR; - } - - // Get a pointer to the previous already existing data level - fHits = static_cast(ioman->GetObject("TutorialDetHit")); - if (!fHits) { - LOG(error) << "No InputDataLevelName array!\n FairTutorialDet4MilleWriter will be inactive"; - return kERROR; - } - - //Open MillePede Output file - if (fWriteAscii) { - fFileName += ".ascii"; - fMille = new Mille(fFileName, false, true); // write human readable ascii file - } else { - fFileName += ".bin"; - fMille = new Mille(fFileName, true, false); // write binary file needed by pede - } - - return kSUCCESS; + LOG(debug) << "Initilization of FairTutorialDet4MilleWriter"; + + // Get a handle from the IO manager + FairRootManager* ioman = FairRootManager::Instance(); + + // Get a pointer to the previous already existing data level + fTracks = static_cast(ioman->GetObject("TutorialDetTrack")); + if (!fTracks) { + LOG(error) << "No InputDataLevelName array!\n FairTutorialDet4MilleWriter will be inactive"; + return kERROR; + } + + // Get a pointer to the previous already existing data level + fHits = static_cast(ioman->GetObject("TutorialDetHit")); + if (!fHits) { + LOG(error) << "No InputDataLevelName array!\n FairTutorialDet4MilleWriter will be inactive"; + return kERROR; + } + + // Open MillePede Output file + if (fWriteAscii) { + fFileName += ".ascii"; + fMille = new Mille(fFileName, false, true); // write human readable ascii file + } else { + fFileName += ".bin"; + fMille = new Mille(fFileName, true, false); // write binary file needed by pede + } + + return kSUCCESS; } InitStatus FairTutorialDet4MilleWriter::ReInit() { - LOG(debug) << "Initilization of FairTutorialDet4MilleWriter"; - return kSUCCESS; + LOG(debug) << "Initilization of FairTutorialDet4MilleWriter"; + return kSUCCESS; } void FairTutorialDet4MilleWriter::Exec(Option_t* /*option*/) { - if (IsGoodEvent()) { - if (1 == fVersion) { StraightLineShiftX(); } - if (2 == fVersion) { StraightLineShiftXY(); } - } + if (IsGoodEvent()) { + if (1 == fVersion) { + StraightLineShiftX(); + } + if (2 == fVersion) { + StraightLineShiftXY(); + } + } } Bool_t FairTutorialDet4MilleWriter::IsGoodEvent() { - // Check if each for the event there is maximum 1 hit per detector - // station. In the moment we create tracks with all hits in the - // event, so we have to check for this. - // In the end the algorithm should be able to work also with - // missing hits in some stations - FairTutorialDet4Hit* hit; - std::set detIdSet; - std::set::iterator it; - - Int_t nHits = fHits->GetEntriesFast(); - for (Int_t iHit=0; iHit(fHits->At(iHit)); - Int_t detId = hit->GetDetectorID(); - it = detIdSet.find(detId); - if (it == detIdSet.end()) { - detIdSet.insert(detId); - } else { - // find hit in already used detector station - // this is not a good event - return kFALSE; + // Check if each for the event there is maximum 1 hit per detector + // station. In the moment we create tracks with all hits in the + // event, so we have to check for this. + // In the end the algorithm should be able to work also with + // missing hits in some stations + FairTutorialDet4Hit* hit; + std::set detIdSet; + std::set::iterator it; + + Int_t nHits = fHits->GetEntriesFast(); + for (Int_t iHit = 0; iHit < nHits; ++iHit) { + hit = static_cast(fHits->At(iHit)); + Int_t detId = hit->GetDetectorID(); + it = detIdSet.find(detId); + if (it == detIdSet.end()) { + detIdSet.insert(detId); + } else { + // find hit in already used detector station + // this is not a good event + return kFALSE; + } } - } - return kTRUE; + return kTRUE; } void FairTutorialDet4MilleWriter::StraightLineShiftX() { - const Int_t nLC = 2; // number of local parameters - // two for track x-coordinate - // x(z) = a1*z + a2 - // dx(z)/da1 = z - // dx(z)/da2 = 1 + const Int_t nLC = 2; // number of local parameters + // two for track x-coordinate + // x(z) = a1*z + a2 + // dx(z)/da1 = z + // dx(z)/da2 = 1 - const Int_t nGL = 1; // number of global parameters per point - // taken from millepede 1 dim example + const Int_t nGL = 1; // number of global parameters per point + // taken from millepede 1 dim example - Float_t sigma = 0.1; + Float_t sigma = 0.1; - Float_t* derLC = new Float_t[nLC]; // array of derivatives for local parameters - Float_t* derGL = new Float_t[nGL]; // array of derivatives for global parameters + Float_t* derLC = new Float_t[nLC]; // array of derivatives for local parameters + Float_t* derGL = new Float_t[nGL]; // array of derivatives for global parameters - Int_t* label = new Int_t[nGL]; // array of labels + Int_t* label = new Int_t[nGL]; // array of labels - for (Int_t help = 0; help < nGL; help++) { - derGL[help] = 0; - } - - for (Int_t help = 0; help < nLC; help++) { - derLC[help] = 0; - } + for (Int_t help = 0; help < nGL; help++) { + derGL[help] = 0; + } - FairTrackParam* track = static_cast(fTracks->At(0)); + for (Int_t help = 0; help < nLC; help++) { + derLC[help] = 0; + } - //Extract Track parameters - Double_t OffX = track->GetX(); - Double_t SlopeX = track->GetTx(); + FairTrackParam* track = static_cast(fTracks->At(0)); - Double_t residual; + // Extract Track parameters + Double_t OffX = track->GetX(); + Double_t SlopeX = track->GetTx(); - FairTutorialDet4Hit* hit; + Double_t residual; - Int_t nHits = fHits->GetEntriesFast(); - for (Int_t iHit=0; iHit(fHits->At(iHit)); + FairTutorialDet4Hit* hit; - Float_t Z = hit->GetZ(); - Float_t hitX = hit->GetX(); - Float_t fitX = OffX + SlopeX * Z; - LOG(debug)<<"hitX, fitX: "<< hitX<<" ,"<GetEntriesFast(); + for (Int_t iHit = 0; iHit < nHits; ++iHit) { + hit = static_cast(fHits->At(iHit)); - label[0] = iHit+1; + Float_t Z = hit->GetZ(); + Float_t hitX = hit->GetX(); + Float_t fitX = OffX + SlopeX * Z; + LOG(debug) << "hitX, fitX: " << hitX << " ," << fitX; - derGL[0] = -1; + label[0] = iHit + 1; - derLC[0] = 1; - derLC[1] = Z; + derGL[0] = -1; - residual = fitX - hitX; - LOG(debug)<<"ResidualX: "<< residual; - //call to Mille Writer - fMille->mille(nLC,derLC,nGL,derGL,label,residual,sigma); + derLC[0] = 1; + derLC[1] = Z; - } - fMille->end(); + residual = fitX - hitX; + LOG(debug) << "ResidualX: " << residual; + // call to Mille Writer + fMille->mille(nLC, derLC, nGL, derGL, label, residual, sigma); + } + fMille->end(); - delete[] derLC; - delete[] derGL; - delete[] label; + delete[] derLC; + delete[] derGL; + delete[] label; } void FairTutorialDet4MilleWriter::StraightLineShiftXY() { - const Int_t nLC = 4; // number of local parameters - // two for track x-coordinate - // x(z) = a1*z + a2 - // dx(z)/da1 = z - // dx(z)/da2 = 1 - - - const Int_t nGL = 2; // number of global parameters per point - // taken from millepede 1 dim example + const Int_t nLC = 4; // number of local parameters + // two for track x-coordinate + // x(z) = a1*z + a2 + // dx(z)/da1 = z + // dx(z)/da2 = 1 - Float_t sigma = 0.1; + const Int_t nGL = 2; // number of global parameters per point + // taken from millepede 1 dim example - Float_t* derLC = new Float_t[nLC]; // array of derivatives for local parameters - Float_t* derGL = new Float_t[nGL]; // array of derivatives for global parameters + Float_t sigma = 0.1; - Int_t* label = new Int_t[nGL]; // array of labels + Float_t* derLC = new Float_t[nLC]; // array of derivatives for local parameters + Float_t* derGL = new Float_t[nGL]; // array of derivatives for global parameters + Int_t* label = new Int_t[nGL]; // array of labels - for (Int_t help = 0; help < nGL; help++) { - derGL[help] = 0; - } - - for (Int_t help = 0; help < nLC; help++) { - derLC[help] = 0; - } + for (Int_t help = 0; help < nGL; help++) { + derGL[help] = 0; + } - FairTrackParam* track = static_cast(fTracks->At(0)); + for (Int_t help = 0; help < nLC; help++) { + derLC[help] = 0; + } - //Extract Track parameters - Double_t OffX = track->GetX(); - Double_t SlopeX = track->GetTx(); - Double_t OffY = track->GetY(); - Double_t SlopeY = track->GetTy(); + FairTrackParam* track = static_cast(fTracks->At(0)); - Double_t residual; + // Extract Track parameters + Double_t OffX = track->GetX(); + Double_t SlopeX = track->GetTx(); + Double_t OffY = track->GetY(); + Double_t SlopeY = track->GetTy(); - FairTutorialDet4Hit* hit; + Double_t residual; - Int_t nHits = fHits->GetEntriesFast(); - for (Int_t iHit=0; iHit(fHits->At(iHit)); + FairTutorialDet4Hit* hit; - Float_t Z = hit->GetZ(); - Float_t hitX = hit->GetX(); - Float_t fitX = OffX + SlopeX * Z; - Float_t hitY = hit->GetY(); - Float_t fitY = OffY + SlopeY * Z; - LOG(debug)<<"hitX, fitX: "<< hitX<<" ,"<GetEntriesFast(); + for (Int_t iHit = 0; iHit < nHits; ++iHit) { + hit = static_cast(fHits->At(iHit)); - label[0] = iHit+1; - label[1] = iHit+101; + Float_t Z = hit->GetZ(); + Float_t hitX = hit->GetX(); + Float_t fitX = OffX + SlopeX * Z; + Float_t hitY = hit->GetY(); + Float_t fitY = OffY + SlopeY * Z; + LOG(debug) << "hitX, fitX: " << hitX << " ," << fitX; - derGL[0] = -1; - derGL[1] = 0; + label[0] = iHit + 1; + label[1] = iHit + 101; - derLC[0] = 1; - derLC[1] = Z; - derLC[2] = 0; - derLC[3] = 0; + derGL[0] = -1; + derGL[1] = 0; - residual = fitX - hitX; - LOG(debug)<<"ResidualX: "<< residual; - //call to Mille Writer - fMille->mille(nLC,derLC,nGL,derGL,label,residual,sigma); + derLC[0] = 1; + derLC[1] = Z; + derLC[2] = 0; + derLC[3] = 0; - derGL[0] = 0; - derGL[1] = -1; + residual = fitX - hitX; + LOG(debug) << "ResidualX: " << residual; + // call to Mille Writer + fMille->mille(nLC, derLC, nGL, derGL, label, residual, sigma); - derLC[0] = 0; - derLC[1] = 0; - derLC[2] = 1; - derLC[3] = Z; + derGL[0] = 0; + derGL[1] = -1; - residual = fitY - hitY; - LOG(debug)<<"ResidualX: "<< residual; - //call to Mille Writer - fMille->mille(nLC,derLC,nGL,derGL,label,residual,sigma); + derLC[0] = 0; + derLC[1] = 0; + derLC[2] = 1; + derLC[3] = Z; - } - fMille->end(); + residual = fitY - hitY; + LOG(debug) << "ResidualX: " << residual; + // call to Mille Writer + fMille->mille(nLC, derLC, nGL, derGL, label, residual, sigma); + } + fMille->end(); - delete[] derLC; - delete[] derGL; - delete[] label; + delete[] derLC; + delete[] derGL; + delete[] label; } -void FairTutorialDet4MilleWriter::Finish() -{ - LOG(debug) << "Finish of FairTutorialDet4MilleWriter"; -} +void FairTutorialDet4MilleWriter::Finish() { LOG(debug) << "Finish of FairTutorialDet4MilleWriter"; } -ClassImp(FairTutorialDet4MilleWriter) +ClassImp(FairTutorialDet4MilleWriter); diff --git a/examples/simulation/Tutorial4/src/reco/FairTutorialDet4MilleWriter.h b/examples/simulation/Tutorial4/src/reco/FairTutorialDet4MilleWriter.h index 3a0281036a..85cb29af18 100644 --- a/examples/simulation/Tutorial4/src/reco/FairTutorialDet4MilleWriter.h +++ b/examples/simulation/Tutorial4/src/reco/FairTutorialDet4MilleWriter.h @@ -1,17 +1,17 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRTUTORIALDET4MILLEWRITER_H #define FAIRTUTORIALDET4MILLEWRITER_H -#include "FairTask.h" // for InitStatus, FairTask +#include "FairTask.h" // for InitStatus, FairTask +#include // for Option_t, Bool_t, etc #include -#include // for Option_t, Bool_t, etc class Mille; class TClonesArray; @@ -43,11 +43,11 @@ class FairTutorialDet4MilleWriter : public FairTask /** Finish task called at the end of the run **/ virtual void Finish(); - void SetWriteAscii(Bool_t val) {fWriteAscii = val;} + void SetWriteAscii(Bool_t val) { fWriteAscii = val; } - void SetVersion(Int_t val) {fVersion = val;} + void SetVersion(Int_t val) { fVersion = val; } - void SetFileName(TString val) {fFileName = val;} + void SetFileName(TString val) { fFileName = val; } private: void ExecVersion1(Option_t* opt); @@ -76,7 +76,7 @@ class FairTutorialDet4MilleWriter : public FairTask FairTutorialDet4MilleWriter(const FairTutorialDet4MilleWriter&); FairTutorialDet4MilleWriter operator=(const FairTutorialDet4MilleWriter&); - ClassDef(FairTutorialDet4MilleWriter,1); + ClassDef(FairTutorialDet4MilleWriter, 1); }; #endif diff --git a/examples/simulation/Tutorial4/src/reco/FairTutorialDet4StraightLineFitter.cxx b/examples/simulation/Tutorial4/src/reco/FairTutorialDet4StraightLineFitter.cxx index f8dd7187cc..7fdeb8eaf7 100644 --- a/examples/simulation/Tutorial4/src/reco/FairTutorialDet4StraightLineFitter.cxx +++ b/examples/simulation/Tutorial4/src/reco/FairTutorialDet4StraightLineFitter.cxx @@ -1,47 +1,46 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "FairTutorialDet4StraightLineFitter.h" -#include "FairLogger.h" // for FairLogger, etc -#include "FairRootManager.h" // for FairRootManager -#include "FairTrackParam.h" // for FairTrackParam -#include "FairTutorialDet4Hit.h" // for FairTutorialDet4Hit +#include "FairLogger.h" // for FairLogger, etc +#include "FairRootManager.h" // for FairRootManager +#include "FairTrackParam.h" // for FairTrackParam +#include "FairTutorialDet4Hit.h" // for FairTutorialDet4Hit -#include // for TClonesArray -#include // for TF1 -#include // for TGraphErrors -#include // for TVector3 - -#include // for set, set<>::iterator, etc +#include // for TClonesArray +#include // for TF1 +#include // for TGraphErrors +#include // for TVector3 +#include // for set, set<>::iterator, etc FairTutorialDet4StraightLineFitter::FairTutorialDet4StraightLineFitter() - :FairTask("FairTutorialDet4StraightLineFitter"), - fHits(nullptr), - fTracks(nullptr), - fVersion(2) + : FairTask("FairTutorialDet4StraightLineFitter") + , fHits(nullptr) + , fTracks(nullptr) + , fVersion(2) { - LOG(debug) << "Default Constructor of FairTutorialDet4StraightLineFitter"; + LOG(debug) << "Default Constructor of FairTutorialDet4StraightLineFitter"; } FairTutorialDet4StraightLineFitter::~FairTutorialDet4StraightLineFitter() { - LOG(debug) << "Destructor of FairTutorialDet4StraightLineFitter"; - if (fTracks) { - fTracks->Delete(); - delete fTracks; - } + LOG(debug) << "Destructor of FairTutorialDet4StraightLineFitter"; + if (fTracks) { + fTracks->Delete(); + delete fTracks; + } } void FairTutorialDet4StraightLineFitter::SetParContainers() { - LOG(debug) << "SetParContainers of FairTutorialDet4StraightLineFitter"; - // Load all necessary parameter containers from the runtime data base - /* + LOG(debug) << "SetParContainers of FairTutorialDet4StraightLineFitter"; + // Load all necessary parameter containers from the runtime data base + /* FairRunAna* ana = FairRunAna::Instance(); FairRuntimeDb* rtdb=ana->GetRuntimeDb(); @@ -52,156 +51,156 @@ void FairTutorialDet4StraightLineFitter::SetParContainers() InitStatus FairTutorialDet4StraightLineFitter::Init() { - LOG(debug) << "Initilization of FairTutorialDet4StraightLineFitter"; + LOG(debug) << "Initilization of FairTutorialDet4StraightLineFitter"; - // Get a handle from the IO manager - FairRootManager* ioman = FairRootManager::Instance(); + // Get a handle from the IO manager + FairRootManager* ioman = FairRootManager::Instance(); - // Get a pointer to the previous already existing data level + // Get a pointer to the previous already existing data level - fHits = static_cast(ioman->GetObject("TutorialDetHit")); - if (!fHits) { - LOG(error)<<"No InputDataLevelName array!\n" - << "FairTutorialDet4StraightLineFitter will be inactive"; - return kERROR; - } - - // Create the TClonesArray for the output data and register - // it in the IO manager - fTracks = new TClonesArray("FairTrackParam", 100); - ioman->Register("TutorialDetTrack","TutorialDet",fTracks,kTRUE); + fHits = static_cast(ioman->GetObject("TutorialDetHit")); + if (!fHits) { + LOG(error) << "No InputDataLevelName array!\n" + << "FairTutorialDet4StraightLineFitter will be inactive"; + return kERROR; + } + // Create the TClonesArray for the output data and register + // it in the IO manager + fTracks = new TClonesArray("FairTrackParam", 100); + ioman->Register("TutorialDetTrack", "TutorialDet", fTracks, kTRUE); - // Do whatever else is needed at the initilization stage - // Create histograms to be filled - // initialize variables + // Do whatever else is needed at the initilization stage + // Create histograms to be filled + // initialize variables - return kSUCCESS; + return kSUCCESS; } InitStatus FairTutorialDet4StraightLineFitter::ReInit() { - LOG(debug) << "Initilization of FairTutorialDet4StraightLineFitter"; - return kSUCCESS; + LOG(debug) << "Initilization of FairTutorialDet4StraightLineFitter"; + return kSUCCESS; } void FairTutorialDet4StraightLineFitter::Exec(Option_t* /*option*/) { - LOG(debug) << "Exec of FairTutorialDet4StraightLineFitter"; + LOG(debug) << "Exec of FairTutorialDet4StraightLineFitter"; - if (!IsGoodEvent()) { return; } + if (!IsGoodEvent()) { + return; + } - // Declare some variables - FairTutorialDet4Hit* hit = nullptr; -/* + // Declare some variables + FairTutorialDet4Hit* hit = nullptr; + /* Int_t detID = 0; // Detector ID Int_t trackID = 0; // Track index Double_t x, y, z; // Position Double_t dx = 0.1; // Position error Double_t tof = 0.; // Time of flight */ - TVector3 pos, dpos; // Position and error vectors - - // Loop over TofPoints - Int_t nHits = fHits->GetEntriesFast(); - Float_t* ZPos = new Float_t[nHits]; - Float_t* XPos = new Float_t[nHits]; - Float_t* XPosErr = new Float_t[nHits]; - Float_t* YPos = new Float_t[nHits]; - Float_t* YPosErr = new Float_t[nHits]; - - for (Int_t iHit=0; iHit(fHits->At(iHit)); - if (!hit) { continue; } - - XPos[iHit] = hit->GetX(); - YPos[iHit] = hit->GetY(); - ZPos[iHit] = hit->GetZ(); - - XPosErr[iHit] = hit->GetDx(); - YPosErr[iHit] = hit->GetDy(); - } - - TF1* f1 = new TF1("f1", "[0]*x + [1]"); - TGraphErrors* LineGraph; - - LineGraph = new TGraphErrors(nHits, ZPos, XPos, 0, XPosErr); - LineGraph->Fit("f1", "Q"); - Double_t SlopeX = f1->GetParameter(0); - Double_t OffX = f1->GetParameter(1); - Double_t Chi2X = f1->GetChisquare(); - Double_t SlopeY = 0.; - Double_t OffY = 0.; - Double_t Chi2Y; - - if (2 == fVersion) { - LineGraph = new TGraphErrors(nHits, ZPos, YPos, 0, YPosErr); + TVector3 pos, dpos; // Position and error vectors + + // Loop over TofPoints + Int_t nHits = fHits->GetEntriesFast(); + Float_t* ZPos = new Float_t[nHits]; + Float_t* XPos = new Float_t[nHits]; + Float_t* XPosErr = new Float_t[nHits]; + Float_t* YPos = new Float_t[nHits]; + Float_t* YPosErr = new Float_t[nHits]; + + for (Int_t iHit = 0; iHit < nHits; iHit++) { + hit = static_cast(fHits->At(iHit)); + if (!hit) { + continue; + } + + XPos[iHit] = hit->GetX(); + YPos[iHit] = hit->GetY(); + ZPos[iHit] = hit->GetZ(); + + XPosErr[iHit] = hit->GetDx(); + YPosErr[iHit] = hit->GetDy(); + } + + TF1* f1 = new TF1("f1", "[0]*x + [1]"); + TGraphErrors* LineGraph; + + LineGraph = new TGraphErrors(nHits, ZPos, XPos, 0, XPosErr); LineGraph->Fit("f1", "Q"); - SlopeY = f1->GetParameter(0); - OffY = f1->GetParameter(1); - Chi2Y = f1->GetChisquare(); - - LOG(debug)<SetX(OffX); - track->SetTx(SlopeX); - track->SetZ(0.); - if (2 == fVersion) { - track->SetY(OffY); - track->SetTy(SlopeY); - } - new ((*fTracks)[0]) FairTrackParam(*track); - // const TMatrixFSym matrix; - // Double_t Z = 0.; - // new ((*fTracks)[0]) FairTrackParam(OffX, OffY, Z, SlopeX, SlopeY, matrix); - - delete[] ZPos; - delete[] XPos; - delete[] XPosErr; - delete[] YPos; - delete[] YPosErr; + Double_t SlopeX = f1->GetParameter(0); + Double_t OffX = f1->GetParameter(1); + Double_t Chi2X = f1->GetChisquare(); + Double_t SlopeY = 0.; + Double_t OffY = 0.; + Double_t Chi2Y; + + if (2 == fVersion) { + LineGraph = new TGraphErrors(nHits, ZPos, YPos, 0, YPosErr); + LineGraph->Fit("f1", "Q"); + SlopeY = f1->GetParameter(0); + OffY = f1->GetParameter(1); + Chi2Y = f1->GetChisquare(); + + LOG(debug) << XPos[0] << "," << XPos[nHits - 1] << "," << YPos[0] << "," << YPos[nHits - 1] << "," << ZPos[0] + << "," << ZPos[nHits - 1]; + Double_t XSlope = (XPos[nHits - 1] - XPos[0]) / (ZPos[nHits - 1] - ZPos[0]); + Double_t YSlope = (YPos[nHits - 1] - YPos[0]) / (ZPos[nHits - 1] - ZPos[0]); + + LOG(debug) << "Slope(x,y): " << SlopeX << " ," << SlopeY; + LOG(debug) << "Slope1(x,y): " << XSlope << " ," << YSlope; + LOG(debug) << "Offset(x,y): " << OffX << " ," << OffY; + LOG(debug) << "Chi2(x,y): " << Chi2X << " ," << Chi2Y; + } + + FairTrackParam* track = new FairTrackParam(); + track->SetX(OffX); + track->SetTx(SlopeX); + track->SetZ(0.); + if (2 == fVersion) { + track->SetY(OffY); + track->SetTy(SlopeY); + } + new ((*fTracks)[0]) FairTrackParam(*track); + // const TMatrixFSym matrix; + // Double_t Z = 0.; + // new ((*fTracks)[0]) FairTrackParam(OffX, OffY, Z, SlopeX, SlopeY, matrix); + + delete[] ZPos; + delete[] XPos; + delete[] XPosErr; + delete[] YPos; + delete[] YPosErr; } Bool_t FairTutorialDet4StraightLineFitter::IsGoodEvent() { - // Check if each for the event there is maximum 1 hit per detector - // station. In the moment we create tracks with all hits in the - // event, so we have to check for this. - // In the end the algorithm should be able to work also with - // missing hits in some stations - FairTutorialDet4Hit* hit; - std::set detIdSet; - std::set::iterator it; - - Int_t nHits = fHits->GetEntriesFast(); - for (Int_t iHit=0; iHit(fHits->At(iHit)); - Int_t detId = hit->GetDetectorID(); - it = detIdSet.find(detId); - if (it == detIdSet.end()) { - detIdSet.insert(detId); - } else { - // find hit in already used detector station - // this is not a good event - return kFALSE; + // Check if each for the event there is maximum 1 hit per detector + // station. In the moment we create tracks with all hits in the + // event, so we have to check for this. + // In the end the algorithm should be able to work also with + // missing hits in some stations + FairTutorialDet4Hit* hit; + std::set detIdSet; + std::set::iterator it; + + Int_t nHits = fHits->GetEntriesFast(); + for (Int_t iHit = 0; iHit < nHits; ++iHit) { + hit = static_cast(fHits->At(iHit)); + Int_t detId = hit->GetDetectorID(); + it = detIdSet.find(detId); + if (it == detIdSet.end()) { + detIdSet.insert(detId); + } else { + // find hit in already used detector station + // this is not a good event + return kFALSE; + } } - } - return kTRUE; + return kTRUE; } -void FairTutorialDet4StraightLineFitter::Finish() -{ - LOG(debug) << "Finish of FairTutorialDet4StraightLineFitter"; -} +void FairTutorialDet4StraightLineFitter::Finish() { LOG(debug) << "Finish of FairTutorialDet4StraightLineFitter"; } -ClassImp(FairTutorialDet4StraightLineFitter) +ClassImp(FairTutorialDet4StraightLineFitter); diff --git a/examples/simulation/Tutorial4/src/reco/FairTutorialDet4StraightLineFitter.h b/examples/simulation/Tutorial4/src/reco/FairTutorialDet4StraightLineFitter.h index ec3330698e..f6fd7291cc 100644 --- a/examples/simulation/Tutorial4/src/reco/FairTutorialDet4StraightLineFitter.h +++ b/examples/simulation/Tutorial4/src/reco/FairTutorialDet4StraightLineFitter.h @@ -1,16 +1,16 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRTUTORIALDET4STRAIGHTLINEFITTER_H #define FAIRTUTORIALDET4STRAIGHTLINEFITTER_H -#include "FairTask.h" // for InitStatus, FairTask +#include "FairTask.h" // for InitStatus, FairTask -#include // for ClassDef +#include // for ClassDef class TClonesArray; @@ -41,7 +41,7 @@ class FairTutorialDet4StraightLineFitter : public FairTask /** Finish task called at the end of the run **/ virtual void Finish(); - void SetVersion(Int_t val) {fVersion = val;} + void SetVersion(Int_t val) { fVersion = val; } private: /** Input array from previous already existing data level **/ @@ -57,7 +57,7 @@ class FairTutorialDet4StraightLineFitter : public FairTask FairTutorialDet4StraightLineFitter(const FairTutorialDet4StraightLineFitter&); FairTutorialDet4StraightLineFitter operator=(const FairTutorialDet4StraightLineFitter&); - ClassDef(FairTutorialDet4StraightLineFitter,1); + ClassDef(FairTutorialDet4StraightLineFitter, 1); }; #endif diff --git a/examples/simulation/Tutorial4/src/tools/FairTutorialDet4GeoHandler.cxx b/examples/simulation/Tutorial4/src/tools/FairTutorialDet4GeoHandler.cxx index 885a3336a5..c8a1861c29 100644 --- a/examples/simulation/Tutorial4/src/tools/FairTutorialDet4GeoHandler.cxx +++ b/examples/simulation/Tutorial4/src/tools/FairTutorialDet4GeoHandler.cxx @@ -12,181 +12,197 @@ #include "FairTutorialDet4GeoHandler.h" -#include "FairLogger.h" // for FairLogger, etc +#include "FairLogger.h" // for FairLogger, etc -#include // for TGeoBBox -#include // for TGeoManager, gGeoManager -#include // for TGeoNode -#include // for TGeoVolume -#include // for TVirtualMC - -#include // for printf -#include // for strlen, strncpy +#include // for TGeoBBox +#include // for TGeoManager, gGeoManager +#include // for TGeoNode +#include // for TGeoVolume +#include // for TVirtualMC +#include // for printf +#include // for strlen, strncpy FairTutorialDet4GeoHandler::FairTutorialDet4GeoHandler() - : TObject(), - fIsSimulation(kFALSE), - fLastUsedDetectorID(0), - fGeoPathHash(0), - fCurrentVolume(nullptr), - fVolumeShape(nullptr), - fGlobal(), - fGlobalMatrix(nullptr) -{ -} + : TObject() + , fIsSimulation(kFALSE) + , fLastUsedDetectorID(0) + , fGeoPathHash(0) + , fCurrentVolume(nullptr) + , fVolumeShape(nullptr) + , fGlobal() + , fGlobalMatrix(nullptr) +{} Int_t FairTutorialDet4GeoHandler::Init(Bool_t isSimulation) { - // Int_t geoVersion = CheckGeometryVersion(); + // Int_t geoVersion = CheckGeometryVersion(); - fIsSimulation=isSimulation; + fIsSimulation = isSimulation; - return 1; + return 1; } void FairTutorialDet4GeoHandler::LocalToGlobal(Double_t* local, Double_t* global, Int_t detID) { - TString path=ConstructFullPathFromDetID(detID); - NavigateTo(path); - gGeoManager->LocalToMaster(local, global); + TString path = ConstructFullPathFromDetID(detID); + NavigateTo(path); + gGeoManager->LocalToMaster(local, global); } TString FairTutorialDet4GeoHandler::ConstructFullPathFromDetID(Int_t detID) { - TString volStr = "/cave_1/tutorial4_0/tut4_det_"; - TString volPath = volStr; - volPath += detID; - return volPath; + TString volStr = "/cave_1/tutorial4_0/tut4_det_"; + TString volPath = volStr; + volPath += detID; + return volPath; } Int_t FairTutorialDet4GeoHandler::GetUniqueDetectorId(TString volName) { - if (fGeoPathHash != volName.Hash()) { - NavigateTo(volName); - } - return GetUniqueDetectorId(); + if (fGeoPathHash != volName.Hash()) { + NavigateTo(volName); + } + return GetUniqueDetectorId(); } Int_t FairTutorialDet4GeoHandler::GetUniqueDetectorId() { - Int_t detectorNr=0; + Int_t detectorNr = 0; - CurrentVolOffID(0, detectorNr); + CurrentVolOffID(0, detectorNr); - return detectorNr; + return detectorNr; } Int_t FairTutorialDet4GeoHandler::VolIdGeo(const char* name) const { - // - // Return the unique numeric identifier for volume name - // - - Int_t uid = gGeoManager->GetUID(name); - if (uid<0) { - printf("VolId: Volume %s not found\n",name); - return 0; - } - return uid; + // + // Return the unique numeric identifier for volume name + // + + Int_t uid = gGeoManager->GetUID(name); + if (uid < 0) { + printf("VolId: Volume %s not found\n", name); + return 0; + } + return uid; } Int_t FairTutorialDet4GeoHandler::VolId(const Text_t* name) const { - if (fIsSimulation) { - return TVirtualMC::GetMC()->VolId(name); - } else { - // - // Return the unique numeric identifier for volume name - // - char sname[20]; - Int_t len = strlen(name)-1; - if (name[len] != ' ') { return VolIdGeo(name); } - strncpy(sname, name, len); - sname[len] = 0; - return VolIdGeo(sname); - } + if (fIsSimulation) { + return TVirtualMC::GetMC()->VolId(name); + } else { + // + // Return the unique numeric identifier for volume name + // + char sname[20]; + Int_t len = strlen(name) - 1; + if (name[len] != ' ') { + return VolIdGeo(name); + } + strncpy(sname, name, len); + sname[len] = 0; + return VolIdGeo(sname); + } } Int_t FairTutorialDet4GeoHandler::CurrentVolID(Int_t& copy) const { - if (fIsSimulation) { - return TVirtualMC::GetMC()->CurrentVolID(copy); - } else { - // - // Returns the current volume ID and copy number - // - if (gGeoManager->IsOutside()) { return 0; } - TGeoNode* node = gGeoManager->GetCurrentNode(); - copy = node->GetNumber(); - Int_t id = node->GetVolume()->GetNumber(); - return id; - } + if (fIsSimulation) { + return TVirtualMC::GetMC()->CurrentVolID(copy); + } else { + // + // Returns the current volume ID and copy number + // + if (gGeoManager->IsOutside()) { + return 0; + } + TGeoNode* node = gGeoManager->GetCurrentNode(); + copy = node->GetNumber(); + Int_t id = node->GetVolume()->GetNumber(); + return id; + } } Int_t FairTutorialDet4GeoHandler::CurrentVolOffID(Int_t off, Int_t& copy) const { - if (fIsSimulation) { - return TVirtualMC::GetMC()->CurrentVolOffID(off, copy); - } else { - // - // Return the current volume "off" upward in the geometrical tree - // ID and copy number - // - if (off<0 || off>gGeoManager->GetLevel()) { return 0; } - if (off==0) { return CurrentVolID(copy); } - TGeoNode* node = gGeoManager->GetMother(off); - if (!node) { return 0; } - copy = node->GetNumber(); - return node->GetVolume()->GetNumber(); - } + if (fIsSimulation) { + return TVirtualMC::GetMC()->CurrentVolOffID(off, copy); + } else { + // + // Return the current volume "off" upward in the geometrical tree + // ID and copy number + // + if (off < 0 || off > gGeoManager->GetLevel()) { + return 0; + } + if (off == 0) { + return CurrentVolID(copy); + } + TGeoNode* node = gGeoManager->GetMother(off); + if (!node) { + return 0; + } + copy = node->GetNumber(); + return node->GetVolume()->GetNumber(); + } } const char* FairTutorialDet4GeoHandler::CurrentVolName() const { - if (fIsSimulation) { - return TVirtualMC::GetMC()->CurrentVolName(); - } else { - // - // Returns the current volume name - // - if (gGeoManager->IsOutside()) { return gGeoManager->GetTopVolume()->GetName(); } - return gGeoManager->GetCurrentVolume()->GetName(); - } + if (fIsSimulation) { + return TVirtualMC::GetMC()->CurrentVolName(); + } else { + // + // Returns the current volume name + // + if (gGeoManager->IsOutside()) { + return gGeoManager->GetTopVolume()->GetName(); + } + return gGeoManager->GetCurrentVolume()->GetName(); + } } const char* FairTutorialDet4GeoHandler::CurrentVolOffName(Int_t off) const { - if (fIsSimulation) { - return TVirtualMC::GetMC()->CurrentVolOffName(off); - } else { - // - // Return the current volume "off" upward in the geometrical tree - // ID, name and copy number - // if name=0 no name is returned - // - if (off<0 || off>gGeoManager->GetLevel()) { return 0; } - if (off==0) { return CurrentVolName(); } - TGeoNode* node = gGeoManager->GetMother(off); - if (!node) { return 0; } - return node->GetVolume()->GetName(); - } + if (fIsSimulation) { + return TVirtualMC::GetMC()->CurrentVolOffName(off); + } else { + // + // Return the current volume "off" upward in the geometrical tree + // ID, name and copy number + // if name=0 no name is returned + // + if (off < 0 || off > gGeoManager->GetLevel()) { + return 0; + } + if (off == 0) { + return CurrentVolName(); + } + TGeoNode* node = gGeoManager->GetMother(off); + if (!node) { + return 0; + } + return node->GetVolume()->GetName(); + } } void FairTutorialDet4GeoHandler::NavigateTo(TString volName) { - if (fIsSimulation) { - LOG(fatal)<<"This methode is not supported in simulation mode"; - } else { - gGeoManager->cd(volName.Data()); - fGeoPathHash = volName.Hash(); - fCurrentVolume = gGeoManager->GetCurrentVolume(); - fVolumeShape = static_cast(fCurrentVolume->GetShape()); - Double_t local[3] = {0., 0., 0.}; // Local centre of volume - gGeoManager->LocalToMaster(local, fGlobal); - LOG(debug2)<<"Pos: "<GetCurrentMatrix(); - } + if (fIsSimulation) { + LOG(fatal) << "This methode is not supported in simulation mode"; + } else { + gGeoManager->cd(volName.Data()); + fGeoPathHash = volName.Hash(); + fCurrentVolume = gGeoManager->GetCurrentVolume(); + fVolumeShape = static_cast(fCurrentVolume->GetShape()); + Double_t local[3] = {0., 0., 0.}; // Local centre of volume + gGeoManager->LocalToMaster(local, fGlobal); + LOG(debug2) << "Pos: " << fGlobal[0] << " , " << fGlobal[1] << " , " << fGlobal[2]; + // fGlobalMatrix = gGeoManager->GetCurrentMatrix(); + } } -ClassImp(FairTutorialDet4GeoHandler) +ClassImp(FairTutorialDet4GeoHandler); diff --git a/examples/simulation/Tutorial4/src/tools/FairTutorialDet4GeoHandler.h b/examples/simulation/Tutorial4/src/tools/FairTutorialDet4GeoHandler.h index b79b9f9867..9dda63044f 100644 --- a/examples/simulation/Tutorial4/src/tools/FairTutorialDet4GeoHandler.h +++ b/examples/simulation/Tutorial4/src/tools/FairTutorialDet4GeoHandler.h @@ -20,10 +20,9 @@ #ifndef FAIRTUTORIALDET4GEOHANDLER_H #define FAIRTUTORIALDET4GEOHANDLER_H 1 -#include // for TObject - -#include // for Int_t, Double_t, Bool_t, etc -#include // for TString +#include // for Int_t, Double_t, Bool_t, etc +#include // for TObject +#include // for TString class TGeoBBox; class TGeoVolume; @@ -43,7 +42,7 @@ class FairTutorialDet4GeoHandler : public TObject // Int_t GetDetectorId(Int_t uniqueId); - Int_t Init(Bool_t isSimulation=kFALSE); + Int_t Init(Bool_t isSimulation = kFALSE); void FillDetectorInfoArray(Int_t uniqueId); void NavigateTo(TString volName); @@ -62,22 +61,22 @@ class FairTutorialDet4GeoHandler : public TObject // Int_t CheckGeometryVersion(); private: - Bool_t fIsSimulation; //! + Bool_t fIsSimulation; //! - Int_t fLastUsedDetectorID; //! + Int_t fLastUsedDetectorID; //! - UInt_t fGeoPathHash; //! - TGeoVolume* fCurrentVolume; //! - TGeoBBox* fVolumeShape; //! - Double_t fGlobal[3]; //! Global centre of volume - TGeoHMatrix* fGlobalMatrix; //! + UInt_t fGeoPathHash; //! + TGeoVolume* fCurrentVolume; //! + TGeoBBox* fVolumeShape; //! + Double_t fGlobal[3]; //! Global centre of volume + TGeoHMatrix* fGlobalMatrix; //! TString ConstructFullPathFromDetID(Int_t detID); FairTutorialDet4GeoHandler(const FairTutorialDet4GeoHandler&); FairTutorialDet4GeoHandler operator=(const FairTutorialDet4GeoHandler&); - ClassDef(FairTutorialDet4GeoHandler,1) + ClassDef(FairTutorialDet4GeoHandler, 1) }; -#endif //FAIRTUTORIALDETGEOHANDLER_H +#endif // FAIRTUTORIALDETGEOHANDLER_H diff --git a/examples/simulation/Tutorial4/src/tools/Mille.h b/examples/simulation/Tutorial4/src/tools/Mille.h index 799da12d57..a64360afb6 100644 --- a/examples/simulation/Tutorial4/src/tools/Mille.h +++ b/examples/simulation/Tutorial4/src/tools/Mille.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef MILLE_H @@ -39,8 +39,7 @@ class Mille Mille(const char* outFileName, bool asBinary = true, bool writeZero = false); ~Mille(); - void mille(int NLC, const float* derLc, int NGL, const float* derGl, - const int* label, float rMeas, float sigma); + void mille(int NLC, const float* derLc, int NGL, const float* derGl, const int* label, float rMeas, float sigma); void special(int nSpecial, const float* floatings, const int* integers); void kill(); void end(); @@ -49,16 +48,22 @@ class Mille void newSet(); bool checkBufferSize(int nLocal, int nGlobal); - std::ofstream myOutFile; // C-binary for output - bool myAsBinary; // if false output as text - bool myWriteZero; // if true also write out derivatives/lables ==0 + std::ofstream myOutFile; // C-binary for output + bool myAsBinary; // if false output as text + bool myWriteZero; // if true also write out derivatives/lables ==0 - enum {myBufferSize = 10000}; - int myBufferInt[myBufferSize]; // to collect labels etc. - float myBufferFloat[myBufferSize]; // to collect derivatives etc. - int myBufferPos; - bool myHasSpecial; // if true, special(..) already called for this record + enum + { + myBufferSize = 10000 + }; + int myBufferInt[myBufferSize]; // to collect labels etc. + float myBufferFloat[myBufferSize]; // to collect derivatives etc. + int myBufferPos; + bool myHasSpecial; // if true, special(..) already called for this record - enum {myMaxLabel = (0xFFFFFFFF - (1 << 31))}; // largest label allowed: 2^31 - 1 + enum + { + myMaxLabel = (0xFFFFFFFF - (1 << 31)) + }; // largest label allowed: 2^31 - 1 }; #endif diff --git a/examples/simulation/rutherford/macros/eventDisplay.C b/examples/simulation/rutherford/macros/eventDisplay.C index 5841b5a033..faabcb7bef 100644 --- a/examples/simulation/rutherford/macros/eventDisplay.C +++ b/examples/simulation/rutherford/macros/eventDisplay.C @@ -5,35 +5,34 @@ * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ -eventDisplay(TString mcEngine="TGeant3") +eventDisplay(TString mcEngine = "TGeant3") { - TString inFile = "data/test_" + mcEngine + ".mc.root"; - TString parFile = "data/params_" + mcEngine + ".root"; - TString outFile = "data/test_" + mcEngine + ".root"; + TString inFile = "data/test_" + mcEngine + ".mc.root"; + TString parFile = "data/params_" + mcEngine + ".root"; + TString outFile = "data/test_" + mcEngine + ".root"; - // ----- Reconstruction run ------------------------------------------- - FairRunAna *fRun= new FairRunAna(); - FairFileSource *fFileSource = new FairFileSource(inFile); - fRun->SetSource(fFileSource); + // ----- Reconstruction run ------------------------------------------- + FairRunAna *fRun = new FairRunAna(); + FairFileSource *fFileSource = new FairFileSource(inFile); + fRun->SetSource(fFileSource); - fRun->SetSink(new FairRootFileSink(outFile)); + fRun->SetSink(new FairRootFileSink(outFile)); - // ----- Parameter database -------------------------------------------- - FairRuntimeDb* rtdb = fRun->GetRuntimeDb(); + // ----- Parameter database -------------------------------------------- + FairRuntimeDb *rtdb = fRun->GetRuntimeDb(); - FairParRootFileIo* parIo1 = new FairParRootFileIo(); - parIo1->open(parFile); - rtdb->setFirstInput(parIo1); - // ------------------------------------------------------------------------ + FairParRootFileIo *parIo1 = new FairParRootFileIo(); + parIo1->open(parFile); + rtdb->setFirstInput(parIo1); + // ------------------------------------------------------------------------ - FairEventManager *fMan = new FairEventManager (); - FairMCTracks *Track = new FairMCTracks ("Monte-Carlo Tracks"); - FairMCPointDraw *RutherfordPoints = new FairMCPointDraw ("FairRutherfordPoint",kBlue , kFullSquare); + FairEventManager *fMan = new FairEventManager(); + FairMCTracks *Track = new FairMCTracks("Monte-Carlo Tracks"); + FairMCPointDraw *RutherfordPoints = new FairMCPointDraw("FairRutherfordPoint", kBlue, kFullSquare); - fMan->AddTask(Track); - fMan->AddTask(RutherfordPoints); - - fMan->Init(); + fMan->AddTask(Track); + fMan->AddTask(RutherfordPoints); + fMan->Init(); } diff --git a/examples/simulation/rutherford/macros/run_rad.C b/examples/simulation/rutherford/macros/run_rad.C index 630c1d562a..d636dd08af 100644 --- a/examples/simulation/rutherford/macros/run_rad.C +++ b/examples/simulation/rutherford/macros/run_rad.C @@ -1,161 +1,157 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ -void run_rad(Int_t nEvents = 100, TString mcEngine="TGeant3") +void run_rad(Int_t nEvents = 100, TString mcEngine = "TGeant3") { - - TString dir = gSystem->Getenv("VMCWORKDIR"); - TString tutdir = dir + "/simulation/rutherford/macros"; - - TString tut_geomdir = dir + "/common/geometry"; - gSystem->Setenv("GEOMPATH",tut_geomdir.Data()); - - TString tut_configdir = dir + "/common/gconfig"; - gSystem->Setenv("CONFIG_DIR",tut_configdir.Data()); - - TString outDir = "data"; - TString outFile = outDir + "/test1_"; - outFile = outFile + mcEngine + ".mc.root"; - - TString geoFile = outDir + "/geofile_rad_"; - geoFile = geoFile + mcEngine + "_full.root"; - - TString parFile = outDir + "/params1_"; - parFile = parFile + mcEngine + ".root"; - - // In general, the following parts need not be touched - // ======================================================================== - - // ---- Debug option ------------------------------------------------- - gDebug = 0; - // ------------------------------------------------------------------------ - - // ----- Timer -------------------------------------------------------- - TStopwatch timer; - timer.Start(); - // ------------------------------------------------------------------------ - - FairLogger *logger = FairLogger::GetLogger(); - // define log file name - logger->SetLogFileName("MyLog.log"); - // log to screen and to file - logger->SetLogToScreen(kTRUE); - logger->SetLogToFile(kTRUE); - // Print very accurate output. Levels are LOW, MEDIUM and HIGH - logger->SetLogVerbosityLevel("HIGH"); - - // ----- Create simulation run ---------------------------------------- - FairRunSim* run = new FairRunSim(); - run->SetName(mcEngine); // Transport engine - run->SetSink(new FairRootFileSink(outFile)); // Output file - FairRuntimeDb* rtdb = run->GetRuntimeDb(); - // ------------------------------------------------------------------------ - - // ----- Create media ------------------------------------------------- - run->SetMaterials("media.geo"); // Materials - // ------------------------------------------------------------------------ - - //----Start the radiation length manager ---------------------------------- - - run->SetRadLenRegister(kTRUE); - - // ----- Create geometry ---------------------------------------------- - - FairModule* cave= new FairCave("CAVE"); - cave->SetGeometryFileName("cave_vacuum.geo"); - run->AddModule(cave); - - FairModule* target= new FairTarget("Target"); - target->SetGeometryFileName("target_rutherford.geo"); - run->AddModule(target); - - FairDetector* rutherford = new FairRutherford("RutherfordDetector", kFALSE); - rutherford->SetGeometryFileName("rutherford.geo"); - run->AddModule(rutherford); - // ------------------------------------------------------------------------ - - // ----- Create PrimaryGenerator -------------------------------------- - FairPrimaryGenerator* primGen = new FairPrimaryGenerator(); - run->SetGenerator(primGen); - - FairBoxGenerator* boxGen1 = new FairBoxGenerator(0, 1); - boxGen1->SetPRange(.005,.005); - boxGen1->SetPhiRange(0.,0.); - boxGen1->SetThetaRange(-90.,90.); - boxGen1->SetXYZ(0.,0.,-3.); - primGen->AddGenerator(boxGen1); - - - // ------------------------------------------------------------------------ - - run->SetStoreTraj(kTRUE); - - // ----- Run initialisation ------------------------------------------- - run->Init(); - // ------------------------------------------------------------------------ - - // Set cuts for storing the trajectories. - // Switch this on only if trajectories are stored. - // Choose this cuts according to your needs, but be aware - // that the file size of the output file depends on these cuts - - FairTrajFilter* trajFilter = FairTrajFilter::Instance(); - // trajFilter->SetStepSizeCut(0.01); // 1 cm - // trajFilter->SetVertexCut(-2000., -2000., 4., 2000., 2000., 100.); - // trajFilter->SetMomentumCutP(10e-3); // p_lab > 10 MeV - // trajFilter->SetEnergyCut(0., 1.02); // 0 < Etot < 1.04 GeV - trajFilter->SetStorePrimaries(kTRUE); - trajFilter->SetStoreSecondaries(kTRUE); - // ------------------------------------------------------------------------ - - // ----- Runtime database --------------------------------------------- - - Bool_t kParameterMerged = kTRUE; - FairParRootFileIo* parOut = new FairParRootFileIo(kParameterMerged); - parOut->open(parFile.Data()); - rtdb->setOutput(parOut); - rtdb->saveOutput(); - rtdb->print(); - // ------------------------------------------------------------------------ - - // ----- Start run ---------------------------------------------------- - run->Run(nEvents); - // ------------------------------------------------------------------------ - run->CreateGeometryFile(geoFile); - - // ----- Finish ------------------------------------------------------- - - cout << endl << endl; - - // Extract the maximal used memory an add is as Dart measurement - // This line is filtered by CTest and the value send to CDash - FairSystemInfo sysInfo; - Float_t maxMemory=sysInfo.GetMaxMemory(); - cout << ""; - cout << maxMemory; - cout << "" << endl; - - timer.Stop(); - Double_t rtime = timer.RealTime(); - Double_t ctime = timer.CpuTime(); - - Float_t cpuUsage=ctime/rtime; - cout << ""; - cout << cpuUsage; - cout << "" << endl; - - cout << endl << endl; - cout << "Output file is " << outFile << endl; - cout << "Parameter file is " << parFile << endl; - cout << "Real time " << rtime << " s, CPU time " << ctime - << "s" << endl << endl; - cout << "Macro finished successfully." << endl; - - // ------------------------------------------------------------------------ -} + TString dir = gSystem->Getenv("VMCWORKDIR"); + TString tutdir = dir + "/simulation/rutherford/macros"; + + TString tut_geomdir = dir + "/common/geometry"; + gSystem->Setenv("GEOMPATH", tut_geomdir.Data()); + + TString tut_configdir = dir + "/common/gconfig"; + gSystem->Setenv("CONFIG_DIR", tut_configdir.Data()); + + TString outDir = "data"; + TString outFile = outDir + "/test1_"; + outFile = outFile + mcEngine + ".mc.root"; + TString geoFile = outDir + "/geofile_rad_"; + geoFile = geoFile + mcEngine + "_full.root"; + + TString parFile = outDir + "/params1_"; + parFile = parFile + mcEngine + ".root"; + + // In general, the following parts need not be touched + // ======================================================================== + + // ---- Debug option ------------------------------------------------- + gDebug = 0; + // ------------------------------------------------------------------------ + + // ----- Timer -------------------------------------------------------- + TStopwatch timer; + timer.Start(); + // ------------------------------------------------------------------------ + + FairLogger* logger = FairLogger::GetLogger(); + // define log file name + logger->SetLogFileName("MyLog.log"); + // log to screen and to file + logger->SetLogToScreen(kTRUE); + logger->SetLogToFile(kTRUE); + // Print very accurate output. Levels are LOW, MEDIUM and HIGH + logger->SetLogVerbosityLevel("HIGH"); + + // ----- Create simulation run ---------------------------------------- + FairRunSim* run = new FairRunSim(); + run->SetName(mcEngine); // Transport engine + run->SetSink(new FairRootFileSink(outFile)); // Output file + FairRuntimeDb* rtdb = run->GetRuntimeDb(); + // ------------------------------------------------------------------------ + + // ----- Create media ------------------------------------------------- + run->SetMaterials("media.geo"); // Materials + // ------------------------------------------------------------------------ + + //----Start the radiation length manager ---------------------------------- + + run->SetRadLenRegister(kTRUE); + + // ----- Create geometry ---------------------------------------------- + + FairModule* cave = new FairCave("CAVE"); + cave->SetGeometryFileName("cave_vacuum.geo"); + run->AddModule(cave); + + FairModule* target = new FairTarget("Target"); + target->SetGeometryFileName("target_rutherford.geo"); + run->AddModule(target); + + FairDetector* rutherford = new FairRutherford("RutherfordDetector", kFALSE); + rutherford->SetGeometryFileName("rutherford.geo"); + run->AddModule(rutherford); + // ------------------------------------------------------------------------ + + // ----- Create PrimaryGenerator -------------------------------------- + FairPrimaryGenerator* primGen = new FairPrimaryGenerator(); + run->SetGenerator(primGen); + + FairBoxGenerator* boxGen1 = new FairBoxGenerator(0, 1); + boxGen1->SetPRange(.005, .005); + boxGen1->SetPhiRange(0., 0.); + boxGen1->SetThetaRange(-90., 90.); + boxGen1->SetXYZ(0., 0., -3.); + primGen->AddGenerator(boxGen1); + + // ------------------------------------------------------------------------ + + run->SetStoreTraj(kTRUE); + + // ----- Run initialisation ------------------------------------------- + run->Init(); + // ------------------------------------------------------------------------ + + // Set cuts for storing the trajectories. + // Switch this on only if trajectories are stored. + // Choose this cuts according to your needs, but be aware + // that the file size of the output file depends on these cuts + + FairTrajFilter* trajFilter = FairTrajFilter::Instance(); + // trajFilter->SetStepSizeCut(0.01); // 1 cm + // trajFilter->SetVertexCut(-2000., -2000., 4., 2000., 2000., 100.); + // trajFilter->SetMomentumCutP(10e-3); // p_lab > 10 MeV + // trajFilter->SetEnergyCut(0., 1.02); // 0 < Etot < 1.04 GeV + trajFilter->SetStorePrimaries(kTRUE); + trajFilter->SetStoreSecondaries(kTRUE); + // ------------------------------------------------------------------------ + + // ----- Runtime database --------------------------------------------- + + Bool_t kParameterMerged = kTRUE; + FairParRootFileIo* parOut = new FairParRootFileIo(kParameterMerged); + parOut->open(parFile.Data()); + rtdb->setOutput(parOut); + rtdb->saveOutput(); + rtdb->print(); + // ------------------------------------------------------------------------ + + // ----- Start run ---------------------------------------------------- + run->Run(nEvents); + // ------------------------------------------------------------------------ + run->CreateGeometryFile(geoFile); + + // ----- Finish ------------------------------------------------------- + + cout << endl << endl; + + // Extract the maximal used memory an add is as Dart measurement + // This line is filtered by CTest and the value send to CDash + FairSystemInfo sysInfo; + Float_t maxMemory = sysInfo.GetMaxMemory(); + cout << ""; + cout << maxMemory; + cout << "" << endl; + + timer.Stop(); + Double_t rtime = timer.RealTime(); + Double_t ctime = timer.CpuTime(); + + Float_t cpuUsage = ctime / rtime; + cout << ""; + cout << cpuUsage; + cout << "" << endl; + + cout << endl << endl; + cout << "Output file is " << outFile << endl; + cout << "Parameter file is " << parFile << endl; + cout << "Real time " << rtime << " s, CPU time " << ctime << "s" << endl << endl; + cout << "Macro finished successfully." << endl; + + // ------------------------------------------------------------------------ +} diff --git a/examples/simulation/rutherford/macros/run_rutherford.C b/examples/simulation/rutherford/macros/run_rutherford.C index b85f2dcfb4..df59fd85a9 100644 --- a/examples/simulation/rutherford/macros/run_rutherford.C +++ b/examples/simulation/rutherford/macros/run_rutherford.C @@ -5,174 +5,169 @@ * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ -void run_rutherford(Int_t nEvents = 10, TString mcEngine="TGeant4", Bool_t isMT=true) +void run_rutherford(Int_t nEvents = 10, TString mcEngine = "TGeant4", Bool_t isMT = true) { - TString dir = gSystem->Getenv("VMCWORKDIR"); - TString tutdir = dir + "/simulation/rutherford/macros"; - - TString tut_geomdir = dir + "/common/geometry"; - gSystem->Setenv("GEOMPATH",tut_geomdir.Data()); - - TString tut_configdir = dir + "/common/gconfig"; - gSystem->Setenv("CONFIG_DIR",tut_configdir.Data()); - - TString outDir = "data"; - TString outFile = outDir + "/test_"; - outFile = outFile + mcEngine + ".mc.root"; - - TString geoFile = outDir + "/geofile_rutherford_"; - geoFile = geoFile + mcEngine + "_full.root"; - - TString parFile = outDir + "/params_"; - parFile = parFile + mcEngine + ".root"; - - // Set the random seed - gRandom->SetSeed(98989); - - // In general, the following parts need not be touched - // ======================================================================== - - // ---- Debug option ------------------------------------------------- - gDebug = 0; - // ------------------------------------------------------------------------ - // ----- Timer -------------------------------------------------------- - TStopwatch timer; - timer.Start(); - // ------------------------------------------------------------------------ - - FairLogger *logger = FairLogger::GetLogger(); - // define log file name - logger->SetLogFileName("MyLog.log"); - // log to screen and to file - logger->SetLogToScreen(kTRUE); - logger->SetLogToFile(kTRUE); - // Print very accurate output. Levels are LOW, MEDIUM and HIGH - logger->SetLogVerbosityLevel("HIGH"); - - // ----- Create simulation run ---------------------------------------- - FairRunSim* run = new FairRunSim(); - run->SetName(mcEngine); // Transport engine - run->SetIsMT(isMT); // Multi-threading mode (Geant4 only) - run->SetSink(new FairRootFileSink(outFile)); // Output file - FairRuntimeDb* rtdb = run->GetRuntimeDb(); - // ------------------------------------------------------------------------ - - run->SetWriteRunInfoFile(kFALSE); - // ----- Create media ------------------------------------------------- - run->SetMaterials("media.geo"); // Materials - // ------------------------------------------------------------------------ - - // ----- Create geometry ---------------------------------------------- - - FairModule* cave= new FairCave("CAVE"); - cave->SetGeometryFileName("cave_vacuum.geo"); - run->AddModule(cave); - - FairModule* target= new FairTarget("Target"); - target->SetGeometryFileName("target_rutherford.geo"); - run->AddModule(target); - - FairDetector* rutherford = new FairRutherford("RutherfordDetector", kTRUE); - rutherford->SetGeometryFileName("rutherford.geo"); - run->AddModule(rutherford); - // ------------------------------------------------------------------------ - - // ----- Create PrimaryGenerator -------------------------------------- - FairPrimaryGenerator* primGen = new FairPrimaryGenerator(); - run->SetGenerator(primGen); - - - // Ion Generator - - FairIonGenerator *fIongen= new FairIonGenerator(2, 4, 2, 1, 0., 0., 1./20., 0., 0., -1.); - primGen->AddGenerator(fIongen); - - - FairBoxGenerator* boxGen1 = new FairBoxGenerator(2212, 1); - boxGen1->SetPRange(.005,.005); - boxGen1->SetPhiRange(0.,0.); - boxGen1->SetThetaRange(0.,0.); - boxGen1->SetXYZ(0.,0.,-3.); - primGen->AddGenerator(boxGen1); - - - - FairYPtGenerator *ypt = new FairYPtGenerator(); - //create and fill histogram with y-pT distribution - TH2D ypt_hist("ypt","ypt;y;p_{T}",100,-2,2,100,0,2); - ypt_hist.Fill(0.2,0.2); - ypt_hist.Fill(0.2,0.4); - ypt->SetYPt(ypt_hist); - ypt->SetMultiplicity(10); - ypt->SetPDGType(211); - // set vertex with gaussian distribution - ypt->SetVertex(0,0,-2.5,0.1,0.1,0.1,FairBaseMCGenerator::kGauss); - primGen->AddGenerator(ypt); - // ------------------------------------------------------------------------ - - run->SetStoreTraj(kTRUE); - - // ----- Run initialisation ------------------------------------------- - run->Init(); - // ------------------------------------------------------------------------ - - // Set cuts for storing the trajectories. - // Switch this on only if trajectories are stored. - // Choose this cuts according to your needs, but be aware - // that the file size of the output file depends on these cuts - - FairTrajFilter* trajFilter = FairTrajFilter::Instance(); - // trajFilter->SetStepSizeCut(0.01); // 1 cm - // trajFilter->SetVertexCut(-2000., -2000., 4., 2000., 2000., 100.); - // trajFilter->SetMomentumCutP(10e-3); // p_lab > 10 MeV - // trajFilter->SetEnergyCut(0., 1.02); // 0 < Etot < 1.04 GeV - trajFilter->SetStorePrimaries(kTRUE); - trajFilter->SetStoreSecondaries(kTRUE); - // ------------------------------------------------------------------------ - - // ----- Runtime database --------------------------------------------- - - Bool_t kParameterMerged = kTRUE; - FairParRootFileIo* parOut = new FairParRootFileIo(kParameterMerged); - parOut->open(parFile.Data()); - rtdb->setOutput(parOut); - rtdb->saveOutput(); - rtdb->print(); - // ------------------------------------------------------------------------ - - // ----- Start run ---------------------------------------------------- - run->Run(nEvents); - // ------------------------------------------------------------------------ - run->CreateGeometryFile(geoFile); - - // ----- Finish ------------------------------------------------------- - - cout << endl << endl; - - // Extract the maximal used memory an add is as Dart measurement - // This line is filtered by CTest and the value send to CDash - FairSystemInfo sysInfo; - Float_t maxMemory=sysInfo.GetMaxMemory(); - cout << ""; - cout << maxMemory; - cout << "" << endl; - - timer.Stop(); - Double_t rtime = timer.RealTime(); - Double_t ctime = timer.CpuTime(); - - Float_t cpuUsage=ctime/rtime; - cout << ""; - cout << cpuUsage; - cout << "" << endl; - - cout << endl << endl; - cout << "Output file is " << outFile << endl; - cout << "Parameter file is " << parFile << endl; - cout << "Real time " << rtime << " s, CPU time " << ctime - << "s" << endl << endl; - cout << "Macro finished successfully." << endl; - - // ------------------------------------------------------------------------ + TString dir = gSystem->Getenv("VMCWORKDIR"); + TString tutdir = dir + "/simulation/rutherford/macros"; + + TString tut_geomdir = dir + "/common/geometry"; + gSystem->Setenv("GEOMPATH", tut_geomdir.Data()); + + TString tut_configdir = dir + "/common/gconfig"; + gSystem->Setenv("CONFIG_DIR", tut_configdir.Data()); + + TString outDir = "data"; + TString outFile = outDir + "/test_"; + outFile = outFile + mcEngine + ".mc.root"; + + TString geoFile = outDir + "/geofile_rutherford_"; + geoFile = geoFile + mcEngine + "_full.root"; + + TString parFile = outDir + "/params_"; + parFile = parFile + mcEngine + ".root"; + + // Set the random seed + gRandom->SetSeed(98989); + + // In general, the following parts need not be touched + // ======================================================================== + + // ---- Debug option ------------------------------------------------- + gDebug = 0; + // ------------------------------------------------------------------------ + // ----- Timer -------------------------------------------------------- + TStopwatch timer; + timer.Start(); + // ------------------------------------------------------------------------ + + FairLogger* logger = FairLogger::GetLogger(); + // define log file name + logger->SetLogFileName("MyLog.log"); + // log to screen and to file + logger->SetLogToScreen(kTRUE); + logger->SetLogToFile(kTRUE); + // Print very accurate output. Levels are LOW, MEDIUM and HIGH + logger->SetLogVerbosityLevel("HIGH"); + + // ----- Create simulation run ---------------------------------------- + FairRunSim* run = new FairRunSim(); + run->SetName(mcEngine); // Transport engine + run->SetIsMT(isMT); // Multi-threading mode (Geant4 only) + run->SetSink(new FairRootFileSink(outFile)); // Output file + FairRuntimeDb* rtdb = run->GetRuntimeDb(); + // ------------------------------------------------------------------------ + + run->SetWriteRunInfoFile(kFALSE); + // ----- Create media ------------------------------------------------- + run->SetMaterials("media.geo"); // Materials + // ------------------------------------------------------------------------ + + // ----- Create geometry ---------------------------------------------- + + FairModule* cave = new FairCave("CAVE"); + cave->SetGeometryFileName("cave_vacuum.geo"); + run->AddModule(cave); + + FairModule* target = new FairTarget("Target"); + target->SetGeometryFileName("target_rutherford.geo"); + run->AddModule(target); + + FairDetector* rutherford = new FairRutherford("RutherfordDetector", kTRUE); + rutherford->SetGeometryFileName("rutherford.geo"); + run->AddModule(rutherford); + // ------------------------------------------------------------------------ + + // ----- Create PrimaryGenerator -------------------------------------- + FairPrimaryGenerator* primGen = new FairPrimaryGenerator(); + run->SetGenerator(primGen); + + // Ion Generator + + FairIonGenerator* fIongen = new FairIonGenerator(2, 4, 2, 1, 0., 0., 1. / 20., 0., 0., -1.); + primGen->AddGenerator(fIongen); + + FairBoxGenerator* boxGen1 = new FairBoxGenerator(2212, 1); + boxGen1->SetPRange(.005, .005); + boxGen1->SetPhiRange(0., 0.); + boxGen1->SetThetaRange(0., 0.); + boxGen1->SetXYZ(0., 0., -3.); + primGen->AddGenerator(boxGen1); + + FairYPtGenerator* ypt = new FairYPtGenerator(); + // create and fill histogram with y-pT distribution + TH2D ypt_hist("ypt", "ypt;y;p_{T}", 100, -2, 2, 100, 0, 2); + ypt_hist.Fill(0.2, 0.2); + ypt_hist.Fill(0.2, 0.4); + ypt->SetYPt(ypt_hist); + ypt->SetMultiplicity(10); + ypt->SetPDGType(211); + // set vertex with gaussian distribution + ypt->SetVertex(0, 0, -2.5, 0.1, 0.1, 0.1, FairBaseMCGenerator::kGauss); + primGen->AddGenerator(ypt); + // ------------------------------------------------------------------------ + + run->SetStoreTraj(kTRUE); + + // ----- Run initialisation ------------------------------------------- + run->Init(); + // ------------------------------------------------------------------------ + + // Set cuts for storing the trajectories. + // Switch this on only if trajectories are stored. + // Choose this cuts according to your needs, but be aware + // that the file size of the output file depends on these cuts + + FairTrajFilter* trajFilter = FairTrajFilter::Instance(); + // trajFilter->SetStepSizeCut(0.01); // 1 cm + // trajFilter->SetVertexCut(-2000., -2000., 4., 2000., 2000., 100.); + // trajFilter->SetMomentumCutP(10e-3); // p_lab > 10 MeV + // trajFilter->SetEnergyCut(0., 1.02); // 0 < Etot < 1.04 GeV + trajFilter->SetStorePrimaries(kTRUE); + trajFilter->SetStoreSecondaries(kTRUE); + // ------------------------------------------------------------------------ + + // ----- Runtime database --------------------------------------------- + + Bool_t kParameterMerged = kTRUE; + FairParRootFileIo* parOut = new FairParRootFileIo(kParameterMerged); + parOut->open(parFile.Data()); + rtdb->setOutput(parOut); + rtdb->saveOutput(); + rtdb->print(); + // ------------------------------------------------------------------------ + + // ----- Start run ---------------------------------------------------- + run->Run(nEvents); + // ------------------------------------------------------------------------ + run->CreateGeometryFile(geoFile); + + // ----- Finish ------------------------------------------------------- + + cout << endl << endl; + + // Extract the maximal used memory an add is as Dart measurement + // This line is filtered by CTest and the value send to CDash + FairSystemInfo sysInfo; + Float_t maxMemory = sysInfo.GetMaxMemory(); + cout << ""; + cout << maxMemory; + cout << "" << endl; + + timer.Stop(); + Double_t rtime = timer.RealTime(); + Double_t ctime = timer.CpuTime(); + + Float_t cpuUsage = ctime / rtime; + cout << ""; + cout << cpuUsage; + cout << "" << endl; + + cout << endl << endl; + cout << "Output file is " << outFile << endl; + cout << "Parameter file is " << parFile << endl; + cout << "Real time " << rtime << " s, CPU time " << ctime << "s" << endl << endl; + cout << "Macro finished successfully." << endl; + + // ------------------------------------------------------------------------ } diff --git a/examples/simulation/rutherford/src/FairRutherford.cxx b/examples/simulation/rutherford/src/FairRutherford.cxx index 41afa5d16e..78619cd850 100644 --- a/examples/simulation/rutherford/src/FairRutherford.cxx +++ b/examples/simulation/rutherford/src/FairRutherford.cxx @@ -1,168 +1,167 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "FairRutherford.h" -#include "FairDetectorList.h" // for DetectorId::kFairRutherford -#include "FairRootManager.h" // for FairRootManager -#include "FairRutherfordGeo.h" // for FairRutherfordGeo -#include "FairRutherfordGeoPar.h" // for FairRutherfordGeoPar -#include "FairRutherfordPoint.h" // for FairRutherfordPoint -#include "FairStack.h" // for FairStack -#include "FairVolume.h" // for FairVolume +#include "FairDetectorList.h" // for DetectorId::kFairRutherford +#include "FairRootManager.h" // for FairRootManager +#include "FairRutherfordGeo.h" // for FairRutherfordGeo +#include "FairRutherfordGeoPar.h" // for FairRutherfordGeoPar +#include "FairRutherfordPoint.h" // for FairRutherfordPoint +#include "FairStack.h" // for FairStack +#include "FairVolume.h" // for FairVolume -#include // for TClonesArray -#include // for TVirtualMC -#include // for TVirtualMCStack +#include // for TClonesArray +#include // for TVirtualMC +#include // for TVirtualMCStack FairRutherfordGeo* FairRutherford::fgGeo = nullptr; FairRutherford::FairRutherford() - : FairDetector("FairRutherford", kTRUE, kFairRutherford), - fTrackID(-1), - fVolumeID(-1), - fPos(), - fMom(), - fTime(-1.), - fLength(-1.), - fELoss(-1), - fFairRutherfordPointCollection(new TClonesArray("FairRutherfordPoint")) -{ -} + : FairDetector("FairRutherford", kTRUE, kFairRutherford) + , fTrackID(-1) + , fVolumeID(-1) + , fPos() + , fMom() + , fTime(-1.) + , fLength(-1.) + , fELoss(-1) + , fFairRutherfordPointCollection(new TClonesArray("FairRutherfordPoint")) +{} FairRutherford::FairRutherford(const char* name, Bool_t active) - : FairDetector(name, active, kFairRutherford), - fTrackID(-1), - fVolumeID(-1), - fPos(), - fMom(), - fTime(-1.), - fLength(-1.), - fELoss(-1), - fFairRutherfordPointCollection(new TClonesArray("FairRutherfordPoint")) -{ -} + : FairDetector(name, active, kFairRutherford) + , fTrackID(-1) + , fVolumeID(-1) + , fPos() + , fMom() + , fTime(-1.) + , fLength(-1.) + , fELoss(-1) + , fFairRutherfordPointCollection(new TClonesArray("FairRutherfordPoint")) +{} FairRutherford::FairRutherford(const FairRutherford& rhs) - : FairDetector(rhs), - fTrackID(-1), - fVolumeID(-1), - fPos(), - fMom(), - fTime(-1.), - fLength(-1.), - fELoss(-1), - fFairRutherfordPointCollection(new TClonesArray("FairRutherfordPoint")) -{ -} + : FairDetector(rhs) + , fTrackID(-1) + , fVolumeID(-1) + , fPos() + , fMom() + , fTime(-1.) + , fLength(-1.) + , fELoss(-1) + , fFairRutherfordPointCollection(new TClonesArray("FairRutherfordPoint")) +{} FairRutherford::~FairRutherford() { - if (fFairRutherfordPointCollection) { - fFairRutherfordPointCollection->Delete(); - delete fFairRutherfordPointCollection; - } + if (fFairRutherfordPointCollection) { + fFairRutherfordPointCollection->Delete(); + delete fFairRutherfordPointCollection; + } } void FairRutherford::Initialize() { - FairDetector::Initialize(); -/* + FairDetector::Initialize(); + /* FairRuntimeDb* rtdb= FairRun::Instance()->GetRuntimeDb(); FairRutherfordGeoPar* par=(FairRutherfordGeoPar*)(rtdb->getContainer("FairRutherfordGeoPar")); */ } -Bool_t FairRutherford::ProcessHits(FairVolume* vol) +Bool_t FairRutherford::ProcessHits(FairVolume* vol) { - /** This method is called from the MC stepping */ - - //Set parameters at entrance of volume. Reset ELoss. - if ( TVirtualMC::GetMC()->IsTrackEntering() ) { - fELoss = 0.; - fTime = TVirtualMC::GetMC()->TrackTime() * 1.0e09; - fLength = TVirtualMC::GetMC()->TrackLength(); - TVirtualMC::GetMC()->TrackPosition(fPos); - TVirtualMC::GetMC()->TrackMomentum(fMom); - } - - // Sum energy loss for all steps in the active volume - fELoss += TVirtualMC::GetMC()->Edep(); - - // Create FairRutherfordPoint at exit of active volume - if ( TVirtualMC::GetMC()->IsTrackExiting() || - TVirtualMC::GetMC()->IsTrackStop() || - TVirtualMC::GetMC()->IsTrackDisappeared() ) { - fTrackID = TVirtualMC::GetMC()->GetStack()->GetCurrentTrackNumber(); - fVolumeID = vol->getMCid(); - if (fELoss == 0. ) { return kFALSE; } - AddHit(fTrackID, fVolumeID, TVector3(fPos.X(), fPos.Y(), fPos.Z()), - TVector3(fMom.Px(), fMom.Py(), fMom.Pz()), fTime, fLength, - fELoss); - - // Increment number of FairRutherford points in TParticle - FairStack* stack = static_cast(TVirtualMC::GetMC()->GetStack()); - stack->AddPoint(kFairRutherford); - } - - return kTRUE; + /** This method is called from the MC stepping */ + + // Set parameters at entrance of volume. Reset ELoss. + if (TVirtualMC::GetMC()->IsTrackEntering()) { + fELoss = 0.; + fTime = TVirtualMC::GetMC()->TrackTime() * 1.0e09; + fLength = TVirtualMC::GetMC()->TrackLength(); + TVirtualMC::GetMC()->TrackPosition(fPos); + TVirtualMC::GetMC()->TrackMomentum(fMom); + } + + // Sum energy loss for all steps in the active volume + fELoss += TVirtualMC::GetMC()->Edep(); + + // Create FairRutherfordPoint at exit of active volume + if (TVirtualMC::GetMC()->IsTrackExiting() || TVirtualMC::GetMC()->IsTrackStop() + || TVirtualMC::GetMC()->IsTrackDisappeared()) { + fTrackID = TVirtualMC::GetMC()->GetStack()->GetCurrentTrackNumber(); + fVolumeID = vol->getMCid(); + if (fELoss == 0.) { + return kFALSE; + } + AddHit(fTrackID, + fVolumeID, + TVector3(fPos.X(), fPos.Y(), fPos.Z()), + TVector3(fMom.Px(), fMom.Py(), fMom.Pz()), + fTime, + fLength, + fELoss); + + // Increment number of FairRutherford points in TParticle + FairStack* stack = static_cast(TVirtualMC::GetMC()->GetStack()); + stack->AddPoint(kFairRutherford); + } + + return kTRUE; } -void FairRutherford::EndOfEvent() -{ - fFairRutherfordPointCollection->Clear(); -} +void FairRutherford::EndOfEvent() { fFairRutherfordPointCollection->Clear(); } void FairRutherford::Register() { - /** This will create a branch in the output tree called + /** This will create a branch in the output tree called FairRutherfordPoint, 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("FairRutherfordPoint", "FairRutherford", - fFairRutherfordPointCollection, kTRUE); + FairRootManager::Instance()->Register( + "FairRutherfordPoint", "FairRutherford", fFairRutherfordPointCollection, kTRUE); } TClonesArray* FairRutherford::GetCollection(Int_t iColl) const { - if (iColl == 0) { return fFairRutherfordPointCollection; } - else { return nullptr; } + if (iColl == 0) { + return fFairRutherfordPointCollection; + } else { + return nullptr; + } } -void FairRutherford::Reset() -{ - fFairRutherfordPointCollection->Clear(); -} +void FairRutherford::Reset() { fFairRutherfordPointCollection->Clear(); } void FairRutherford::ConstructGeometry() { - /** If you are using the standard ASCII input for 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. */ ConstructASCIIGeometry(fgGeo, "FairRutherfordGeoPar"); } -FairRutherfordPoint* FairRutherford::AddHit(Int_t trackID, Int_t detID, - TVector3 pos, TVector3 mom, - Double_t time, Double_t length, - Double_t eLoss) +FairRutherfordPoint* FairRutherford::AddHit(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t time, + Double_t length, + Double_t eLoss) { - TClonesArray& clref = *fFairRutherfordPointCollection; - Int_t size = clref.GetEntriesFast(); - return new(clref[size]) FairRutherfordPoint(trackID, detID, pos, mom, - time, length, eLoss, pos.Mag(), pos.Phi(), pos.Theta()); + TClonesArray& clref = *fFairRutherfordPointCollection; + Int_t size = clref.GetEntriesFast(); + return new (clref[size]) + FairRutherfordPoint(trackID, detID, pos, mom, time, length, eLoss, pos.Mag(), pos.Phi(), pos.Theta()); } -FairModule* FairRutherford::CloneModule() const -{ - return new FairRutherford(*this); -} +FairModule* FairRutherford::CloneModule() const { return new FairRutherford(*this); } -ClassImp(FairRutherford) +ClassImp(FairRutherford); diff --git a/examples/simulation/rutherford/src/FairRutherford.h b/examples/simulation/rutherford/src/FairRutherford.h index 50b1c4971d..dd2e52aa1d 100644 --- a/examples/simulation/rutherford/src/FairRutherford.h +++ b/examples/simulation/rutherford/src/FairRutherford.h @@ -1,18 +1,18 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef CBMRUTHERFORD_H #define CBMRUTHERFORD_H -#include "FairDetector.h" // for FairDetector +#include "FairDetector.h" // for FairDetector -#include // for Int_t, Double32_t, Double_t, etc -#include // for TLorentzVector -#include // for TVector3 +#include // for Int_t, Double32_t, Double_t, etc +#include // for TLorentzVector +#include // for TVector3 class FairRutherfordPoint; class FairRutherfordGeo; @@ -20,13 +20,13 @@ class FairVolume; class TClonesArray; class FairModule; -class FairRutherford: public FairDetector +class FairRutherford : public FairDetector { public: /** Name : Detector Name * Active: kTRUE for active detectors (ProcessHits() will be called) * kFALSE for inactive detectors - */ + */ FairRutherford(const char* Name, Bool_t Active); /** default constructor */ @@ -36,39 +36,37 @@ class FairRutherford: public FairDetector virtual ~FairRutherford(); /** 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(); /** This method is an example of how to add your own point * of type FairRutherfordPoint to the clones array - */ - FairRutherfordPoint* AddHit(Int_t trackID, Int_t detID, - TVector3 pos, TVector3 mom, - Double_t time, Double_t length, - Double_t eLoss); + */ + FairRutherfordPoint* + AddHit(Int_t trackID, Int_t detID, TVector3 pos, TVector3 mom, Double_t time, Double_t length, Double_t eLoss); /** 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 CopyClones( TClonesArray* cl1, TClonesArray* cl2 , + // Int_t offset) {;} virtual void SetSpecialPhysicsCuts() {} virtual void EndOfEvent(); virtual void FinishPrimary() {} @@ -83,25 +81,25 @@ class FairRutherford: public FairDetector private: static FairRutherfordGeo* fgGeo; //! - /** Track information to be stored until the track leaves the + /** 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* fFairRutherfordPointCollection; + TClonesArray* fFairRutherfordPointCollection; FairRutherford(const FairRutherford&); FairRutherford& operator=(const FairRutherford&); - ClassDef(FairRutherford,1) + ClassDef(FairRutherford, 1) }; -#endif //CBMRUTHERFORD_H +#endif // CBMRUTHERFORD_H diff --git a/examples/simulation/rutherford/src/FairRutherfordContFact.cxx b/examples/simulation/rutherford/src/FairRutherfordContFact.cxx index c0cd660a70..31bb600a51 100644 --- a/examples/simulation/rutherford/src/FairRutherfordContFact.cxx +++ b/examples/simulation/rutherford/src/FairRutherfordContFact.cxx @@ -1,63 +1,60 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "FairRutherfordContFact.h" -#include "FairRuntimeDb.h" // for FairRuntimeDb -#include "FairRutherfordGeoPar.h" // for FairRutherfordGeoPar +#include "FairRuntimeDb.h" // for FairRuntimeDb +#include "FairRutherfordGeoPar.h" // for FairRutherfordGeoPar -#include // for TList -#include // for TString - -#include // for strcmp +#include // for TList +#include // for TString +#include // for strcmp class FairParSet; -ClassImp(FairRutherfordContFact) +ClassImp(FairRutherfordContFact); static FairRutherfordContFact gFairRutherfordContFact; FairRutherfordContFact::FairRutherfordContFact() - : FairContFact() + : FairContFact() { - /** Constructor (called when the library is loaded) */ - fName="FairRutherfordContFact"; - fTitle="Factory for parameter containers in libFairRutherford"; - setAllContainers(); - FairRuntimeDb::instance()->addContFactory(this); + /** Constructor (called when the library is loaded) */ + fName = "FairRutherfordContFact"; + fTitle = "Factory for parameter containers in libFairRutherford"; + setAllContainers(); + FairRuntimeDb::instance()->addContFactory(this); } void FairRutherfordContFact::setAllContainers() { - /** Creates the Container objects with all accepted + /** Creates the Container objects with all accepted contexts and adds them to the list of containers for the FairRutherford library. */ - FairContainer* p= new FairContainer("FairRutherfordGeoPar", - "FairRutherford Geometry Parameters", - "TestDefaultContext"); - p->addContext("TestNonDefaultContext"); + FairContainer* p = + new FairContainer("FairRutherfordGeoPar", "FairRutherford Geometry Parameters", "TestDefaultContext"); + p->addContext("TestNonDefaultContext"); - containers->Add(p); + containers->Add(p); } FairParSet* FairRutherfordContFact::createContainer(FairContainer* c) { - /** Calls the constructor of the corresponding parameter container. + /** 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=nullptr; - if (strcmp(name,"FairRutherfordGeoPar")==0) { - p=new FairRutherfordGeoPar(c->getConcatName().Data(), - c->GetTitle(),c->getContext()); - } - return p; + const char* name = c->GetName(); + FairParSet* p = nullptr; + if (strcmp(name, "FairRutherfordGeoPar") == 0) { + p = new FairRutherfordGeoPar(c->getConcatName().Data(), c->GetTitle(), c->getContext()); + } + return p; } diff --git a/examples/simulation/rutherford/src/FairRutherfordContFact.h b/examples/simulation/rutherford/src/FairRutherfordContFact.h index 8335521cca..0d6d54f974 100644 --- a/examples/simulation/rutherford/src/FairRutherfordContFact.h +++ b/examples/simulation/rutherford/src/FairRutherfordContFact.h @@ -1,16 +1,16 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef CBMRUTHERFORDCONTFACT_H #define CBMRUTHERFORDCONTFACT_H -#include "FairContFact.h" // for FairContFact, etc +#include "FairContFact.h" // for FairContFact, etc -#include // for ClassDef +#include // for ClassDef class FairParSet; @@ -18,11 +18,12 @@ class FairRutherfordContFact : public FairContFact { private: void setAllContainers(); + public: FairRutherfordContFact(); ~FairRutherfordContFact() {} FairParSet* createContainer(FairContainer*); - ClassDef( FairRutherfordContFact,0) // Factory for all FairRutherford parameter containers + ClassDef(FairRutherfordContFact, 0) // Factory for all FairRutherford parameter containers }; #endif diff --git a/examples/simulation/rutherford/src/FairRutherfordGeo.cxx b/examples/simulation/rutherford/src/FairRutherfordGeo.cxx index 4343f09c31..552e937ce5 100644 --- a/examples/simulation/rutherford/src/FairRutherfordGeo.cxx +++ b/examples/simulation/rutherford/src/FairRutherfordGeo.cxx @@ -1,39 +1,39 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "FairRutherfordGeo.h" -#include // for sprintf +#include // for sprintf -ClassImp(FairRutherfordGeo) +ClassImp(FairRutherfordGeo); FairRutherfordGeo::FairRutherfordGeo() - : FairGeoSet() + : FairGeoSet() { - // Constructor - fName="rutherford"; - maxSectors=0; - maxModules=10; + // Constructor + fName = "rutherford"; + maxSectors = 0; + maxModules = 10; } const char* FairRutherfordGeo::getModuleName(Int_t m) { - /** Returns the module name of FairRutherford number m + /** Returns the module name of FairRutherford number m Setting MyDet here means that all modules names in the ASCII file should start with FairRutherford otherwise they will not be constructed */ - sprintf(modName,"rutherford%i",m+1); - return modName; + sprintf(modName, "rutherford%i", m + 1); + return modName; } const char* FairRutherfordGeo::getEleName(Int_t m) { - /** Returns the element name of Det number m */ - sprintf(eleName,"rutherford%i",m+1); - return eleName; + /** Returns the element name of Det number m */ + sprintf(eleName, "rutherford%i", m + 1); + return eleName; } diff --git a/examples/simulation/rutherford/src/FairRutherfordGeo.h b/examples/simulation/rutherford/src/FairRutherfordGeo.h index d654e47afd..3d34c0b9fb 100644 --- a/examples/simulation/rutherford/src/FairRutherfordGeo.h +++ b/examples/simulation/rutherford/src/FairRutherfordGeo.h @@ -1,42 +1,41 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef CBMRUTHERFORDGEO_H #define CBMRUTHERFORDGEO_H -#include "FairGeoSet.h" // for FairGeoSet +#include "FairGeoSet.h" // for FairGeoSet -#include // for Int_t, etc +#include // for Int_t, etc +#include // for TString -#include // for TString - -class FairRutherfordGeo : public FairGeoSet +class FairRutherfordGeo : public FairGeoSet { protected: - char modName[20]; // name of module - char eleName[20]; // substring for elements in module + char modName[20]; // name of module + char eleName[20]; // substring for elements in module public: FairRutherfordGeo(); ~FairRutherfordGeo() {} const char* getModuleName(Int_t); const char* getEleName(Int_t); inline Int_t getModNumInMod(const TString&); - ClassDef(FairRutherfordGeo,1) + ClassDef(FairRutherfordGeo, 1) }; inline Int_t FairRutherfordGeo::getModNumInMod(const TString& name) { - /** returns the module index from module name + /** returns the module index from module name ?? in name[??] has to be the length of the detector name in the .geo file. For example if all nodes in this file starts with newdetector ?? has to be 11. */ - return static_cast((name[10]-'0')-1); // + return static_cast((name[10] - '0') - 1); // } #endif diff --git a/examples/simulation/rutherford/src/FairRutherfordGeoPar.cxx b/examples/simulation/rutherford/src/FairRutherfordGeoPar.cxx index 8db0dfae99..5daf3be36a 100644 --- a/examples/simulation/rutherford/src/FairRutherfordGeoPar.cxx +++ b/examples/simulation/rutherford/src/FairRutherfordGeoPar.cxx @@ -1,48 +1,51 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "FairRutherfordGeoPar.h" -#include "FairParamList.h" // for FairParamList +#include "FairParamList.h" // for FairParamList -#include // for TObjArray +#include // for TObjArray -ClassImp(FairRutherfordGeoPar) +ClassImp(FairRutherfordGeoPar); -FairRutherfordGeoPar ::FairRutherfordGeoPar(const char* name, - const char* title, - const char* context) - : FairParGenericSet(name,title,context), - fGeoSensNodes(new TObjArray()), - fGeoPassNodes(new TObjArray()) -{ -} +FairRutherfordGeoPar ::FairRutherfordGeoPar(const char* name, const char* title, const char* context) + : FairParGenericSet(name, title, context) + , fGeoSensNodes(new TObjArray()) + , fGeoPassNodes(new TObjArray()) +{} -FairRutherfordGeoPar::~FairRutherfordGeoPar(void) -{ -} +FairRutherfordGeoPar::~FairRutherfordGeoPar(void) {} void FairRutherfordGeoPar::clear(void) { - delete fGeoSensNodes; - delete fGeoPassNodes; + delete fGeoSensNodes; + delete fGeoPassNodes; } void FairRutherfordGeoPar::putParams(FairParamList* l) { - if (!l) { return; } - l->addObject("FairGeoNodes Sensitive List", fGeoSensNodes); - l->addObject("FairGeoNodes Passive List", fGeoPassNodes); + if (!l) { + return; + } + l->addObject("FairGeoNodes Sensitive List", fGeoSensNodes); + l->addObject("FairGeoNodes Passive List", fGeoPassNodes); } Bool_t FairRutherfordGeoPar::getParams(FairParamList* l) { - if (!l) { return kFALSE; } - if (!l->fillObject("FairGeoNodes Sensitive List", fGeoSensNodes)) { return kFALSE; } - if (!l->fillObject("FairGeoNodes Passive List", fGeoPassNodes)) { return kFALSE; } - return kTRUE; + if (!l) { + return kFALSE; + } + if (!l->fillObject("FairGeoNodes Sensitive List", fGeoSensNodes)) { + return kFALSE; + } + if (!l->fillObject("FairGeoNodes Passive List", fGeoPassNodes)) { + return kFALSE; + } + return kTRUE; } diff --git a/examples/simulation/rutherford/src/FairRutherfordGeoPar.h b/examples/simulation/rutherford/src/FairRutherfordGeoPar.h index e34ad4040f..9f3fd0540a 100644 --- a/examples/simulation/rutherford/src/FairRutherfordGeoPar.h +++ b/examples/simulation/rutherford/src/FairRutherfordGeoPar.h @@ -1,45 +1,44 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef CBMRUTHERFORDGEOPAR_H #define CBMRUTHERFORDGEOPAR_H -#include "FairParGenericSet.h" // for FairParGenericSet +#include "FairParGenericSet.h" // for FairParGenericSet -#include // for FairRutherfordGeoPar::Class, etc +#include // for FairRutherfordGeoPar::Class, etc class TObjArray; class FairParamList; -class FairRutherfordGeoPar : public FairParGenericSet +class FairRutherfordGeoPar : public FairParGenericSet { public: - /** List of FairGeoNodes for sensitive volumes */ - TObjArray* fGeoSensNodes; + TObjArray* fGeoSensNodes; /** List of FairGeoNodes for sensitive volumes */ - TObjArray* fGeoPassNodes; + TObjArray* fGeoPassNodes; - FairRutherfordGeoPar(const char* name="FairRutherfordGeoPar", - const char* title="FairRutherford Geometry Parameters", - const char* context="TestDefaultContext"); + FairRutherfordGeoPar(const char* name = "FairRutherfordGeoPar", + const char* title = "FairRutherford Geometry Parameters", + const char* context = "TestDefaultContext"); ~FairRutherfordGeoPar(void); void clear(void); void putParams(FairParamList*); Bool_t getParams(FairParamList*); - TObjArray* GetGeoSensitiveNodes() {return fGeoSensNodes;} - TObjArray* GetGeoPassiveNodes() {return fGeoPassNodes;} + TObjArray* GetGeoSensitiveNodes() { return fGeoSensNodes; } + TObjArray* GetGeoPassiveNodes() { return fGeoPassNodes; } private: FairRutherfordGeoPar(const FairRutherfordGeoPar&); FairRutherfordGeoPar& operator=(const FairRutherfordGeoPar&); - ClassDef(FairRutherfordGeoPar,1) + ClassDef(FairRutherfordGeoPar, 1) }; #endif diff --git a/examples/simulation/rutherford/src/FairRutherfordPoint.cxx b/examples/simulation/rutherford/src/FairRutherfordPoint.cxx index 8bcc5436ab..c1e22be2de 100644 --- a/examples/simulation/rutherford/src/FairRutherfordPoint.cxx +++ b/examples/simulation/rutherford/src/FairRutherfordPoint.cxx @@ -1,51 +1,50 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "FairRutherfordPoint.h" -#include // for operator<<, basic_ostream, etc +#include // for operator<<, basic_ostream, etc using std::cout; using std::endl; FairRutherfordPoint::FairRutherfordPoint() - : FairMCPoint(), - fRadius(0.), - fPhi(0.), - fTheta(0.) -{ -} + : FairMCPoint() + , fRadius(0.) + , fPhi(0.) + , fTheta(0.) +{} -FairRutherfordPoint::FairRutherfordPoint(Int_t trackID, Int_t detID, - TVector3 pos, TVector3 mom, - Double_t tof, Double_t length, - Double_t eLoss, Double_t radius, - Double_t phi, Double_t theta) - : FairMCPoint(trackID, detID, pos, mom, tof, length, eLoss), - fRadius(radius), - fPhi(phi), - fTheta(theta) -{ -} +FairRutherfordPoint::FairRutherfordPoint(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t tof, + Double_t length, + Double_t eLoss, + Double_t radius, + Double_t phi, + Double_t theta) + : FairMCPoint(trackID, detID, pos, mom, tof, length, eLoss) + , fRadius(radius) + , fPhi(phi) + , fTheta(theta) +{} -FairRutherfordPoint::~FairRutherfordPoint() -{ -} +FairRutherfordPoint::~FairRutherfordPoint() {} void FairRutherfordPoint::Print(const Option_t* /*opt*/) const { - cout << "-I- FairRutherfordPoint: FairRutherford 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- FairRutherfordPoint: FairRutherford 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; } -ClassImp(FairRutherfordPoint) +ClassImp(FairRutherfordPoint); diff --git a/examples/simulation/rutherford/src/FairRutherfordPoint.h b/examples/simulation/rutherford/src/FairRutherfordPoint.h index c45eb6f8cd..45dec50548 100644 --- a/examples/simulation/rutherford/src/FairRutherfordPoint.h +++ b/examples/simulation/rutherford/src/FairRutherfordPoint.h @@ -1,27 +1,25 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef CBMRUTHERFORDPOINT_H #define CBMRUTHERFORDPOINT_H 1 -#include "FairMCPoint.h" // for FairMCPoint +#include "FairMCPoint.h" // for FairMCPoint -#include // for Double_t, Double32_t, etc -#include // for TVector3 +#include // for Double_t, Double32_t, etc +#include // for TVector3 class FairRutherfordPoint : public FairMCPoint { public: - /** Default constructor **/ FairRutherfordPoint(); - /** Constructor with arguments *@param trackID Index of MCTrack *@param detID Detector ID @@ -31,12 +29,16 @@ class FairRutherfordPoint : public FairMCPoint *@param length Track length since creation [cm] *@param eLoss Energy deposit [GeV] **/ - FairRutherfordPoint(Int_t trackID, Int_t detID, TVector3 pos, TVector3 mom, - Double_t tof, Double_t length, Double_t eLoss, - Double_t radius, Double_t phi, Double_t theta); - - - + FairRutherfordPoint(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t tof, + Double_t length, + Double_t eLoss, + Double_t radius, + Double_t phi, + Double_t theta); /** Destructor **/ virtual ~FairRutherfordPoint(); @@ -45,15 +47,13 @@ class FairRutherfordPoint : public FairMCPoint virtual void Print(const Option_t* opt) const; private: - Double32_t fRadius, fPhi, fTheta; /** Copy constructor **/ FairRutherfordPoint(const FairRutherfordPoint& point); FairRutherfordPoint operator=(const FairRutherfordPoint& point); - ClassDef(FairRutherfordPoint,1) - + ClassDef(FairRutherfordPoint, 1) }; #endif diff --git a/fairtools/FairLogger.cxx b/fairtools/FairLogger.cxx index 266fafc081..28210ce18e 100644 --- a/fairtools/FairLogger.cxx +++ b/fairtools/FairLogger.cxx @@ -1,24 +1,23 @@ /******************************************************************************** -* 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" * -********************************************************************************/ + * 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" * + ********************************************************************************/ /* -* FairLogger.cxx -* -* Created on: Mar 03, 2011 -* Author: f.uhlig -*/ + * FairLogger.cxx + * + * Created on: Mar 03, 2011 + * Author: f.uhlig + */ #include "FairLogger.h" -#include // for TString, operator==, etc -#include // for gSystem, TSystem - -#include // for fclose, freopen, remove, etc -#include // for cout, cerr +#include // for TString, operator==, etc +#include // for gSystem, TSystem +#include // for cout, cerr +#include // for fclose, freopen, remove, etc FairLogger* FairLogger::instance = nullptr; @@ -39,8 +38,7 @@ FairLogger::FairLogger() FairLogger* FairLogger::GetLogger() { - if (!instance) - { + if (!instance) { instance = new FairLogger(); } @@ -57,8 +55,7 @@ void FairLogger::Fatal(const char* file, const char* line, const char* func, con void FairLogger::Error(const char* file, const char* line, const char* func, const char* format, ...) { - if (IsLogNeeded(fair::Severity::error)) - { + if (IsLogNeeded(fair::Severity::error)) { va_list ap; va_start(ap, format); Log(fair::Severity::error, file, line, func, format, ap); @@ -68,8 +65,7 @@ void FairLogger::Error(const char* file, const char* line, const char* func, con void FairLogger::Warning(const char* file, const char* line, const char* func, const char* format, ...) { - if (IsLogNeeded(fair::Severity::warning)) - { + if (IsLogNeeded(fair::Severity::warning)) { va_list ap; va_start(ap, format); Log(fair::Severity::warning, file, line, func, format, ap); @@ -79,8 +75,7 @@ void FairLogger::Warning(const char* file, const char* line, const char* func, c void FairLogger::Info(const char* file, const char* line, const char* func, const char* format, ...) { - if (IsLogNeeded(fair::Severity::info)) - { + if (IsLogNeeded(fair::Severity::info)) { va_list ap; va_start(ap, format); Log(fair::Severity::info, file, line, func, format, ap); @@ -90,8 +85,7 @@ void FairLogger::Info(const char* file, const char* line, const char* func, cons void FairLogger::Debug(const char* file, const char* line, const char* func, const char* format, ...) { - if (IsLogNeeded(fair::Severity::debug)) - { + if (IsLogNeeded(fair::Severity::debug)) { va_list ap; va_start(ap, format); Log(fair::Severity::debug, file, line, func, format, ap); @@ -101,8 +95,7 @@ void FairLogger::Debug(const char* file, const char* line, const char* func, con void FairLogger::Debug1(const char* file, const char* line, const char* func, const char* format, ...) { - if (IsLogNeeded(fair::Severity::debug1)) - { + if (IsLogNeeded(fair::Severity::debug1)) { va_list ap; va_start(ap, format); Log(fair::Severity::debug1, file, line, func, format, ap); @@ -112,8 +105,7 @@ void FairLogger::Debug1(const char* file, const char* line, const char* func, co void FairLogger::Debug2(const char* file, const char* line, const char* func, const char* format, ...) { - if (IsLogNeeded(fair::Severity::debug2)) - { + if (IsLogNeeded(fair::Severity::debug2)) { va_list ap; va_start(ap, format); Log(fair::Severity::debug2, file, line, func, format, ap); @@ -123,8 +115,7 @@ void FairLogger::Debug2(const char* file, const char* line, const char* func, co void FairLogger::Debug3(const char* file, const char* line, const char* func, const char* format, ...) { - if (IsLogNeeded(fair::Severity::debug3)) - { + if (IsLogNeeded(fair::Severity::debug3)) { va_list ap; va_start(ap, format); Log(fair::Severity::debug3, file, line, func, format, ap); @@ -134,8 +125,7 @@ void FairLogger::Debug3(const char* file, const char* line, const char* func, co void FairLogger::Debug4(const char* file, const char* line, const char* func, const char* format, ...) { - if (IsLogNeeded(fair::Severity::debug4)) - { + if (IsLogNeeded(fair::Severity::debug4)) { va_list ap; va_start(ap, format); Log(fair::Severity::debug4, file, line, func, format, ap); @@ -143,7 +133,12 @@ void FairLogger::Debug4(const char* file, const char* line, const char* func, co } } -void FairLogger::Log(fair::Severity severity, const char* file, const char* line, const char* func, const char* format, va_list arglist) +void FairLogger::Log(fair::Severity severity, + const char* file, + const char* line, + const char* func, + const char* format, + va_list arglist) { // If the format string together with the argument list was used once it can't // be used another time. Don't know why but if we do so the arguments are not @@ -152,8 +147,7 @@ void FairLogger::Log(fair::Severity severity, const char* file, const char* line // To vercome the problem the output is written to a buffer which then can be // used several times. - while (true) - { + while (true) { fBufferSizeNeeded = vsnprintf(fBufferPointer, fBufferSize, format, arglist); // Try to vsnprintf into our buffer. @@ -177,15 +171,9 @@ void FairLogger::Log(fair::Severity severity, const char* file, const char* line } } -bool FairLogger::IsLogNeeded(fair::Severity severity) -{ - return fair::Logger::Logging(severity); -} +bool FairLogger::IsLogNeeded(fair::Severity severity) { return fair::Logger::Logging(severity); } -bool FairLogger::IsLogNeeded(FairLogLevel level) -{ - return fair::Logger::Logging(ConvertLogLevelToString(level)); -} +bool FairLogger::IsLogNeeded(FairLogLevel level) { return fair::Logger::Logging(ConvertLogLevelToString(level)); } void FairLogger::LogFatalMessage() { @@ -196,16 +184,14 @@ void FairLogger::LogFatalMessage() // Fatal also indicates a problem which is so severe that the process should // not go on, so the process is aborted. - if (gSystem) - { + if (gSystem) { TString corefile = "core_dump_"; int pid = gSystem->GetPid(); corefile += pid; std::cerr << "For later analysis we write a core dump to " << corefile << std::endl; - if (freopen(corefile, "w", stderr)) - { + if (freopen(corefile, "w", stderr)) { gSystem->StackTrace(); fclose(stderr); } @@ -214,4 +200,4 @@ void FairLogger::LogFatalMessage() throw fair::FatalException("Fatal error occured. Exiting..."); } -ClassImp(FairLogger) +ClassImp(FairLogger); diff --git a/fairtools/FairLogger.h b/fairtools/FairLogger.h index 7b5c9c63cb..3edcbe7721 100644 --- a/fairtools/FairLogger.h +++ b/fairtools/FairLogger.h @@ -15,13 +15,11 @@ #ifndef BASE_FAIRLOGGER_H_ #define BASE_FAIRLOGGER_H_ +#include // for bool, FairLogger::Class, etc #include - -#include // for bool, FairLogger::Class, etc - -#include // for va_list -#include // for operator<< -#include // for vector +#include // for va_list +#include // for operator<< +#include // for vector #define MESSAGE_ORIGIN __FILE__, CONVERTTOSTRING(__LINE__), __FUNCTION__ @@ -40,17 +38,8 @@ enum FairLogLevel }; // backwards-compatibility with older FairLogger calls, TODO: delete me as soon as possible -static const char* const LogLevelString[] = { - "FATAL", - "ERROR", - "WARNING", - "INFO", - "DEBUG", - "DEBUG1", - "DEBUG2", - "DEBUG3", - "DEBUG4" -}; +static const char* const LogLevelString[] = + {"FATAL", "ERROR", "WARNING", "INFO", "DEBUG", "DEBUG1", "DEBUG2", "DEBUG3", "DEBUG4"}; class FairLogger { @@ -59,12 +48,9 @@ class FairLogger void SetLogToScreen(bool enabled) { - if (enabled) - { + if (enabled) { fair::Logger::SetConsoleSeverity(fConsoleSeverity); - } - else - { + } else { fair::Logger::SetConsoleSeverity(fair::Severity::fatal); } } @@ -77,12 +63,9 @@ class FairLogger void SetLogToFile(bool enabled) { - if (enabled) - { + if (enabled) { fair::Logger::SetFileSeverity(fLogFileSeverity); - } - else - { + } else { fair::Logger::SetFileSeverity(fair::Severity::fatal); } } @@ -99,35 +82,40 @@ class FairLogger OpenLogFile(); } - void SetColoredLog(bool enabled) - { - fair::Logger::SetConsoleColor(enabled); - } + void SetColoredLog(bool enabled) { fair::Logger::SetConsoleColor(enabled); } - void SetLogVerbosityLevel(const char* verbosity) - { - fair::Logger::SetVerbosity(verbosity); - } + void SetLogVerbosityLevel(const char* verbosity) { fair::Logger::SetVerbosity(verbosity); } bool IsLogNeeded(fair::Severity severity); - bool IsLogNeeded(FairLogLevel level) __attribute__((deprecated("Use 'IsLogNeeded(fair::Severity severity)' or 'fair::Logger::Logging(const fair::Severity severity)' or 'fair::Logger::Logging(const std::string& severityStr)'"))); - - void Fatal (const char* file, const char* line, const char* func, const char* format, ...) __attribute__((deprecated("Use 'LOG(fatal) << content;' macro interface instead."))); - void Error (const char* file, const char* line, const char* func, const char* format, ...) __attribute__((deprecated("Use 'LOG(error) << content;' macro interface instead."))); - void Warning(const char* file, const char* line, const char* func, const char* format, ...) __attribute__((deprecated("Use 'LOG(warn) << content;' macro interface instead."))); - void Info (const char* file, const char* line, const char* func, const char* format, ...) __attribute__((deprecated("Use 'LOG(info) << content;' macro interface instead."))); - void Debug (const char* file, const char* line, const char* func, const char* format, ...) __attribute__((deprecated("Use 'LOG(debug) << content;' macro interface instead."))); - void Debug1 (const char* file, const char* line, const char* func, const char* format, ...) __attribute__((deprecated("Use 'LOG(debug1) << content;' macro interface instead."))); - void Debug2 (const char* file, const char* line, const char* func, const char* format, ...) __attribute__((deprecated("Use 'LOG(debug2) << content;' macro interface instead."))); - void Debug3 (const char* file, const char* line, const char* func, const char* format, ...) __attribute__((deprecated("Use 'LOG(debug3) << content;' macro interface instead."))); - void Debug4 (const char* file, const char* line, const char* func, const char* format, ...) __attribute__((deprecated("Use 'LOG(debug4) << content;' macro interface instead."))); - - static char const endl __attribute__((deprecated("Line break is now added automatically by the LOG macro, this variable only adds empty space."))); - static char const flush __attribute__((deprecated("Data is now flushed automatically by the LOG macro, this variable only adds empty space."))); - - void SetScreenStreamToCerr(bool /* useCerr */) - { - } + bool IsLogNeeded(FairLogLevel level) __attribute__(( + deprecated("Use 'IsLogNeeded(fair::Severity severity)' or 'fair::Logger::Logging(const fair::Severity " + "severity)' or 'fair::Logger::Logging(const std::string& severityStr)'"))); + + void Fatal(const char* file, const char* line, const char* func, const char* format, ...) + __attribute__((deprecated("Use 'LOG(fatal) << content;' macro interface instead."))); + void Error(const char* file, const char* line, const char* func, const char* format, ...) + __attribute__((deprecated("Use 'LOG(error) << content;' macro interface instead."))); + void Warning(const char* file, const char* line, const char* func, const char* format, ...) + __attribute__((deprecated("Use 'LOG(warn) << content;' macro interface instead."))); + void Info(const char* file, const char* line, const char* func, const char* format, ...) + __attribute__((deprecated("Use 'LOG(info) << content;' macro interface instead."))); + void Debug(const char* file, const char* line, const char* func, const char* format, ...) + __attribute__((deprecated("Use 'LOG(debug) << content;' macro interface instead."))); + void Debug1(const char* file, const char* line, const char* func, const char* format, ...) + __attribute__((deprecated("Use 'LOG(debug1) << content;' macro interface instead."))); + void Debug2(const char* file, const char* line, const char* func, const char* format, ...) + __attribute__((deprecated("Use 'LOG(debug2) << content;' macro interface instead."))); + void Debug3(const char* file, const char* line, const char* func, const char* format, ...) + __attribute__((deprecated("Use 'LOG(debug3) << content;' macro interface instead."))); + void Debug4(const char* file, const char* line, const char* func, const char* format, ...) + __attribute__((deprecated("Use 'LOG(debug4) << content;' macro interface instead."))); + + static char const endl __attribute__(( + deprecated("Line break is now added automatically by the LOG macro, this variable only adds empty space."))); + static char const flush __attribute__(( + deprecated("Data is now flushed automatically by the LOG macro, this variable only adds empty space."))); + + void SetScreenStreamToCerr(bool /* useCerr */) {} private: static FairLogger* instance; @@ -138,21 +126,20 @@ class FairLogger ~FairLogger() {} - void Log(fair::Severity level, const char* file, const char* line, const char*, const char* format, va_list arglist); + void Log(fair::Severity level, + const char* file, + const char* line, + const char*, + const char* format, + va_list arglist); const char* ConvertLogLevelToString(FairLogLevel level) const { return LogLevelString[level]; } static void LogFatalMessage(); - void OpenLogFile() - { - fair::Logger::InitFileSink(fLogFileSeverity, fLogFileName, false); - } + void OpenLogFile() { fair::Logger::InitFileSink(fLogFileSeverity, fLogFileName, false); } - void CloseLogFile() - { - fair::Logger::RemoveFileSink(); - } + void CloseLogFile() { fair::Logger::RemoveFileSink(); } std::string fLogFileName; std::string fLogFileSeverity; @@ -168,4 +155,4 @@ class FairLogger #define gLogger (FairLogger::GetLogger()) -#endif // BASE_FAIRLOGGER_H_ +#endif // BASE_FAIRLOGGER_H_ diff --git a/fairtools/FairMonitor.cxx b/fairtools/FairMonitor.cxx index 5d610caa07..d9080ef8ec 100644 --- a/fairtools/FairMonitor.cxx +++ b/fairtools/FairMonitor.cxx @@ -13,6 +13,7 @@ */ #include "FairMonitor.h" + #include "FairLogger.h" #include "FairSystemInfo.h" @@ -20,615 +21,655 @@ #include #include #include +#include #include +#include #include #include #include +#include #include +#include #include #include #include -#include #include #include -#include -#include -#include - #include FairMonitor* FairMonitor::instance = nullptr; FairMonitor::FairMonitor() - : TNamed("FairMonitor","Monitor for FairRoot") - , fRunMonitor(kFALSE) - , fDrawCanvas(kFALSE) - , fRunTime(0.) - , fRunMem(0.) - , fTimerMap() - , fMemoryMap() - , fHistList(new TList()) - , fCanvas() - , fNoTaskRequired(0) - , fNoTaskCreated(0) - , fCurrentTask(0) - , fTaskRequired() - , fTaskCreated() - , fTaskCreatedTemp() - , fObjectMap() - , fTaskMap() - , fObjectPos() - , fTaskPos() -{ -} - -FairMonitor::~FairMonitor() -{ -} + : TNamed("FairMonitor", "Monitor for FairRoot") + , fRunMonitor(kFALSE) + , fDrawCanvas(kFALSE) + , fRunTime(0.) + , fRunMem(0.) + , fTimerMap() + , fMemoryMap() + , fHistList(new TList()) + , fCanvas() + , fNoTaskRequired(0) + , fNoTaskCreated(0) + , fCurrentTask(0) + , fTaskRequired() + , fTaskCreated() + , fTaskCreatedTemp() + , fObjectMap() + , fTaskMap() + , fObjectPos() + , fTaskPos() +{} + +FairMonitor::~FairMonitor() {} FairMonitor* FairMonitor::GetMonitor() { - if (!instance) { - instance = new FairMonitor(); - } - return instance; + if (!instance) { + instance = new FairMonitor(); + } + return instance; } void FairMonitor::StartTimer(const TTask* tTask, const char* identStr) { - if (!fRunMonitor) return; + if (!fRunMonitor) + return; - TString tempString = Form("timer_%p_%s_%s",tTask,tTask->GetName(),identStr); + TString tempString = Form("timer_%p_%s_%s", tTask, tTask->GetName(), identStr); - auto itt = fTimerMap.find(tempString); - if (itt == fTimerMap.end()) { - fTimerMap.insert(std::pair (tempString,TStopwatch())); - itt = fTimerMap.find(tempString); - } - fTimerMap[tempString].Start(); + auto itt = fTimerMap.find(tempString); + if (itt == fTimerMap.end()) { + fTimerMap.insert(std::pair(tempString, TStopwatch())); + itt = fTimerMap.find(tempString); + } + fTimerMap[tempString].Start(); } void FairMonitor::StopTimer(const TTask* tTask, const char* identStr) { - if (!fRunMonitor) return; + if (!fRunMonitor) + return; - TString tempString = Form("timer_%p_%s_%s",tTask,tTask->GetName(),identStr); + TString tempString = Form("timer_%p_%s_%s", tTask, tTask->GetName(), identStr); - auto itt = fTimerMap.find(tempString); - if (itt == fTimerMap.end()) { - LOG(info) << "FairMonitor::StopTimer() called without matching StartTimer()"; - return; - } - // itt->second - fTimerMap[tempString].Stop(); + auto itt = fTimerMap.find(tempString); + if (itt == fTimerMap.end()) { + LOG(info) << "FairMonitor::StopTimer() called without matching StartTimer()"; + return; + } + // itt->second + fTimerMap[tempString].Stop(); - Double_t time = fTimerMap[tempString].RealTime(); - RecordInfo(tTask,Form("%s_TIM",identStr),time); + Double_t time = fTimerMap[tempString].RealTime(); + RecordInfo(tTask, Form("%s_TIM", identStr), time); - if (tempString.EndsWith("_EXEC")) - fRunTime += time; + if (tempString.EndsWith("_EXEC")) + fRunTime += time; } void FairMonitor::StartMemoryMonitor(const TTask* tTask, const char* identStr) { - if (!fRunMonitor) return; - FairSystemInfo sysInfo; - Int_t memoryAtStart = static_cast(sysInfo.GetCurrentMemory()); + if (!fRunMonitor) + return; + FairSystemInfo sysInfo; + Int_t memoryAtStart = static_cast(sysInfo.GetCurrentMemory()); - TString memMon = Form("mem_%p_%s_%s",tTask,tTask->GetName(),identStr); + TString memMon = Form("mem_%p_%s_%s", tTask, tTask->GetName(), identStr); - auto iti = fMemoryMap.find(memMon); - if (iti == fMemoryMap.end()) - fMemoryMap.insert(std::pair (memMon,memoryAtStart)); - else - iti->second = memoryAtStart; + auto iti = fMemoryMap.find(memMon); + if (iti == fMemoryMap.end()) + fMemoryMap.insert(std::pair(memMon, memoryAtStart)); + else + iti->second = memoryAtStart; } void FairMonitor::StopMemoryMonitor(const TTask* tTask, const char* identStr) { - if (!fRunMonitor) return; - FairSystemInfo sysInfo; - Int_t memoryAtEnd = static_cast(sysInfo.GetCurrentMemory()); + if (!fRunMonitor) + return; + FairSystemInfo sysInfo; + Int_t memoryAtEnd = static_cast(sysInfo.GetCurrentMemory()); - TString memMon = Form("mem_%p_%s_%s",tTask,tTask->GetName(),identStr); + TString memMon = Form("mem_%p_%s_%s", tTask, tTask->GetName(), identStr); - auto iti = fMemoryMap.find(memMon); - if (iti == fMemoryMap.end()) - LOG(warn) << "FairMonitor::StopMemoryMonitor() Could not find corresponding entry for \"" << memMon.Data() << "\"."; - else { - RecordInfo(tTask,Form("%s_MEM",identStr),memoryAtEnd-iti->second); + auto iti = fMemoryMap.find(memMon); + if (iti == fMemoryMap.end()) + LOG(warn) << "FairMonitor::StopMemoryMonitor() Could not find corresponding entry for \"" << memMon.Data() + << "\"."; + else { + RecordInfo(tTask, Form("%s_MEM", identStr), memoryAtEnd - iti->second); - if (memMon.EndsWith("_EXEC")) - fRunMem += memoryAtEnd-iti->second; - } + if (memMon.EndsWith("_EXEC")) + fRunMem += memoryAtEnd - iti->second; + } } void FairMonitor::RecordInfo(const TTask* tTask, const char* identStr, Double_t value) { - if (!fRunMonitor) return; - - TString tempString = Form("hist_%p_%s_%s",tTask,tTask->GetName(),identStr); - - Int_t nofHists = fHistList->GetEntries(); - Int_t ihist = 0; - for (ihist = 0 ; ihist < nofHists ; ihist++) { - if (!tempString.CompareTo(fHistList->At(ihist)->GetName())) { - break; - } - } - if (ihist == nofHists) { - TString titleString = Form("Histogram %s for %s",identStr,tTask->GetName()); - fHistList->Add(new TH1F(tempString,titleString,1000,0,1000)); - } - TH1F* tempHist = (static_cast((fHistList->At(ihist)))); - Int_t nofEntries = tempHist->GetEntries(); - if (nofEntries > tempHist->GetNbinsX()) - tempHist->SetBins(tempHist->GetNbinsX()*10, 0, tempHist->GetXaxis()->GetXmax()*10); - - tempHist->SetBinContent(nofEntries+1,value); + if (!fRunMonitor) + return; + + TString tempString = Form("hist_%p_%s_%s", tTask, tTask->GetName(), identStr); + + Int_t nofHists = fHistList->GetEntries(); + Int_t ihist = 0; + for (ihist = 0; ihist < nofHists; ihist++) { + if (!tempString.CompareTo(fHistList->At(ihist)->GetName())) { + break; + } + } + if (ihist == nofHists) { + TString titleString = Form("Histogram %s for %s", identStr, tTask->GetName()); + fHistList->Add(new TH1F(tempString, titleString, 1000, 0, 1000)); + } + TH1F* tempHist = (static_cast((fHistList->At(ihist)))); + Int_t nofEntries = tempHist->GetEntries(); + if (nofEntries > tempHist->GetNbinsX()) + tempHist->SetBins(tempHist->GetNbinsX() * 10, 0, tempHist->GetXaxis()->GetXmax() * 10); + + tempHist->SetBinContent(nofEntries + 1, value); } void FairMonitor::RecordRegister(const char* name, const char* folderName, Bool_t toFile) { - if (!fRunMonitor) return; - - LOG(debug) << "*** FM::RecordRegister(" << name << ", " << folderName << (toFile?", kTRUE)":", kFALSE") << " for task >>" << fCurrentTask << "<< (" << (fCurrentTask?fCurrentTask->GetName():"") << ")"; - if (fCurrentTask == 0) { - fNoTaskCreated ++; - LOG(info) << "*** FM::RecordRegister(" << name << ", " << folderName << (toFile?", kTRUE)":", kFALSE") << " WITHOUT TASK"; - return; - } - TString tempString = Form("%p_%s",fCurrentTask,fCurrentTask->GetName()); - if (toFile) { - fTaskCreated.insert(std::pair(tempString,TString(name))); - } - else { - fTaskCreatedTemp.insert(std::pair(tempString,TString(name))); - } + if (!fRunMonitor) + return; + + LOG(debug) << "*** FM::RecordRegister(" << name << ", " << folderName << (toFile ? ", kTRUE)" : ", kFALSE") + << " for task >>" << fCurrentTask << "<< (" << (fCurrentTask ? fCurrentTask->GetName() : "") << ")"; + if (fCurrentTask == 0) { + fNoTaskCreated++; + LOG(info) << "*** FM::RecordRegister(" << name << ", " << folderName << (toFile ? ", kTRUE)" : ", kFALSE") + << " WITHOUT TASK"; + return; + } + TString tempString = Form("%p_%s", fCurrentTask, fCurrentTask->GetName()); + if (toFile) { + fTaskCreated.insert(std::pair(tempString, TString(name))); + } else { + fTaskCreatedTemp.insert(std::pair(tempString, TString(name))); + } } void FairMonitor::RecordGetting(const char* name) { - if (!fRunMonitor) return; + if (!fRunMonitor) + return; - LOG(debug) << "*** FM::RecordGetting(" << name << ") for task >>" << fCurrentTask << "<< (" << (fCurrentTask?fCurrentTask->GetName():"") << ")"; + LOG(debug) << "*** FM::RecordGetting(" << name << ") for task >>" << fCurrentTask << "<< (" + << (fCurrentTask ? fCurrentTask->GetName() : "") << ")"; - if (fCurrentTask == 0) { - fNoTaskRequired ++; - return; - } - TString tempString = Form("%p_%s",fCurrentTask,fCurrentTask->GetName()); - fTaskRequired.insert(std::pair(tempString,TString(name))); + if (fCurrentTask == 0) { + fNoTaskRequired++; + return; + } + TString tempString = Form("%p_%s", fCurrentTask, fCurrentTask->GetName()); + fTaskRequired.insert(std::pair(tempString, TString(name))); } void FairMonitor::PrintTask(TTask* tempTask, Int_t taskLevel) const { - if (!fRunMonitor) return; - - Int_t nofHists = fHistList->GetEntries(); - TString tempString = ""; - - Double_t timInt = -1.; - Double_t timEnt = 0.; - Int_t memInt = -1.; - - char byteChar[4] = {'B','k','M','G'}; - - for (Int_t ihist = 0 ; ihist < nofHists ; ihist++) { - tempString = Form("%s",fHistList->At(ihist)->GetName()); - if (tempString.Contains(Form("%p",tempTask))) { - if (tempString.Contains("EXEC_TIM")) { - timInt = (static_cast(fHistList->At(ihist))->Integral()); - timEnt = (static_cast(fHistList->At(ihist))->GetEntries()); - } - if (tempString.Contains("EXEC_MEM")) { - memInt = (static_cast(fHistList->At(ihist))->Integral()); - } - } - } - if (timInt < 0) { - LOG(warn) << "FairMonitor::PrintTask(), task \"" << tempTask->GetName() << "\" not found!"; - } - else { - // LOG(info) << "\"" << tempTask->GetName() << "\" --> TIME integral = " << timInt << " -- MEMORY integral = " << memInt; - TString printString = Form("%f", timInt/timEnt); - for (Int_t itemp = printString.Length() ; itemp < 10 ; itemp++) - printString.Insert(0,' '); - if (printString.Length() > 10) printString.Remove(11,100); - printString += " s/ev |"; - Double_t timePerc = 100.*timInt/fRunTime; - if (timePerc < 100.) printString += ' '; - if (timePerc < 10.) printString += ' '; - tempString = Form("%f",timePerc); - for (Int_t itemp = tempString.Length() ; itemp < 8 ; itemp++) - printString += ' '; - printString += tempString; - printString.Remove(27,100); - Int_t byteIdent = 0; - while (memInt > 1024) { - memInt = memInt/1024; - byteIdent++; - } - tempString = Form("%4d",memInt); - printString += " % ] "; - if (memInt < 0) - printString += "- - -"; - else { - printString += tempString; - printString += byteChar[byteIdent]; - } - printString += " \""; - for (Int_t ilev = 0 ; ilev < taskLevel ; ilev++) - printString += " "; - printString += tempTask->GetName(); - if (printString.Length() > 80) - printString.Remove(80,100); - printString += "\""; - Int_t timeFrac = static_cast((timePerc/100.*30.)); - - printString.Insert(37,"\033[0m"); - switch (byteIdent) { - case 0: printString.Insert(32,"\033[42m"); break; - case 1: printString.Insert(32,"\033[43m"); break; - default: printString.Insert(32,"\033[41m"); break; - } - printString.Insert(timeFrac,"\033[0m"); - if (timePerc < 30) - printString.Insert(0,"[\033[42m"); - else if (timePerc < 90) - printString.Insert(0,"[\033[43m"); - else - printString.Insert(0,"[\033[41m"); - LOG(INFO) << printString.Data(); - } - - TList* subTaskList = tempTask->GetListOfTasks(); - if (!subTaskList) return; - for (Int_t itask = 0 ; itask < subTaskList->GetEntries() ; itask++) { - TTask* subTask = static_cast(subTaskList->At(itask)); - if (subTask) - PrintTask(subTask,taskLevel+1); - } + if (!fRunMonitor) + return; + + Int_t nofHists = fHistList->GetEntries(); + TString tempString = ""; + + Double_t timInt = -1.; + Double_t timEnt = 0.; + Int_t memInt = -1.; + + char byteChar[4] = {'B', 'k', 'M', 'G'}; + + for (Int_t ihist = 0; ihist < nofHists; ihist++) { + tempString = Form("%s", fHistList->At(ihist)->GetName()); + if (tempString.Contains(Form("%p", tempTask))) { + if (tempString.Contains("EXEC_TIM")) { + timInt = (static_cast(fHistList->At(ihist))->Integral()); + timEnt = (static_cast(fHistList->At(ihist))->GetEntries()); + } + if (tempString.Contains("EXEC_MEM")) { + memInt = (static_cast(fHistList->At(ihist))->Integral()); + } + } + } + if (timInt < 0) { + LOG(warn) << "FairMonitor::PrintTask(), task \"" << tempTask->GetName() << "\" not found!"; + } else { + // LOG(info) << "\"" << tempTask->GetName() << "\" --> TIME integral = " << timInt << " -- MEMORY integral = + // " << memInt; + TString printString = Form("%f", timInt / timEnt); + for (Int_t itemp = printString.Length(); itemp < 10; itemp++) + printString.Insert(0, ' '); + if (printString.Length() > 10) + printString.Remove(11, 100); + printString += " s/ev |"; + Double_t timePerc = 100. * timInt / fRunTime; + if (timePerc < 100.) + printString += ' '; + if (timePerc < 10.) + printString += ' '; + tempString = Form("%f", timePerc); + for (Int_t itemp = tempString.Length(); itemp < 8; itemp++) + printString += ' '; + printString += tempString; + printString.Remove(27, 100); + Int_t byteIdent = 0; + while (memInt > 1024) { + memInt = memInt / 1024; + byteIdent++; + } + tempString = Form("%4d", memInt); + printString += " % ] "; + if (memInt < 0) + printString += "- - -"; + else { + printString += tempString; + printString += byteChar[byteIdent]; + } + printString += " \""; + for (Int_t ilev = 0; ilev < taskLevel; ilev++) + printString += " "; + printString += tempTask->GetName(); + if (printString.Length() > 80) + printString.Remove(80, 100); + printString += "\""; + Int_t timeFrac = static_cast((timePerc / 100. * 30.)); + + printString.Insert(37, "\033[0m"); + switch (byteIdent) { + case 0: + printString.Insert(32, "\033[42m"); + break; + case 1: + printString.Insert(32, "\033[43m"); + break; + default: + printString.Insert(32, "\033[41m"); + break; + } + printString.Insert(timeFrac, "\033[0m"); + if (timePerc < 30) + printString.Insert(0, "[\033[42m"); + else if (timePerc < 90) + printString.Insert(0, "[\033[43m"); + else + printString.Insert(0, "[\033[41m"); + LOG(INFO) << printString.Data(); + } + + TList* subTaskList = tempTask->GetListOfTasks(); + if (!subTaskList) + return; + for (Int_t itask = 0; itask < subTaskList->GetEntries(); itask++) { + TTask* subTask = static_cast(subTaskList->At(itask)); + if (subTask) + PrintTask(subTask, taskLevel + 1); + } } void FairMonitor::Print(Option_t*) const { - if (!fRunMonitor) { - LOG(warn) << "FairMonitor was disabled. Nothing to print!"; - return; - } - - LOG(info) << "- Total Run Time: " << fRunTime << " s ---------------------------------------------------------"; - TTask* mainFairTask = static_cast((gROOT->GetListOfBrowsables()->FindObject("FairTaskList"))); - if (mainFairTask) - PrintTask(mainFairTask,0); - LOG(info) << "-------------------------------------------------------------------------------------"; + if (!fRunMonitor) { + LOG(warn) << "FairMonitor was disabled. Nothing to print!"; + return; + } + + LOG(info) << "- Total Run Time: " << fRunTime << " s ---------------------------------------------------------"; + TTask* mainFairTask = static_cast((gROOT->GetListOfBrowsables()->FindObject("FairTaskList"))); + if (mainFairTask) + PrintTask(mainFairTask, 0); + LOG(info) << "-------------------------------------------------------------------------------------"; } void FairMonitor::PrintTask(TString specString) const { - if (!fRunMonitor) { - LOG(warn) << "FairMonitor was disabled. Nothing to print!"; - return; - } - - TString unitString = ""; - - Int_t nofHists = fHistList->GetEntries(); - for (Int_t ihist = 0 ; ihist < nofHists ; ihist++) { - TString histString = Form("%s",fHistList->At(ihist)->GetName()); - if (histString.Contains(specString)) { - histString.Replace(0,histString.First('_')+1,""); - histString.Replace(0,histString.First('_')+1,""); - Double_t integral = (static_cast((fHistList->At(ihist)))->Integral()); - Double_t entries = (static_cast((fHistList->At(ihist)))->GetEntries()); - // Double_t valPent = integral/entries; - if (histString.EndsWith("_TIM")) unitString = " s"; - if (histString.EndsWith("_MEM")) unitString = " B"; - LOG(info) << histString.Data() << " >>>>> " << integral << unitString.Data() << " / " << entries << " ent = " << integral/entries << unitString.Data() << " / ent"; - } - } + if (!fRunMonitor) { + LOG(warn) << "FairMonitor was disabled. Nothing to print!"; + return; + } + + TString unitString = ""; + + Int_t nofHists = fHistList->GetEntries(); + for (Int_t ihist = 0; ihist < nofHists; ihist++) { + TString histString = Form("%s", fHistList->At(ihist)->GetName()); + if (histString.Contains(specString)) { + histString.Replace(0, histString.First('_') + 1, ""); + histString.Replace(0, histString.First('_') + 1, ""); + Double_t integral = (static_cast((fHistList->At(ihist)))->Integral()); + Double_t entries = (static_cast((fHistList->At(ihist)))->GetEntries()); + // Double_t valPent = integral/entries; + if (histString.EndsWith("_TIM")) + unitString = " s"; + if (histString.EndsWith("_MEM")) + unitString = " B"; + LOG(info) << histString.Data() << " >>>>> " << integral << unitString.Data() << " / " << entries + << " ent = " << integral / entries << unitString.Data() << " / ent"; + } + } } void FairMonitor::Draw(Option_t*) { - if (!fRunMonitor) { - LOG(warn) << "FairMonitor was disabled. Nothing to print!"; - return; - } - - typedef std::map::iterator tiMapIter; - tiMapIter iti; - - TTask* mainFairTask = static_cast((gROOT->GetListOfBrowsables()->FindObject("FairTaskList"))); - if (!mainFairTask) return; - - GetTaskMap(mainFairTask); - - for (auto itb = fTaskRequired.begin(); itb != fTaskRequired.end() ; itb++) { - iti = fTaskMap.find(itb->first); - if (iti == fTaskMap.end()) - fTaskMap.insert(std::pair (itb->first,0)); - iti = fObjectMap.find(itb->second); - if (iti == fObjectMap.end()) - fObjectMap.insert(std::pair (itb->second,0)); - } - for (auto itb = fTaskCreated.begin(); itb != fTaskCreated.end() ; itb++) { - iti = fTaskMap.find(itb->first); - if (iti == fTaskMap.end()) - fTaskMap.insert(std::pair (itb->first,0)); - iti = fObjectMap.find(itb->second); - if (iti == fObjectMap.end()) - fObjectMap.insert(std::pair (itb->second,0)); - } - for (auto itb = fTaskCreatedTemp.begin(); itb != fTaskCreatedTemp.end() ; itb++) { - iti = fTaskMap.find(itb->first); - if (iti == fTaskMap.end()) - fTaskMap.insert(std::pair (itb->first,0)); - iti = fObjectMap.find(itb->second); - if (iti == fObjectMap.end()) - fObjectMap.insert(std::pair (itb->second,0)); - } - - AnalyzeObjectMap(mainFairTask); - - Int_t maxHierarchyNumber = 0; - for (iti = fObjectMap.begin() ; iti != fObjectMap.end() ; iti++) { - if (maxHierarchyNumber < iti->second) - maxHierarchyNumber = iti->second; - } - - LOG(debug) << "Max hierarchy number is " << maxHierarchyNumber; - - fCanvas = new TCanvas("MonitorCanvas","Fair Monitor",10,10,960,600); - fCanvas->cd(); - - fCanvas->SetFillStyle(4000); - fCanvas->Range(0,0,960,800); - fCanvas->SetFillColor(0); - fCanvas->SetBorderSize(0); - fCanvas->SetBorderMode(0); - fCanvas->SetFrameFillColor(0); - - for (Int_t ihier = 0 ; ihier < maxHierarchyNumber+1 ; ihier++) { - Int_t nofHier = 0; - for (iti = fTaskMap.begin() ; iti != fTaskMap.end() ; iti++) { - if (iti->second == ihier) { - nofHier++; - } - } - LOG(debug) << "There are " << nofHier << " tasks on level " << ihier << "."; - - if (ihier == 0) { - Double_t iObj = 0.; - for (iti = fTaskMap.begin() ; iti != fTaskMap.end() ; iti++) { - if (iti->second == ihier) { - std::pair tempPos(50,600-iObj*40); - fTaskPos.insert(std::pair > (iti->first,tempPos)); - iObj+=1.; + if (!fRunMonitor) { + LOG(warn) << "FairMonitor was disabled. Nothing to print!"; + return; + } + + typedef std::map::iterator tiMapIter; + tiMapIter iti; + + TTask* mainFairTask = static_cast((gROOT->GetListOfBrowsables()->FindObject("FairTaskList"))); + if (!mainFairTask) + return; + + GetTaskMap(mainFairTask); + + for (auto itb = fTaskRequired.begin(); itb != fTaskRequired.end(); itb++) { + iti = fTaskMap.find(itb->first); + if (iti == fTaskMap.end()) + fTaskMap.insert(std::pair(itb->first, 0)); + iti = fObjectMap.find(itb->second); + if (iti == fObjectMap.end()) + fObjectMap.insert(std::pair(itb->second, 0)); + } + for (auto itb = fTaskCreated.begin(); itb != fTaskCreated.end(); itb++) { + iti = fTaskMap.find(itb->first); + if (iti == fTaskMap.end()) + fTaskMap.insert(std::pair(itb->first, 0)); + iti = fObjectMap.find(itb->second); + if (iti == fObjectMap.end()) + fObjectMap.insert(std::pair(itb->second, 0)); + } + for (auto itb = fTaskCreatedTemp.begin(); itb != fTaskCreatedTemp.end(); itb++) { + iti = fTaskMap.find(itb->first); + if (iti == fTaskMap.end()) + fTaskMap.insert(std::pair(itb->first, 0)); + iti = fObjectMap.find(itb->second); + if (iti == fObjectMap.end()) + fObjectMap.insert(std::pair(itb->second, 0)); + } + + AnalyzeObjectMap(mainFairTask); + + Int_t maxHierarchyNumber = 0; + for (iti = fObjectMap.begin(); iti != fObjectMap.end(); iti++) { + if (maxHierarchyNumber < iti->second) + maxHierarchyNumber = iti->second; + } + + LOG(debug) << "Max hierarchy number is " << maxHierarchyNumber; + + fCanvas = new TCanvas("MonitorCanvas", "Fair Monitor", 10, 10, 960, 600); + fCanvas->cd(); + + fCanvas->SetFillStyle(4000); + fCanvas->Range(0, 0, 960, 800); + fCanvas->SetFillColor(0); + fCanvas->SetBorderSize(0); + fCanvas->SetBorderMode(0); + fCanvas->SetFrameFillColor(0); + + for (Int_t ihier = 0; ihier < maxHierarchyNumber + 1; ihier++) { + Int_t nofHier = 0; + for (iti = fTaskMap.begin(); iti != fTaskMap.end(); iti++) { + if (iti->second == ihier) { + nofHier++; + } + } + LOG(debug) << "There are " << nofHier << " tasks on level " << ihier << "."; + + if (ihier == 0) { + Double_t iObj = 0.; + for (iti = fTaskMap.begin(); iti != fTaskMap.end(); iti++) { + if (iti->second == ihier) { + std::pair tempPos(50, 600 - iObj * 40); + fTaskPos.insert(std::pair>(iti->first, tempPos)); + iObj += 1.; + } + } + } else { + Int_t iObj = 0; + Int_t secLine = 0; + Int_t secLineEven = 0; + if (nofHier > 9) { + secLine = 1; + if (nofHier % 2 == 0) + secLineEven = 1; + } + Int_t startingPosition = 575 - nofHier / (1 + secLine) * 45 - secLine * (1 - secLineEven) * 45; + + Double_t topEdge = + 800. + - 800. * (2. * static_cast(ihier) - 0.5) / (static_cast(2 * maxHierarchyNumber + 1)) + + secLine * 15; + LOG(debug) << "for level " << ihier << " will put top edge at " << topEdge << ". " + << (secLineEven ? "Two lines" : "One line") << (secLineEven ? " with offset" : ""); + for (iti = fTaskMap.begin(); iti != fTaskMap.end(); iti++) { + if (iti->second == ihier) { + std::pair tempPos(startingPosition + iObj * 90 / (1 + secLine) + - secLineEven * (iObj % 2) * 45, + topEdge - 15 - secLine * (iObj % 2) * 35); + fTaskPos.insert(std::pair>(iti->first, tempPos)); + iObj += 1; + } + } + } + + nofHier = 0; + for (iti = fObjectMap.begin(); iti != fObjectMap.end(); iti++) { + if (TMath::Abs(iti->second) == ihier) { + nofHier++; + } + } + LOG(debug) << "There are " << nofHier << " objects on level " << ihier << "."; + + Int_t iObj = 0; + Int_t secLine = 0; + Int_t secLineEven = 0; + if (nofHier > 9) { + secLine = 1; + if (nofHier % 2 == 0) + secLineEven = 1; + } + Int_t startingPosition = 575 - nofHier / (1 + secLine) * 45 - secLine * (1 - secLineEven) * 45; + + Double_t topEdge = + 800. + - 800. * (2. * static_cast(ihier) + 0.5) / (static_cast(2 * maxHierarchyNumber + 1)) + + secLine * 15; + LOG(debug) << "for level " << ihier << " will put top edge at " << topEdge << ". " + << (secLineEven ? "Two lines" : "One line") << (secLineEven ? " with offset" : ""); + for (iti = fObjectMap.begin(); iti != fObjectMap.end(); iti++) { + if (TMath::Abs(iti->second) == ihier) { + std::pair tempPos(startingPosition + iObj * 90 / (1 + secLine) + - secLineEven * (iObj % 2) * 45, + topEdge - 15 - secLine * (iObj % 2) * 35); + fObjectPos.insert(std::pair>(iti->first, tempPos)); + iObj += 1; + } } - } } - else { - Int_t iObj = 0; - Int_t secLine = 0; - Int_t secLineEven = 0; - if (nofHier > 9) { - secLine = 1; - if (nofHier%2 == 0) secLineEven = 1; - } - Int_t startingPosition = 575 - nofHier/(1+secLine)*45-secLine*(1-secLineEven)*45; - - Double_t topEdge = 800.-800.*(2.*static_cast(ihier)-0.5)/(static_cast(2*maxHierarchyNumber+1))+secLine*15; - LOG(debug) << "for level " << ihier << " will put top edge at " << topEdge - << ". " << (secLineEven?"Two lines":"One line") << (secLineEven?" with offset":""); - for (iti = fTaskMap.begin() ; iti != fTaskMap.end() ; iti++) { - if (iti->second == ihier) { - std::pair tempPos(startingPosition+iObj*90/(1+secLine)-secLineEven*(iObj%2)*45,topEdge-15-secLine*(iObj%2)*35); - fTaskPos.insert(std::pair > (iti->first,tempPos)); - iObj+=1; + + typedef std::map>::iterator tddMapIter; + tddMapIter itt; + tddMapIter ito; + + for (auto itb = fTaskRequired.begin(); itb != fTaskRequired.end(); itb++) { + itt = fTaskPos.find(itb->first); + ito = fObjectPos.find(itb->second); + if (itt != fTaskPos.end() && ito != fObjectPos.end()) { + std::pair taskPos = itt->second; + std::pair objectPos = ito->second; + TArrow* tempArrow = + new TArrow(objectPos.first, objectPos.second - 15, taskPos.first, taskPos.second + 15, 0.01, "|>"); + tempArrow->Draw(); } - } - } - - nofHier = 0; - for (iti = fObjectMap.begin() ; iti != fObjectMap.end() ; iti++) { - if (TMath::Abs(iti->second) == ihier) { - nofHier++; - } - } - LOG(debug) << "There are " << nofHier << " objects on level " << ihier << "."; - - Int_t iObj = 0; - Int_t secLine = 0; - Int_t secLineEven = 0; - if (nofHier > 9) { - secLine = 1; - if (nofHier%2 == 0) secLineEven = 1; - } - Int_t startingPosition = 575 - nofHier/(1+secLine)*45-secLine*(1-secLineEven)*45; - - Double_t topEdge = 800.-800.*(2.*static_cast(ihier)+0.5)/(static_cast(2*maxHierarchyNumber+1))+secLine*15; - LOG(debug) << "for level " << ihier << " will put top edge at " << topEdge - << ". " << (secLineEven?"Two lines":"One line") << (secLineEven?" with offset":""); - for (iti = fObjectMap.begin() ; iti != fObjectMap.end() ; iti++) { - if (TMath::Abs(iti->second) == ihier) { - std::pair tempPos(startingPosition+iObj*90/(1+secLine)-secLineEven*(iObj%2)*45,topEdge-15-secLine*(iObj%2)*35); - fObjectPos.insert(std::pair > (iti->first,tempPos)); - iObj+=1; - } - } - } - - typedef std::map >::iterator tddMapIter; - tddMapIter itt; - tddMapIter ito; - - for (auto itb = fTaskRequired.begin(); itb != fTaskRequired.end() ; itb++) { - itt = fTaskPos.find(itb->first); - ito = fObjectPos.find(itb->second); - if (itt != fTaskPos.end() && ito != fObjectPos.end()) { - std::pair taskPos = itt->second; - std::pair objectPos = ito->second; - TArrow* tempArrow = new TArrow(objectPos.first,objectPos.second-15,taskPos.first,taskPos.second+15,0.01,"|>"); - tempArrow->Draw(); - } - } - for (auto itb = fTaskCreated.begin(); itb != fTaskCreated.end() ; itb++) { - itt = fTaskPos.find(itb->first); - ito = fObjectPos.find(itb->second); - if (itt != fTaskPos.end() && ito != fObjectPos.end()) { - std::pair taskPos = itt->second; - std::pair objectPos = ito->second; - TArrow* tempArrow = new TArrow(taskPos.first,taskPos.second-15,objectPos.first,objectPos.second+15,0.01,"|>"); - tempArrow->Draw(); - } - } - for (auto itb = fTaskCreatedTemp.begin(); itb != fTaskCreatedTemp.end() ; itb++) { - itt = fTaskPos.find(itb->first); - ito = fObjectPos.find(itb->second); - if (itt != fTaskPos.end() && ito != fObjectPos.end()) { - std::pair taskPos = itt->second; - std::pair objectPos = ito->second; - TArrow* tempArrow = new TArrow(taskPos.first,taskPos.second-15,objectPos.first,objectPos.second+15,0.01,"|>"); - tempArrow->Draw(); - } - } - - for (itt = fTaskPos.begin() ; itt != fTaskPos.end() ; itt++) { - std::pair taskPos = itt->second; - TBox* bkgBox = new TBox(taskPos.first-40,taskPos.second-15,taskPos.first+40,taskPos.second+15); - bkgBox->SetFillColor(kGreen-9); - bkgBox->Draw(); - - TString tempString = Form("hist_%s_%s",itt->first.Data(),"EXEC_TIM"); - Int_t nofHists = fHistList->GetEntries(); - for (Int_t ihist = 0 ; ihist < nofHists ; ihist++) { - if (!tempString.CompareTo(fHistList->At(ihist)->GetName())) { - Double_t timeInt = (static_cast(fHistList->At(ihist))->Integral()); - Double_t timeFrac = 80.*timeInt/fRunTime; - TBox* barBox = new TBox(taskPos.first-40,taskPos.second-15,taskPos.first-40+timeFrac,taskPos.second+15); - barBox->SetFillColor(kRed); - barBox->Draw(); - } - } - - tempString = itt->first; - tempString.Replace(0,tempString.First('_')+1,""); - if (tempString.Length() > 16) tempString.Replace(16,tempString.Length(),""); - TLatex* taskText = new TLatex(taskPos.first,taskPos.second,tempString.Data()); - taskText->SetTextAlign(22); - taskText->SetTextSize(0.015); - taskText->Draw(); - } - - for (ito = fObjectPos.begin() ; ito != fObjectPos.end() ; ito++) { - std::pair objectPos = ito->second; - iti = fObjectMap.find(ito->first); - TPaveText* paveText = new TPaveText(objectPos.first-40,objectPos.second-15,objectPos.first+40,objectPos.second+15,"nb"); - paveText->SetFillColor(kMagenta-9); - if (iti != fObjectMap.end()) - if (iti->second < 0) - paveText->SetFillColor(kGray); - paveText->SetShadowColor(0); - paveText->SetTextSize(0.015); - TString tempString = ito->first; - if (tempString.Length() > 16) tempString.Replace(16,tempString.Length(),""); - paveText->AddText(tempString); - paveText->Draw(); - } + } + for (auto itb = fTaskCreated.begin(); itb != fTaskCreated.end(); itb++) { + itt = fTaskPos.find(itb->first); + ito = fObjectPos.find(itb->second); + if (itt != fTaskPos.end() && ito != fObjectPos.end()) { + std::pair taskPos = itt->second; + std::pair objectPos = ito->second; + TArrow* tempArrow = + new TArrow(taskPos.first, taskPos.second - 15, objectPos.first, objectPos.second + 15, 0.01, "|>"); + tempArrow->Draw(); + } + } + for (auto itb = fTaskCreatedTemp.begin(); itb != fTaskCreatedTemp.end(); itb++) { + itt = fTaskPos.find(itb->first); + ito = fObjectPos.find(itb->second); + if (itt != fTaskPos.end() && ito != fObjectPos.end()) { + std::pair taskPos = itt->second; + std::pair objectPos = ito->second; + TArrow* tempArrow = + new TArrow(taskPos.first, taskPos.second - 15, objectPos.first, objectPos.second + 15, 0.01, "|>"); + tempArrow->Draw(); + } + } + + for (itt = fTaskPos.begin(); itt != fTaskPos.end(); itt++) { + std::pair taskPos = itt->second; + TBox* bkgBox = new TBox(taskPos.first - 40, taskPos.second - 15, taskPos.first + 40, taskPos.second + 15); + bkgBox->SetFillColor(kGreen - 9); + bkgBox->Draw(); + + TString tempString = Form("hist_%s_%s", itt->first.Data(), "EXEC_TIM"); + Int_t nofHists = fHistList->GetEntries(); + for (Int_t ihist = 0; ihist < nofHists; ihist++) { + if (!tempString.CompareTo(fHistList->At(ihist)->GetName())) { + Double_t timeInt = (static_cast(fHistList->At(ihist))->Integral()); + Double_t timeFrac = 80. * timeInt / fRunTime; + TBox* barBox = new TBox( + taskPos.first - 40, taskPos.second - 15, taskPos.first - 40 + timeFrac, taskPos.second + 15); + barBox->SetFillColor(kRed); + barBox->Draw(); + } + } + + tempString = itt->first; + tempString.Replace(0, tempString.First('_') + 1, ""); + if (tempString.Length() > 16) + tempString.Replace(16, tempString.Length(), ""); + TLatex* taskText = new TLatex(taskPos.first, taskPos.second, tempString.Data()); + taskText->SetTextAlign(22); + taskText->SetTextSize(0.015); + taskText->Draw(); + } + + for (ito = fObjectPos.begin(); ito != fObjectPos.end(); ito++) { + std::pair objectPos = ito->second; + iti = fObjectMap.find(ito->first); + TPaveText* paveText = new TPaveText( + objectPos.first - 40, objectPos.second - 15, objectPos.first + 40, objectPos.second + 15, "nb"); + paveText->SetFillColor(kMagenta - 9); + if (iti != fObjectMap.end()) + if (iti->second < 0) + paveText->SetFillColor(kGray); + paveText->SetShadowColor(0); + paveText->SetTextSize(0.015); + TString tempString = ito->first; + if (tempString.Length() > 16) + tempString.Replace(16, tempString.Length(), ""); + paveText->AddText(tempString); + paveText->Draw(); + } } void FairMonitor::DrawHist(TString specString) { - if (!fRunMonitor) { - LOG(warn) << "FairMonitor was disabled. Nothing to draw!"; - return; - } - - Int_t nofHists = fHistList->GetEntries(); - Int_t nofDraws = 0; - TString drawStr = "P"; - - TLegend* tempLeg = new TLegend(0.0,0.5,0.5,0.9); - - Double_t histMax = 0.; - for (Int_t ihist = 0 ; ihist < nofHists ; ihist++) { - TString histString = Form("%s",fHistList->At(ihist)->GetName()); - if (histString.Contains(specString)) { - TH1F* tempHist = (static_cast((fHistList->At(ihist)))); - if (histMax < tempHist->GetMaximum()) - histMax = tempHist->GetMaximum(); - } - } - - for (Int_t ihist = 0 ; ihist < nofHists ; ihist++) { - TString histString = Form("%s",fHistList->At(ihist)->GetName()); - if (histString.Contains(specString)) { - TH1F* tempHist = (static_cast((fHistList->At(ihist)))); - if (tempHist->GetXaxis()->GetXmax() > tempHist->GetEntries()) - tempHist->SetBins(tempHist->GetEntries(),0,tempHist->GetEntries()); - tempHist->SetMarkerColor(nofDraws%6+2); - tempHist->SetMarkerStyle(nofDraws%4+20); - tempHist->SetAxisRange(0.,histMax*1.1,"Y"); - tempHist->Draw(drawStr); - TString tempName = tempHist->GetName(); - tempName.Remove(0,tempName.First('_')+1); - tempName.Remove(0,tempName.First('_')+1); - tempLeg->AddEntry(tempHist,tempName,"p"); - nofDraws++; - drawStr = "Psame"; - } - } - if (nofDraws > 1) - tempLeg->Draw(); + if (!fRunMonitor) { + LOG(warn) << "FairMonitor was disabled. Nothing to draw!"; + return; + } + + Int_t nofHists = fHistList->GetEntries(); + Int_t nofDraws = 0; + TString drawStr = "P"; + + TLegend* tempLeg = new TLegend(0.0, 0.5, 0.5, 0.9); + + Double_t histMax = 0.; + for (Int_t ihist = 0; ihist < nofHists; ihist++) { + TString histString = Form("%s", fHistList->At(ihist)->GetName()); + if (histString.Contains(specString)) { + TH1F* tempHist = (static_cast((fHistList->At(ihist)))); + if (histMax < tempHist->GetMaximum()) + histMax = tempHist->GetMaximum(); + } + } + + for (Int_t ihist = 0; ihist < nofHists; ihist++) { + TString histString = Form("%s", fHistList->At(ihist)->GetName()); + if (histString.Contains(specString)) { + TH1F* tempHist = (static_cast((fHistList->At(ihist)))); + if (tempHist->GetXaxis()->GetXmax() > tempHist->GetEntries()) + tempHist->SetBins(tempHist->GetEntries(), 0, tempHist->GetEntries()); + tempHist->SetMarkerColor(nofDraws % 6 + 2); + tempHist->SetMarkerStyle(nofDraws % 4 + 20); + tempHist->SetAxisRange(0., histMax * 1.1, "Y"); + tempHist->Draw(drawStr); + TString tempName = tempHist->GetName(); + tempName.Remove(0, tempName.First('_') + 1); + tempName.Remove(0, tempName.First('_') + 1); + tempLeg->AddEntry(tempHist, tempName, "p"); + nofDraws++; + drawStr = "Psame"; + } + } + if (nofDraws > 1) + tempLeg->Draw(); } void FairMonitor::StoreHistograms(TFile* sinkFile) { - if (!fRunMonitor) { - return; - } - Bool_t wasBatch = gROOT->IsBatch(); - if (!fDrawCanvas && !wasBatch) // default: switching to batch mode if draw canvas disabled - gROOT->SetBatch(kTRUE); - this->Draw(); - if (!fDrawCanvas && !wasBatch) // default: switching to batch mode if draw canvas disabled - gROOT->SetBatch(kFALSE); - - TFile* histoFile = sinkFile; - if (fOutputFileName.Length() > 1 && fOutputFileName != sinkFile->GetName()) { - histoFile = TFile::Open(fOutputFileName,"recreate"); - } - - histoFile->mkdir("MonitorResults"); - histoFile->cd("MonitorResults"); - TIter next(fHistList); - while (TH1* thist = (static_cast(next()))) { - thist->SetBins(thist->GetEntries(),0,thist->GetEntries()); - thist->Write(); - } - fCanvas->Write(); - - if (histoFile != sinkFile) { - histoFile->Close(); - delete histoFile; - } + if (!fRunMonitor) { + return; + } + Bool_t wasBatch = gROOT->IsBatch(); + if (!fDrawCanvas && !wasBatch) // default: switching to batch mode if draw canvas disabled + gROOT->SetBatch(kTRUE); + this->Draw(); + if (!fDrawCanvas && !wasBatch) // default: switching to batch mode if draw canvas disabled + gROOT->SetBatch(kFALSE); + + TFile* histoFile = sinkFile; + if (fOutputFileName.Length() > 1 && fOutputFileName != sinkFile->GetName()) { + histoFile = TFile::Open(fOutputFileName, "recreate"); + } + + histoFile->mkdir("MonitorResults"); + histoFile->cd("MonitorResults"); + TIter next(fHistList); + while (TH1* thist = (static_cast(next()))) { + thist->SetBins(thist->GetEntries(), 0, thist->GetEntries()); + thist->Write(); + } + fCanvas->Write(); + + if (histoFile != sinkFile) { + histoFile->Close(); + delete histoFile; + } } // Private function to fill the map of the tasks void FairMonitor::GetTaskMap(TTask* tempTask) { - TString tempString = Form("%p_%s",tempTask,tempTask->GetName()); - fTaskMap.insert(std::pair (tempString,0)); - - TList* subTaskList = tempTask->GetListOfTasks(); - if (!subTaskList) return; - for (Int_t itask = 0 ; itask < subTaskList->GetEntries() ; itask++) { - TTask* subTask = static_cast(subTaskList->At(itask)); - if (subTask) - GetTaskMap(subTask); - } + TString tempString = Form("%p_%s", tempTask, tempTask->GetName()); + fTaskMap.insert(std::pair(tempString, 0)); + + TList* subTaskList = tempTask->GetListOfTasks(); + if (!subTaskList) + return; + for (Int_t itask = 0; itask < subTaskList->GetEntries(); itask++) { + TTask* subTask = static_cast(subTaskList->At(itask)); + if (subTask) + GetTaskMap(subTask); + } } // Private function to analyze the object list: @@ -640,55 +681,62 @@ void FairMonitor::GetTaskMap(TTask* tempTask) // tasks number i create objects number -i (if they are not persistent) void FairMonitor::AnalyzeObjectMap(TTask* tempTask) { - TString tempString = Form("%p_%s",tempTask,tempTask->GetName()); - - Int_t hierarchyNumber = 0; - - typedef std::map::iterator tiMapIter; - tiMapIter iti; - - LOG(debug) << "TASK \"" << tempTask->GetName() << "\" NEEDS:"; - for (auto itb = fTaskRequired.begin(); itb != fTaskRequired.end() ; itb++) { - if (itb->first != tempString) continue; - LOG(debug) << " \"" << itb->second.Data() << "\""; - iti = fObjectMap.find(itb->second); - if (iti == fObjectMap.end()) continue; - if (hierarchyNumber <= TMath::Abs(iti->second)) - hierarchyNumber = TMath::Abs(iti->second)+1; - } - - // hierarchyNumber++; - - LOG(debug) << "WILL GET hierarchyNumber = " << hierarchyNumber; - - iti = fTaskMap.find(tempString); - if (iti != fTaskMap.end()) - iti->second = hierarchyNumber; - - LOG(debug) << " \"" << tempTask->GetName() << "\" CREATES:"; - for (auto itb = fTaskCreated.begin(); itb != fTaskCreated.end() ; itb++) { - if (itb->first != tempString) continue; - LOG(debug) << " + \"" << itb->second.Data() << "\""; - iti = fObjectMap.find(itb->second); - if (iti == fObjectMap.end()) continue; - iti->second = hierarchyNumber; - } - - for (auto itb = fTaskCreatedTemp.begin(); itb != fTaskCreatedTemp.end() ; itb++) { - if (itb->first != tempString) continue; - LOG(debug) << " - \"" << itb->second.Data() << "\""; - iti = fObjectMap.find(itb->second); - if (iti == fObjectMap.end()) continue; - iti->second = -hierarchyNumber; - } - - TList* subTaskList = tempTask->GetListOfTasks(); - if (!subTaskList) return; - for (Int_t itask = 0 ; itask < subTaskList->GetEntries() ; itask++) { - TTask* subTask = static_cast(subTaskList->At(itask)); - if (subTask) - AnalyzeObjectMap(subTask); - } + TString tempString = Form("%p_%s", tempTask, tempTask->GetName()); + + Int_t hierarchyNumber = 0; + + typedef std::map::iterator tiMapIter; + tiMapIter iti; + + LOG(debug) << "TASK \"" << tempTask->GetName() << "\" NEEDS:"; + for (auto itb = fTaskRequired.begin(); itb != fTaskRequired.end(); itb++) { + if (itb->first != tempString) + continue; + LOG(debug) << " \"" << itb->second.Data() << "\""; + iti = fObjectMap.find(itb->second); + if (iti == fObjectMap.end()) + continue; + if (hierarchyNumber <= TMath::Abs(iti->second)) + hierarchyNumber = TMath::Abs(iti->second) + 1; + } + + // hierarchyNumber++; + + LOG(debug) << "WILL GET hierarchyNumber = " << hierarchyNumber; + + iti = fTaskMap.find(tempString); + if (iti != fTaskMap.end()) + iti->second = hierarchyNumber; + + LOG(debug) << " \"" << tempTask->GetName() << "\" CREATES:"; + for (auto itb = fTaskCreated.begin(); itb != fTaskCreated.end(); itb++) { + if (itb->first != tempString) + continue; + LOG(debug) << " + \"" << itb->second.Data() << "\""; + iti = fObjectMap.find(itb->second); + if (iti == fObjectMap.end()) + continue; + iti->second = hierarchyNumber; + } + + for (auto itb = fTaskCreatedTemp.begin(); itb != fTaskCreatedTemp.end(); itb++) { + if (itb->first != tempString) + continue; + LOG(debug) << " - \"" << itb->second.Data() << "\""; + iti = fObjectMap.find(itb->second); + if (iti == fObjectMap.end()) + continue; + iti->second = -hierarchyNumber; + } + + TList* subTaskList = tempTask->GetListOfTasks(); + if (!subTaskList) + return; + for (Int_t itask = 0; itask < subTaskList->GetEntries(); itask++) { + TTask* subTask = static_cast(subTaskList->At(itask)); + if (subTask) + AnalyzeObjectMap(subTask); + } } -ClassImp(FairMonitor) +ClassImp(FairMonitor); diff --git a/fairtools/FairMonitor.h b/fairtools/FairMonitor.h index 65624d1fe9..190a3ebaf5 100644 --- a/fairtools/FairMonitor.h +++ b/fairtools/FairMonitor.h @@ -16,11 +16,10 @@ #ifndef BASE_FAIRMONITOR_H_ #define BASE_FAIRMONITOR_H_ -#include - #include #include #include +#include class TCanvas; class TFile; @@ -32,24 +31,30 @@ class FairMonitor : public TNamed public: static FairMonitor* GetMonitor(); - void EnableMonitor(Bool_t tempBool = kTRUE, TString fileName = "") { fRunMonitor = tempBool; fOutputFileName = fileName; } + void EnableMonitor(Bool_t tempBool = kTRUE, TString fileName = "") + { + fRunMonitor = tempBool; + fOutputFileName = fileName; + } void EnableDrawing(Bool_t tempBool = kTRUE) { fDrawCanvas = tempBool; } Bool_t IsRunning() { return fRunMonitor; } - void StartMonitoring(const TTask* tTask, const char* identStr) { - StartTimer(tTask,identStr); - StartMemoryMonitor(tTask,identStr); + void StartMonitoring(const TTask* tTask, const char* identStr) + { + StartTimer(tTask, identStr); + StartMemoryMonitor(tTask, identStr); } - void StopMonitoring(const TTask* tTask, const char* identStr) { - StopTimer(tTask,identStr); - StopMemoryMonitor(tTask,identStr); + void StopMonitoring(const TTask* tTask, const char* identStr) + { + StopTimer(tTask, identStr); + StopMemoryMonitor(tTask, identStr); } void StartTimer(const TTask* tTask, const char* identStr); void StopTimer(const TTask* tTask, const char* identStr); void StartMemoryMonitor(const TTask* tTask, const char* identStr); - void StopMemoryMonitor(const TTask* tTask, const char* identStr); + void StopMemoryMonitor(const TTask* tTask, const char* identStr); void RecordInfo(const TTask* tTask, const char* identStr, Double_t value); @@ -59,10 +64,10 @@ class FairMonitor : public TNamed void SetCurrentTask(TTask* tTask) { fCurrentTask = tTask; } virtual void Print(Option_t* option = "") const; - virtual void Draw (Option_t* option = ""); + virtual void Draw(Option_t* option = ""); void PrintTask(TString specString) const; - void PrintTask(TTask* tempTask, Int_t taskLevel=0) const; + void PrintTask(TTask* tempTask, Int_t taskLevel = 0) const; void DrawHist(TString specString); TList* GetHistList() { return fHistList; } @@ -93,7 +98,7 @@ class FairMonitor : public TNamed TTask* fCurrentTask; - TString fOutputFileName; // output file name, if empty then try to use FairSink to store histograms + TString fOutputFileName; // output file name, if empty then try to use FairSink to store histograms std::multimap fTaskRequired; std::multimap fTaskCreated; @@ -102,8 +107,8 @@ class FairMonitor : public TNamed std::map fObjectMap; std::map fTaskMap; - std::map > fObjectPos; - std::map > fTaskPos; + std::map> fObjectPos; + std::map> fTaskPos; void GetTaskMap(TTask* tempTask); void AnalyzeObjectMap(TTask* tempTask); @@ -113,4 +118,4 @@ class FairMonitor : public TNamed extern FairMonitor* gMonitor; -#endif // BASE_FAIRMONITOR_H_ +#endif // BASE_FAIRMONITOR_H_ diff --git a/fairtools/FairSystemInfo.cxx b/fairtools/FairSystemInfo.cxx index 4cdaf6d88b..1f7180d617 100644 --- a/fairtools/FairSystemInfo.cxx +++ b/fairtools/FairSystemInfo.cxx @@ -14,15 +14,15 @@ #include "FairSystemInfo.h" -#include #include +#include #if defined(__APPLE__) && defined(__MACH__) #include #elif defined(__linux__) || defined(__linux) || defined(linux) || defined(__gnu_linux__) -#include #include +#include #else #error "Unknown OS." @@ -30,15 +30,15 @@ Float_t FairSystemInfo::GetMaxMemory() { - // Returns the maximal used memory in MB + // Returns the maximal used memory in MB - struct rusage rusage; - getrusage( RUSAGE_SELF, &rusage ); + struct rusage rusage; + getrusage(RUSAGE_SELF, &rusage); #if defined(__APPLE__) && defined(__MACH__) - return static_cast(rusage.ru_maxrss)/(1024*1024); + return static_cast(rusage.ru_maxrss) / (1024 * 1024); #else - return static_cast(rusage.ru_maxrss)/1024; + return static_cast(rusage.ru_maxrss) / 1024; #endif } @@ -46,16 +46,16 @@ Float_t FairSystemInfo::GetMaxMemory() * Returns the current resident set size (physical memory use) measured * in bytes, or zero if the value cannot be determined on this OS. */ -size_t FairSystemInfo::GetCurrentMemory( ) +size_t FairSystemInfo::GetCurrentMemory() { #if defined(__APPLE__) && defined(__MACH__) /* OSX ------------------------------------------------------ */ struct mach_task_basic_info info; mach_msg_type_number_t infoCount = MACH_TASK_BASIC_INFO_COUNT; - if ( task_info( mach_task_self( ), MACH_TASK_BASIC_INFO, - reinterpret_cast(&info), &infoCount ) != KERN_SUCCESS ) -// (task_info_t)&info, &infoCount ) != KERN_SUCCESS ) - return static_cast(0L); /* Can't access? */ + if (task_info(mach_task_self(), MACH_TASK_BASIC_INFO, reinterpret_cast(&info), &infoCount) + != KERN_SUCCESS) + // (task_info_t)&info, &infoCount ) != KERN_SUCCESS ) + return static_cast(0L); /* Can't access? */ return static_cast(info.resident_size); #elif defined(__linux__) || defined(__linux) || defined(linux) || defined(__gnu_linux__) @@ -63,22 +63,21 @@ size_t FairSystemInfo::GetCurrentMemory( ) long rss = 0L; long pagesize = sysconf(_SC_PAGESIZE); FILE* fp = NULL; - if ( (fp = fopen( "/proc/self/statm", "r" )) == NULL ) - return (size_t)0L; /* Can't open? */ - if ( fscanf( fp, "%*s%ld", &rss ) != 1 ) - { - fclose( fp ); - return (size_t)0L; /* Can't read? */ + if ((fp = fopen("/proc/self/statm", "r")) == NULL) + return (size_t)0L; /* Can't open? */ + if (fscanf(fp, "%*s%ld", &rss) != 1) { + fclose(fp); + return (size_t)0L; /* Can't read? */ } - fclose( fp ); - if (rss > 0 && rss < std::numeric_limits::max()/pagesize) { - return (size_t)rss * (size_t)sysconf(_SC_PAGESIZE); + fclose(fp); + if (rss > 0 && rss < std::numeric_limits::max() / pagesize) { + return (size_t)rss * (size_t)sysconf(_SC_PAGESIZE); } else { - return (size_t)0L; + return (size_t)0L; } #else /* AIX, BSD, Solaris, and Unknown OS ------------------------ */ - return (size_t)0L; /* Unsupported. */ + return (size_t)0L; /* Unsupported. */ #endif } diff --git a/fairtools/FairSystemInfo.h b/fairtools/FairSystemInfo.h index 605553ce32..9676e4bd83 100644 --- a/fairtools/FairSystemInfo.h +++ b/fairtools/FairSystemInfo.h @@ -17,19 +17,18 @@ #define BASE_FAIRSYSTEMINFO_H_ #include - #include class FairSystemInfo { - public: - FairSystemInfo() {} - virtual ~FairSystemInfo() {} + public: + FairSystemInfo() {} + virtual ~FairSystemInfo() {} - Float_t GetMaxMemory(); - size_t GetCurrentMemory(); + Float_t GetMaxMemory(); + size_t GetCurrentMemory(); - ClassDef(FairSystemInfo, 1) + ClassDef(FairSystemInfo, 1) }; -#endif // BASE_FAIRSYSTEMINFO_H_ +#endif // BASE_FAIRSYSTEMINFO_H_ diff --git a/fairtools/MCConfigurator/FairYamlVMCConfig.cxx b/fairtools/MCConfigurator/FairYamlVMCConfig.cxx index d90ef17989..66e038c290 100644 --- a/fairtools/MCConfigurator/FairYamlVMCConfig.cxx +++ b/fairtools/MCConfigurator/FairYamlVMCConfig.cxx @@ -11,45 +11,42 @@ // ------------------------------------------------------------------------- #include "FairYamlVMCConfig.h" +#include "FairFastSimRunConfiguration.h" #include "FairLogger.h" #include "FairRunSim.h" -#include "FairFastSimRunConfiguration.h" -#include "FairSink.h" // for FairSink +#include "FairSink.h" // for FairSink +#include #include #include #include - -#include +#include // for TObjString +#include // for TObject, TObject::kSingleKey #include -#include // for TObjString -#include // for TObject, TObject::kSingleKey -#include // for TSystem, gSystem -#include // for TVirtualMC - -#include // for vector -#include // for operator<<, ostringstream -#include // for string, basic_string, cha... -#include // for strcmp, strncmp -#include // for getenv +#include // for TSystem, gSystem +#include // for TVirtualMC +#include // for getenv +#include // for strcmp, strncmp +#include // for operator<<, ostringstream +#include // for string, basic_string, cha... +#include // for vector FairYamlVMCConfig::FairYamlVMCConfig() : FairGenericVMCConfig() -{ -} +{} void FairYamlVMCConfig::Setup(const char* mcEngine) { - if (!((strcmp(mcEngine,"TGeant4")==0) || (strcmp(mcEngine,"TGeant3")==0))) { + if (!((strcmp(mcEngine, "TGeant4") == 0) || (strcmp(mcEngine, "TGeant3") == 0))) { LOG(fatal) << "FairYamlVMCConfig::Setup() Engine \"" << mcEngine << "\" unknown!"; } TString yamlFileName = ObtainYamlFileName(mcEngine); fYamlConfig = YAML::LoadFile(yamlFileName.Data()); - if (strcmp(mcEngine,"TGeant4") == 0) { + if (strcmp(mcEngine, "TGeant4") == 0) { SetupGeant4(); - } else if (strcmp(mcEngine,"TGeant3") == 0) { + } else if (strcmp(mcEngine, "TGeant3") == 0) { SetupGeant3(); } SetupStack(); @@ -61,15 +58,13 @@ void FairYamlVMCConfig::Setup(const char* mcEngine) void FairYamlVMCConfig::SetupGeant3() { LOG(info) << "FairYamlVMCConfig::SetupGeant3() called"; - FairRunSim *fRun = FairRunSim::Instance(); + FairRunSim* fRun = FairRunSim::Instance(); TString* gModel = fRun->GetGeoModel(); TGeant3* geant3 = nullptr; - if (strncmp(gModel->Data(),"TGeo",4) == 0) { - geant3 - = new TGeant3TGeo("C++ Interface to Geant3"); - }else{ - geant3 - = new TGeant3("C++ Interface to Geant3"); + if (strncmp(gModel->Data(), "TGeo", 4) == 0) { + geant3 = new TGeant3TGeo("C++ Interface to Geant3"); + } else { + geant3 = new TGeant3("C++ Interface to Geant3"); } if (fYamlConfig["G3_TRIG"]) @@ -100,7 +95,6 @@ void FairYamlVMCConfig::SetupGeant3() geant3->SetERAN(fYamlConfig["G3_ERAN"].as()); if (fYamlConfig["G3_CKOV"]) geant3->SetCKOV(fYamlConfig["G3_CKOV"].as()); - } void FairYamlVMCConfig::SetupGeant4() @@ -128,12 +122,12 @@ void FairYamlVMCConfig::SetupGeant4() // LOG(info) << "Setting Geant4 multithreaded to " << (mtMode?"true":"false"); } - FairFastSimRunConfiguration* runConfiguration - = new FairFastSimRunConfiguration(fYamlConfig["Geant4_UserGeometry"] .as(), - fYamlConfig["Geant4_PhysicsList"] .as(), - fYamlConfig["Geant4_SpecialProcess"].as(), - specialStacking, - mtMode); + FairFastSimRunConfiguration* runConfiguration = + new FairFastSimRunConfiguration(fYamlConfig["Geant4_UserGeometry"].as(), + fYamlConfig["Geant4_PhysicsList"].as(), + fYamlConfig["Geant4_SpecialProcess"].as(), + specialStacking, + mtMode); TGeant4* geant4 = new TGeant4("TGeant4", "The Geant4 Monte Carlo", runConfiguration); @@ -145,19 +139,19 @@ void FairYamlVMCConfig::SetCuts() LOG(info) << "FairYamlVMCConfig::SetCuts() called"; if (fYamlConfig["MonteCarlo_Process"]) { YAML::Node mcProcess = fYamlConfig["MonteCarlo_Process"]; - TVirtualMC *MC =TVirtualMC::GetMC(); + TVirtualMC* MC = TVirtualMC::GetMC(); for (auto it = mcProcess.begin(); it != mcProcess.end(); ++it) { // LOG(info) << "proc: " << it->first << " --> " << it->second; - MC->SetProcess(it->first.as().c_str(),it->second.as()); + MC->SetProcess(it->first.as().c_str(), it->second.as()); } } if (fYamlConfig["MonteCarlo_Cut"]) { YAML::Node mcProcess = fYamlConfig["MonteCarlo_Cut"]; - TVirtualMC *MC =TVirtualMC::GetMC(); + TVirtualMC* MC = TVirtualMC::GetMC(); for (auto it = mcProcess.begin(); it != mcProcess.end(); ++it) { // LOG(info) << "cut: " << it->first << " --> " << it->second; - MC->SetCut(it->first.as().c_str(),it->second.as()); + MC->SetCut(it->first.as().c_str(), it->second.as()); } } } @@ -167,38 +161,42 @@ TString FairYamlVMCConfig::ObtainYamlFileName(const char* mcEngine) TString lUserConfig = FairRunSim::Instance()->GetUserConfig(); TString work = getenv("VMCWORKDIR"); - TString work_config=work+"/gconfig/"; - work_config.ReplaceAll("//","/"); + TString work_config = work + "/gconfig/"; + work_config.ReplaceAll("//", "/"); - TString config_dir= getenv("CONFIG_DIR"); - config_dir.ReplaceAll("//","/"); + TString config_dir = getenv("CONFIG_DIR"); + config_dir.ReplaceAll("//", "/"); - Bool_t AbsPath=kFALSE; + Bool_t AbsPath = kFALSE; TString configFileWithPath; TString configFile; if (lUserConfig.IsNull()) { - if (strcmp(mcEngine,"TGeant4") == 0) { + if (strcmp(mcEngine, "TGeant4") == 0) { configFile = "g4Config.yaml"; } - if (strcmp(mcEngine,"TGeant3") == 0) { + if (strcmp(mcEngine, "TGeant3") == 0) { configFile = "g3Config.yaml"; } lUserConfig = configFile; } else { - if (lUserConfig.Contains("/")) { AbsPath=kTRUE; } + if (lUserConfig.Contains("/")) { + AbsPath = kTRUE; + } configFile = lUserConfig; - LOG(info) << "---------------User config is used: " - << configFile.Data(); + LOG(info) << "---------------User config is used: " << configFile.Data(); } - if (!AbsPath && TString(gSystem->FindFile(config_dir.Data(),configFile)) != TString("")) { - LOG(info) << "---------------CONFIG_DIR is used: " - << config_dir.Data() << " to get \"" << configFile.Data() << "\""; - configFileWithPath=configFile; + if (!AbsPath && TString(gSystem->FindFile(config_dir.Data(), configFile)) != TString("")) { + LOG(info) << "---------------CONFIG_DIR is used: " << config_dir.Data() << " to get \"" << configFile.Data() + << "\""; + configFileWithPath = configFile; } else { - if (AbsPath) { configFileWithPath = lUserConfig; } - else { configFileWithPath =work_config+lUserConfig; } + if (AbsPath) { + configFileWithPath = lUserConfig; + } else { + configFileWithPath = work_config + lUserConfig; + } } return configFileWithPath; } @@ -210,9 +208,9 @@ void FairYamlVMCConfig::StoreYamlInfo() nodestring << fYamlConfig; nodestring << "\n"; TObjString* configObject = new TObjString(nodestring.str().c_str()); - FairRunSim::Instance()->GetSink()->WriteObject(configObject,"SimulationSetup", TObject::kSingleKey); + FairRunSim::Instance()->GetSink()->WriteObject(configObject, "SimulationSetup", TObject::kSingleKey); LOG(info) << "FairYamlVMCConfig::StoreYamlInfo() done."; } -ClassImp(FairYamlVMCConfig) +ClassImp(FairYamlVMCConfig); diff --git a/fairtools/MCConfigurator/FairYamlVMCConfig.h b/fairtools/MCConfigurator/FairYamlVMCConfig.h index 961549faab..fc5e570f19 100644 --- a/fairtools/MCConfigurator/FairYamlVMCConfig.h +++ b/fairtools/MCConfigurator/FairYamlVMCConfig.h @@ -41,5 +41,3 @@ class FairYamlVMCConfig : public FairGenericVMCConfig }; #endif - - diff --git a/fairtools/MCStepLogger/MCStepInterceptor.cxx b/fairtools/MCStepLogger/MCStepInterceptor.cxx index 67000454f7..09895c8fbc 100644 --- a/fairtools/MCStepLogger/MCStepInterceptor.cxx +++ b/fairtools/MCStepLogger/MCStepInterceptor.cxx @@ -29,49 +29,49 @@ // @brief Modified for FairRoot // (re)declare symbols to be able to hook into them -#define DECLARE_INTERCEPT_SYMBOLS(APP) \ - class APP \ - { \ - public: \ - void Stepping(); \ - void FinishEvent(); \ - void FinishRun(); \ - }; \ +#define DECLARE_INTERCEPT_SYMBOLS(APP) \ + class APP \ + { \ + public: \ + void Stepping(); \ + void FinishEvent(); \ + void FinishRun(); \ + }; DECLARE_INTERCEPT_SYMBOLS(FairMCApplication) -extern "C" void performLogging(FairMCApplication*); -extern "C" void dispatchStepping(FairMCApplication*, char const *libname, char const*); -extern "C" void dispatchFinishEvent(FairMCApplication*, char const *libname, char const*); -extern "C" void dispatchFinishRun(FairMCApplication*, char const *libname, char const*); +extern "C" void performLogging(FairMCApplication *); +extern "C" void dispatchStepping(FairMCApplication *, char const *libname, char const *); +extern "C" void dispatchFinishEvent(FairMCApplication *, char const *libname, char const *); +extern "C" void dispatchFinishRun(FairMCApplication *, char const *libname, char const *); extern "C" void flushLog(); extern "C" void flushFinalLog(); -#define INTERCEPT_STEPPING(APP, LIB, SYMBOL) \ - void APP::Stepping() \ - { \ - auto baseptr=reinterpret_cast(this); \ - performLogging(baseptr); \ - dispatchStepping(baseptr, LIB, SYMBOL); \ - } \ +#define INTERCEPT_STEPPING(APP, LIB, SYMBOL) \ + void APP::Stepping() \ + { \ + auto baseptr = reinterpret_cast(this); \ + performLogging(baseptr); \ + dispatchStepping(baseptr, LIB, SYMBOL); \ + } -#define INTERCEPT_FINISHEVENT(APP, LIB, SYMBOL) \ - void APP::FinishEvent() \ - { \ - auto baseptr=reinterpret_cast(this); \ - flushLog(); \ - dispatchFinishEvent(baseptr, LIB, SYMBOL); \ - } \ +#define INTERCEPT_FINISHEVENT(APP, LIB, SYMBOL) \ + void APP::FinishEvent() \ + { \ + auto baseptr = reinterpret_cast(this); \ + flushLog(); \ + dispatchFinishEvent(baseptr, LIB, SYMBOL); \ + } -#define INTERCEPT_FINISHRUN(APP, LIB, SYMBOL) \ - void APP::FinishRun() \ - { \ - auto baseptr=reinterpret_cast(this); \ - flushFinalLog(); \ - dispatchFinishRun(baseptr, LIB, SYMBOL); \ - } \ +#define INTERCEPT_FINISHRUN(APP, LIB, SYMBOL) \ + void APP::FinishRun() \ + { \ + auto baseptr = reinterpret_cast(this); \ + flushFinalLog(); \ + dispatchFinishRun(baseptr, LIB, SYMBOL); \ + } // the runtime will now dispatch to these functions due to LD_PRELOAD -INTERCEPT_STEPPING(FairMCApplication,"libBase","_ZN17FairMCApplication8SteppingEv") -INTERCEPT_FINISHEVENT(FairMCApplication,"libBase","_ZN17FairMCApplication11FinishEventEv") -INTERCEPT_FINISHRUN(FairMCApplication,"libBase","_ZN17FairMCApplication9FinishRunEv") +INTERCEPT_STEPPING(FairMCApplication, "libBase", "_ZN17FairMCApplication8SteppingEv") +INTERCEPT_FINISHEVENT(FairMCApplication, "libBase", "_ZN17FairMCApplication11FinishEventEv") +INTERCEPT_FINISHRUN(FairMCApplication, "libBase", "_ZN17FairMCApplication9FinishRunEv") diff --git a/fairtools/MCStepLogger/MCStepLoggerImpl.cxx b/fairtools/MCStepLogger/MCStepLoggerImpl.cxx index b334426d1f..27ccce94c4 100644 --- a/fairtools/MCStepLogger/MCStepLoggerImpl.cxx +++ b/fairtools/MCStepLogger/MCStepLoggerImpl.cxx @@ -29,88 +29,93 @@ // @brief Modified for FairRoot #include - +#include // for TAxis +#include // for TAxis +#include // for TH1F #include -#include // for TAxis -#include // for TAxis -#include // for TH1F #include -#include // for TVirtualMCStack - +#include // for TVirtualMCStack +#include #include #include #include #include -#include -#include // for pair +#include // for pair #ifdef NDEBUG #undef NDEBUG #endif class StepLogger { - int stepcounter = 0; + int stepcounter = 0; - std::set trackset; - std::set pdgset; - std::map volumetosteps; - std::map volumetostepsGlobal; - std::map idtovolname; + std::set trackset; + std::set pdgset; + std::map volumetosteps; + std::map volumetostepsGlobal; + std::map idtovolname; - // TODO: consider writing to a TTree/TFile + // TODO: consider writing to a TTree/TFile public: void addStep(TVirtualMC* mc) { - assert(mc); - stepcounter++; - auto stack=mc->GetStack(); - assert(stack); - trackset.insert(stack->GetCurrentTrackNumber()); - pdgset.insert(mc->TrackPid()); - int copyNo; - auto id = mc->CurrentVolID(copyNo); - if (volumetosteps.find(id) == volumetosteps.end()){ - volumetosteps.insert(std::pair(id, 0)); - } else { - volumetosteps[id]++; - } - if (volumetostepsGlobal.find(id) == volumetostepsGlobal.end()){ - volumetostepsGlobal.insert(std::pair(id, 0)); - } else { - volumetostepsGlobal[id]++; - } - if (idtovolname.find(id) == idtovolname.end()) { - idtovolname.insert(std::pair(id, mc->CurrentVolName())); - } + assert(mc); + stepcounter++; + auto stack = mc->GetStack(); + assert(stack); + trackset.insert(stack->GetCurrentTrackNumber()); + pdgset.insert(mc->TrackPid()); + int copyNo; + auto id = mc->CurrentVolID(copyNo); + if (volumetosteps.find(id) == volumetosteps.end()) { + volumetosteps.insert(std::pair(id, 0)); + } else { + volumetosteps[id]++; + } + if (volumetostepsGlobal.find(id) == volumetostepsGlobal.end()) { + volumetostepsGlobal.insert(std::pair(id, 0)); + } else { + volumetostepsGlobal[id]++; + } + if (idtovolname.find(id) == idtovolname.end()) { + idtovolname.insert(std::pair(id, mc->CurrentVolName())); + } } - void clear() { - stepcounter = 0; - trackset.clear(); - pdgset.clear(); - volumetosteps.clear(); + void clear() + { + stepcounter = 0; + trackset.clear(); + pdgset.clear(); + volumetosteps.clear(); } - void flush() { - std::cerr << "did " << stepcounter << " steps \n"; - std::cerr << "transported " << trackset.size() << " different tracks \n"; - std::cerr << "transported " << pdgset.size() << " different types \n"; - // summarize steps per volume - for (auto& p : volumetosteps) { - std::cout << " VolName " << idtovolname[p.first] << " COUNT " << p.second << "\n"; - } - clear(); + void flush() + { + std::cerr << "did " << stepcounter << " steps \n"; + std::cerr << "transported " << trackset.size() << " different tracks \n"; + std::cerr << "transported " << pdgset.size() << " different types \n"; + // summarize steps per volume + for (auto& p : volumetosteps) { + std::cout << " VolName " << idtovolname[p.first] << " COUNT " << p.second << "\n"; + } + clear(); } - void flushFinal() { + void flushFinal() + { // summarize steps per volume - TFile* stepLoggerFile = TFile::Open("stepLogger.root","recreate"); - TH1F* stepLoggerHistogram = new TH1F("stepLoggerHistogram","Step logger results;volume number;number of steps",volumetostepsGlobal.size(),0.5,volumetostepsGlobal.size()+0.5); + TFile* stepLoggerFile = TFile::Open("stepLogger.root", "recreate"); + TH1F* stepLoggerHistogram = new TH1F("stepLoggerHistogram", + "Step logger results;volume number;number of steps", + volumetostepsGlobal.size(), + 0.5, + volumetostepsGlobal.size() + 0.5); uint binNumber = 0; for (auto& p : volumetostepsGlobal) { std::cout << " VolName " << idtovolname[p.first] << " COUNT " << p.second << "\n"; - stepLoggerHistogram->SetBinContent(++binNumber,p.second); - stepLoggerHistogram->GetXaxis()->SetBinLabel ( binNumber,idtovolname[p.first]); + stepLoggerHistogram->SetBinContent(++binNumber, p.second); + stepLoggerHistogram->GetXaxis()->SetBinLabel(binNumber, idtovolname[p.first]); } stepLoggerHistogram->DrawClone(); stepLoggerFile->Write(); @@ -122,113 +127,109 @@ StepLogger logger; // a generic function that can dispatch to the original method of a FairMCApplication // (for functions of type void FairMCApplication::Method(void); ) -// RK: did two versions, because on the first call while Stepping the origMethod was set to avoid calling it over and over again -// RK: but this setting also prevented the FinishEvent ever be calling - instead Stepping was also called +// RK: did two versions, because on the first call while Stepping the origMethod was set to avoid calling it over and +// over again RK: but this setting also prevented the FinishEvent ever be calling - instead Stepping was also called extern "C" void dispatchStepping(FairMCApplication* app, char const* libname, char const* origFunctionName) { - typedef void (FairMCApplication::*StepMethodType)(); - static StepMethodType origMethod = nullptr; - if (origMethod == nullptr) { - auto libHandle = dlopen(libname, RTLD_NOW); - // try to make the library loading a bit more portable: - if (!libHandle){ - // try appending *.so - std::stringstream stream; - stream << libname << ".so"; - libHandle = dlopen(stream.str().c_str(), RTLD_NOW); - } - if (!libHandle){ - // try appending *.dylib - std::stringstream stream; - stream << libname << ".dylib"; - libHandle = dlopen(stream.str().c_str(), RTLD_NOW); + typedef void (FairMCApplication::*StepMethodType)(); + static StepMethodType origMethod = nullptr; + if (origMethod == nullptr) { + auto libHandle = dlopen(libname, RTLD_NOW); + // try to make the library loading a bit more portable: + if (!libHandle) { + // try appending *.so + std::stringstream stream; + stream << libname << ".so"; + libHandle = dlopen(stream.str().c_str(), RTLD_NOW); + } + if (!libHandle) { + // try appending *.dylib + std::stringstream stream; + stream << libname << ".dylib"; + libHandle = dlopen(stream.str().c_str(), RTLD_NOW); + } + assert(libHandle); + void* symbolAddress = dlsym(libHandle, origFunctionName); + assert(symbolAddress); + // hack since C++ does not allow casting to C++ member function pointers + // thanks to gist.github.com/mooware/1174572 + memcpy(&origMethod, &symbolAddress, sizeof(symbolAddress)); } - assert(libHandle); - void* symbolAddress = dlsym(libHandle, origFunctionName); - assert(symbolAddress); - // hack since C++ does not allow casting to C++ member function pointers - // thanks to gist.github.com/mooware/1174572 - memcpy(&origMethod, &symbolAddress, sizeof(symbolAddress)); - } - (app->*origMethod)(); + (app->*origMethod)(); } // a generic function that can dispatch to the original method of a FairMCApplication // (for functions of type void FairMCApplication::Method(void); ) -// RK: did two versions, because on the first call while Stepping the origMethod was set to avoid calling it over and over again -// RK: but this setting also prevented the FinishEvent ever be calling - instead Stepping was also called +// RK: did two versions, because on the first call while Stepping the origMethod was set to avoid calling it over and +// over again RK: but this setting also prevented the FinishEvent ever be calling - instead Stepping was also called extern "C" void dispatchFinishEvent(FairMCApplication* app, char const* libname, char const* origFunctionName) { - typedef void (FairMCApplication::*StepMethodType)(); - static StepMethodType origMethod = nullptr; - if (origMethod == nullptr) { - auto libHandle = dlopen(libname, RTLD_NOW); - // try to make the library loading a bit more portable: - if (!libHandle){ - // try appending *.so - std::stringstream stream; - stream << libname << ".so"; - libHandle = dlopen(stream.str().c_str(), RTLD_NOW); - } - if (!libHandle){ - // try appending *.dylib - std::stringstream stream; - stream << libname << ".dylib"; - libHandle = dlopen(stream.str().c_str(), RTLD_NOW); + typedef void (FairMCApplication::*StepMethodType)(); + static StepMethodType origMethod = nullptr; + if (origMethod == nullptr) { + auto libHandle = dlopen(libname, RTLD_NOW); + // try to make the library loading a bit more portable: + if (!libHandle) { + // try appending *.so + std::stringstream stream; + stream << libname << ".so"; + libHandle = dlopen(stream.str().c_str(), RTLD_NOW); + } + if (!libHandle) { + // try appending *.dylib + std::stringstream stream; + stream << libname << ".dylib"; + libHandle = dlopen(stream.str().c_str(), RTLD_NOW); + } + assert(libHandle); + void* symbolAddress = dlsym(libHandle, origFunctionName); + assert(symbolAddress); + // hack since C++ does not allow casting to C++ member function pointers + // thanks to gist.github.com/mooware/1174572 + memcpy(&origMethod, &symbolAddress, sizeof(symbolAddress)); } - assert(libHandle); - void* symbolAddress = dlsym(libHandle, origFunctionName); - assert(symbolAddress); - // hack since C++ does not allow casting to C++ member function pointers - // thanks to gist.github.com/mooware/1174572 - memcpy(&origMethod, &symbolAddress, sizeof(symbolAddress)); - } - (app->*origMethod)(); + (app->*origMethod)(); } // a generic function that can dispatch to the original method of a FairMCApplication // (for functions of type void FairMCApplication::Method(void); ) -// RK: did two versions, because on the first call while Stepping the origMethod was set to avoid calling it over and over again -// RK: but this setting also prevented the FinishEvent ever be calling - instead Stepping was also called +// RK: did two versions, because on the first call while Stepping the origMethod was set to avoid calling it over and +// over again RK: but this setting also prevented the FinishEvent ever be calling - instead Stepping was also called extern "C" void dispatchFinishRun(FairMCApplication* app, char const* libname, char const* origFunctionName) { - typedef void (FairMCApplication::*StepMethodType)(); - static StepMethodType origMethod = nullptr; - if (origMethod == nullptr) { - auto libHandle = dlopen(libname, RTLD_NOW); - // try to make the library loading a bit more portable: - if (!libHandle){ - // try appending *.so - std::stringstream stream; - stream << libname << ".so"; - libHandle = dlopen(stream.str().c_str(), RTLD_NOW); - } - if (!libHandle){ - // try appending *.dylib - std::stringstream stream; - stream << libname << ".dylib"; - libHandle = dlopen(stream.str().c_str(), RTLD_NOW); + typedef void (FairMCApplication::*StepMethodType)(); + static StepMethodType origMethod = nullptr; + if (origMethod == nullptr) { + auto libHandle = dlopen(libname, RTLD_NOW); + // try to make the library loading a bit more portable: + if (!libHandle) { + // try appending *.so + std::stringstream stream; + stream << libname << ".so"; + libHandle = dlopen(stream.str().c_str(), RTLD_NOW); + } + if (!libHandle) { + // try appending *.dylib + std::stringstream stream; + stream << libname << ".dylib"; + libHandle = dlopen(stream.str().c_str(), RTLD_NOW); + } + assert(libHandle); + void* symbolAddress = dlsym(libHandle, origFunctionName); + assert(symbolAddress); + // hack since C++ does not allow casting to C++ member function pointers + // thanks to gist.github.com/mooware/1174572 + memcpy(&origMethod, &symbolAddress, sizeof(symbolAddress)); } - assert(libHandle); - void* symbolAddress = dlsym(libHandle, origFunctionName); - assert(symbolAddress); - // hack since C++ does not allow casting to C++ member function pointers - // thanks to gist.github.com/mooware/1174572 - memcpy(&origMethod, &symbolAddress, sizeof(symbolAddress)); - } - (app->*origMethod)(); + (app->*origMethod)(); } extern "C" void performLogging(FairMCApplication* app) { - static TVirtualMC* mc = TVirtualMC::GetMC(); - logger.addStep(mc); + static TVirtualMC* mc = TVirtualMC::GetMC(); + logger.addStep(mc); } -extern "C" void flushLog(){ - logger.flush(); -} +extern "C" void flushLog() { logger.flush(); } -extern "C" void flushFinalLog(){ - logger.flushFinal(); -} +extern "C" void flushFinalLog() { logger.flushFinal(); } diff --git a/geane/FairGeane.cxx b/geane/FairGeane.cxx index 1ee0f5ed29..3ee1832bc5 100644 --- a/geane/FairGeane.cxx +++ b/geane/FairGeane.cxx @@ -11,132 +11,137 @@ // #include "FairGeane.h" -#include "FairField.h" // for FairField -#include "FairGeaneApplication.h" // for FairGeaneApplication -#include "FairRunAna.h" // for FairRunAna +#include "FairField.h" // for FairField +#include "FairGeaneApplication.h" // for FairGeaneApplication +#include "FairRunAna.h" // for FairRunAna -#include // for TGeoManager -#include // for TROOT, gROOT -#include // for TString, operator!=, etc -#include // for TSystem, gSystem - -#include // for getenv -#include // for operator<<, basic_ostream, etc +#include // for TGeoManager +#include // for TROOT, gROOT +#include // for TString, operator!=, etc +#include // for TSystem, gSystem +#include // for getenv +#include // for operator<<, basic_ostream, etc using std::cout; using std::endl; // ----- Default constructor ------------------------------------------- -//FairGeane::FairGeane() { +// FairGeane::FairGeane() { // cout << "This ctr should not be called by user !!"<< endl; //} // ----- Standard constructor ------------------------------------------ FairGeane::FairGeane(const char* name, TString UserConfig, TString UserCuts) - : FairTask("Geane Application"), - fApp(new FairGeaneApplication(kTRUE)), - fName(name), - fUserConfig(UserConfig), - fUserCuts (UserCuts) + : FairTask("Geane Application") + , fApp(new FairGeaneApplication(kTRUE)) + , fName(name) + , fUserConfig(UserConfig) + , fUserCuts(UserCuts) { - //Create a new Geometry - new TGeoManager("Geometry", "Geane geometry"); - // now import the geometry from file to the empty TGeo - TGeoManager::Import(name); + // Create a new Geometry + new TGeoManager("Geometry", "Geane geometry"); + // now import the geometry from file to the empty TGeo + TGeoManager::Import(name); } FairGeane::FairGeane(TString UserConfig, TString UserCuts) - : FairTask("Geane Application"), - fApp(new FairGeaneApplication(kFALSE)), - fName(""), - fUserConfig(UserConfig), - fUserCuts (UserCuts) -{ -} - -void FairGeane::SetParTask() + : FairTask("Geane Application") + , fApp(new FairGeaneApplication(kFALSE)) + , fName("") + , fUserConfig(UserConfig) + , fUserCuts(UserCuts) +{} + +void FairGeane::SetParTask() { - cout << "------------------------FairGeane::SetParTask()------------------------------" << endl; + cout << "------------------------FairGeane::SetParTask()------------------------------" << endl; } InitStatus FairGeane::Init() { - cout << "------------------------FairGeane::Init ()------------------------------" << endl; - - TString LibMacro; - TString LibFunction; - TString ConfigMacro; - TString cuts=fUserCuts; - if(cuts== TString("")) { cuts="SetCuts.C"; } - - TString work = getenv("VMCWORKDIR"); - TString work_config=work+"/gconfig/"; - work_config.ReplaceAll("//","/"); - TString config_dir= getenv("CONFIG_DIR"); - config_dir.ReplaceAll("//","/"); - - Bool_t AbsPath=kFALSE; - if (!config_dir.EndsWith("/")) { config_dir+="/"; } - - - TString geaneLibMacro="g3libs.C"; - TString geaneMacro; - if(fUserConfig.IsNull()) { - geaneMacro="Geane.C"; - fUserConfig = geaneMacro; - } else { - if (fUserConfig.Contains("/")) { AbsPath=kTRUE; } - geaneMacro = fUserConfig; - cout << "---------------User config is used : " << geaneMacro.Data() <<"-----------------"<< endl; - } - if (TString(gSystem->FindFile(config_dir.Data(),geaneLibMacro)) != TString("")) { - cout << "---User path for Configuration (g3libs.C) is used : " << config_dir.Data() << endl; - } else { - geaneLibMacro=work_config+"g3libs.C"; - } - LibMacro=geaneLibMacro; - LibFunction="g3libs()"; - - if (!AbsPath && TString(gSystem->FindFile(config_dir.Data(),geaneMacro)) != TString("")) { - cout << "---User path for Configuration (Geane.C) is used : " << config_dir.Data() << endl; - ConfigMacro =geaneMacro; - } else { - if(AbsPath) { ConfigMacro = fUserConfig; } - else { ConfigMacro =work_config+fUserConfig; } - } - - if (!AbsPath &&TString(gSystem->FindFile(config_dir.Data(),cuts)) != TString("")) { - cout << "---User path for Cuts and Processes (SetCuts.C) is used : " << config_dir.Data() << endl; - } else { - cuts =work_config+ "SetCuts.C"; - } - - gROOT->LoadMacro(LibMacro.Data()); - gROOT->ProcessLine(LibFunction.Data()); - - gROOT->LoadMacro(ConfigMacro.Data()); - gROOT->ProcessLine("Config()"); - - //gROOT->LoadMacro(cuts); - //gROOT->ProcessLine("SetCuts()"); - - FairField* field=FairRunAna::Instance()->GetField(); - field->Print(""); - fApp->SetField(field); - - fApp->InitMC(ConfigMacro.Data(), ""); - - cout <<"I- FairGeane::FairGeane: Geane is Initialized " << endl; - return kSUCCESS; - + cout << "------------------------FairGeane::Init ()------------------------------" << endl; + + TString LibMacro; + TString LibFunction; + TString ConfigMacro; + TString cuts = fUserCuts; + if (cuts == TString("")) { + cuts = "SetCuts.C"; + } + + TString work = getenv("VMCWORKDIR"); + TString work_config = work + "/gconfig/"; + work_config.ReplaceAll("//", "/"); + TString config_dir = getenv("CONFIG_DIR"); + config_dir.ReplaceAll("//", "/"); + + Bool_t AbsPath = kFALSE; + if (!config_dir.EndsWith("/")) { + config_dir += "/"; + } + + TString geaneLibMacro = "g3libs.C"; + TString geaneMacro; + if (fUserConfig.IsNull()) { + geaneMacro = "Geane.C"; + fUserConfig = geaneMacro; + } else { + if (fUserConfig.Contains("/")) { + AbsPath = kTRUE; + } + geaneMacro = fUserConfig; + cout << "---------------User config is used : " << geaneMacro.Data() << "-----------------" << endl; + } + if (TString(gSystem->FindFile(config_dir.Data(), geaneLibMacro)) != TString("")) { + cout << "---User path for Configuration (g3libs.C) is used : " << config_dir.Data() << endl; + } else { + geaneLibMacro = work_config + "g3libs.C"; + } + LibMacro = geaneLibMacro; + LibFunction = "g3libs()"; + + if (!AbsPath && TString(gSystem->FindFile(config_dir.Data(), geaneMacro)) != TString("")) { + cout << "---User path for Configuration (Geane.C) is used : " << config_dir.Data() << endl; + ConfigMacro = geaneMacro; + } else { + if (AbsPath) { + ConfigMacro = fUserConfig; + } else { + ConfigMacro = work_config + fUserConfig; + } + } + + if (!AbsPath && TString(gSystem->FindFile(config_dir.Data(), cuts)) != TString("")) { + cout << "---User path for Cuts and Processes (SetCuts.C) is used : " << config_dir.Data() << endl; + } else { + cuts = work_config + "SetCuts.C"; + } + + gROOT->LoadMacro(LibMacro.Data()); + gROOT->ProcessLine(LibFunction.Data()); + + gROOT->LoadMacro(ConfigMacro.Data()); + gROOT->ProcessLine("Config()"); + + // gROOT->LoadMacro(cuts); + // gROOT->ProcessLine("SetCuts()"); + + FairField* field = FairRunAna::Instance()->GetField(); + field->Print(""); + fApp->SetField(field); + + fApp->InitMC(ConfigMacro.Data(), ""); + + cout << "I- FairGeane::FairGeane: Geane is Initialized " << endl; + return kSUCCESS; } -FairGeane::~FairGeane() -{ -} +FairGeane::~FairGeane() {} void FairGeane::SetField(FairField* /*field*/) { - cout<< "\033[5m\033[31m -W- FairGeane::SetField This method is not used anymore, use FairRunAna::SetField instead \033[0m " << endl; + cout << "\033[5m\033[31m -W- FairGeane::SetField This method is not used anymore, use FairRunAna::SetField " + "instead \033[0m " + << endl; } -ClassImp(FairGeane) +ClassImp(FairGeane); diff --git a/geane/FairGeane.h b/geane/FairGeane.h index 4670f987a6..a634c9b0f4 100644 --- a/geane/FairGeane.h +++ b/geane/FairGeane.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // Class for the GEANE initialization @@ -12,23 +12,23 @@ #ifndef FAIRGeane_H #define FAIRGeane_H -#include "FairTask.h" // for FairTask, InitStatus +#include "FairTask.h" // for FairTask, InitStatus -#include // for FairGeane::Class, ClassDef, etc -#include // for TString +#include // for FairGeane::Class, ClassDef, etc +#include // for TString class FairGeaneApplication; class FairField; -class FairGeane : public FairTask +class FairGeane : public FairTask { public: /** Default constructor **/ // FairGeane(); - FairGeane(const char* name, TString UserConfig="", TString UserCuts=""); + FairGeane(const char* name, TString UserConfig = "", TString UserCuts = ""); - FairGeane(TString fUserConfig="", TString fUserCuts=""); + FairGeane(TString fUserConfig = "", TString fUserCuts = ""); InitStatus Init(); @@ -38,13 +38,12 @@ class FairGeane : public FairTask void SetField(FairField* field); - ClassDef(FairGeane,1) + ClassDef(FairGeane, 1) - protected: - FairGeaneApplication* fApp; //! - const char* fName; //! - TString fUserConfig; //! - TString fUserCuts; //! + protected : FairGeaneApplication* fApp; //! + const char* fName; //! + TString fUserConfig; //! + TString fUserCuts; //! private: FairGeane(const FairGeane&); diff --git a/geane/FairGeanePro.cxx b/geane/FairGeanePro.cxx index 5ffab47da9..fd66e04af9 100644 --- a/geane/FairGeanePro.cxx +++ b/geane/FairGeanePro.cxx @@ -11,474 +11,530 @@ // #include "FairGeanePro.h" -#include "FairGeaneApplication.h" // for FairGeaneApplication -#include "FairGeaneUtil.h" // for FairGeaneUtil +#include "FairGeaneApplication.h" // for FairGeaneApplication +#include "FairGeaneUtil.h" // for FairGeaneUtil #include "FairLogger.h" -#include "FairTrackPar.h" // for FairTrackPar -#include "FairTrackParH.h" // for FairTrackParH -#include "FairTrackParP.h" // for FairTrackParP - -#include // for TDatabasePDG -#include // for TGeoTorus -#include // for pow, ACos, Cos, sqrt -#include // for Abs -#include // for TVector3, operator-, etc -#include // for gMC - -#include // for operator<<, basic_ostream, etc -#include // IWYU pragma: keep for fabs +#include "FairTrackPar.h" // for FairTrackPar +#include "FairTrackParH.h" // for FairTrackParH +#include "FairTrackParP.h" // for FairTrackParP + +#include // for TDatabasePDG +#include // for TGeoTorus +#include // for pow, ACos, Cos, sqrt +#include // for Abs +#include // for TVector3, operator-, etc +#include // for gMC +#include // IWYU pragma: keep for fabs +#include // for operator<<, basic_ostream, etc // IWYU pragma: no_include // ----- Default constructor ------------------------------------------- FairGeanePro::FairGeanePro() - : FairPropagator("Geane", "Propagate Tracks"), - gMC3(static_cast (TVirtualMC::GetMC())), - fPropOption(""), - nepred(1), - fdbPDG(TDatabasePDG::Instance()), - afErtrio(nullptr), - GeantCode(0), - ProMode(0), - VName(""), - VCopyNo(0), - VEnter(kTRUE), - fpoint(TVector3(0., 0., 0.)), - fwire1(TVector3(0., 0., 0.)), - fwire2(TVector3(0., 0., 0.)), - fPCA(0), - fRad(0.), - fDi(0.), - fvpf(TVector3(0., 0., 0.)), - fvwi(TVector3(0., 0., 0.)), - ftrklength(0.), - ftrktime(0.), - flag(0), - fApp(FairGeaneApplication::Instance()), - fPrintErrors(kTRUE) + : FairPropagator("Geane", "Propagate Tracks") + , gMC3(static_cast(TVirtualMC::GetMC())) + , fPropOption("") + , nepred(1) + , fdbPDG(TDatabasePDG::Instance()) + , afErtrio(nullptr) + , GeantCode(0) + , ProMode(0) + , VName("") + , VCopyNo(0) + , VEnter(kTRUE) + , fpoint(TVector3(0., 0., 0.)) + , fwire1(TVector3(0., 0., 0.)) + , fwire2(TVector3(0., 0., 0.)) + , fPCA(0) + , fRad(0.) + , fDi(0.) + , fvpf(TVector3(0., 0., 0.)) + , fvwi(TVector3(0., 0., 0.)) + , ftrklength(0.) + , ftrktime(0.) + , flag(0) + , fApp(FairGeaneApplication::Instance()) + , fPrintErrors(kTRUE) { - if(gMC3==NULL) { - LOG(fatal)<<"FairGeanePro::TGeant3 has not been initialized! ABORTING!"; - throw; - } - afErtrio = gMC3->fErtrio; - - - // nepred=1; - xlf[0] = 0.; - // fdbPDG= TDatabasePDG::Instance(); - // fErrorMat= new TArrayD(15); - // afErtrio=gMC3->fErtrio; - // Pos=TVector3(0, 0 , 0); - // PosErr = TVector3(0,0,0); - // Mom=TVector3(0,0,0); - // fTrkPar= new FairTrackPar(); - // ProMode=0; - // FairRunAna *fRun= FairRunAna::Instance(); - // fField= fRun->GetField(); - - // PCA stuff - // fPCA = 0; - /* + if (gMC3 == NULL) { + LOG(fatal) << "FairGeanePro::TGeant3 has not been initialized! ABORTING!"; + throw; + } + afErtrio = gMC3->fErtrio; + + // nepred=1; + xlf[0] = 0.; + // fdbPDG= TDatabasePDG::Instance(); + // fErrorMat= new TArrayD(15); + // afErtrio=gMC3->fErtrio; + // Pos=TVector3(0, 0 , 0); + // PosErr = TVector3(0,0,0); + // Mom=TVector3(0,0,0); + // fTrkPar= new FairTrackPar(); + // ProMode=0; + // FairRunAna *fRun= FairRunAna::Instance(); + // fField= fRun->GetField(); + + // PCA stuff + // fPCA = 0; + /* fpoint = TVector3(0., 0., 0.); fwire1 = TVector3(0., 0., 0.); fwire2 = TVector3(0., 0., 0.); */ - for(int i = 0; i < 5; i++) for(int j = 0; j < 5; j++) { trpmat[i][j] = 0.; } + for (int i = 0; i < 5; i++) + for (int j = 0; j < 5; j++) { + trpmat[i][j] = 0.; + } - // fApp = FairGeaneApplication::Instance(); + // fApp = FairGeaneApplication::Instance(); - // fPropOption = ""; - for(int i = 0; i < 15; i++) { - ein[i] = 0.; - if(i < 3) { - x2[i] = 0; - p2[i] = 0; - x1[i] = 0; - p1[i] = 0; + // fPropOption = ""; + for (int i = 0; i < 15; i++) { + ein[i] = 0.; + if (i < 3) { + x2[i] = 0; + p2[i] = 0; + x1[i] = 0; + p1[i] = 0; + } } - } - - pli[0] = 1.; - pli[1] = 0.; - pli[2] = 0.; - pli[3] = 0.; - pli[4] = 1.; - pli[5] = 0.; - - plo[0] = 0.; - plo[1] = 0.; - plo[2] = 0.; - plo[3] = 1.; - plo[4] = 0.; - plo[5] = 0.; - plo[6] = 0.; - plo[7] = 1.; - plo[8] = 0.; - plo[9] = 0.; - plo[10] = 0.; - plo[11] = 1.; - - // GeantCode = 0; - /* + + pli[0] = 1.; + pli[1] = 0.; + pli[2] = 0.; + pli[3] = 0.; + pli[4] = 1.; + pli[5] = 0.; + + plo[0] = 0.; + plo[1] = 0.; + plo[2] = 0.; + plo[3] = 1.; + plo[4] = 0.; + plo[5] = 0.; + plo[6] = 0.; + plo[7] = 1.; + plo[8] = 0.; + plo[9] = 0.; + plo[10] = 0.; + plo[11] = 1.; + + // GeantCode = 0; + /* VName = ""; VCopyNo = 0; VEnter = kTRUE; */ - } -FairGeanePro::~FairGeanePro() { } +FairGeanePro::~FairGeanePro() {} bool FairGeanePro::Propagate(FairTrackParH* TParam, FairTrackParH* TEnd, int PDG) { - // Propagate a helix track and return a helix (SC system) + // Propagate a helix track and return a helix (SC system) - //bool NeedSDSC=kFALSE; - int ch=1; // CHARGE OF PARTICLE + // bool NeedSDSC=kFALSE; + int ch = 1; // CHARGE OF PARTICLE - double fCov[15], fCovOut[15]; - TParam->GetCovQ(fCov); - - Init(TParam); - double Q = TParam->GetQ(); - if (fabs(Q)>1.E-8) { ch= int (Q/TMath::Abs(Q)); } - if (ProMode==1) { //Propagate to Volume - //***** We have the right representation go further - for(int i=0; i<15; i++) { - ein[i]=fCov[i]; + double fCov[15], fCovOut[15]; + TParam->GetCovQ(fCov); + Init(TParam); + double Q = TParam->GetQ(); + if (fabs(Q) > 1.E-8) { + ch = int(Q / TMath::Abs(Q)); } - if(fPropOption.Contains("V")) { - //LOG(debug) << "Propagate Helix to Volume"; - int option; - if(VEnter) { option =1; } - else { option =2; } - gMC3->Eufilv(1, ein, const_cast(VName.Data()), &VCopyNo, &option); - } else if(fPropOption.Contains("L")) { - if(fPCA == 0) { - gMC3->Eufill(nepred, ein,xlf); - } else if(fPCA != 0) { - - // max length estimate: - // we calculate the geometrical distance of the start point - // from the point/wire extremity and multiply it * 2 - TVector3 start = TVector3(TParam->GetX(), TParam->GetY(), TParam->GetZ()); - double maxdistance = 0; - if(fPCA == 1) { maxdistance = (fpoint - start).Mag(); } - else if(fPCA == 2) { - double distance1, distance2; - distance1 = (fwire1 - start).Mag(); - distance2 = (fwire2 - start).Mag(); - if(distance1 < distance2) { maxdistance = distance2; } - else { maxdistance = distance1; } + if (ProMode == 1) { // Propagate to Volume + //***** We have the right representation go further + for (int i = 0; i < 15; i++) { + ein[i] = fCov[i]; + } + if (fPropOption.Contains("V")) { + // LOG(debug) << "Propagate Helix to Volume"; + int option; + if (VEnter) { + option = 1; + } else { + option = 2; + } + gMC3->Eufilv(1, ein, const_cast(VName.Data()), &VCopyNo, &option); + } else if (fPropOption.Contains("L")) { + if (fPCA == 0) { + gMC3->Eufill(nepred, ein, xlf); + } else if (fPCA != 0) { + + // max length estimate: + // we calculate the geometrical distance of the start point + // from the point/wire extremity and multiply it * 2 + TVector3 start = TVector3(TParam->GetX(), TParam->GetY(), TParam->GetZ()); + double maxdistance = 0; + if (fPCA == 1) { + maxdistance = (fpoint - start).Mag(); + } else if (fPCA == 2) { + double distance1, distance2; + distance1 = (fwire1 - start).Mag(); + distance2 = (fwire2 - start).Mag(); + if (distance1 < distance2) { + maxdistance = distance2; + } else { + maxdistance = distance1; + } + } + maxdistance *= 2.; + + // output + int findpca = + FindPCA(fPCA, PDG, fpoint, fwire1, fwire2, maxdistance, fRad, fvpf, fvwi, fDi, ftrklength); + if (findpca != 0) { + return kFALSE; + } + + // reset parameters + Init(TParam); + gMC3->Eufill(nepred, ein, &ftrklength); + } } - maxdistance *= 2.; + } else if (ProMode == 3) { + LOG(warning) << "Propagate Helix parameter to Plane is not implimented yet"; + return kFALSE; + } + // Propagate + if (Propagate(PDG) == kFALSE) { + return kFALSE; + } - // output - int findpca = FindPCA(fPCA, PDG, fpoint, fwire1, fwire2, maxdistance, fRad, fvpf, fvwi, fDi, ftrklength); - if(findpca != 0) { return kFALSE; } + for (int i = 0; i < 15; i++) { + fCovOut[i] = afErtrio->errout[i]; + if (i == 0) { + fCovOut[i] = fCovOut[i] * ch * ch; + } + if (i > 0 && i < 5) { + fCovOut[i] = fCovOut[i] * ch; + } + } - // reset parameters - Init(TParam); - gMC3->Eufill(nepred, ein, &ftrklength); - } + // do not remove (useful for debug) + if (fabs(p2[0]) < 1e-9 && fabs(p2[1]) < 1e-9 && fabs(p2[2]) < 1e-9) { + return kFALSE; } - } else if(ProMode ==3) { - LOG(warning) << "Propagate Helix parameter to Plane is not implimented yet"; - return kFALSE; - } - //Propagate - if(Propagate(PDG)==kFALSE) { return kFALSE; } - - for(int i=0; i<15; i++) { - fCovOut[i]=afErtrio->errout[i]; - if(i == 0) { fCovOut[i] = fCovOut[i] * ch * ch; } - if(i > 0 && i < 5) { fCovOut[i] = fCovOut[i] * ch; } - } - - // do not remove (useful for debug) - if(fabs(p2[0]) < 1e-9 && fabs(p2[1]) < 1e-9 && fabs(p2[2]) < 1e-9) { return kFALSE; } - TEnd->SetTrackPar(x2[0], x2[1], x2[2],p2[0],p2[1],p2[2], ch ,fCovOut ); - return kTRUE; + TEnd->SetTrackPar(x2[0], x2[1], x2[2], p2[0], p2[1], p2[2], ch, fCovOut); + return kTRUE; } bool FairGeanePro::Propagate(FairTrackParP* /*TStart*/, FairTrackParH* /*TEnd*/, int /*PDG*/) { - // Propagate a parabola track (SD system) and return a helix (SC system) (not used nor implemented) - LOG(warning) << "FairGeanePro::Propagate(FairTrackParP *TParam, FairTrackParH &TEnd, int PDG) : (not used nor implemented)"; + // Propagate a parabola track (SD system) and return a helix (SC system) (not used nor implemented) + LOG(warning) + << "FairGeanePro::Propagate(FairTrackParP *TParam, FairTrackParH &TEnd, int PDG) : (not used nor implemented)"; return kFALSE; } bool FairGeanePro::Propagate(FairTrackParP* TStart, FairTrackParP* TEnd, int PDG) { - // Propagate a parabola track (SD system) and return a parabola (SD system) (not used nor implemented) - int ch=1; // CHARGE OF PARTICLE - double fCov[15], fCovOut[15]; - TStart->GetCovQ(fCov); - - Init(TStart); - double Q = TStart->GetQ() ; - if (Q!=0) { ch= int (Q/TMath::Abs(Q)); } - - if (ProMode==1) { //Propagate to Volume - LOG(warning) << "Propagate Parabola parameter to Volume is not implimented yet"; - return kFALSE; - } else if(ProMode ==3) { - /** We have the right representation go further*/ - for(int i=0; i<15; i++) { - ein[i]=fCov[i]; - + // Propagate a parabola track (SD system) and return a parabola (SD system) (not used nor implemented) + int ch = 1; // CHARGE OF PARTICLE + double fCov[15], fCovOut[15]; + TStart->GetCovQ(fCov); + + Init(TStart); + double Q = TStart->GetQ(); + if (Q != 0) { + ch = int(Q / TMath::Abs(Q)); } - if(fPropOption.Contains("P")) { gMC3->Eufilp(nepred, ein, pli, plo); } - else if(fPropOption.Contains("L")) { - if(fPCA == 0) { LOG(warning) << "Propagate Parabola to Parabola in Length not yet implemented"; } - else if(fPCA != 0) { - - // max length estimate: - // we calculate the geometrical distance of the start point - // from the point/wire extremity and multiply it * 2 - TVector3 start = TVector3(TStart->GetX(), TStart->GetY(), TStart->GetZ()); - double maxdistance = 0; - if(fPCA == 1) { maxdistance = (fpoint - start).Mag(); } - else if(fPCA == 2) { - double distance1, distance2; - distance1 = (fwire1 - start).Mag(); - distance2 = (fwire2 - start).Mag(); - if(distance1 < distance2) { maxdistance = distance2; } - else { maxdistance = distance1; } + if (ProMode == 1) { // Propagate to Volume + LOG(warning) << "Propagate Parabola parameter to Volume is not implimented yet"; + return kFALSE; + } else if (ProMode == 3) { + /** We have the right representation go further*/ + for (int i = 0; i < 15; i++) { + ein[i] = fCov[i]; } - maxdistance *= 2.; - - // output - int findpca = FindPCA(fPCA, PDG, fpoint, fwire1, fwire2, maxdistance, fRad, fvpf, fvwi, fDi, ftrklength); - //LOG(info)<<" FairGeanePro::ftrklength="<1E-4) { - LOG(fatal)<<"fromwire.Mag()!=1"; - return kFALSE; + + if (fPropOption.Contains("P")) { + gMC3->Eufilp(nepred, ein, pli, plo); + } else if (fPropOption.Contains("L")) { + if (fPCA == 0) { + LOG(warning) << "Propagate Parabola to Parabola in Length not yet implemented"; + } else if (fPCA != 0) { + + // max length estimate: + // we calculate the geometrical distance of the start point + // from the point/wire extremity and multiply it * 2 + TVector3 start = TVector3(TStart->GetX(), TStart->GetY(), TStart->GetZ()); + double maxdistance = 0; + if (fPCA == 1) { + maxdistance = (fpoint - start).Mag(); + } else if (fPCA == 2) { + double distance1, distance2; + distance1 = (fwire1 - start).Mag(); + distance2 = (fwire2 - start).Mag(); + if (distance1 < distance2) { + maxdistance = distance2; + } else { + maxdistance = distance1; + } + } + maxdistance *= 2.; + + // output + int findpca = + FindPCA(fPCA, PDG, fpoint, fwire1, fwire2, maxdistance, fRad, fvpf, fvwi, fDi, ftrklength); + // LOG(info)<<" FairGeanePro::ftrklength="< 1E-4) { + LOG(fatal) << "fromwire.Mag()!=1"; + return kFALSE; + } + + // for wires: + // unitary vector along the wire + TVector3 wiredirection = fwire2 - fwire1; + if (fPCA == 1) { // point + TVector3 mom(TStart->GetPx(), TStart->GetPy(), TStart->GetPz()); + wiredirection = mom.Cross(fromwiretoextr); + } + wiredirection.SetMag(1.); + // check orthogonality + if (fabs(fromwiretoextr * wiredirection) > 1e-3) { + return kFALSE; // throw away the event + // wiredirection = (fromwiretoextr.Cross(wiredirection)).Cross(fromwiretoextr); + // wiredirection.SetMag(1.); + } + + TVector3 jver = TStart->GetJVer(); + ; + TVector3 kver = TStart->GetKVer(); + bool backtracking = kFALSE; + if (fPropOption.Contains("B")) { + backtracking = kTRUE; + } + SetOriginPlane(jver, kver); + SetDestinationPlane(fvwi, fromwiretoextr, wiredirection); + if (backtracking == kTRUE) { + fPropOption = "BPE"; + } + + gMC3->Eufilp(nepred, ein, pli, plo); + } } + } + // Propagate + if (Propagate(PDG) == kFALSE) { + return kFALSE; + } - //for wires: - // unitary vector along the wire - TVector3 wiredirection = fwire2 - fwire1; - if(fPCA==1) { // point - TVector3 mom(TStart->GetPx(),TStart->GetPy(),TStart->GetPz()); - wiredirection=mom.Cross(fromwiretoextr); + for (int i = 0; i < 15; i++) { + fCovOut[i] = afErtrio->errout[i]; + if (i == 0) { + fCovOut[i] = fCovOut[i] * ch * ch; } - wiredirection.SetMag(1.); - // check orthogonality - if(fabs(fromwiretoextr * wiredirection) > 1e-3) { - return kFALSE; // throw away the event - // wiredirection = (fromwiretoextr.Cross(wiredirection)).Cross(fromwiretoextr); - // wiredirection.SetMag(1.); + if (i > 0 && i < 5) { + fCovOut[i] = fCovOut[i] * ch; } - - TVector3 jver = TStart->GetJVer();; - TVector3 kver = TStart->GetKVer(); - bool backtracking = kFALSE; - if(fPropOption.Contains("B")) { backtracking = kTRUE; } - SetOriginPlane (jver, kver); - SetDestinationPlane(fvwi, fromwiretoextr, wiredirection); - if(backtracking == kTRUE) { fPropOption = "BPE"; } - - gMC3->Eufilp(nepred, ein, pli, plo); - } } - } - //Propagate - if(Propagate(PDG)==kFALSE) { return kFALSE; } - - for(int i=0; i<15; i++) { - fCovOut[i]=afErtrio->errout[i]; - if(i == 0) { fCovOut[i] = fCovOut[i] * ch * ch; } - if(i > 0 && i < 5) { fCovOut[i] = fCovOut[i] * ch; } - } - - // plane - TVector3 origin(plo[6], plo[7], plo[8]); - TVector3 dj(plo[0], plo[1], plo[2]); - TVector3 dk(plo[3], plo[4], plo[5]); - TVector3 di(plo[9], plo[10], plo[11]); // = dj.Cross(dk); + // plane + TVector3 origin(plo[6], plo[7], plo[8]); + TVector3 dj(plo[0], plo[1], plo[2]); + TVector3 dk(plo[3], plo[4], plo[5]); + TVector3 di(plo[9], plo[10], plo[11]); // = dj.Cross(dk); - if(fabs(p2[0]) < 1e-9 && fabs(p2[1]) < 1e-9 && fabs(p2[2]) < 1e-9) { return kFALSE; } + if (fabs(p2[0]) < 1e-9 && fabs(p2[1]) < 1e-9 && fabs(p2[2]) < 1e-9) { + return kFALSE; + } - TEnd->SetTrackPar(x2[0], x2[1], x2[2],p2[0],p2[1],p2[2], ch ,fCovOut, origin, di, dj, dk); + TEnd->SetTrackPar(x2[0], x2[1], x2[2], p2[0], p2[1], p2[2], ch, fCovOut, origin, di, dj, dk); - return kTRUE; + return kTRUE; } bool FairGeanePro::Propagate(FairTrackParH* /*TStart*/, FairTrackParP* /*TEnd*/, int /*PDG*/) { - // Propagate a helix track (SC system) and return a parabola (SD system) (not used nor implemented) + // Propagate a helix track (SC system) and return a parabola (SD system) (not used nor implemented) LOG(warning) << "FairGeanePro::Propagate(FairTrackParH *TParam, FairTrackParP &TEnd, int PDG) not implemented"; return kFALSE; } -bool FairGeanePro::Propagate(float* X1, float* P1, float* X2, float* P2,int PDG) +bool FairGeanePro::Propagate(float* X1, float* P1, float* X2, float* P2, int PDG) { -// fApp->GeanePreTrack(X1, P1, PDG); - GeantCode=fdbPDG->ConvertPdgToGeant3(PDG); - xlf[0]=1000 - ; - gMC3->Eufill(1, ein,xlf); - gMC3->Ertrak(X1,P1,X2,P2,GeantCode, "L"); - if(X2[0]<-1.E29) { return kFALSE; } - if(gMC3->IsTrackOut()) { return kFALSE; } - return kTRUE; + // fApp->GeanePreTrack(X1, P1, PDG); + GeantCode = fdbPDG->ConvertPdgToGeant3(PDG); + xlf[0] = 1000; + gMC3->Eufill(1, ein, xlf); + gMC3->Ertrak(X1, P1, X2, P2, GeantCode, "L"); + if (X2[0] < -1.E29) { + return kFALSE; + } + if (gMC3->IsTrackOut()) { + return kFALSE; + } + return kTRUE; } bool FairGeanePro::Propagate(int PDG) { - // main propagate call to fortran ERTRAK - - GeantCode=fdbPDG->ConvertPdgToGeant3(PDG); - //LOG(info) << " FairGeanePro::Propagate ---------------------------"<< " " << x1[0]<< " "<< x1[1]<< " "<< x1[2]; - //fApp->GeanePreTrack(x1, p1, PDG); - gMC3->Ertrak(x1,p1,x2,p2,GeantCode, fPropOption.Data()); - if(x2[0]<-1.E29) { return kFALSE; } - if(gMC3->IsTrackOut()) { return kFALSE; } - - ftrklength=gMC3->TrackLength(); - - ftrktime=gMC3->TrackTime(); - - double trasp[25]; - for(int i = 0; i < 25; i++) { - // trasp[i] = afErtrio->ertrsp[i]; // single precision tr. mat. - trasp[i] = afErtrio->erdtrp[i]; // double precision tr. mat. - } - FairGeaneUtil fUtil; - fUtil.FromVecToMat(trpmat, trasp); - return kTRUE; + // main propagate call to fortran ERTRAK + + GeantCode = fdbPDG->ConvertPdgToGeant3(PDG); + // LOG(info) << " FairGeanePro::Propagate ---------------------------"<< " " << x1[0]<< " "<< x1[1]<< " "<< + // x1[2]; fApp->GeanePreTrack(x1, p1, PDG); + gMC3->Ertrak(x1, p1, x2, p2, GeantCode, fPropOption.Data()); + if (x2[0] < -1.E29) { + return kFALSE; + } + if (gMC3->IsTrackOut()) { + return kFALSE; + } + + ftrklength = gMC3->TrackLength(); + + ftrktime = gMC3->TrackTime(); + + double trasp[25]; + for (int i = 0; i < 25; i++) { + // trasp[i] = afErtrio->ertrsp[i]; // single precision tr. mat. + trasp[i] = afErtrio->erdtrp[i]; // double precision tr. mat. + } + FairGeaneUtil fUtil; + fUtil.FromVecToMat(trpmat, trasp); + return kTRUE; } void FairGeanePro::Init(FairTrackPar* TParam) { - // starting and ending point initialization - x1[0]=TParam->GetX(); - x1[1]=TParam->GetY(); - x1[2]=TParam->GetZ(); - p1[0]=TParam->GetPx(); - p1[1]=TParam->GetPy(); - p1[2]=TParam->GetPz(); - - x2[0]=0; - x2[1]=0; - x2[2]=0; - p2[0]=0; - p2[1]=0; - p2[2]=0; + // starting and ending point initialization + x1[0] = TParam->GetX(); + x1[1] = TParam->GetY(); + x1[2] = TParam->GetZ(); + p1[0] = TParam->GetPx(); + p1[1] = TParam->GetPy(); + p1[2] = TParam->GetPz(); + + x2[0] = 0; + x2[1] = 0; + x2[2] = 0; + p2[0] = 0; + p2[1] = 0; + p2[2] = 0; } bool FairGeanePro::SetOriginPlane(const TVector3& v1, const TVector3& v2) { - // define initial plane (option "P") - TVector3 v1u=v1.Unit(); - TVector3 v2u=v2.Unit(); - pli[0]=v1u.X(); - pli[1]=v1u.Y(); - pli[2]=v1u.Z(); - pli[3]=v2u.X(); - pli[4]=v2u.Y(); - pli[5]=v2u.Z(); - return kTRUE; + // define initial plane (option "P") + TVector3 v1u = v1.Unit(); + TVector3 v2u = v2.Unit(); + pli[0] = v1u.X(); + pli[1] = v1u.Y(); + pli[2] = v1u.Z(); + pli[3] = v2u.X(); + pli[4] = v2u.Y(); + pli[5] = v2u.Z(); + return kTRUE; } bool FairGeanePro::SetDestinationPlane(const TVector3& v0, const TVector3& v1, const TVector3& v2) { - // define final plane (option "P") - // uncomment to set the initial error to zero - // for(int i=0;i<15;i++) ein[i]=0.00; - TVector3 v1u=v1.Unit(); - TVector3 v2u=v2.Unit(); - - - plo[0]=v1u.X(); - plo[1]=v1u.Y(); - plo[2]=v1u.Z(); - plo[3]=v2u.X(); - plo[4]=v2u.Y(); - plo[5]=v2u.Z(); - - plo[6]=v0.X(); - plo[7]=v0.Y(); - plo[8]=v0.Z(); - - TVector3 v3=v1u.Cross(v2u); - - plo[9]=v3(0); - plo[10]=v3(1); - plo[11]=v3(2); - - fPropOption="PE"; - ProMode=3; //need errors in representation 3 (SD)(see Geane doc) - // gMC3->Eufilp(nepred, ein, pli, plo); - return kTRUE; + // define final plane (option "P") + // uncomment to set the initial error to zero + // for(int i=0;i<15;i++) ein[i]=0.00; + TVector3 v1u = v1.Unit(); + TVector3 v2u = v2.Unit(); + + plo[0] = v1u.X(); + plo[1] = v1u.Y(); + plo[2] = v1u.Z(); + plo[3] = v2u.X(); + plo[4] = v2u.Y(); + plo[5] = v2u.Z(); + + plo[6] = v0.X(); + plo[7] = v0.Y(); + plo[8] = v0.Z(); + + TVector3 v3 = v1u.Cross(v2u); + + plo[9] = v3(0); + plo[10] = v3(1); + plo[11] = v3(2); + + fPropOption = "PE"; + ProMode = 3; // need errors in representation 3 (SD)(see Geane doc) + // gMC3->Eufilp(nepred, ein, pli, plo); + return kTRUE; } -bool FairGeanePro::SetDestinationVolume(std::string VolName, int CopyNo , int option) +bool FairGeanePro::SetDestinationVolume(std::string VolName, int CopyNo, int option) { - // define final volume (option "V") - for(int i=0; i<15; i++) { ein[i]=0.00; } - VName= VolName; - VCopyNo= CopyNo; - if(option==1) { VEnter=kTRUE; } - else { VEnter=kFALSE; } - fPropOption="VE"; - ProMode=1; //need errors in representation 1 (SC) (see Geane doc) - return kTRUE; + // define final volume (option "V") + for (int i = 0; i < 15; i++) { + ein[i] = 0.00; + } + VName = VolName; + VCopyNo = CopyNo; + if (option == 1) { + VEnter = kTRUE; + } else { + VEnter = kFALSE; + } + fPropOption = "VE"; + ProMode = 1; // need errors in representation 1 (SC) (see Geane doc) + return kTRUE; } bool FairGeanePro::SetDestinationLength(float length) { - // define final length (option "L") - if(length < 0) { - xlf[0]=-length; - fPropOption="BLE"; - }else { - xlf[0]=length; - fPropOption="LE"; - } - ProMode=1; //need errors in representation 1 (SC)(see Geane doc) - return kTRUE; + // define final length (option "L") + if (length < 0) { + xlf[0] = -length; + fPropOption = "BLE"; + } else { + xlf[0] = length; + fPropOption = "LE"; + } + ProMode = 1; // need errors in representation 1 (SC)(see Geane doc) + return kTRUE; } bool FairGeanePro::SetPropagateOnlyParameters() { - int index = fPropOption.Index("E"); - if(index == -1) { fPropOption.Append("O"); } - else { fPropOption.Replace(index, 1, "O"); } - return kTRUE; + int index = fPropOption.Index("E"); + if (index == -1) { + fPropOption.Append("O"); + } else { + fPropOption.Replace(index, 1, "O"); + } + return kTRUE; } bool FairGeanePro::PropagateFromPlane(const TVector3& v1, const TVector3& v2) { LOG(warning) << "Function PropagateFromPlane depracated, use SetOriginPlane."; - return SetOriginPlane(v1,v2); + return SetOriginPlane(v1, v2); } bool FairGeanePro::PropagateToPlane(const TVector3& v0, const TVector3& v1, const TVector3& v2) { LOG(warning) << "Function PropagateToPlane depracated, use SetDestinationPlane."; - return SetDestinationPlane(v0,v1,v2); + return SetDestinationPlane(v0, v1, v2); } -bool FairGeanePro::PropagateToVolume(TString VolName, int CopyNo , int option) +bool FairGeanePro::PropagateToVolume(TString VolName, int CopyNo, int option) { LOG(warning) << "Function PropagateToVolume depracated, use SetDestinationVolume."; - return SetDestinationVolume(VolName.Data(),CopyNo,option); + return SetDestinationVolume(VolName.Data(), CopyNo, option); } bool FairGeanePro::PropagateToLength(float length) @@ -510,29 +566,27 @@ bool FairGeanePro::SetPoint(TVector3 pnt) bool FairGeanePro::SetPCAPropagation(int pca, int dir, FairTrackParP* par) { - if ( par ) { + if (par) { Init(par); - for(int i=0; i<15; i++) { - ein[i]=0.00; + for (int i = 0; i < 15; i++) { + ein[i] = 0.00; } } // through track length - if(dir > 0) { - fPropOption="LE"; - } - else if(dir < 0) { - fPropOption="BLE"; - } - else { + if (dir > 0) { + fPropOption = "LE"; + } else if (dir < 0) { + fPropOption = "BLE"; + } else { LOG(warning) << "FairGeanePro::SetPCAPropagation ERROR: no direction set"; } - ProMode=1; //need errors in representation 1 (SC)(see Geane doc) + ProMode = 1; // need errors in representation 1 (SC)(see Geane doc) fPCA = pca; // initialization fRad = 0.; fDi = 0.; - fvpf = TVector3(0.,0.,0.); - fvwi = TVector3(0.,0.,0.); + fvpf = TVector3(0., 0., 0.); + fvwi = TVector3(0., 0., 0.); ftrklength = 0; ftrktime = 0; return kTRUE; @@ -547,80 +601,97 @@ bool FairGeanePro::PropagateToPCA(int pca) bool FairGeanePro::PropagateToPCA(int pca, int dir) { LOG(warning) << "Function PropagateToPCA depracated, use SetPCAPropagation."; - return SetPCAPropagation(pca,dir); + return SetPCAPropagation(pca, dir); } bool FairGeanePro::ActualFindPCA(int pca, FairTrackParP* par, int dir) { LOG(warning) << "Function ActualFindPCA depracated, use SetPCAPropagation."; - return SetPCAPropagation(pca,dir,par); + return SetPCAPropagation(pca, dir, par); } bool FairGeanePro::BackTrackToVertex() { - LOG(warning) << "Function BackTrackToVertex questionable, contact FairRoot if you need it."; - // through track length - fPropOption="BLE"; - ProMode=1; //need errors in representation 1 (SC)(see Geane doc) - fPCA = 1; // to point - // initialization (forse non necessario) CHECK!!!! - fRad = 0.; - fDi = 0.; - fvpf = TVector3(0.,0.,0.); - fvwi = TVector3(0.,0.,0.); - ftrklength = 0; - ftrktime = 0; - return kTRUE; + LOG(warning) << "Function BackTrackToVertex questionable, contact FairRoot if you need it."; + // through track length + fPropOption = "BLE"; + ProMode = 1; // need errors in representation 1 (SC)(see Geane doc) + fPCA = 1; // to point + // initialization (forse non necessario) CHECK!!!! + fRad = 0.; + fDi = 0.; + fvpf = TVector3(0., 0., 0.); + fvwi = TVector3(0., 0., 0.); + ftrklength = 0; + ftrktime = 0; + return kTRUE; } bool FairGeanePro::PropagateToVirtualPlaneAtPCA(int pca) { - LOG(warning) << "Function PropagateToVirtualPlaneAtPCA questionable, contact FairRoot if you need it."; - // through track length - fPropOption="LE"; - ProMode=3; //need errors in representation 3 (SD)(see Geane doc) - fPCA = pca; - // initialization - fRad = 0.; - fDi = 0.; - fvpf = TVector3(0.,0.,0.); - fvwi = TVector3(0.,0.,0.); - ftrklength = 0; - ftrktime = 0; - return kTRUE; + LOG(warning) << "Function PropagateToVirtualPlaneAtPCA questionable, contact FairRoot if you need it."; + // through track length + fPropOption = "LE"; + ProMode = 3; // need errors in representation 3 (SD)(see Geane doc) + fPCA = pca; + // initialization + fRad = 0.; + fDi = 0.; + fvpf = TVector3(0., 0., 0.); + fvwi = TVector3(0., 0., 0.); + ftrklength = 0; + ftrktime = 0; + return kTRUE; } bool FairGeanePro::BackTrackToVirtualPlaneAtPCA(int pca) { - LOG(warning) << "Function BackTrackToVirtualPlaneAtPCA questionable, contact FairRoot if you need it."; - // through track length - fPropOption="BLE"; - ProMode=3; //need errors in representation 3 (SD)(see Geane doc) - fPCA = pca; - // initialization - fRad = 0.; - fDi = 0.; - fvpf = TVector3(0.,0.,0.); - fvwi = TVector3(0.,0.,0.); - ftrklength = 0; - ftrktime = 0; - return kTRUE; + LOG(warning) << "Function BackTrackToVirtualPlaneAtPCA questionable, contact FairRoot if you need it."; + // through track length + fPropOption = "BLE"; + ProMode = 3; // need errors in representation 3 (SD)(see Geane doc) + fPCA = pca; + // initialization + fRad = 0.; + fDi = 0.; + fvpf = TVector3(0., 0., 0.); + fvwi = TVector3(0., 0., 0.); + ftrklength = 0; + ftrktime = 0; + return kTRUE; } //===================== -int FairGeanePro::FindPCA(int pca, int PDGCode, TVector3 point, TVector3 wire1, TVector3 wire2, double maxdistance, double& Rad, TVector3& vpf, TVector3& vwi, double& Di, float& trklength) { - LOG(warning) << "Function FindPCA(many parameters) depracated, it is replaced by PCAOutputStruct FindPCA(pca, PDGCode, point, wire1, wire2, maxdistance)."; - PCAOutputStruct pcaoutput = FindPCA(pca,PDGCode,point,wire1,wire2,maxdistance); - Rad = pcaoutput.Radius; - vpf = pcaoutput.OnTrackPCA; - vwi = pcaoutput.OnWirePCA; - Di = pcaoutput.Distance; +int FairGeanePro::FindPCA(int pca, + int PDGCode, + TVector3 point, + TVector3 wire1, + TVector3 wire2, + double maxdistance, + double& Rad, + TVector3& vpf, + TVector3& vwi, + double& Di, + float& trklength) +{ + LOG(warning) << "Function FindPCA(many parameters) depracated, it is replaced by PCAOutputStruct FindPCA(pca, " + "PDGCode, point, wire1, wire2, maxdistance)."; + PCAOutputStruct pcaoutput = FindPCA(pca, PDGCode, point, wire1, wire2, maxdistance); + Rad = pcaoutput.Radius; + vpf = pcaoutput.OnTrackPCA; + vwi = pcaoutput.OnWirePCA; + Di = pcaoutput.Distance; trklength = pcaoutput.TrackLength; return pcaoutput.PCAStatusFlag; } -PCAOutputStruct FairGeanePro::FindPCA(int PCA, int PDGCode, TVector3 Point, TVector3 Wire1, TVector3 Wire2, double MaxDistance) +PCAOutputStruct FairGeanePro::FindPCA(int PCA, + int PDGCode, + TVector3 Point, + TVector3 Wire1, + TVector3 Wire2, + double MaxDistance) { // find the point of closest approach of the track to a point(measured position) or to a line(wire) @@ -646,24 +717,24 @@ PCAOutputStruct FairGeanePro::FindPCA(int PCA, int PDGCode, TVector3 Point, TVec float w1[3] = {static_cast(Wire1.X()), static_cast(Wire1.Y()), static_cast(Wire1.Z())}; float w2[3] = {static_cast(Wire2.X()), static_cast(Wire2.Y()), static_cast(Wire2.Z())}; - GeantCode=fdbPDG->ConvertPdgToGeant3(PDGCode); + GeantCode = fdbPDG->ConvertPdgToGeant3(PDGCode); // flags Rotondi's function - int flg=0; + int flg = 0; // cl track length to the three last points of closest approach // dst assigned distance between initial point in ERTRAK and PFINAL along straight line (currently noy used) - float cl[3],dst; + float cl[3], dst; // GEANE filled points - float po1[3],po2[3],po3[3]; + float po1[3], po2[3], po3[3]; // cl track length to the three last points of closest approach float clen[3]; // track length to add to GEANE computed one - double Le=0.0; - double dist1,dist2; + double Le = 0.0; + double dist1, dist2; // initialization of some variables dst = 999.; @@ -672,684 +743,827 @@ PCAOutputStruct FairGeanePro::FindPCA(int PCA, int PDGCode, TVector3 Point, TVec cl[2] = 0; // GEANE filled points - po1[0]=0; - po1[1]=0; - po1[2]=0; - po2[0]=0; - po2[1]=0; - po2[2]=0; - po3[0]=0; - po3[1]=0; - po3[2]=0; - - gMC3->SetClose(PCA,pf,dst,w1,w2,po1,po2,po3,cl); - - // maximum distance calculated 2 * geometric distance - // start point - end point (the point to which we want - // to find the PCA) - float stdlength[1] = {static_cast(MaxDistance)}; - - gMC3->Eufill(1, ein, stdlength); - - //check needed for low momentum tracks - gMC3->Ertrak(x1,p1,x2,p2,GeantCode, fPropOption.Data()); - if(x2[0]<-1.E29) { return pcastruct; } - if(gMC3->IsTrackOut()) { return pcastruct; } - gMC3->GetClose(po1,po2,po3,clen); - - // check on cases when only two steps are performed! - // in these cases po1[i] = 0 ==> let' s copy po2 into - // po1 in order to use only the two actually extrapolated - // points po2 and po3 to complete the PCA calculation - if(clen[0] == 0 && clen[1] == 0) { - po1[0] = po2[0]; - po1[1] = po2[1]; - po1[2] = po2[2]; - } - - if(PCA == 1) { - if((po1[0] == po2[0] && po1[1] == po2[1] && po1[2] == po2[2]) - || (po2[0] == po3[0] && po2[1] == po3[1] && po2[2] == po3[2])) { - int quitFlag=0; - Track2ToPoint(TVector3(po1),TVector3(po3),TVector3(pf),pcastruct.OnTrackPCA,pcastruct.Distance,Le,quitFlag); - if(quitFlag!=0) { - if(fPrintErrors) { LOG(warning) << "FairGeanePro:FindPCA: Track2ToPoint quitFlag " << quitFlag << " ABORT"; } + po1[0] = 0; + po1[1] = 0; + po1[2] = 0; + po2[0] = 0; + po2[1] = 0; + po2[2] = 0; + po3[0] = 0; + po3[1] = 0; + po3[2] = 0; + + gMC3->SetClose(PCA, pf, dst, w1, w2, po1, po2, po3, cl); + + // maximum distance calculated 2 * geometric distance + // start point - end point (the point to which we want + // to find the PCA) + float stdlength[1] = {static_cast(MaxDistance)}; + + gMC3->Eufill(1, ein, stdlength); + + // check needed for low momentum tracks + gMC3->Ertrak(x1, p1, x2, p2, GeantCode, fPropOption.Data()); + if (x2[0] < -1.E29) { return pcastruct; - } //abort - } else { - Track3ToPoint(TVector3(po1),TVector3(po2),TVector3(po3),TVector3(pf),pcastruct.OnTrackPCA,flg,pcastruct.Distance,Le,pcastruct.Radius); - if(flg==1) { - int quitFlag=0; - Track2ToPoint(TVector3(po1),TVector3(po3),TVector3(pf),pcastruct.OnTrackPCA,pcastruct.Distance,Le,quitFlag); - if(quitFlag!=0) { - if(fPrintErrors) { LOG(warning) << "FairGeanePro:FindPCA: Track2ToPoint quitFlag " << quitFlag << " ABORT"; } - return pcastruct; - } //abort - } else if(flg==2) { - if(fPrintErrors) { LOG(warning)<<"FairGeanePro:FindPCA: Track3ToPoint flg " << flg << " ABORT"; } - return pcastruct; - } //abort } - // if the propagation to closest approach to a POINT is performed - // vwi is the point itself (with respect to which the PCA is calculated) - pcastruct.OnWirePCA = Point; - } else if(PCA == 2) { - if((po1[0] == po2[0] && po1[1] == po2[1] && po1[2] == po2[2]) - || (po2[0] == po3[0] && po2[1] == po3[1] && po2[2] == po3[2])) { - Track2ToLine(TVector3(po1),TVector3(po3),TVector3(w1), - TVector3(w2),pcastruct.OnTrackPCA,pcastruct.OnWirePCA,flg,pcastruct.Distance,Le); - if(flg==1) { - dist1 = (pcastruct.OnWirePCA-TVector3(w1)).Mag(); - dist2 = (pcastruct.OnWirePCA-TVector3(w2)).Mag(); - int quitFlag=0; - dist1IsTrackOut()) { return pcastruct; - } - } else { - Track3ToLine(TVector3(po1),TVector3(po2),TVector3(po3), - TVector3(w1),TVector3(w2),pcastruct.OnTrackPCA,pcastruct.OnWirePCA,flg,pcastruct.Distance,Le,pcastruct.Radius); - if(flg==1) { - Track2ToLine(TVector3(po1),TVector3(po3),TVector3(w1), - TVector3(w2),pcastruct.OnTrackPCA,pcastruct.OnWirePCA,flg,pcastruct.Distance,Le); - if(flg==1) { - dist1 = (pcastruct.OnWirePCA-TVector3(w1)).Mag(); - dist2 = (pcastruct.OnWirePCA-TVector3(w2)).Mag(); - int quitFlag=0; - dist1GetClose(po1, po2, po3, clen); + + // check on cases when only two steps are performed! + // in these cases po1[i] = 0 ==> let' s copy po2 into + // po1 in order to use only the two actually extrapolated + // points po2 and po3 to complete the PCA calculation + if (clen[0] == 0 && clen[1] == 0) { + po1[0] = po2[0]; + po1[1] = po2[1]; + po1[2] = po2[2]; + } + + if (PCA == 1) { + if ((po1[0] == po2[0] && po1[1] == po2[1] && po1[2] == po2[2]) + || (po2[0] == po3[0] && po2[1] == po3[1] && po2[2] == po3[2])) { + int quitFlag = 0; + Track2ToPoint( + TVector3(po1), TVector3(po3), TVector3(pf), pcastruct.OnTrackPCA, pcastruct.Distance, Le, quitFlag); + if (quitFlag != 0) { + if (fPrintErrors) { + LOG(warning) << "FairGeanePro:FindPCA: Track2ToPoint quitFlag " << quitFlag << " ABORT"; + } + return pcastruct; + } // abort + } else { + Track3ToPoint(TVector3(po1), + TVector3(po2), + TVector3(po3), + TVector3(pf), + pcastruct.OnTrackPCA, + flg, + pcastruct.Distance, + Le, + pcastruct.Radius); + if (flg == 1) { + int quitFlag = 0; + Track2ToPoint( + TVector3(po1), TVector3(po3), TVector3(pf), pcastruct.OnTrackPCA, pcastruct.Distance, Le, quitFlag); + if (quitFlag != 0) { + if (fPrintErrors) { + LOG(warning) << "FairGeanePro:FindPCA: Track2ToPoint quitFlag " << quitFlag << " ABORT"; + } + return pcastruct; + } // abort + } else if (flg == 2) { + if (fPrintErrors) { + LOG(warning) << "FairGeanePro:FindPCA: Track3ToPoint flg " << flg << " ABORT"; + } + return pcastruct; + } // abort } - } else if(flg==2) { - dist1 = (pcastruct.OnWirePCA-TVector3(w1)).Mag(); - dist2 = (pcastruct.OnWirePCA-TVector3(w2)).Mag(); - - dist1 Eps) { - double t1 = (a1*e1-b1*d1)/Delta1; - double s1 = (b1*e1-c1*d1)/Delta1; - - Pfinal = (X1 + x21*s1); - Pwire = (w1 + w21*t1); - Length = s1*x21.Mag(); - Dist= (Pfinal-Pwire).Mag(); - - } else { - // lines are paralllel, no solution does exist - Pfinal.SetXYZ(0.,0.,0.); - Pwire.SetXYZ(0.,0.,0.); - Dist=0.; - Length=0.; - Iflag = 2; - return; - } - // flag when the point on the wire is outside (w1,w2) - if((((Pwire[0] 1e-11 && fabs(Pwire[0]- w2[0]) > 1e-11)) - || (((Pwire[1] 1e-11 && fabs(Pwire[1]- w2[1]) > 1e-11)) - || (((Pwire[2] 1e-11 && fabs(Pwire[2]- w2[2]) > 1e-11))) { - Iflag=1; - } + // Closest approach to a line from 2 GEANE points + // + // METHOD: the nearest points on the two lines + // x1,x2 and w1,w2 is found. + // The method is described in: + // http://softsurfer.com/Archive/algorithm_0106/algorithm_0106.htm + // http://www.geometrictools.com/Documentation/DistanceLine3Line3.pdf. + // + // INPUT: x1, x2 closest appoach GEANE points + // w1, w2 points of the line (wire) to approach + // + // OUTPUT: Pfinal point of closest approach on the track + // Pwire point of closest approach on the wire + // Dist distance between Pfian and w1 + // Length arc length to add to the GEANE length of x1 + // Iflag =1 when Pwire is outside [w1,w2] + // In this case, when w1 and w2 are the extremes + // of the wire, the user could remake the procedure + // by calling Track3ToPoint or Track2ToPoint, where the + // Point is w1 or w2; + // = 2 when the two lines are parallel and the solution + // does not exists. + // + // Authors: Andrea Fontana and Alberto Rotondi 20 MAy 2007 + // + + TVector3 x21, x32, w21; + TVector3 xw1, xw2; + + double a1, b1, c1, d1, e1; + double Delta1; + + double Eps = 1.E-08; + + Iflag = 0; + + // line-line distance + x21 = X2 - X1; + w21 = w2 - w1; + + xw1 = X1 - w1; + xw2 = X2 - w1; + + a1 = x21.Mag2(); + b1 = x21.Dot(w21); + c1 = w21.Mag2(); + d1 = xw1.Dot(x21); + e1 = xw1.Dot(w21); + + Delta1 = a1 * c1 - b1 * b1; + + if (Delta1 > Eps) { + double t1 = (a1 * e1 - b1 * d1) / Delta1; + double s1 = (b1 * e1 - c1 * d1) / Delta1; + + Pfinal = (X1 + x21 * s1); + Pwire = (w1 + w21 * t1); + Length = s1 * x21.Mag(); + Dist = (Pfinal - Pwire).Mag(); + + } else { + // lines are paralllel, no solution does exist + Pfinal.SetXYZ(0., 0., 0.); + Pwire.SetXYZ(0., 0., 0.); + Dist = 0.; + Length = 0.; + Iflag = 2; + return; + } + // flag when the point on the wire is outside (w1,w2) + if ((((Pwire[0] < w1[0] && Pwire[0] < w2[0]) || (w2[0] < Pwire[0] && w1[0] < Pwire[0])) + && (fabs(Pwire[0] - w1[0]) > 1e-11 && fabs(Pwire[0] - w2[0]) > 1e-11)) + || (((Pwire[1] < w1[1] && Pwire[1] < w2[1]) || (w2[1] < Pwire[1] && w1[1] < Pwire[1])) + && (fabs(Pwire[1] - w1[1]) > 1e-11 && fabs(Pwire[1] - w2[1]) > 1e-11)) + || (((Pwire[2] < w1[2] && Pwire[2] < w2[2]) || (w2[2] < Pwire[2] && w1[2] < Pwire[2])) + && (fabs(Pwire[2] - w1[2]) > 1e-11 && fabs(Pwire[2] - w2[2]) > 1e-11))) { + Iflag = 1; + } } -void FairGeanePro::Track2ToPoint( TVector3 X1, TVector3 X2, TVector3 w1, TVector3& Pfinal, - double& Dist, double& Length, int& quitFlag) +void FairGeanePro::Track2ToPoint(TVector3 X1, + TVector3 X2, + TVector3 w1, + TVector3& Pfinal, + double& Dist, + double& Length, + int& quitFlag) { - // - // Closest approach to a point from 2 GEANE points - // - // METHOD: the nearest point to w1 on the line x1,x2 - // is found. Elementary vector calculus is used! - // - // INPUT: x1, x2 closest appoach GEANE points - // w1 point to approach w1 - // - // OUTPUT: Pfinal point of closest approach - // Dist distance between Pfinal and w1 - // Length arc length to add to the GEANE length of x1 - // quitFlag error flag which will be set to 1 if points dont form line - // Authors: Andrea Fontana and Alberto Rotondi May 2007 - // - - quitFlag = 0; - - TVector3 u21; - - double a, t1; - - // w-point - x-line distance - double d=(X2-X1).Mag(); - if(fabs(d)<1.E-8) { - quitFlag=1; - return; - } - a= 1./d; - - u21 = (X2-X1).Unit(); - - // output - Dist= ((w1-X1).Cross(u21)).Mag(); - t1 = a*(w1-X1).Dot(u21); - Pfinal = (X2-X1)*t1 + X1; - Length = (X2-X1).Mag()*t1; + // + // Closest approach to a point from 2 GEANE points + // + // METHOD: the nearest point to w1 on the line x1,x2 + // is found. Elementary vector calculus is used! + // + // INPUT: x1, x2 closest appoach GEANE points + // w1 point to approach w1 + // + // OUTPUT: Pfinal point of closest approach + // Dist distance between Pfinal and w1 + // Length arc length to add to the GEANE length of x1 + // quitFlag error flag which will be set to 1 if points dont form line + // Authors: Andrea Fontana and Alberto Rotondi May 2007 + // + + quitFlag = 0; + + TVector3 u21; + + double a, t1; + + // w-point - x-line distance + double d = (X2 - X1).Mag(); + if (fabs(d) < 1.E-8) { + quitFlag = 1; + return; + } + a = 1. / d; + + u21 = (X2 - X1).Unit(); + + // output + Dist = ((w1 - X1).Cross(u21)).Mag(); + t1 = a * (w1 - X1).Dot(u21); + Pfinal = (X2 - X1) * t1 + X1; + Length = (X2 - X1).Mag() * t1; } -void FairGeanePro::Track3ToLine(TVector3 X1, TVector3 X2, TVector3 X3, - TVector3 w1, TVector3 w2, +void FairGeanePro::Track3ToLine(TVector3 X1, + TVector3 X2, + TVector3 X3, + TVector3 w1, + TVector3 w2, // output - TVector3& Pfinal, TVector3& Wire, - int& Iflag, double& Dist, - double& Length, double& Radius) + TVector3& Pfinal, + TVector3& Wire, + int& Iflag, + double& Dist, + double& Length, + double& Radius) { - // Find the closest approach points between a curve (helix) - // and a line (wire) - // - // METHOD:the classical Eberly method is used: see - // http://www.geometrictools.com/Documentation/DistanceLine3Circle.pdf. - // (see also www.geometrictools.com for the other formulae used - // in this interface). - // The 4-degree polynomial resulting for the line parameter t is - // solved with the efficient SolveQuartic Root routine. - // The minimal distance solution is found by using our Track3ToPoint - // routine - // - // INPUT: x1, x2, x3 closest appoach GEANE points - // w1, w2 points of the line (wire) to approach - // - // OUTPUT: Pfinal track point of closest approach - // Wire line point of closest approach - // Iflag = 1, the points are on a straight line - // within the precision of the method (20 micron). - // In this case the user should recall Track2ToPoint - // = 2, Pwire is outside [w1,w2] - // In this case, when w1 and w2 are the extremes - // of the wire, the user could remake the procedure - // by calling Track3ToPoint, where the Point is w1 or w2. - // = 3 both conditions 1 and 2 are encountered - // = 4, the method failed for mathematical reasons. - // In this case the user should use Track2ToLine where - // x1=x1 and x2=x3. - // Dist distance between Pfinal and Wire - // Length arc length to add to the GEANE length of x1 - // Radius radius of the found circle - // - // Authors: Andrea Fontana and Alberto Rotondi 20 June 2007 - // - - TVector3 xp1, xp2, xp3, xp32; - TVector3 x21, x31; - TVector3 e1, e2, e3, aperp; - TVector3 Ppfinal, Pwire; - TVector3 wp1, wp2, wpt, xR, xpR; - TVector3 xw1, xw2; - TVector3 px; - - double T[3][3], TM1[3][3]; - - TVector3 N, M, D, B, Pointw; - double a0, a1, b0, b1, c0, c1, c2; - double d0, d1, d2, d3, d4, sol4[4], dmin; - double Angle; - double dx; - int it, imin; - - Iflag = 0; - - // go to the circle plane: matrix of director cosines - - x21 = X2-X1; - e1 = x21.Unit(); - T[0][0] = e1.X(); - T[0][1] = e1.Y(); - T[0][2] = e1.Z(); - - x31 = X3-X1; - e3 = e1.Cross(x31); - // if the points are on the same line - if(e3.Mag() < 1e-8) { - Iflag = 1; - return; - } - e3 = e3.Unit(); - - T[2][0] = e3.X(); - T[2][1] = e3.Y(); - T[2][2] = e3.Z(); - - e2 = e3.Cross(e1); - T[1][0] = e2.X(); - T[1][1] = e2.Y(); - T[1][2] = e2.Z(); - - // new coordinates - for(int i=0; i<3; i++) { - xp1[i]=0.; - xp2[i]=0.; - xp3[i]=0.; - wp1[i]=0.; - wp2[i]=0.; - } - for(int i=0; i<3; i++) { - xp1[i] = 0.; - for(int j=0; j<3; j++) { - TM1[i][j] = T[j][i]; - xp2[i] += T[i][j] * (X2[j]-X1[j]); - xp3[i] += T[i][j] * (X3[j]-X1[j]); - wp1[i] += T[i][j] * (w1[j]-X1[j]); - wp2[i] += T[i][j] * (w2[j]-X1[j]); + // Find the closest approach points between a curve (helix) + // and a line (wire) + // + // METHOD:the classical Eberly method is used: see + // http://www.geometrictools.com/Documentation/DistanceLine3Circle.pdf. + // (see also www.geometrictools.com for the other formulae used + // in this interface). + // The 4-degree polynomial resulting for the line parameter t is + // solved with the efficient SolveQuartic Root routine. + // The minimal distance solution is found by using our Track3ToPoint + // routine + // + // INPUT: x1, x2, x3 closest appoach GEANE points + // w1, w2 points of the line (wire) to approach + // + // OUTPUT: Pfinal track point of closest approach + // Wire line point of closest approach + // Iflag = 1, the points are on a straight line + // within the precision of the method (20 micron). + // In this case the user should recall Track2ToPoint + // = 2, Pwire is outside [w1,w2] + // In this case, when w1 and w2 are the extremes + // of the wire, the user could remake the procedure + // by calling Track3ToPoint, where the Point is w1 or w2. + // = 3 both conditions 1 and 2 are encountered + // = 4, the method failed for mathematical reasons. + // In this case the user should use Track2ToLine where + // x1=x1 and x2=x3. + // Dist distance between Pfinal and Wire + // Length arc length to add to the GEANE length of x1 + // Radius radius of the found circle + // + // Authors: Andrea Fontana and Alberto Rotondi 20 June 2007 + // + + TVector3 xp1, xp2, xp3, xp32; + TVector3 x21, x31; + TVector3 e1, e2, e3, aperp; + TVector3 Ppfinal, Pwire; + TVector3 wp1, wp2, wpt, xR, xpR; + TVector3 xw1, xw2; + TVector3 px; + + double T[3][3], TM1[3][3]; + + TVector3 N, M, D, B, Pointw; + double a0, a1, b0, b1, c0, c1, c2; + double d0, d1, d2, d3, d4, sol4[4], dmin; + double Angle; + double dx; + int it, imin; + + Iflag = 0; + + // go to the circle plane: matrix of director cosines + + x21 = X2 - X1; + e1 = x21.Unit(); + T[0][0] = e1.X(); + T[0][1] = e1.Y(); + T[0][2] = e1.Z(); + + x31 = X3 - X1; + e3 = e1.Cross(x31); + // if the points are on the same line + if (e3.Mag() < 1e-8) { + Iflag = 1; + return; + } + e3 = e3.Unit(); + + T[2][0] = e3.X(); + T[2][1] = e3.Y(); + T[2][2] = e3.Z(); + + e2 = e3.Cross(e1); + T[1][0] = e2.X(); + T[1][1] = e2.Y(); + T[1][2] = e2.Z(); + + // new coordinates + for (int i = 0; i < 3; i++) { + xp1[i] = 0.; + xp2[i] = 0.; + xp3[i] = 0.; + wp1[i] = 0.; + wp2[i] = 0.; + } + for (int i = 0; i < 3; i++) { + xp1[i] = 0.; + for (int j = 0; j < 3; j++) { + TM1[i][j] = T[j][i]; + xp2[i] += T[i][j] * (X2[j] - X1[j]); + xp3[i] += T[i][j] * (X3[j] - X1[j]); + wp1[i] += T[i][j] * (w1[j] - X1[j]); + wp2[i] += T[i][j] * (w2[j] - X1[j]); + } + } + + // radius and center + + xp32 = xp3 - xp2; + xpR[0] = 0.5 * xp2[0]; + if (fabs(xp3[1]) < 1.E-8) { + Iflag = 4; + return; + } + xpR[1] = 0.5 * (xp32[0] * xp3[0] / xp3[1] + xp3[1]); + xpR[2] = 0.; + Radius = sqrt(pow(xpR[0] - xp1[0], 2) + pow(xpR[1] - xp1[1], 2)); + + // Eberly's method + + B = wp1; + M = wp2 - wp1; + D = wp1 - xpR; + N.SetXYZ(0., 0., 1.); + + a0 = M.Dot(D); + a1 = M.Dot(M); + b0 = M.Dot(D) - (N.Dot(M)) * (N.Dot(D)); + b1 = M.Dot(M) - (N.Dot(M)) * (N.Dot(M)); + c0 = D.Dot(D) - (N.Dot(D)) * (N.Dot(D)); + c1 = b0; + c2 = b1; + + d0 = a0 * a0 * c0 - b0 * b0 * Radius * Radius; + d1 = 2. * (a0 * a1 * c0 + a0 * a0 * c1 - b0 * b1 * Radius * Radius); + d2 = a1 * a1 * c0 + 4. * a0 * a1 * c1 + a0 * a0 * c2 - b1 * b1 * Radius * Radius; + d3 = 2. * (a1 * a1 * c1 + a0 * a1 * c2); + d4 = a1 * a1 * c2; + + // solve the quartic equation + for (int k = 0; k < 4; k++) { + sol4[k] = 0.; + } + if (fabs(d4) < 1.E-12) { + Iflag = 4; + return; + } + + TGeoTorus t; + it = t.SolveQuartic(d3 / d4, d2 / d4, d1 / d4, d0 / d4, sol4); + + if (it == 0) { + Iflag = 4; + return; + } + + // select the right solution + dmin = 1.e+08; + imin = 0; // This was set to -1 which could make problem if the indx is negative!! (MT) + + for (int j = 0; j < it; j++) { + Pointw[0] = B[0] + sol4[j] * M[0]; + Pointw[1] = B[1] + sol4[j] * M[1]; + Pointw[2] = B[2] + sol4[j] * M[2]; + Track3ToPoint(xp1, xp2, xp3, Pointw, px, Iflag, dx, Length, Radius); + if (Iflag == 2) { + Iflag = 4; + return; + } + if (dx < dmin) { + dmin = dx; + imin = j; + } } - } - - // radius and center - - xp32= xp3 - xp2; - xpR[0] = 0.5*xp2[0]; - if(fabs(xp3[1])<1.E-8) { - Iflag = 4; - return; - } - xpR[1] = 0.5*(xp32[0]*xp3[0]/xp3[1]+ xp3[1]); - xpR[2] = 0.; - Radius = sqrt(pow(xpR[0]-xp1[0],2)+pow(xpR[1]-xp1[1],2)); - - // Eberly's method - - B = wp1; - M = wp2 - wp1; - D = wp1-xpR; - N.SetXYZ(0.,0.,1.); - - a0 = M.Dot(D); - a1 = M.Dot(M); - b0 = M.Dot(D) -(N.Dot(M))*(N.Dot(D)); - b1 = M.Dot(M) -(N.Dot(M))*(N.Dot(M)); - c0 = D.Dot(D) -(N.Dot(D))*(N.Dot(D)); - c1 = b0; - c2 = b1; - - d0 = a0*a0*c0 -b0*b0*Radius*Radius; - d1 = 2.*(a0*a1*c0+a0*a0*c1-b0*b1*Radius*Radius); - d2 = a1*a1*c0+4.*a0*a1*c1+a0*a0*c2-b1*b1*Radius*Radius; - d3 = 2.*(a1*a1*c1+a0*a1*c2); - d4 = a1*a1*c2; - - // solve the quartic equation - for(int k=0; k<4; k++) { - sol4[k] =0.; - } - if(fabs(d4) < 1.E-12) { - Iflag = 4; - return; - } - - TGeoTorus t; - it = t.SolveQuartic(d3/d4,d2/d4,d1/d4,d0/d4,sol4); - - if(it==0) { - Iflag = 4; - return; - } - - // select the right solution - dmin = 1.e+08; - imin=0; // This was set to -1 which could make problem if the indx is negative!! (MT) - - for(int j=0; j 1E-8) { + epsi = Radius * (1. - TMath::Cos(0.5 * (X3 - X1).Mag() / Radius)); + } + if (epsi < 0.0020) { + Iflag = 1; + } + + // flag when the point on the wire is outside (w1,w2) + if ((((Wire[0] < w1[0] && Wire[0] < w2[0]) || (w2[0] < Wire[0] && w1[0] < Wire[0])) + && (fabs(Wire[0] - w1[0]) > 1e-11 && fabs(Wire[0] - w2[0]) > 1e-11)) + || (((Wire[1] < w1[1] && Wire[1] < w2[1]) || (w2[1] < Wire[1] && w1[1] < Wire[1])) + && (fabs(Wire[1] - w1[1]) > 1e-11 && fabs(Wire[1] - w2[1]) > 1e-11)) + || (((Wire[2] < w1[2] && Wire[2] < w2[2]) || (w2[2] < Wire[2] && w1[2] < Wire[2])) + && (fabs(Wire[2] - w1[2]) > 1e-11 && fabs(Wire[2] - w2[2]) > 1e-11))) { + Iflag = 2; } - } - Pfinal = Pfinal+X1; - Wire = Wire + X1; - xR = xR + X1; - - double dx1=(X1-xR).Mag(); - double dx2=(Pfinal-xR).Mag(); - double dx12=dx1*dx2; - if(fabs(dx12)<1.E-8) { - Iflag = 4; - return; - } - - // now find the length - Angle = TMath::ACos((X1-xR).Dot(Pfinal-xR)/(dx12)); - Length = Radius*Angle; - if((X2-X1).Dot(Pfinal-X1) < 0.) { Length = -Length; } - - // flag straight points within 20 microns - double epsi=0; - if(Radius>1E-8) { epsi = Radius*(1.-TMath::Cos(0.5*(X3-X1).Mag()/Radius)); } - if(epsi < 0.0020) { Iflag=1; } - - // flag when the point on the wire is outside (w1,w2) - if((((Wire[0] 1e-11 && fabs(Wire[0]- w2[0]) > 1e-11)) - || (((Wire[1] 1e-11 && fabs(Wire[1]- w2[1]) > 1e-11)) - || (((Wire[2] 1e-11 && fabs(Wire[2]- w2[2]) > 1e-11))) { - Iflag=2; - } } -void FairGeanePro::Track3ToPoint( TVector3 X1, TVector3 X2, TVector3 X3, TVector3 w1, - // output - TVector3& Pfinal, int& Iflag, - double& Dist, double& Length, double& Radius) +void FairGeanePro::Track3ToPoint(TVector3 X1, + TVector3 X2, + TVector3 X3, + TVector3 w1, + // output + TVector3& Pfinal, + int& Iflag, + double& Dist, + double& Length, + double& Radius) { - // Closest approach to a point from 3 GEANE points - // - // METHOD: first, we go on the circle plane to have - // x1=(0,0), x2=(x2,0), x3=(x3,y3). - // Then, the point on the circle is found as the - // intersection between the circle and the line - // joining the circle center and the projection of - // the point on the circle plane. - // The 3D distance is found between w1 and this - // point on the circle. - // - // INPUT: x1, x2, x3 closest appoach GEANE points - // w1 point to approach - // - // OUTPUT: Pfinal point of closest approach on the track - // Dist distance between Pfinal and w1 - // Length arc length to add to the GEANE length of x1 - // Iflag when =1 the points are on a straight line - // within the precision of the method (20 micron). - // In this case the user should recall Track2ToPoint - // if =2 mathematical errors - // Authors: Andrea Fontana and Alberto Rotondi 20 May 2007 - // - - TVector3 xp1, xp2, xp3, xp32; - TVector3 x21, x31; - TVector3 e1, e2, e3; - TVector3 Ppfinal, x32; - TVector3 wp1, wpt, xR, xpR; - TVector3 xw1, xw2; - - TVector3 xc1, xc2, xc3, wc1; - - double m1, m3, Rt; - double T[3][3], TM1[3][3]; - - double Angle; - - Iflag = 0; - - // go to the circle plane with origin in x1 prime (xp1): - // matrix of director cosines - - x21 = X2-X1; - - double x21mag=x21.Mag(); - if(x21mag<1.E-8) { - Iflag=2; - return; - } - - m1 = 1./x21mag; - e1 = m1*x21; - T[0][0] = e1.X(); - T[0][1] = e1.Y(); - T[0][2] = e1.Z(); - - x31 = X3-X1; - e3 = e1.Cross(x31); - - // if the points are on the same line - if(e3.Mag() < 1e-8) { - Iflag = 1; - return; - } - - m3 = 1./e3.Mag(); - e3 = m3*e3; - T[2][0] = e3.X(); - T[2][1] = e3.Y(); - T[2][2] = e3.Z(); - - e2 = e3.Cross(e1); - T[1][0] = e2.X(); - T[1][1] = e2.Y(); - T[1][2] = e2.Z(); - - // new coordinates - for(int i=0; i<3; i++) { - xp1[i]=0.; - xp2[i]=0.; - xp3[i]=0.; - wp1[i]=0.; - } - for(int i=0; i<3; i++) { - for(int j=0; j<3; j++) { - TM1[i][j] = T[j][i]; - xp1[i] += 0.; - xp2[i] += T[i][j] * (X2[j]-X1[j]); - xp3[i] += T[i][j] * (X3[j]-X1[j]); - wp1[i] += T[i][j] * (w1[j]-X1[j]); + // Closest approach to a point from 3 GEANE points + // + // METHOD: first, we go on the circle plane to have + // x1=(0,0), x2=(x2,0), x3=(x3,y3). + // Then, the point on the circle is found as the + // intersection between the circle and the line + // joining the circle center and the projection of + // the point on the circle plane. + // The 3D distance is found between w1 and this + // point on the circle. + // + // INPUT: x1, x2, x3 closest appoach GEANE points + // w1 point to approach + // + // OUTPUT: Pfinal point of closest approach on the track + // Dist distance between Pfinal and w1 + // Length arc length to add to the GEANE length of x1 + // Iflag when =1 the points are on a straight line + // within the precision of the method (20 micron). + // In this case the user should recall Track2ToPoint + // if =2 mathematical errors + // Authors: Andrea Fontana and Alberto Rotondi 20 May 2007 + // + + TVector3 xp1, xp2, xp3, xp32; + TVector3 x21, x31; + TVector3 e1, e2, e3; + TVector3 Ppfinal, x32; + TVector3 wp1, wpt, xR, xpR; + TVector3 xw1, xw2; + + TVector3 xc1, xc2, xc3, wc1; + + double m1, m3, Rt; + double T[3][3], TM1[3][3]; + + double Angle; + + Iflag = 0; + + // go to the circle plane with origin in x1 prime (xp1): + // matrix of director cosines + + x21 = X2 - X1; + + double x21mag = x21.Mag(); + if (x21mag < 1.E-8) { + Iflag = 2; + return; } - } - - // radius Radius and center xpR - - xp32= xp3 - xp2; - xpR[0] = 0.5*xp2[0]; - if(fabs(xp3[1])<1.E-8) { - Iflag = 2; - return; - } - xpR[1] = 0.5*(xp32[0]*xp3[0]/xp3[1]+ xp3[1]); - xpR[2] = 0.; - - Radius = sqrt( pow(xpR[0]-xp1[0],2) + pow(xpR[1]-xp1[1],2) ); - - // distance and points - wpt = wp1; - wpt[2] =0.; // point projection on the circle plane - - double dwp=(wpt-xpR).Mag(); - if(fabs(dwp)<1.E-8) { - Iflag = 2; - return; - } - Rt = Radius/dwp; - Ppfinal = (wpt-xpR)*Rt + xpR; - Dist = (wp1-Ppfinal).Mag(); - - // back to lab coordinates: - //from Ppfinal to Pfinal and from xpR to xR - - xR[0]=0.; - xR[1]=0.; - xR[2]=0.; - Pfinal[0]=0.; - Pfinal[1]=0.; - Pfinal[2]=0.; - for(int i=0; i<3; i++) { - for(int j=0; j<3; j++) { - Pfinal[i] += TM1[i][j] * Ppfinal[j]; - xR[i] += TM1[i][j] * xpR[j]; + + m1 = 1. / x21mag; + e1 = m1 * x21; + T[0][0] = e1.X(); + T[0][1] = e1.Y(); + T[0][2] = e1.Z(); + + x31 = X3 - X1; + e3 = e1.Cross(x31); + + // if the points are on the same line + if (e3.Mag() < 1e-8) { + Iflag = 1; + return; + } + + m3 = 1. / e3.Mag(); + e3 = m3 * e3; + T[2][0] = e3.X(); + T[2][1] = e3.Y(); + T[2][2] = e3.Z(); + + e2 = e3.Cross(e1); + T[1][0] = e2.X(); + T[1][1] = e2.Y(); + T[1][2] = e2.Z(); + + // new coordinates + for (int i = 0; i < 3; i++) { + xp1[i] = 0.; + xp2[i] = 0.; + xp3[i] = 0.; + wp1[i] = 0.; + } + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + TM1[i][j] = T[j][i]; + xp1[i] += 0.; + xp2[i] += T[i][j] * (X2[j] - X1[j]); + xp3[i] += T[i][j] * (X3[j] - X1[j]); + wp1[i] += T[i][j] * (w1[j] - X1[j]); + } + } + + // radius Radius and center xpR + + xp32 = xp3 - xp2; + xpR[0] = 0.5 * xp2[0]; + if (fabs(xp3[1]) < 1.E-8) { + Iflag = 2; + return; + } + xpR[1] = 0.5 * (xp32[0] * xp3[0] / xp3[1] + xp3[1]); + xpR[2] = 0.; + + Radius = sqrt(pow(xpR[0] - xp1[0], 2) + pow(xpR[1] - xp1[1], 2)); + + // distance and points + wpt = wp1; + wpt[2] = 0.; // point projection on the circle plane + + double dwp = (wpt - xpR).Mag(); + if (fabs(dwp) < 1.E-8) { + Iflag = 2; + return; + } + Rt = Radius / dwp; + Ppfinal = (wpt - xpR) * Rt + xpR; + Dist = (wp1 - Ppfinal).Mag(); + + // back to lab coordinates: + // from Ppfinal to Pfinal and from xpR to xR + + xR[0] = 0.; + xR[1] = 0.; + xR[2] = 0.; + Pfinal[0] = 0.; + Pfinal[1] = 0.; + Pfinal[2] = 0.; + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + Pfinal[i] += TM1[i][j] * Ppfinal[j]; + xR[i] += TM1[i][j] * xpR[j]; + } + } + Pfinal = Pfinal + X1; + xR = xR + X1; + + // now find the length + double dx1 = (X1 - xR).Mag(); + double dx2 = (Pfinal - xR).Mag(); + double dx12 = dx1 * dx2; + if (fabs(dx12) < 1.E-8) { + Iflag = 2; + return; + } + // now find the length + Angle = TMath::ACos((X1 - xR).Dot(Pfinal - xR) / (dx12)); + Length = Radius * Angle; + + // flag straight points within 20 microns + double epsi = 0; + if (Radius > 1E-8) { + epsi = Radius * (1. - TMath::Cos(0.5 * (X3 - X1).Mag() / Radius)); + } + if (epsi < 0.0020) { + Iflag = 1; } - } - Pfinal = Pfinal+X1; - xR = xR +X1; - - // now find the length - double dx1=(X1-xR).Mag(); - double dx2=(Pfinal-xR).Mag(); - double dx12=dx1*dx2; - if(fabs(dx12)<1.E-8) { - Iflag = 2; - return; - } - // now find the length - Angle = TMath::ACos((X1-xR).Dot(Pfinal-xR)/(dx12)); - Length = Radius*Angle; - - // flag straight points within 20 microns - double epsi=0; - if(Radius>1E-8) { epsi = Radius*(1.-TMath::Cos(0.5*(X3-X1).Mag()/Radius)); } - if(epsi < 0.0020) { Iflag=1; } } void FairGeanePro::GetTransportMatrix(double trm[5][5]) { - for(int i = 0; i < 5; i++) for(int j = 0; j < 5; j++) { trm[i][j] = trpmat[i][j]; } + for (int i = 0; i < 5; i++) + for (int j = 0; j < 5; j++) { + trm[i][j] = trpmat[i][j]; + } } -ClassImp(FairGeanePro) +ClassImp(FairGeanePro); diff --git a/geane/FairGeanePro.h b/geane/FairGeanePro.h index 9effff54f2..b9b5618376 100644 --- a/geane/FairGeanePro.h +++ b/geane/FairGeanePro.h @@ -12,13 +12,11 @@ #ifndef FAIRGEANEPRO_H #define FAIRGEANEPRO_H 1 -#include "FairPropagator.h" // for TNamed - #include "FairLogger.h" - -#include "TGeant3.h" // for Ertrio_t, etc -#include "TString.h" // for TString -#include "TVector3.h" // for TVector3 +#include "FairPropagator.h" // for TNamed +#include "TGeant3.h" // for Ertrio_t, etc +#include "TString.h" // for TString +#include "TVector3.h" // for TVector3 class FairTrackPar; class FairTrackParP; @@ -67,13 +65,13 @@ class FairGeanePro : public FairPropagator virtual bool SetDestinationLength(float length); /**New method to set to propagate only parameters - */ + */ virtual bool SetPropagateOnlyParameters(); /* ====== Depracated functions ====== */ bool PropagateToPlane(const TVector3& v0, const TVector3& v1, const TVector3& v2); bool PropagateFromPlane(const TVector3& v1, const TVector3& v2); - bool PropagateToVolume(TString VolName, int CopyNo ,int option); + bool PropagateToVolume(TString VolName, int CopyNo, int option); bool PropagateToLength(float length); bool PropagateOnlyParameters(); /* ====== ====== ====== ====== ====== */ @@ -82,14 +80,56 @@ class FairGeanePro : public FairPropagator bool Propagate(int PDG); private: - void Track2ToLine(TVector3 x1, TVector3 x2, TVector3 w1, TVector3 w2, TVector3& Pfinal, TVector3& Pwire, int& Iflag, double& Dist, double& Length); - void Track2ToPoint(TVector3 x1, TVector3 x2, TVector3 w1, TVector3& Pfinal, double& Dist, double& Length, int& quitFlag); - void Track3ToLine(TVector3 x1, TVector3 x2, TVector3 x3, TVector3 w1, TVector3 w2, TVector3& Pfinal, TVector3& Wire, int& Iflag, double& Dist, double& Length, double& Radius); - void Track3ToPoint(TVector3 x1, TVector3 x2, TVector3 x3, TVector3 w1, TVector3& Pfinal, int& Iflag, double& Dist, double& Length, double& Radius); + void Track2ToLine(TVector3 x1, + TVector3 x2, + TVector3 w1, + TVector3 w2, + TVector3& Pfinal, + TVector3& Pwire, + int& Iflag, + double& Dist, + double& Length); + void Track2ToPoint(TVector3 x1, + TVector3 x2, + TVector3 w1, + TVector3& Pfinal, + double& Dist, + double& Length, + int& quitFlag); + void Track3ToLine(TVector3 x1, + TVector3 x2, + TVector3 x3, + TVector3 w1, + TVector3 w2, + TVector3& Pfinal, + TVector3& Wire, + int& Iflag, + double& Dist, + double& Length, + double& Radius); + void Track3ToPoint(TVector3 x1, + TVector3 x2, + TVector3 x3, + TVector3 w1, + TVector3& Pfinal, + int& Iflag, + double& Dist, + double& Length, + double& Radius); public: /* ====== Depracated functions ====== */ - int FindPCA(int pca, int PDGCode, TVector3 point, TVector3 wire1, TVector3 wire2, double maxdistance, double& Rad, TVector3& vpf, TVector3& vwi, double& Di, float& trklength); + int FindPCA(int pca, + int PDGCode, + TVector3 point, + TVector3 wire1, + TVector3 wire2, + double maxdistance, + double& Rad, + TVector3& vpf, + TVector3& vwi, + double& Di, + float& trklength); bool SetWire(TVector3 extremity1, TVector3 extremity2); bool SetPoint(TVector3 pnt); @@ -99,19 +139,23 @@ class FairGeanePro : public FairPropagator // the PCA. bool ActualFindPCA(int pca, FairTrackParP* par, int dir); - TVector3 GetPCAOnWire() { + TVector3 GetPCAOnWire() + { LOG(warning) << "Function GetPCAOnWire obsolete, contact FairRoot group if you need it."; return fvwi; } - TVector3 GetPCAOnTrack() { + TVector3 GetPCAOnTrack() + { LOG(warning) << "Function GetPCAOnTrack obsolete, contact FairRoot group if you need it."; return fvpf; } - float GetLengthAtPCA() { + float GetLengthAtPCA() + { LOG(warning) << "Function GetLengthAtPCA obsolete, contact FairRoot group if you need it."; return ftrklength; } - float GetTimeAtPCA() { + float GetTimeAtPCA() + { LOG(warning) << "Function GetTimeAtPCA obsolete, contact FairRoot group if you need it."; return ftrktime; } @@ -121,13 +165,16 @@ class FairGeanePro : public FairPropagator bool BackTrackToVirtualPlaneAtPCA(int pca); /* ====== ====== ====== ====== ====== */ - void setBackProp() { - fPropOption="BPE"; - } + void setBackProp() { fPropOption = "BPE"; } virtual bool SetPCAPropagation(int pca, int dir = 1, FairTrackParP* par = nullptr); - virtual PCAOutputStruct FindPCA(int PCA, int PDGCode, TVector3 Point, TVector3 Wire1, TVector3 Wire2, double MaxDistance); + virtual PCAOutputStruct FindPCA(int PCA, + int PDGCode, + TVector3 Point, + TVector3 Wire1, + TVector3 Wire2, + double MaxDistance); // transport matrix void GetTransportMatrix(double trm[5][5]); @@ -178,7 +225,7 @@ class FairGeanePro : public FairPropagator FairGeanePro(const FairGeanePro&); FairGeanePro& operator=(const FairGeanePro&); - ClassDef(FairGeanePro,2); + ClassDef(FairGeanePro, 2); }; #endif diff --git a/generators/FairAsciiGenerator.cxx b/generators/FairAsciiGenerator.cxx index 64eef6bf82..7795b4f3df 100644 --- a/generators/FairAsciiGenerator.cxx +++ b/generators/FairAsciiGenerator.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -11,96 +11,93 @@ // ------------------------------------------------------------------------- #include "FairAsciiGenerator.h" -#include "FairPrimaryGenerator.h" // for FairPrimaryGenerator #include "FairLogger.h" +#include "FairPrimaryGenerator.h" // for FairPrimaryGenerator +#include // for INT_MAX #include -#include // for INT_MAX FairAsciiGenerator::FairAsciiGenerator() - :FairGenerator(), - fInputFile(nullptr), - fFileName("") -{ -} + : FairGenerator() + , fInputFile(nullptr) + , fFileName("") +{} FairAsciiGenerator::FairAsciiGenerator(const char* fileName) - :FairGenerator(), - fInputFile(0), - fFileName(fileName) + : FairGenerator() + , fInputFile(0) + , fFileName(fileName) { - // fFileName = fileName; - LOG(info) << "FairAsciiGenerator: Opening input file " << fileName; - fInputFile = new std::ifstream(fFileName); - if (! fInputFile->is_open()) { - LOG(fatal) << "Cannot open input file."; - } - - // fPDG=TDatabasePDG::Instance(); -} + // fFileName = fileName; + LOG(info) << "FairAsciiGenerator: Opening input file " << fileName; + fInputFile = new std::ifstream(fFileName); + if (!fInputFile->is_open()) { + LOG(fatal) << "Cannot open input file."; + } -FairAsciiGenerator::~FairAsciiGenerator() -{ - CloseInput(); + // fPDG=TDatabasePDG::Instance(); } +FairAsciiGenerator::~FairAsciiGenerator() { CloseInput(); } + Bool_t FairAsciiGenerator::ReadEvent(FairPrimaryGenerator* primGen) { - // Check for input file - if (! fInputFile->is_open()) { - LOG(error) << "FairAsciiGenerator: Input file not open!"; - return kFALSE; - } - - // Define event variable to be read from file - Int_t ntracks = 0, eventID = 0; - Double_t vx = 0., vy = 0., vz = 0.; - - // Define track variables to be read from file - Int_t pdgID = 0; - Double_t px = 0., py = 0., pz = 0.; - - // Read event header line from input file - *fInputFile >> ntracks; - if (fInputFile->fail() || ntracks < 0 || ntracks > (INT_MAX-1)) LOG(fatal) << "Error reading the number of events from event header."; - *fInputFile >> eventID >> vx >> vy >> vz; + // Check for input file + if (!fInputFile->is_open()) { + LOG(error) << "FairAsciiGenerator: Input file not open!"; + return kFALSE; + } - // If end of input file is reached : close it and abort run - if (fInputFile->eof()) { - LOG(info) << "FairAsciiGenerator: End of input file reached "; - CloseInput(); - return kFALSE; - } + // Define event variable to be read from file + Int_t ntracks = 0, eventID = 0; + Double_t vx = 0., vy = 0., vz = 0.; + + // Define track variables to be read from file + Int_t pdgID = 0; + Double_t px = 0., py = 0., pz = 0.; + + // Read event header line from input file + *fInputFile >> ntracks; + if (fInputFile->fail() || ntracks < 0 || ntracks > (INT_MAX - 1)) + LOG(fatal) << "Error reading the number of events from event header."; + *fInputFile >> eventID >> vx >> vy >> vz; + + // If end of input file is reached : close it and abort run + if (fInputFile->eof()) { + LOG(info) << "FairAsciiGenerator: End of input file reached "; + CloseInput(); + return kFALSE; + } - LOG(info) << "FairAsciiGenerator: Event " << eventID << ", vertex = (" - << vx << "," << vy << "," << vz << ") cm, multiplicity " << ntracks; + LOG(info) << "FairAsciiGenerator: Event " << eventID << ", vertex = (" << vx << "," << vy << "," << vz + << ") cm, multiplicity " << ntracks; - // Loop over tracks in the current event - for (Int_t itrack=0; itrack> pdgID >> px >> py >> pz; - // convert Geant3 code to PDG code + // Read PID and momentum from file + *fInputFile >> pdgID >> px >> py >> pz; + // convert Geant3 code to PDG code - // Int_t pdg= fPDG->ConvertGeant3ToPdg(pdgID); + // Int_t pdg= fPDG->ConvertGeant3ToPdg(pdgID); - // Give track to PrimaryGenerator - primGen->AddTrack(pdgID, px, py, pz, vx, vy, vz); - } + // Give track to PrimaryGenerator + primGen->AddTrack(pdgID, px, py, pz, vx, vy, vz); + } - return kTRUE; + return kTRUE; } void FairAsciiGenerator::CloseInput() { - if (fInputFile) { - if (fInputFile->is_open()) { - LOG(info) << "FairAsciiGenerator: Closing input file " << fFileName; - fInputFile->close(); + if (fInputFile) { + if (fInputFile->is_open()) { + LOG(info) << "FairAsciiGenerator: Closing input file " << fFileName; + fInputFile->close(); + } + delete fInputFile; + fInputFile = nullptr; } - delete fInputFile; - fInputFile = nullptr; - } } -ClassImp(FairAsciiGenerator) +ClassImp(FairAsciiGenerator); diff --git a/generators/FairAsciiGenerator.h b/generators/FairAsciiGenerator.h index d4e2253097..90f6f3ed25 100644 --- a/generators/FairAsciiGenerator.h +++ b/generators/FairAsciiGenerator.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -28,10 +28,10 @@ #ifndef FAIR_ASCIIGENERATOR_H #define FAIR_ASCIIGENERATOR_H -#include "FairGenerator.h" // for FairGenerator +#include "FairGenerator.h" // for FairGenerator -#include // for ifstream -#include // for FairAsciiGenerator::Class, etc +#include // for FairAsciiGenerator::Class, etc +#include // for ifstream class FairPrimaryGenerator; @@ -56,8 +56,8 @@ class FairAsciiGenerator : public FairGenerator virtual Bool_t ReadEvent(FairPrimaryGenerator* primGen); private: - std::ifstream* fInputFile; //! Input file stream - const Char_t* fFileName; //! Input file Name + std::ifstream* fInputFile; //! Input file stream + const Char_t* fFileName; //! Input file Name /** Private method CloseInput. Just for convenience. Closes the ** input file properly. Called from destructor and from ReadEvent. **/ @@ -70,7 +70,7 @@ class FairAsciiGenerator : public FairGenerator // TDatabasePDG *fPDG; //! - ClassDef(FairAsciiGenerator,1); + ClassDef(FairAsciiGenerator, 1); }; #endif diff --git a/generators/FairBaseMCGenerator.cxx b/generators/FairBaseMCGenerator.cxx index eb4edbf931..d41dd1c064 100644 --- a/generators/FairBaseMCGenerator.cxx +++ b/generators/FairBaseMCGenerator.cxx @@ -7,24 +7,38 @@ * Warsaw University of Technology, Faculty of Physics */ #include "FairBaseMCGenerator.h" + #include "FairLogger.h" -#include #include +#include #include -FairBaseMCGenerator::FairBaseMCGenerator() : - FairGenerator(), - fPDGType(0), - fMult(0),fVertexSmear(kBox), - fPDGMass(0.0), - fVx(0.0),fVy(0.0),fVz(0.0), - fVex(0.0),fVey(0.0),fVez(0.0), - fX(0),fY(0),fZ(0){ -} +FairBaseMCGenerator::FairBaseMCGenerator() + : FairGenerator() + , fPDGType(0) + , fMult(0) + , fVertexSmear(kBox) + , fPDGMass(0.0) + , fVx(0.0) + , fVy(0.0) + , fVz(0.0) + , fVex(0.0) + , fVey(0.0) + , fVez(0.0) + , fX(0) + , fY(0) + , fZ(0) +{} -void FairBaseMCGenerator::SetVertex(Double_t vx, Double_t vy, Double_t vz, - Double_t evx, Double_t evy, Double_t evz, eVertexSmear VertexSmear) { +void FairBaseMCGenerator::SetVertex(Double_t vx, + Double_t vy, + Double_t vz, + Double_t evx, + Double_t evy, + Double_t evz, + eVertexSmear VertexSmear) +{ fX = fVx = vx; fY = fVy = vy; fZ = fVz = vz; @@ -34,56 +48,57 @@ void FairBaseMCGenerator::SetVertex(Double_t vx, Double_t vy, Double_t vz, fVertexSmear = VertexSmear; } -FairBaseMCGenerator::~FairBaseMCGenerator() { - // TODO Auto-generated destructor stub +FairBaseMCGenerator::~FairBaseMCGenerator() +{ + // TODO Auto-generated destructor stub } -Bool_t FairBaseMCGenerator::Init() { - if(fMult<=0) return kFALSE; +Bool_t FairBaseMCGenerator::Init() +{ + if (fMult <= 0) + return kFALSE; TDatabasePDG *pid = TDatabasePDG::Instance(); TParticlePDG *p = pid->GetParticle(fPDGType); - if(p!=nullptr){ - LOG(info)<ClassName()<<": particle with PDG ="<ClassName() << ": particle with PDG =" << GetPDGType() << " Found"; fPDGMass = p->Mass(); } return kTRUE; } -void FairBaseMCGenerator::SetPDGType(Int_t pdg) { - fPDGType = pdg; -} +void FairBaseMCGenerator::SetPDGType(Int_t pdg) { fPDGType = pdg; } -void FairBaseMCGenerator::GenerateEventParameters() { - switch(fVertexSmear){ - case kGauss:{ - fX = gRandom->Gaus(fVx,fVex); - fY = gRandom->Gaus(fVy,fVey); - fZ = gRandom->Gaus(fVz,fVez); - }break; - case kBox:{ - fX = gRandom->Uniform(fVx-fVex, fVx+fVex); - fY = gRandom->Uniform(fVy-fVey, fVy+fVey); - fZ = gRandom->Uniform(fVz-fVez, fVz+fVez); - }break; - case kExp:{ - if(gRandom->Uniform()<0.5){ - fX = fVx +gRandom->Exp(fVex); - }else{ - fX = fVx - gRandom->Exp(fVex); - } - if(gRandom->Uniform()<0.5){ - fY = fVy +gRandom->Exp(fVey); - }else{ - fY = fVy - gRandom->Exp(fVey); - } - if(gRandom->Uniform()<0.5){ - fZ = fVz + gRandom->Exp(fVez); - }else{ - fZ = fVz - gRandom->Exp(fVez); - } - }break; +void FairBaseMCGenerator::GenerateEventParameters() +{ + switch (fVertexSmear) { + case kGauss: { + fX = gRandom->Gaus(fVx, fVex); + fY = gRandom->Gaus(fVy, fVey); + fZ = gRandom->Gaus(fVz, fVez); + } break; + case kBox: { + fX = gRandom->Uniform(fVx - fVex, fVx + fVex); + fY = gRandom->Uniform(fVy - fVey, fVy + fVey); + fZ = gRandom->Uniform(fVz - fVez, fVz + fVez); + } break; + case kExp: { + if (gRandom->Uniform() < 0.5) { + fX = fVx + gRandom->Exp(fVex); + } else { + fX = fVx - gRandom->Exp(fVex); + } + if (gRandom->Uniform() < 0.5) { + fY = fVy + gRandom->Exp(fVey); + } else { + fY = fVy - gRandom->Exp(fVey); + } + if (gRandom->Uniform() < 0.5) { + fZ = fVz + gRandom->Exp(fVez); + } else { + fZ = fVz - gRandom->Exp(fVez); + } + } break; } - LOG(info) << this->ClassName()<< ": Event, vertex = (" - << fX << "," << fY << "," << fZ << ") cm, multiplicity " << fMult; + LOG(info) << this->ClassName() << ": Event, vertex = (" << fX << "," << fY << "," << fZ << ") cm, multiplicity " + << fMult; } diff --git a/generators/FairBaseMCGenerator.h b/generators/FairBaseMCGenerator.h index 12acb35478..00087a414e 100644 --- a/generators/FairBaseMCGenerator.h +++ b/generators/FairBaseMCGenerator.h @@ -14,59 +14,67 @@ /** * abstract class for generators that use "macro input" to generate partcles */ -class FairBaseMCGenerator : public FairGenerator{ -public: - enum eVertexSmear{ - kBox, - kGauss, - kExp - }; - FairBaseMCGenerator(); - /** - * set PDG code of generated particles - * @param pdg - */ - void SetPDGType(Int_t pdg); - /** - * set vertex position and algorithm of vertex generation - * @param vx, vy, vz Vertex coordinates [cm] - * @param evx, evy, evz Vertex dispersion [cm] - * @param sm distribution of vertex, gaussian or box - */ - void SetVertex(Double_t vx, Double_t vy, Double_t vz, - Double_t evx=0, Double_t evy=0, Double_t evz=0, eVertexSmear sm = kBox); - /** - * set number of particles per event - * @param mult - */ - void SetMultiplicity(Int_t mult){fMult = mult;}; +class FairBaseMCGenerator : public FairGenerator +{ + public: + enum eVertexSmear + { + kBox, + kGauss, + kExp + }; + FairBaseMCGenerator(); + /** + * set PDG code of generated particles + * @param pdg + */ + void SetPDGType(Int_t pdg); + /** + * set vertex position and algorithm of vertex generation + * @param vx, vy, vz Vertex coordinates [cm] + * @param evx, evy, evz Vertex dispersion [cm] + * @param sm distribution of vertex, gaussian or box + */ + void SetVertex(Double_t vx, + Double_t vy, + Double_t vz, + Double_t evx = 0, + Double_t evy = 0, + Double_t evz = 0, + eVertexSmear sm = kBox); + /** + * set number of particles per event + * @param mult + */ + void SetMultiplicity(Int_t mult) { fMult = mult; }; virtual Bool_t Init(); - virtual ~FairBaseMCGenerator(); -protected: - FairBaseMCGenerator(const FairBaseMCGenerator &other) = default; - FairBaseMCGenerator& operator=(const FairBaseMCGenerator &rhs) = default; - Int_t GetPDGType()const{return fPDGType;}; - Int_t GetMultiplicity()const{return fMult;}; - Double_t GetPDGMass()const{return fPDGMass;}; - /** - * generate event parameters like current event - */ - virtual void GenerateEventParameters(); - Double_t GetVxAv()const{return fVx;}; - Double_t GetVyAv()const{return fVy;}; - Double_t GetVzAv()const{return fVz;}; - Double_t GetVxRms()const{return fVex;} - Double_t GetVyRms()const{return fVey;} - Double_t GetVzRms()const{return fVez;} - Double_t fX, fY, fZ; // current vertex coordinates [cm] -private: - Int_t fPDGType; // Particle type (PDG encoding) - Int_t fMult; //Multiplicity; - eVertexSmear fVertexSmear; - Double_t fPDGMass; - Double_t fVx, fVy,fVz; - Double_t fVex, fVey, fVez; - ClassDef(FairBaseMCGenerator,1) + virtual ~FairBaseMCGenerator(); + + protected: + FairBaseMCGenerator(const FairBaseMCGenerator &other) = default; + FairBaseMCGenerator &operator=(const FairBaseMCGenerator &rhs) = default; + Int_t GetPDGType() const { return fPDGType; }; + Int_t GetMultiplicity() const { return fMult; }; + Double_t GetPDGMass() const { return fPDGMass; }; + /** + * generate event parameters like current event + */ + virtual void GenerateEventParameters(); + Double_t GetVxAv() const { return fVx; }; + Double_t GetVyAv() const { return fVy; }; + Double_t GetVzAv() const { return fVz; }; + Double_t GetVxRms() const { return fVex; } + Double_t GetVyRms() const { return fVey; } + Double_t GetVzRms() const { return fVez; } + Double_t fX, fY, fZ; // current vertex coordinates [cm] + private: + Int_t fPDGType; // Particle type (PDG encoding) + Int_t fMult; // Multiplicity; + eVertexSmear fVertexSmear; + Double_t fPDGMass; + Double_t fVx, fVy, fVz; + Double_t fVex, fVey, fVez; + ClassDef(FairBaseMCGenerator, 1) }; #endif /* FAIR_BASEMCGENERATOR_H_ */ diff --git a/generators/FairBoxGenerator.cxx b/generators/FairBoxGenerator.cxx index d567521e09..25d4f6b452 100644 --- a/generators/FairBoxGenerator.cxx +++ b/generators/FairBoxGenerator.cxx @@ -27,161 +27,188 @@ */ #include "FairBoxGenerator.h" + #include "FairLogger.h" #include "FairPrimaryGenerator.h" -#include -#include #include #include #include - -#include // for cos, acos -#include // for printf - -FairBoxGenerator::FairBoxGenerator() : - FairBaseMCGenerator(),fPtMin(0),fPtMax(0), - fPhiMin(0),fPhiMax(0),fEtaMin(0),fEtaMax(0),fYMin(0),fYMax(0), - fPMin(0),fPMax(0),fThetaMin(0),fThetaMax(0), - fEkinMin(0),fEkinMax(0), - fEtaRangeIsSet(0),fYRangeIsSet(0),fThetaRangeIsSet(0), - fCosThetaIsSet(0),fPtRangeIsSet(0),fPRangeIsSet(0), - fEkinRangeIsSet(0) +#include +#include +#include // for cos, acos +#include // for printf + +FairBoxGenerator::FairBoxGenerator() + : FairBaseMCGenerator() + , fPtMin(0) + , fPtMax(0) + , fPhiMin(0) + , fPhiMax(0) + , fEtaMin(0) + , fEtaMax(0) + , fYMin(0) + , fYMax(0) + , fPMin(0) + , fPMax(0) + , fThetaMin(0) + , fThetaMax(0) + , fEkinMin(0) + , fEkinMax(0) + , fEtaRangeIsSet(0) + , fYRangeIsSet(0) + , fThetaRangeIsSet(0) + , fCosThetaIsSet(0) + , fPtRangeIsSet(0) + , fPRangeIsSet(0) + , fEkinRangeIsSet(0) { - // Default constructor + // Default constructor } -FairBoxGenerator::FairBoxGenerator(Int_t pdgid, Int_t mult) : - FairBaseMCGenerator(), - fPtMin(0),fPtMax(0), - fPhiMin(0),fPhiMax(0),fEtaMin(0),fEtaMax(0),fYMin(0),fYMax(0), - fPMin(0),fPMax(0),fThetaMin(0),fThetaMax(0), - fEkinMin(0),fEkinMax(0), - fEtaRangeIsSet(0), fYRangeIsSet(0),fThetaRangeIsSet(0), - fCosThetaIsSet(0), fPtRangeIsSet(0), fPRangeIsSet(0), - fEkinRangeIsSet(0) +FairBoxGenerator::FairBoxGenerator(Int_t pdgid, Int_t mult) + : FairBaseMCGenerator() + , fPtMin(0) + , fPtMax(0) + , fPhiMin(0) + , fPhiMax(0) + , fEtaMin(0) + , fEtaMax(0) + , fYMin(0) + , fYMax(0) + , fPMin(0) + , fPMax(0) + , fThetaMin(0) + , fThetaMax(0) + , fEkinMin(0) + , fEkinMax(0) + , fEtaRangeIsSet(0) + , fYRangeIsSet(0) + , fThetaRangeIsSet(0) + , fCosThetaIsSet(0) + , fPtRangeIsSet(0) + , fPRangeIsSet(0) + , fEkinRangeIsSet(0) { - // Constructor. Set default kinematics limits - SetPDGType(pdgid); - SetMultiplicity(mult); - SetPhiRange(); + // Constructor. Set default kinematics limits + SetPDGType(pdgid); + SetMultiplicity(mult); + SetPhiRange(); } -void FairBoxGenerator::SetXYZ(Double32_t x, Double32_t y, Double32_t z){ - SetVertex(x,y,z, 0, 0, 0, kBox); -} +void FairBoxGenerator::SetXYZ(Double32_t x, Double32_t y, Double32_t z) { SetVertex(x, y, z, 0, 0, 0, kBox); } -void FairBoxGenerator::SetBoxXYZ(Double32_t x1, Double32_t y1, Double32_t x2, Double32_t y2, Double32_t z){ - Double_t X1 = TMath::Min(x1,x2); - Double_t X2 = TMath::Max(x1,x2); - Double_t Y1 = TMath::Min(y1,y2); - Double_t Y2 = TMath::Max(y1,y2); - Double_t dX = 0.5*(X2 - X1); - Double_t dY = 0.5*(Y2 - Y1); - Double_t x = 0.5*(X1+X2); - Double_t y = 0.5*(Y1+Y2); +void FairBoxGenerator::SetBoxXYZ(Double32_t x1, Double32_t y1, Double32_t x2, Double32_t y2, Double32_t z) +{ + Double_t X1 = TMath::Min(x1, x2); + Double_t X2 = TMath::Max(x1, x2); + Double_t Y1 = TMath::Min(y1, y2); + Double_t Y2 = TMath::Max(y1, y2); + Double_t dX = 0.5 * (X2 - X1); + Double_t dY = 0.5 * (Y2 - Y1); + Double_t x = 0.5 * (X1 + X2); + Double_t y = 0.5 * (Y1 + Y2); SetVertex(x, y, z, dX, dY, 0, kBox); } -Bool_t FairBoxGenerator::Init() +Bool_t FairBoxGenerator::Init() { - // Initialize parent generator - if(FairBaseMCGenerator::Init()==kFALSE) return kFALSE; - // Check for particle type - TDatabasePDG* pdgBase = TDatabasePDG::Instance(); - TParticlePDG* particle = pdgBase->GetParticle(GetPDGType()); - - if (! particle) { - LOG(fatal)<<"FairBoxGenerator: PDG "<< GetPDGType()<< " not defined"; - } - - if (fPhiMax-fPhiMin>360){ - LOG(fatal)<<"FairBoxGenerator:Init(): phi range is too wide: " - <GetParticle(GetPDGType()); + + if (!particle) { + LOG(fatal) << "FairBoxGenerator: PDG " << GetPDGType() << " not defined"; + } + + if (fPhiMax - fPhiMin > 360) { + LOG(fatal) << "FairBoxGenerator:Init(): phi range is too wide: " << fPhiMin << "Uniform(fPhiMin,fPhiMax) * TMath::DegToRad(); - - if (fPRangeIsSet ) { pabs = gRandom->Uniform(fPMin,fPMax); } - else if (fPtRangeIsSet) { pt = gRandom->Uniform(fPtMin,fPtMax); } - - if (fThetaRangeIsSet) { - if (fCosThetaIsSet) - theta = acos(gRandom->Uniform(cos(fThetaMin* TMath::DegToRad()), - cos(fThetaMax* TMath::DegToRad()))); - else { - theta = gRandom->Uniform(fThetaMin,fThetaMax) * TMath::DegToRad(); - } - } else if (fEtaRangeIsSet) { - eta = gRandom->Uniform(fEtaMin,fEtaMax); - theta = 2*TMath::ATan(TMath::Exp(-eta)); - } else if (fYRangeIsSet) { - y = gRandom->Uniform(fYMin,fYMax); - mt = TMath::Sqrt(GetPDGMass()*GetPDGMass() + pt*pt); - pz = mt * TMath::SinH(y); + // Generate one event: produce primary particles emitted from one vertex. + // Primary particles are distributed uniformly along + // those kinematics variables which were limitted by setters. + // if SetCosTheta() function is used, the distribution will be uniform in + // cos(theta) + + Double32_t pabs = 0, phi, pt = 0, theta = 0, eta, y, mt, px, py, pz = 0; + GenerateEventParameters(); + // Generate particles + for (Int_t k = 0; k < GetMultiplicity(); k++) { + phi = gRandom->Uniform(fPhiMin, fPhiMax) * TMath::DegToRad(); + + if (fPRangeIsSet) { + pabs = gRandom->Uniform(fPMin, fPMax); + } else if (fPtRangeIsSet) { + pt = gRandom->Uniform(fPtMin, fPtMax); + } + + if (fThetaRangeIsSet) { + if (fCosThetaIsSet) + theta = acos(gRandom->Uniform(cos(fThetaMin * TMath::DegToRad()), cos(fThetaMax * TMath::DegToRad()))); + else { + theta = gRandom->Uniform(fThetaMin, fThetaMax) * TMath::DegToRad(); + } + } else if (fEtaRangeIsSet) { + eta = gRandom->Uniform(fEtaMin, fEtaMax); + theta = 2 * TMath::ATan(TMath::Exp(-eta)); + } else if (fYRangeIsSet) { + y = gRandom->Uniform(fYMin, fYMax); + mt = TMath::Sqrt(GetPDGMass() * GetPDGMass() + pt * pt); + pz = mt * TMath::SinH(y); + } + + if (fThetaRangeIsSet || fEtaRangeIsSet) { + if (fPRangeIsSet) { + pz = pabs * TMath::Cos(theta); + pt = pabs * TMath::Sin(theta); + } else if (fPtRangeIsSet) { + pz = pt / TMath::Tan(theta); + } + } + + px = pt * TMath::Cos(phi); + py = pt * TMath::Sin(phi); + + LOG(debug) << "FairBoxGen: " << Form("PDG %i p=(%.2f, %.2f, %.2f) GeV,", GetPDGType(), px, py, pz); + primGen->AddTrack(GetPDGType(), px, py, pz, fX, fY, fZ); } - - if (fThetaRangeIsSet || fEtaRangeIsSet) { - if (fPRangeIsSet ) { - pz = pabs*TMath::Cos(theta); - pt = pabs*TMath::Sin(theta); - } else if (fPtRangeIsSet) { - pz = pt/TMath::Tan(theta); - } - } - - px = pt*TMath::Cos(phi); - py = pt*TMath::Sin(phi); - - LOG(debug)<<"FairBoxGen: "<< - Form("PDG %i p=(%.2f, %.2f, %.2f) GeV,",GetPDGType(),px,py,pz); - primGen->AddTrack(GetPDGType(), px, py, pz, fX, fY, fZ); - } - return kTRUE; - + return kTRUE; } FairGenerator* FairBoxGenerator::CloneGenerator() const { - // Clone for worker (used in MT mode only) + // Clone for worker (used in MT mode only) - return new FairBoxGenerator(*this); + return new FairBoxGenerator(*this); } -ClassImp(FairBoxGenerator) +ClassImp(FairBoxGenerator); diff --git a/generators/FairBoxGenerator.h b/generators/FairBoxGenerator.h index c6f5528827..90b97c5917 100644 --- a/generators/FairBoxGenerator.h +++ b/generators/FairBoxGenerator.h @@ -16,7 +16,7 @@ * The FairBoxGenerator generates particles within given range * over pt, phi, eta, y or theta a fixed multiplicity per event. * Derived from FairGenerator. -**/ + **/ /* $Id: FairBoxGenerator.h,v 1.3 2006/07/14 11:23:57 kharlov Exp $ */ @@ -34,16 +34,16 @@ #ifndef FAIR_BOXGENERATOR_H #define FAIR_BOXGENERATOR_H -#include "FairGenerator.h" // for FairGenerator -#include // for Double32_t, Bool_t, kTRUE, etc #include "FairBaseMCGenerator.h" +#include "FairGenerator.h" // for FairGenerator + +#include // for Double32_t, Bool_t, kTRUE, etc class FairPrimaryGenerator; class FairBoxGenerator : public FairBaseMCGenerator { public: - /** Default constructor. **/ FairBoxGenerator(); @@ -51,38 +51,72 @@ class FairBoxGenerator : public FairBaseMCGenerator **@param pdgid Particle type (PDG encoding) **@param mult Multiplicity (default is 1) **/ - FairBoxGenerator(Int_t pdgid, Int_t mult=1); + FairBoxGenerator(Int_t pdgid, Int_t mult = 1); /** Destructor **/ virtual ~FairBoxGenerator() {} /** Modifiers **/ - void SetPRange(Double32_t pmin=0, Double32_t pmax=10) { fPMin=pmin; fPMax=pmax; fPRangeIsSet=kTRUE; } - - void SetPtRange(Double32_t ptmin=0, Double32_t ptmax=10) { fPtMin=ptmin; fPtMax=ptmax; fPtRangeIsSet=kTRUE; } - - void SetEkinRange(Double32_t kmin=0, Double32_t kmax=10) { fEkinMin=kmin; fEkinMax=kmax; fEkinRangeIsSet=kTRUE; } - - void SetPhiRange(Double32_t phimin=0, Double32_t phimax=360) { fPhiMin=phimin; fPhiMax=phimax; } - - void SetEtaRange(Double32_t etamin=-5, Double32_t etamax=7) { fEtaMin=etamin; fEtaMax=etamax; fEtaRangeIsSet=kTRUE; } - - void SetYRange(Double32_t ymin=-5, Double32_t ymax=7) { fYMin=ymin; fYMax=ymax; fYRangeIsSet=kTRUE; } - - void SetThetaRange(Double32_t thetamin=0, Double32_t thetamax=90) { fThetaMin=thetamin; fThetaMax=thetamax; fThetaRangeIsSet=kTRUE; } - - void SetCosTheta() { fCosThetaIsSet=kTRUE; } - - void SetXYZ(Double32_t x=0, Double32_t y=0, Double32_t z=0); - - void SetBoxXYZ(Double32_t x1=0, Double32_t y1=0, Double32_t x2=0, Double32_t y2=0, Double32_t z=0); + void SetPRange(Double32_t pmin = 0, Double32_t pmax = 10) + { + fPMin = pmin; + fPMax = pmax; + fPRangeIsSet = kTRUE; + } + + void SetPtRange(Double32_t ptmin = 0, Double32_t ptmax = 10) + { + fPtMin = ptmin; + fPtMax = ptmax; + fPtRangeIsSet = kTRUE; + } + + void SetEkinRange(Double32_t kmin = 0, Double32_t kmax = 10) + { + fEkinMin = kmin; + fEkinMax = kmax; + fEkinRangeIsSet = kTRUE; + } + + void SetPhiRange(Double32_t phimin = 0, Double32_t phimax = 360) + { + fPhiMin = phimin; + fPhiMax = phimax; + } + + void SetEtaRange(Double32_t etamin = -5, Double32_t etamax = 7) + { + fEtaMin = etamin; + fEtaMax = etamax; + fEtaRangeIsSet = kTRUE; + } + + void SetYRange(Double32_t ymin = -5, Double32_t ymax = 7) + { + fYMin = ymin; + fYMax = ymax; + fYRangeIsSet = kTRUE; + } + + void SetThetaRange(Double32_t thetamin = 0, Double32_t thetamax = 90) + { + fThetaMin = thetamin; + fThetaMax = thetamax; + fThetaRangeIsSet = kTRUE; + } + + void SetCosTheta() { fCosThetaIsSet = kTRUE; } + + void SetXYZ(Double32_t x = 0, Double32_t y = 0, Double32_t z = 0); + + void SetBoxXYZ(Double32_t x1 = 0, Double32_t y1 = 0, Double32_t x2 = 0, Double32_t y2 = 0, Double32_t z = 0); /** * not used, for backward compatibility, please user FairLogger to set debug mode * @param */ - void SetDebug(Bool_t /*debug*/){} + void SetDebug(Bool_t /*debug*/) {} /** Initializer **/ Bool_t Init(); @@ -96,29 +130,28 @@ class FairBoxGenerator : public FairBaseMCGenerator protected: /** Copy constructor. **/ - FairBoxGenerator(const FairBoxGenerator&)=default; - FairBoxGenerator& operator=(const FairBoxGenerator&)=default; + FairBoxGenerator(const FairBoxGenerator&) = default; + FairBoxGenerator& operator=(const FairBoxGenerator&) = default; private: - - Double32_t fPtMin, fPtMax; // Transverse momentum range [GeV] - Double32_t fPhiMin, fPhiMax; // Azimuth angle range [degree] - Double32_t fEtaMin, fEtaMax; // Pseudorapidity range in lab system - Double32_t fYMin, fYMax; // Rapidity range in lab system - Double32_t fPMin, fPMax; // Momentum range in lab system - Double32_t fThetaMin, fThetaMax; // Polar angle range in lab system [degree] - Double32_t fEkinMin,fEkinMax; // Kinetic Energy range in lab system [GeV] - - Bool_t fEtaRangeIsSet; // True if eta range is set - Bool_t fYRangeIsSet; // True if rapidity range is set - Bool_t fThetaRangeIsSet; // True if theta range is set - Bool_t fCosThetaIsSet; // True if uniform distribution in - //cos(theta) is set (default -> not set) - Bool_t fPtRangeIsSet; // True if transverse momentum range is set - Bool_t fPRangeIsSet; // True if abs.momentum range is set - Bool_t fEkinRangeIsSet; // True if kinetic energy range is set - - ClassDef(FairBoxGenerator,5); + Double32_t fPtMin, fPtMax; // Transverse momentum range [GeV] + Double32_t fPhiMin, fPhiMax; // Azimuth angle range [degree] + Double32_t fEtaMin, fEtaMax; // Pseudorapidity range in lab system + Double32_t fYMin, fYMax; // Rapidity range in lab system + Double32_t fPMin, fPMax; // Momentum range in lab system + Double32_t fThetaMin, fThetaMax; // Polar angle range in lab system [degree] + Double32_t fEkinMin, fEkinMax; // Kinetic Energy range in lab system [GeV] + + Bool_t fEtaRangeIsSet; // True if eta range is set + Bool_t fYRangeIsSet; // True if rapidity range is set + Bool_t fThetaRangeIsSet; // True if theta range is set + Bool_t fCosThetaIsSet; // True if uniform distribution in + // cos(theta) is set (default -> not set) + Bool_t fPtRangeIsSet; // True if transverse momentum range is set + Bool_t fPRangeIsSet; // True if abs.momentum range is set + Bool_t fEkinRangeIsSet; // True if kinetic energy range is set + + ClassDef(FairBoxGenerator, 5); }; #endif diff --git a/generators/FairEvtGenGenerator.cxx b/generators/FairEvtGenGenerator.cxx index 84158c6779..caea273e51 100644 --- a/generators/FairEvtGenGenerator.cxx +++ b/generators/FairEvtGenGenerator.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -11,162 +11,177 @@ // ------------------------------------------------------------------------- #include "FairEvtGenGenerator.h" -#include "FairPrimaryGenerator.h" // for FairPrimaryGenerator #include "FairLogger.h" +#include "FairPrimaryGenerator.h" // for FairPrimaryGenerator -#include // for TF1 -#include // for TRandom, gRandom - -#include // max +#include // for TF1 +#include // for TRandom, gRandom +#include // max FairEvtGenGenerator::FairEvtGenGenerator() - : FairGenerator(), - fFileName(""), - fInputFile(nullptr), - fGasmode(0), - fRsigma (0.), - fDensityFunction(nullptr) -{ -} + : FairGenerator() + , fFileName("") + , fInputFile(nullptr) + , fGasmode(0) + , fRsigma(0.) + , fDensityFunction(nullptr) +{} FairEvtGenGenerator::FairEvtGenGenerator(const char* fileName) - :FairGenerator ("EvtGen", fileName), - fFileName(fileName), - fInputFile(nullptr), - fGasmode(0), - fRsigma (0.), - fDensityFunction(0) + : FairGenerator("EvtGen", fileName) + , fFileName(fileName) + , fInputFile(nullptr) + , fGasmode(0) + , fRsigma(0.) + , fDensityFunction(0) { - LOG(info) << "FairEvtGenGenerator: Opening input file " << fileName; - if ((fInputFile = fopen(fFileName,"r"))==nullptr) + LOG(info) << "FairEvtGenGenerator: Opening input file " << fileName; + if ((fInputFile = fopen(fFileName, "r")) == nullptr) // fInputFile = new ifstream(fFileName); // if ( ! fInputFile->is_open() ) - { - Fatal("FairEvtGenGenerator","Cannot open input file."); - } + { + Fatal("FairEvtGenGenerator", "Cannot open input file."); + } - // fPDG=TDatabasePDG::Instance(); + // fPDG=TDatabasePDG::Instance(); } FairEvtGenGenerator::FairEvtGenGenerator(const char* fileName, Double_t Rsigma, TF1* DensityFunction) - :FairGenerator ("EvtGen", fileName), - fFileName(fileName), - fInputFile(nullptr), - fGasmode(1), - fRsigma (Rsigma), - fDensityFunction(DensityFunction) + : FairGenerator("EvtGen", fileName) + , fFileName(fileName) + , fInputFile(nullptr) + , fGasmode(1) + , fRsigma(Rsigma) + , fDensityFunction(DensityFunction) { - LOG(info) << "FairEvtGenGenerator: Opening input file " << fileName; - if ((fInputFile = fopen(fFileName,"r"))==nullptr) { - LOG(fatal) << "Cannot open input file."; - } + LOG(info) << "FairEvtGenGenerator: Opening input file " << fileName; + if ((fInputFile = fopen(fFileName, "r")) == nullptr) { + LOG(fatal) << "Cannot open input file."; + } } FairEvtGenGenerator::~FairEvtGenGenerator() { - delete fDensityFunction; - if(fInputFile) { fclose(fInputFile); } + delete fDensityFunction; + if (fInputFile) { + fclose(fInputFile); + } } Bool_t FairEvtGenGenerator::ReadEvent(FairPrimaryGenerator* primGen) { - // Check for input file - if (!fInputFile) { - // if ( ! fInputFile->is_open() ) { - LOG(info) << "FairEvtGenGenerator: Input file not open!"; - return kFALSE; - } - - // Define event variable to be read from file - Int_t ntracks = 0, eventID = 0, ncols = 0; + // Check for input file + if (!fInputFile) { + // if ( ! fInputFile->is_open() ) { + LOG(info) << "FairEvtGenGenerator: Input file not open!"; + return kFALSE; + } - // Define track variables to be read from file - Int_t nLine = 0, pdgID = 0, nDecay = 0, nM1 = -1, nM2 = -1, nDF = -1, nDL = -1; - Float_t fPx = 0., fPy = 0., fPz = 0., fE = 0.; - Float_t fVx = 0., fVy = 0., fVz = 0., fT = 0.; + // Define event variable to be read from file + Int_t ntracks = 0, eventID = 0, ncols = 0; - // Read event header line from input file + // Define track variables to be read from file + Int_t nLine = 0, pdgID = 0, nDecay = 0, nM1 = -1, nM2 = -1, nDF = -1, nDL = -1; + Float_t fPx = 0., fPy = 0., fPz = 0., fE = 0.; + Float_t fVx = 0., fVy = 0., fVz = 0., fT = 0.; - Int_t max_nr = 0; + // Read event header line from input file - Text_t buffer[200]; - ncols = fscanf(fInputFile,"%d\t%d", &eventID, &ntracks); + Int_t max_nr = 0; - if (ncols && ntracks>0) { + Text_t buffer[200]; + ncols = fscanf(fInputFile, "%d\t%d", &eventID, &ntracks); - // LOG(info) << "Event number: " << eventID << "\tNtracks: " << ntracks; - // std::stringstream ss; - for (Int_t ii=0; ii<15; ii++) { - ncols += fscanf(fInputFile,"%s",buffer); - // ss << buffer << "\t" ; - } - //LOG(info) << ss.str(); - - for (Int_t ll=0; llGaus(0,fRsigma); - gRandom->Circle(fX, fY, radius); - fVx = fVx + fX; - fVy = fVy + fY; - - // calculate fZ according to some (probability) density function of the - // gas - fZ=fDensityFunction->GetRandom(); - fVz = fVz + fZ; + if (ncols && ntracks > 0) { + // LOG(info) << "Event number: " << eventID << "\tNtracks: " << ntracks; + // std::stringstream ss; + for (Int_t ii = 0; ii < 15; ii++) { + ncols += fscanf(fInputFile, "%s", buffer); + // ss << buffer << "\t" ; } -// printf("Insert coordinates: %f, %f, %f ...\n", fVx, fVy, fVz); - primGen->AddTrack(pdgID, fPx, fPy, fPz, fVx, fVy, fVz); - - } + // LOG(info) << ss.str(); + + for (Int_t ll = 0; ll < ntracks; ll++) { + ncols += fscanf(fInputFile, + "%d %d %d %d %d %d %d %g %f %f %f %f %f %f %f", + &nLine, + &pdgID, + &nDecay, + &nM1, + &nM2, + &nDF, + &nDL, + &fPx, + &fPy, + &fPz, + &fE, + &fT, + &fVx, + &fVy, + &fVz); + // LOG(info) << nLine << "\t" << pdgID << "\t" << nDecay << "\t" << nM1 << "\t" << nM2 << "\t" << nDF << + // "\t" << nDL << + // "\t" << fPx << "\t" << fPy << "\t" << fPz << "\t" << fE << "\t" << fT << "\t" << fVx << "\t" << fVy << + // "\t" << fVz; + max_nr = std::max(max_nr, nDF); + max_nr = std::max(max_nr, nDL); + if ((nDF == -1) && (nDL == -1)) { + + /* Check if fGasmode is set */ + if (fGasmode == 1) { + + // Random 2D point in a circle of radius r (simple beamprofile) + Double_t fX, fY, fZ, radius; + radius = gRandom->Gaus(0, fRsigma); + gRandom->Circle(fX, fY, radius); + fVx = fVx + fX; + fVy = fVy + fY; + + // calculate fZ according to some (probability) density function of the + // gas + fZ = fDensityFunction->GetRandom(); + fVz = fVz + fZ; + } + // printf("Insert coordinates: %f, %f, %f ...\n", fVx, fVy, fVz); + primGen->AddTrack(pdgID, fPx, fPy, fPz, fVx, fVy, fVz); + } + } + } else { + LOG(info) << "FairEvtGenGenerator: End of input file reached "; + CloseInput(); + return kFALSE; } - } else { - LOG(info) << "FairEvtGenGenerator: End of input file reached "; - CloseInput(); - return kFALSE; - } + // If end of input file is reached : close it and abort run + if (feof(fInputFile)) { + LOG(info) << "FairEvtGenGenerator: End of input file reached "; + CloseInput(); + return kFALSE; + } - // If end of input file is reached : close it and abort run - if ( feof(fInputFile) ) { - LOG(info) << "FairEvtGenGenerator: End of input file reached "; - CloseInput(); - return kFALSE; - } - - /* + /* LOG(info) << "FairEvtGenGenerator: Event " << eventID << ", vertex = (" << vx << "," << vy << "," << vz << ") cm, multiplicity " << ntracks; */ - return kTRUE; + return kTRUE; } void FairEvtGenGenerator::CloseInput() { - if ( fInputFile ) { - //if ( fInputFile->is_open() ) { - { - LOG(info) << "FairEvtGenGenerator: Closing input file " << fFileName; - // fInputFile->close(); + if (fInputFile) { + // if ( fInputFile->is_open() ) { + { + LOG(info) << "FairEvtGenGenerator: Closing input file " << fFileName; + // fInputFile->close(); - fclose(fInputFile); + fclose(fInputFile); + } + // delete fInputFile; + fInputFile = nullptr; } - // delete fInputFile; - fInputFile = nullptr; - } } -ClassImp(FairEvtGenGenerator) +ClassImp(FairEvtGenGenerator); diff --git a/generators/FairEvtGenGenerator.h b/generators/FairEvtGenGenerator.h index bbcdcb0f80..19c092d827 100644 --- a/generators/FairEvtGenGenerator.h +++ b/generators/FairEvtGenGenerator.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -81,11 +81,10 @@ #ifndef FAIR_EVTGENGENERATOR_H #define FAIR_EVTGENGENERATOR_H -#include "FairGenerator.h" // for FairGenerator +#include "FairGenerator.h" // for FairGenerator -#include // for FairEvtGenGenerator::Class, etc - -#include // for FILE +#include // for FairEvtGenGenerator::Class, etc +#include // for FILE class FairPrimaryGenerator; class TF1; @@ -115,15 +114,15 @@ class FairEvtGenGenerator : public FairGenerator virtual Bool_t ReadEvent(FairPrimaryGenerator* primGen); private: - //ifstream* fInputFile; //! Input file stream - const Char_t* fFileName; //! Input file Name - FILE* fInputFile; //! Input file pointer + // ifstream* fInputFile; //! Input file stream + const Char_t* fFileName; //! Input file Name + FILE* fInputFile; //! Input file pointer /** Private method CloseInput. Just for convenience. Closes the ** input file properly. Called from destructor and from ReadEvent. **/ void CloseInput(); - int fGasmode; + int fGasmode; double fRsigma; /** PDG data base */ @@ -134,7 +133,7 @@ class FairEvtGenGenerator : public FairGenerator FairEvtGenGenerator(const FairEvtGenGenerator&); FairEvtGenGenerator& operator=(const FairEvtGenGenerator&); - ClassDef(FairEvtGenGenerator,1); + ClassDef(FairEvtGenGenerator, 1); }; #endif diff --git a/generators/FairIonGenerator.cxx b/generators/FairIonGenerator.cxx index 486d08d0d4..83807bd039 100644 --- a/generators/FairIonGenerator.cxx +++ b/generators/FairIonGenerator.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -11,74 +11,94 @@ // ------------------------------------------------------------------------- #include "FairIonGenerator.h" -#include "FairIon.h" // for FairIon -#include "FairParticle.h" // for FairParticle -#include "FairPrimaryGenerator.h" // for FairPrimaryGenerator -#include "FairRunSim.h" // for FairRunSim -#include "FairLogger.h" // for logging +#include "FairIon.h" // for FairIon +#include "FairLogger.h" // for logging +#include "FairParticle.h" // for FairParticle +#include "FairPrimaryGenerator.h" // for FairPrimaryGenerator +#include "FairRunSim.h" // for FairRunSim -#include // for TDatabasePDG -#include // for TObjArray -#include // for TParticle -#include // for TParticlePDG - -#include // for sprintf +#include // for TDatabasePDG +#include // for TObjArray +#include // for TParticle +#include // for TParticlePDG +#include // for sprintf Int_t FairIonGenerator::fgNIon = 0; FairIonGenerator::FairIonGenerator() - :FairBaseMCGenerator(), - fPx(0), fPy(0), fPz(0), - fIon(nullptr), fQ(0) + : FairBaseMCGenerator() + , fPx(0) + , fPy(0) + , fPz(0) + , fIon(nullptr) + , fQ(0) { - // LOG(warn) << "FairIonGenerator: Please do not use the default constructor!"; + // LOG(warn) << "FairIonGenerator: Please do not use the default constructor!"; } -FairIonGenerator::FairIonGenerator(const Char_t* ionName, Int_t mult, - Double_t px, Double_t py, Double_t pz, - Double_t vx, Double_t vy, Double_t vz) - :FairBaseMCGenerator(), - fPx(px), fPy(py), fPz(pz), - fIon(nullptr), fQ(0) +FairIonGenerator::FairIonGenerator(const Char_t* ionName, + Int_t mult, + Double_t px, + Double_t py, + Double_t pz, + Double_t vx, + Double_t vy, + Double_t vz) + : FairBaseMCGenerator() + , fPx(px) + , fPy(py) + , fPz(pz) + , fIon(nullptr) + , fQ(0) { - SetVertex(vx, vy, vz); - SetMultiplicity(mult); - FairRunSim* fRun=FairRunSim::Instance(); - TObjArray* UserIons=fRun->GetUserDefIons(); - TObjArray* UserParticles=fRun->GetUserDefParticles(); - FairParticle* part=0; - fIon =static_cast(UserIons->FindObject(ionName)); - if(fIon) { - fgNIon++; - fPx = Double_t(fIon->GetA()) * px; - fPy = Double_t(fIon->GetA()) * py; - fPz = Double_t(fIon->GetA()) * pz; - } else { - part= static_cast(UserParticles->FindObject(ionName)); - if(part) { - fgNIon++; - TParticle* particle=part->GetParticle(); - fPx = Double_t(particle->GetMass()/0.92827231) * px; - fPy = Double_t(particle->GetMass()/0.92827231) * py; - fPz = Double_t(particle->GetMass()/0.92827231) * pz; + SetVertex(vx, vy, vz); + SetMultiplicity(mult); + FairRunSim* fRun = FairRunSim::Instance(); + TObjArray* UserIons = fRun->GetUserDefIons(); + TObjArray* UserParticles = fRun->GetUserDefParticles(); + FairParticle* part = 0; + fIon = static_cast(UserIons->FindObject(ionName)); + if (fIon) { + fgNIon++; + fPx = Double_t(fIon->GetA()) * px; + fPy = Double_t(fIon->GetA()) * py; + fPz = Double_t(fIon->GetA()) * pz; + } else { + part = static_cast(UserParticles->FindObject(ionName)); + if (part) { + fgNIon++; + TParticle* particle = part->GetParticle(); + fPx = Double_t(particle->GetMass() / 0.92827231) * px; + fPy = Double_t(particle->GetMass() / 0.92827231) * py; + fPz = Double_t(particle->GetMass() / 0.92827231) * pz; + } + } + if (fIon == 0 && part == 0) { + LOG(fatal) << "Ion or Particle is not defined !"; } - } - if(fIon==0 && part==0 ) { - LOG(fatal) << "Ion or Particle is not defined !"; - } } -FairIonGenerator::FairIonGenerator(Int_t z, Int_t a, Int_t q, Int_t mult, - Double_t px, Double_t py, Double_t pz, - Double_t vx, Double_t vy, Double_t vz) - :FairBaseMCGenerator(), - fPx(Double_t(a)*px), fPy(Double_t(a)*py), fPz(Double_t(a)*pz), - fIon(nullptr), fQ(0) +FairIonGenerator::FairIonGenerator(Int_t z, + Int_t a, + Int_t q, + Int_t mult, + Double_t px, + Double_t py, + Double_t pz, + Double_t vx, + Double_t vy, + Double_t vz) + : FairBaseMCGenerator() + , fPx(Double_t(a) * px) + , fPy(Double_t(a) * py) + , fPz(Double_t(a) * pz) + , fIon(nullptr) + , fQ(0) { - fgNIon++; - SetVertex(vx, vy, vz); - SetMultiplicity(mult); - /* + fgNIon++; + SetVertex(vx, vy, vz); + SetMultiplicity(mult); + /* fMult = mult; fPx = Double_t(a) * px; fPy = Double_t(a) * py; @@ -87,78 +107,73 @@ FairIonGenerator::FairIonGenerator(Int_t z, Int_t a, Int_t q, Int_t mult, fVy = vy; fVz = vz; */ - char buffer[20]; - sprintf(buffer, "FairIon%d", fgNIon); - fIon= new FairIon(buffer, z, a, q); - FairRunSim* run = FairRunSim::Instance(); - if ( ! run ) { - LOG(error) << "No FairRun instantised!"; - } else { - run->AddNewIon(fIon); - } + char buffer[20]; + sprintf(buffer, "FairIon%d", fgNIon); + fIon = new FairIon(buffer, z, a, q); + FairRunSim* run = FairRunSim::Instance(); + if (!run) { + LOG(error) << "No FairRun instantised!"; + } else { + run->AddNewIon(fIon); + } } FairIonGenerator::FairIonGenerator(const FairIonGenerator& rhs) - :FairBaseMCGenerator(rhs), - fPx(rhs.fPx), fPy(rhs.fPy), fPz(rhs.fPz), - fIon(rhs.fIon), // CHECK - fQ(0) + : FairBaseMCGenerator(rhs) + , fPx(rhs.fPx) + , fPy(rhs.fPy) + , fPz(rhs.fPz) + , fIon(rhs.fIon) + , // CHECK + fQ(0) { - // fIon= new FairIon(buffer, z, a, q); - FairRunSim* run = FairRunSim::Instance(); - if ( ! run ) { - LOG(error) << "No FairRun instantised!"; - } else { - run->AddNewIon(fIon); - } + // fIon= new FairIon(buffer, z, a, q); + FairRunSim* run = FairRunSim::Instance(); + if (!run) { + LOG(error) << "No FairRun instantised!"; + } else { + run->AddNewIon(fIon); + } } FairIonGenerator::~FairIonGenerator() { -// if (fIon) delete fIon; + // if (fIon) delete fIon; } -void FairIonGenerator::SetExcitationEnergy(Double_t eExc) -{ - fIon->SetExcEnergy(eExc); -} +void FairIonGenerator::SetExcitationEnergy(Double_t eExc) { fIon->SetExcEnergy(eExc); } -void FairIonGenerator::SetMass(Double_t mass) -{ - fIon->SetMass(mass); -} +void FairIonGenerator::SetMass(Double_t mass) { fIon->SetMass(mass); } Bool_t FairIonGenerator::ReadEvent(FairPrimaryGenerator* primGen) { - // if ( ! fIon ) { - // LOG(warn) << "FairIonGenerator: No ion defined! "; - // return kFALSE; - // } - GenerateEventParameters(); - TParticlePDG* thisPart = - TDatabasePDG::Instance()->GetParticle(fIon->GetName()); - if ( ! thisPart ) { - LOG(warn) << "FairIonGenerator: Ion " << fIon->GetName() - << " not found in database!"; - return kFALSE; - } - - int pdgType = thisPart->PdgCode(); - - for(Int_t i=0; iGetName()<< - Form(" p=(%.2f, %.2f, %.2f) GeV,",fPx,fPy,fPz); - primGen->AddTrack(pdgType, fPx, fPy, fPz, fX, fY, fZ); - } - - return kTRUE; + // if ( ! fIon ) { + // LOG(warn) << "FairIonGenerator: No ion defined! "; + // return kFALSE; + // } + GenerateEventParameters(); + TParticlePDG* thisPart = TDatabasePDG::Instance()->GetParticle(fIon->GetName()); + if (!thisPart) { + LOG(warn) << "FairIonGenerator: Ion " << fIon->GetName() << " not found in database!"; + return kFALSE; + } + + int pdgType = thisPart->PdgCode(); + + for (Int_t i = 0; i < GetMultiplicity(); i++) { + LOG(debug) << "FairIonGenerator: Generating ion " << fIon->GetName() + << Form(" p=(%.2f, %.2f, %.2f) GeV,", fPx, fPy, fPz); + primGen->AddTrack(pdgType, fPx, fPy, fPz, fX, fY, fZ); + } + + return kTRUE; } FairGenerator* FairIonGenerator::CloneGenerator() const { - // Clone for worker (used in MT mode only) + // Clone for worker (used in MT mode only) - return new FairIonGenerator(*this); + return new FairIonGenerator(*this); } -ClassImp(FairIonGenerator) +ClassImp(FairIonGenerator); diff --git a/generators/FairIonGenerator.h b/generators/FairIonGenerator.h index 923e318ed8..cacfb2be2f 100644 --- a/generators/FairIonGenerator.h +++ b/generators/FairIonGenerator.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -12,13 +12,14 @@ /** * 24.10.07 implement constructor with ion name. M. Al-Turany -*/ + */ #ifndef FAIRIONGENERATOR_H #define FAIRIONGENERATOR_H -#include // for Double_t, Int_t, etc -#include "FairBaseMCGenerator.h" // for FairGenerator +#include "FairBaseMCGenerator.h" // for FairGenerator + +#include // for Double_t, Int_t, etc class FairIon; class FairPrimaryGenerator; @@ -30,7 +31,7 @@ class FairIonGenerator : public FairBaseMCGenerator FairIonGenerator(); /** Constructor with ion name - ** For the generation of ions with pre-defined FairIon + ** For the generation of ions with pre-defined FairIon ** By default, the excitation energy is zero. This can be changed with the ** respective modifiers. **@param ionName Ion name @@ -38,9 +39,14 @@ class FairIonGenerator : public FairBaseMCGenerator **@param px,py,pz Momentum components [GeV] per nucleon! **@param vx,vy,vz Vertex coordinates [cm] **/ - FairIonGenerator(const Char_t* ionName, Int_t mult, Double_t px, - Double_t py, Double_t pz, Double_t vx = 0, - Double_t vy = 0, Double_t vz = 0); + FairIonGenerator(const Char_t* ionName, + Int_t mult, + Double_t px, + Double_t py, + Double_t pz, + Double_t vx = 0, + Double_t vy = 0, + Double_t vz = 0); /** Default constructor ** For the generation of ions with atomic number z and mass number a. @@ -54,15 +60,22 @@ class FairIonGenerator : public FairBaseMCGenerator **@param px,py,pz Momentum components [GeV] per nucleon! **@param vx,vy,vz Vertex coordinates [cm] **/ - FairIonGenerator(Int_t z, Int_t a, Int_t q, Int_t mult, Double_t px, - Double_t py, Double_t pz, Double_t vx = 0, - Double_t vy = 0, Double_t vz = 0); + FairIonGenerator(Int_t z, + Int_t a, + Int_t q, + Int_t mult, + Double_t px, + Double_t py, + Double_t pz, + Double_t vx = 0, + Double_t vy = 0, + Double_t vz = 0); /** Destructor **/ virtual ~FairIonGenerator(); /** Modifiers **/ - void SetCharge(Int_t charge) {fQ=charge;} + void SetCharge(Int_t charge) { fQ = charge; } void SetExcitationEnergy(Double_t eExc); void SetMass(Double_t mass); @@ -76,15 +89,15 @@ class FairIonGenerator : public FairBaseMCGenerator virtual FairGenerator* CloneGenerator() const; private: - static Int_t fgNIon; //! Number of the instance of this class - Double_t fPx, fPy, fPz; // Momentum components [GeV] per nucleon - FairIon* fIon; // Pointer to the FairIon to be generated - Int_t fQ; // Electric charge [e] + static Int_t fgNIon; //! Number of the instance of this class + Double_t fPx, fPy, fPz; // Momentum components [GeV] per nucleon + FairIon* fIon; // Pointer to the FairIon to be generated + Int_t fQ; // Electric charge [e] FairIonGenerator(const FairIonGenerator&); FairIonGenerator& operator=(const FairIonGenerator&); - ClassDef(FairIonGenerator,2) + ClassDef(FairIonGenerator, 2) }; #endif diff --git a/generators/FairParticleGenerator.cxx b/generators/FairParticleGenerator.cxx index c0245ba0ae..a0254702c1 100644 --- a/generators/FairParticleGenerator.cxx +++ b/generators/FairParticleGenerator.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -10,27 +10,31 @@ // ----- Created 09/07/04 by V. Friese / D.Bertini ----- // ------------------------------------------------------------------------- #include "FairParticleGenerator.h" -#include "FairLogger.h" -#include "FairPrimaryGenerator.h" // for FairPrimaryGenerator +#include "FairLogger.h" +#include "FairPrimaryGenerator.h" // for FairPrimaryGenerator FairParticleGenerator::FairParticleGenerator() - : FairBaseMCGenerator(), - fPx(0), - fPy(0), - fPz(0) + : FairBaseMCGenerator() + , fPx(0) + , fPy(0) + , fPz(0) { SetPDGType(-1); } -FairParticleGenerator::FairParticleGenerator(Int_t pdgid, Int_t mult, - Double32_t px, Double32_t py, - Double32_t pz, Double32_t vx, - Double32_t vy, Double32_t vz) - : FairBaseMCGenerator(), - fPx(px), - fPy(py), - fPz(pz) +FairParticleGenerator::FairParticleGenerator(Int_t pdgid, + Int_t mult, + Double32_t px, + Double32_t py, + Double32_t pz, + Double32_t vx, + Double32_t vy, + Double32_t vz) + : FairBaseMCGenerator() + , fPx(px) + , fPy(py) + , fPz(pz) { SetPDGType(pdgid); SetMultiplicity(mult); @@ -39,27 +43,27 @@ FairParticleGenerator::FairParticleGenerator(Int_t pdgid, Int_t mult, void FairParticleGenerator::SetMomentum(Double32_t px, Double32_t py, Double32_t pz) { - fPx = px; - fPy = py; - fPz = pz; + fPx = px; + fPy = py; + fPz = pz; } Bool_t FairParticleGenerator::ReadEvent(FairPrimaryGenerator* primGen) { - // Check for particle type - GenerateEventParameters(); - if ( GetPDGType() == -1 ) { - LOG(fatal)<<"FairParticleGenerator PDG code not defined"; - } + // Check for particle type + GenerateEventParameters(); + if (GetPDGType() == -1) { + LOG(fatal) << "FairParticleGenerator PDG code not defined"; + } - // Generate particles - for (Int_t k = 0; k < GetMultiplicity(); k++) { - LOG(debug)<<"FairParticleGenerator: "<< - Form("PDG %i p=(%.2f, %.2f, %.2f) GeV,",GetPDGType(),fPx,fPy,fPz); - primGen->AddTrack(GetPDGType(), fPx, fPy, fPz, fX, fY, fZ); - } + // Generate particles + for (Int_t k = 0; k < GetMultiplicity(); k++) { + LOG(debug) << "FairParticleGenerator: " + << Form("PDG %i p=(%.2f, %.2f, %.2f) GeV,", GetPDGType(), fPx, fPy, fPz); + primGen->AddTrack(GetPDGType(), fPx, fPy, fPz, fX, fY, fZ); + } - return kTRUE; + return kTRUE; } -ClassImp(FairParticleGenerator) +ClassImp(FairParticleGenerator); diff --git a/generators/FairParticleGenerator.h b/generators/FairParticleGenerator.h index e5ad570f43..8016519669 100644 --- a/generators/FairParticleGenerator.h +++ b/generators/FairParticleGenerator.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -19,12 +19,12 @@ Derived from FairGenerator. **/ - #ifndef FAIR_PARTICLEGENERATOR_H #define FAIR_PARTICLEGENERATOR_H -#include // for Double32_t, Int_t, etc -#include "FairBaseMCGenerator.h" // for FairGenerator +#include "FairBaseMCGenerator.h" // for FairGenerator + +#include // for Double32_t, Int_t, etc class FairPrimaryGenerator; @@ -41,12 +41,17 @@ class FairParticleGenerator : public FairBaseMCGenerator **@param px,py,pz Momentum components [GeV] **@param vx,vy,vz Vertex coordinates [cm], Default (0,0,0) **/ - FairParticleGenerator(Int_t pdgid, Int_t mult, Double32_t px, - Double32_t py, Double32_t pz, Double32_t vx = 0., - Double32_t vy = 0., Double32_t vz = 0.); + FairParticleGenerator(Int_t pdgid, + Int_t mult, + Double32_t px, + Double32_t py, + Double32_t pz, + Double32_t vx = 0., + Double32_t vy = 0., + Double32_t vz = 0.); /** Destructor **/ - virtual ~FairParticleGenerator() {}; + virtual ~FairParticleGenerator(){}; /** Modifiers **/ void SetMomentum(Double32_t px, Double32_t py, Double32_t pz); @@ -57,9 +62,9 @@ class FairParticleGenerator : public FairBaseMCGenerator virtual Bool_t ReadEvent(FairPrimaryGenerator* primGen); private: - Double32_t fPx, fPy, fPz; // Momentum components [GeV] + Double32_t fPx, fPy, fPz; // Momentum components [GeV] - ClassDef(FairParticleGenerator,2); + ClassDef(FairParticleGenerator, 2); }; #endif diff --git a/generators/FairShieldGenerator.cxx b/generators/FairShieldGenerator.cxx index 1b59556093..f36b338f96 100644 --- a/generators/FairShieldGenerator.cxx +++ b/generators/FairShieldGenerator.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -11,168 +11,166 @@ // ------------------------------------------------------------------------- #include "FairShieldGenerator.h" -#include "FairIon.h" // for FairIon -#include "FairPrimaryGenerator.h" // for FairPrimaryGenerator -#include "FairRunSim.h" // for FairRunSim -#include "FairLogger.h" // for logging +#include "FairIon.h" // for FairIon +#include "FairLogger.h" // for logging +#include "FairPrimaryGenerator.h" // for FairPrimaryGenerator +#include "FairRunSim.h" // for FairRunSim -#include // for TDatabasePDG -#include // for TParticlePDG - -#include // for sprintf -#include // for pair -#include // for INT_MAX -#include // for ifstream +#include // for TDatabasePDG +#include // for TParticlePDG +#include // for INT_MAX +#include // for sprintf +#include // for ifstream +#include // for pair FairShieldGenerator::FairShieldGenerator() - :FairGenerator(), - fInputFile(nullptr), - fFileName(nullptr), - fPDG(nullptr), - fIonMap() -{ -} + : FairGenerator() + , fInputFile(nullptr) + , fFileName(nullptr) + , fPDG(nullptr) + , fIonMap() +{} FairShieldGenerator::FairShieldGenerator(const char* fileName) - :FairGenerator(), - fInputFile(nullptr), - fFileName(fileName), - fPDG(TDatabasePDG::Instance()), - fIonMap() + : FairGenerator() + , fInputFile(nullptr) + , fFileName(fileName) + , fPDG(TDatabasePDG::Instance()) + , fIonMap() { - LOG(info) << "FairShieldGenerator: Opening input file " << fileName; - fInputFile = new std::ifstream(fFileName); - if (!fInputFile->is_open()) { - LOG(fatal) << "Cannot open input file."; - } - LOG(info) << "FairShieldGenerator: Looking for ions..."; - Int_t nIons = RegisterIons(); - LOG(info) << "FairShieldGenerator: " << nIons << " ions registered."; - CloseInput(); - LOG(info) << "FairShieldGenerator: Reopening input file " << fileName; - fInputFile = new std::ifstream(fFileName); + LOG(info) << "FairShieldGenerator: Opening input file " << fileName; + fInputFile = new std::ifstream(fFileName); + if (!fInputFile->is_open()) { + LOG(fatal) << "Cannot open input file."; + } + LOG(info) << "FairShieldGenerator: Looking for ions..."; + Int_t nIons = RegisterIons(); + LOG(info) << "FairShieldGenerator: " << nIons << " ions registered."; + CloseInput(); + LOG(info) << "FairShieldGenerator: Reopening input file " << fileName; + fInputFile = new std::ifstream(fFileName); } -FairShieldGenerator::~FairShieldGenerator() -{ - CloseInput(); -} +FairShieldGenerator::~FairShieldGenerator() { CloseInput(); } Bool_t FairShieldGenerator::ReadEvent(FairPrimaryGenerator* primGen) { - // Check for input file - if (!fInputFile->is_open()) { - LOG(error) << "FairShieldGenerator: Input file not open!"; - return kFALSE; - } - - // Define event variable to be read from file - Int_t eventId = 0; - Int_t nTracks = 0; - Double_t pBeam = 0.; - Double_t b = 0.; - - // Define track variables to be read from file - Int_t iPid = 0; - Int_t iMass = 0; - Int_t iCharge = 0; - Double_t px = 0.; - Double_t py = 0.; - Double_t pz = 0.; - Int_t pdgType = 0; - - // Read event header line from input file - *fInputFile >> eventId; - *fInputFile >> nTracks; - if (nTracks < 0 || nTracks > (INT_MAX-1)) LOG(fatal) << "Error reading the number of events from event header."; - *fInputFile >> pBeam >> b; - - - // If end of input file is reached : close it and abort run - if (fInputFile->eof()) { - LOG(info) << "FairShieldGenerator: End of input file reached "; - CloseInput(); - return kFALSE; - } - - LOG(info) << "FairShieldGenerator: Event " << eventId << ", pBeam = " - << pBeam << "GeV, b = " << b << " fm, multiplicity " << nTracks; - - // Loop over tracks in the current event - for (Int_t itrack=0; itrack> iPid >> iMass >> iCharge >> px >> py >> pz; + // Check for input file + if (!fInputFile->is_open()) { + LOG(error) << "FairShieldGenerator: Input file not open!"; + return kFALSE; + } - // Case ion - if (iPid == 1000) { - char ionName[20]; - sprintf(ionName, "Ion_%d_%d", iMass, iCharge); - TParticlePDG* part = fPDG->GetParticle(ionName); - if (!part) { - LOG(warn) << "FairShieldGenerator::ReadEvent: Cannot find " - << ionName << " in database!"; - continue; - } - pdgType = part->PdgCode(); - } else { pdgType = fPDG->ConvertGeant3ToPdg(iPid); } // "normal" particle + // Define event variable to be read from file + Int_t eventId = 0; + Int_t nTracks = 0; + Double_t pBeam = 0.; + Double_t b = 0.; + + // Define track variables to be read from file + Int_t iPid = 0; + Int_t iMass = 0; + Int_t iCharge = 0; + Double_t px = 0.; + Double_t py = 0.; + Double_t pz = 0.; + Int_t pdgType = 0; + + // Read event header line from input file + *fInputFile >> eventId; + *fInputFile >> nTracks; + if (nTracks < 0 || nTracks > (INT_MAX - 1)) + LOG(fatal) << "Error reading the number of events from event header."; + *fInputFile >> pBeam >> b; - // Give track to PrimaryGenerator - primGen->AddTrack(pdgType, px, py, pz, 0., 0., 0.); + // If end of input file is reached : close it and abort run + if (fInputFile->eof()) { + LOG(info) << "FairShieldGenerator: End of input file reached "; + CloseInput(); + return kFALSE; + } - } + LOG(info) << "FairShieldGenerator: Event " << eventId << ", pBeam = " << pBeam << "GeV, b = " << b + << " fm, multiplicity " << nTracks; + + // Loop over tracks in the current event + for (Int_t itrack = 0; itrack < nTracks; itrack++) { + + // Read PID and momentum from file + *fInputFile >> iPid >> iMass >> iCharge >> px >> py >> pz; + + // Case ion + if (iPid == 1000) { + char ionName[20]; + sprintf(ionName, "Ion_%d_%d", iMass, iCharge); + TParticlePDG* part = fPDG->GetParticle(ionName); + if (!part) { + LOG(warn) << "FairShieldGenerator::ReadEvent: Cannot find " << ionName << " in database!"; + continue; + } + pdgType = part->PdgCode(); + } else { + pdgType = fPDG->ConvertGeant3ToPdg(iPid); + } // "normal" particle + + // Give track to PrimaryGenerator + primGen->AddTrack(pdgType, px, py, pz, 0., 0., 0.); + } - return kTRUE; + return kTRUE; } void FairShieldGenerator::CloseInput() { - if (fInputFile) { - if (fInputFile->is_open()) { - LOG(info) << "FairShieldGenerator: Closing input file " << fFileName; - fInputFile->close(); + if (fInputFile) { + if (fInputFile->is_open()) { + LOG(info) << "FairShieldGenerator: Closing input file " << fFileName; + fInputFile->close(); + } + delete fInputFile; + fInputFile = nullptr; } - delete fInputFile; - fInputFile = nullptr; - } } Int_t FairShieldGenerator::RegisterIons() { - Int_t nIons = 0; - Int_t eventId, nTracks, iPid, iMass, iCharge; - Double_t pBeam, b, px, py, pz; - fIonMap.clear(); - - while (!fInputFile->eof()) { + Int_t nIons = 0; + Int_t eventId, nTracks, iPid, iMass, iCharge; + Double_t pBeam, b, px, py, pz; + fIonMap.clear(); + + while (!fInputFile->eof()) { + + *fInputFile >> eventId; + *fInputFile >> nTracks; + if (nTracks < 0 || nTracks > (INT_MAX - 1)) + LOG(fatal) << "Error reading the number of events from event header."; + *fInputFile >> pBeam >> b; + if (fInputFile->eof()) { + continue; + } + for (Int_t iTrack = 0; iTrack < nTracks; iTrack++) { + *fInputFile >> iPid >> iMass >> iCharge >> px >> py >> pz; + if (iPid == 1000) { // ion + char buffer[20]; + sprintf(buffer, "Ion_%d_%d", iMass, iCharge); + TString ionName(buffer); + if (fIonMap.find(ionName) == fIonMap.end()) { // new ion + FairIon* ion = new FairIon(ionName, iCharge, iMass, iCharge); + fIonMap[ionName] = ion; + nIons++; + } // new ion + } // ion + } // track loop + } // event loop + + FairRunSim* run = FairRunSim::Instance(); + for (const auto& mi : fIonMap) { + FairIon* ion = mi.second; + run->AddNewIon(ion); + } - *fInputFile >> eventId; - *fInputFile >> nTracks; - if (nTracks < 0 || nTracks > (INT_MAX-1)) LOG(fatal) << "Error reading the number of events from event header."; - *fInputFile >> pBeam >> b; - if (fInputFile->eof()) { continue; } - for (Int_t iTrack=0; iTrack> iPid >> iMass >> iCharge >> px >> py >> pz; - if (iPid == 1000) { // ion - char buffer[20]; - sprintf(buffer, "Ion_%d_%d", iMass, iCharge); - TString ionName(buffer); - if (fIonMap.find(ionName) == fIonMap.end()) { // new ion - FairIon* ion = new FairIon(ionName, iCharge, iMass, iCharge); - fIonMap[ionName] = ion; - nIons++; - } // new ion - } // ion - } // track loop - } // event loop - - FairRunSim* run = FairRunSim::Instance(); - for (const auto& mi : fIonMap) { - FairIon* ion = mi.second; - run->AddNewIon(ion); - } - - return nIons; + return nIons; } -ClassImp(FairShieldGenerator) +ClassImp(FairShieldGenerator); diff --git a/generators/FairShieldGenerator.h b/generators/FairShieldGenerator.h index 9cd9eb11bf..d31c1836fc 100644 --- a/generators/FairShieldGenerator.h +++ b/generators/FairShieldGenerator.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -23,18 +23,17 @@ ** PID; A; Z; px; py; pz ** The PID must be given as for Geant3. For ions, it is 1000. The total ** momentum is required, not momentum per nucleon. -**/ + **/ #ifndef FAIRSHIELDGENERATOR_H #define FAIRSHIELDGENERATOR_H 1 -#include "FairGenerator.h" // for FairGenerator +#include "FairGenerator.h" // for FairGenerator -#include // for FairShieldGenerator::Class, etc -#include // for TString - -#include // for ifstream -#include // for map +#include // for FairShieldGenerator::Class, etc +#include // for TString +#include // for ifstream +#include // for map class TDatabasePDG; class FairPrimaryGenerator; @@ -61,9 +60,9 @@ class FairShieldGenerator : public FairGenerator virtual Bool_t ReadEvent(FairPrimaryGenerator* primGen); private: - std::ifstream* fInputFile; //! Input file stream - const Char_t* fFileName; //! Input file Name - TDatabasePDG* fPDG; //! PDG database + std::ifstream* fInputFile; //! Input file stream + const Char_t* fFileName; //! Input file Name + TDatabasePDG* fPDG; //! PDG database /** Private method CloseInput. Just for convenience. Closes the ** input file properly. Called from destructor and from ReadEvent. **/ @@ -74,12 +73,12 @@ class FairShieldGenerator : public FairGenerator Int_t RegisterIons(); /** STL map from ion name to FairIon **/ - std::map fIonMap; //! + std::map fIonMap; //! FairShieldGenerator(const FairShieldGenerator&); FairShieldGenerator& operator=(const FairShieldGenerator&); - ClassDef(FairShieldGenerator,1); + ClassDef(FairShieldGenerator, 1); }; #endif diff --git a/generators/FairUrqmdGenerator.cxx b/generators/FairUrqmdGenerator.cxx index b70b4bd40a..7343c8d2a8 100644 --- a/generators/FairUrqmdGenerator.cxx +++ b/generators/FairUrqmdGenerator.cxx @@ -11,55 +11,53 @@ // ------------------------------------------------------------------------- #include "FairUrqmdGenerator.h" -#include "FairMCEventHeader.h" // for FairMCEventHeader -#include "FairPrimaryGenerator.h" // for FairPrimaryGenerator -#include "FairLogger.h" // for logging - -#include // for TDatabasePDG -#include // for TLorentzVector -#include // for Sqrt, sqrt -#include // for TParticlePDG -#include // for TString, operator+ -#include // for TVector3 - -#include // for getenv -#include // for INT_MAX -#include // IWYU pragma: keep for ifstream -#include // sqrt +#include "FairLogger.h" // for logging +#include "FairMCEventHeader.h" // for FairMCEventHeader +#include "FairPrimaryGenerator.h" // for FairPrimaryGenerator + +#include // for TDatabasePDG +#include // for TLorentzVector +#include // for Sqrt, sqrt +#include // for TParticlePDG +#include // for TString, operator+ +#include // for TVector3 +#include // for INT_MAX +#include // sqrt +#include // for getenv +#include // IWYU pragma: keep for ifstream FairUrqmdGenerator::FairUrqmdGenerator() - :FairGenerator(), - fInputFile(nullptr), - fParticleTable(), - fFileName(nullptr) -{ -} + : FairGenerator() + , fInputFile(nullptr) + , fParticleTable() + , fFileName(nullptr) +{} FairUrqmdGenerator::FairUrqmdGenerator(const char* fileName) - :FairGenerator(), - fInputFile(nullptr), - fParticleTable(), - fFileName(fileName) + : FairGenerator() + , fInputFile(nullptr) + , fParticleTable() + , fFileName(fileName) { - // fFileName = fileName; - LOG(info) << "FairUrqmdGenerator: Opening input file " << fileName; - fInputFile = fopen(fFileName, "r"); - if ( ! fInputFile ) { - LOG(fatal) << "Cannot open input file."; - } - ReadConversionTable(); + // fFileName = fileName; + LOG(info) << "FairUrqmdGenerator: Opening input file " << fileName; + fInputFile = fopen(fFileName, "r"); + if (!fInputFile) { + LOG(fatal) << "Cannot open input file."; + } + ReadConversionTable(); } -FairUrqmdGenerator::FairUrqmdGenerator(const char* fileName, const char* conversion_table) - :FairGenerator(), - fInputFile(nullptr), - fParticleTable(), - fFileName(fileName) +FairUrqmdGenerator::FairUrqmdGenerator(const char* fileName, const char* conversion_table) + : FairGenerator() + , fInputFile(nullptr) + , fParticleTable() + , fFileName(fileName) { // fFileName = fileName; LOG(info) << "FairUrqmdGenerator: Opening input file " << fileName; fInputFile = fopen(fFileName, "r"); - if ( ! fInputFile ) { + if (!fInputFile) { LOG(fatal) << "Cannot open input file."; } ReadConversionTable(conversion_table); @@ -67,203 +65,61 @@ FairUrqmdGenerator::FairUrqmdGenerator(const char* fileName, const char* conver FairUrqmdGenerator::~FairUrqmdGenerator() { - // LOG(debug) << "Enter Destructor of FairUrqmdGenerator"; - if ( fInputFile ) { - fclose(fInputFile); - fInputFile = nullptr; - } - fParticleTable.clear(); - // LOG(debug) << "Leave Destructor of FairUrqmdGenerator"; + // LOG(debug) << "Enter Destructor of FairUrqmdGenerator"; + if (fInputFile) { + fclose(fInputFile); + fInputFile = nullptr; + } + fParticleTable.clear(); + // LOG(debug) << "Leave Destructor of FairUrqmdGenerator"; } -namespace +namespace { +// silence fgets warnings (with a runtime error message if it actually happens) +// for correctness should be handled in the code instead, if this methods are still relevant in the future. +void skipBytes(char* bytes, size_t numBytes, FILE* file) { - // silence fgets warnings (with a runtime error message if it actually happens) - // for correctness should be handled in the code instead, if this methods are still relevant in the future. - void skipBytes(char* bytes, size_t numBytes, FILE* file) - { if (fgets(bytes, numBytes, file) == nullptr) { - LOG(error) << "Failed reading from file stream"; + LOG(error) << "Failed reading from file stream"; } - } - } +} // namespace + Bool_t FairUrqmdGenerator::ReadEvent(FairPrimaryGenerator* primGen) { - // ---> Check for input file - if ( ! fInputFile ) { - LOG(error) << "FairUrqmdGenerator: Input file not open! "; - return kFALSE; - } - - // ---> Check for primary generator - if ( ! primGen ) { - LOG(error) << "FairUrqmdGenerator::ReadEvent: " - << "No PrimaryGenerator!"; - return kFALSE; - } - - // ---> Define event variables to be read from file - int evnr=0, ntracks=0, aProj=0, zProj=0, aTarg=0, zTarg=0; - float b = 0., ekin = 0.; - - int ityp=0, i3=0, ichg=0, pid=0; - float ppx=0., ppy=0., ppz=0., m=0.; - - // ---> Read and check first event header line from input file - char read[200]; - skipBytes(read, 200, fInputFile); - if ( feof(fInputFile) ) { - LOG(info) << "FairUrqmdGenerator : End of input file reached."; - fclose(fInputFile); - fInputFile = nullptr; - return kFALSE; - } - if ( read[0] != 'U' ) { - LOG(error) << "FairUrqmdGenerator: Wrong event header"; - return kFALSE; - } - - Int_t retval = 0; - - // ---> Read rest of event header - skipBytes(read, 26, fInputFile); - retval = fscanf(fInputFile, "%d", &aProj); - CheckReturnValue(retval); - retval = fscanf(fInputFile, "%d", &zProj); - CheckReturnValue(retval); - skipBytes(read, 25, fInputFile); - retval = fscanf(fInputFile, "%d", &aTarg); - CheckReturnValue(retval); - retval = fscanf(fInputFile, "%d", &zTarg); - CheckReturnValue(retval); - skipBytes(read, 200, fInputFile); - skipBytes(read, 200, fInputFile); - skipBytes(read, 36, fInputFile); - retval = fscanf(fInputFile, "%f", &b); - CheckReturnValue(retval); - skipBytes(read, 200, fInputFile); - skipBytes(read, 39, fInputFile); - retval = fscanf(fInputFile, "%e", &ekin); - CheckReturnValue(retval); - skipBytes(read, 200, fInputFile); - skipBytes(read, 7, fInputFile); - retval = fscanf(fInputFile, "%d", &evnr); - CheckReturnValue(retval); - skipBytes(read, 200, fInputFile); - for (int iline=0; iline<8; iline++) { skipBytes(read, 200,fInputFile); } - retval = fscanf(fInputFile, "%d", &ntracks); - if (ntracks < 0 || ntracks > (INT_MAX-1)) LOG(fatal) << "Error reading the number of events from event header."; - CheckReturnValue(retval); - skipBytes(read, 200, fInputFile); - skipBytes(read, 200, fInputFile); - - // ---> Calculate beta and gamma for Lorentztransformation - TDatabasePDG* pdgDB = TDatabasePDG::Instance(); - TParticlePDG* kProton = pdgDB->GetParticle(2212); - Double_t kProtonMass=kProton->Mass(); - - Double_t eBeam = ekin + kProtonMass; - Double_t pBeam = TMath::Sqrt(eBeam*eBeam - kProtonMass*kProtonMass); - Double_t betaCM = pBeam / (eBeam + kProtonMass); - Double_t gammaCM = TMath::Sqrt( 1. / ( 1. - betaCM*betaCM) ); - - LOG(info) << "FairUrqmdGenerator: Event " << evnr << ", b = " << b - << " fm, multiplicity " << ntracks << ", ekin: " - << ekin; - - // Set event id and impact parameter in MCEvent if not yet done - FairMCEventHeader* event = primGen->GetEvent(); - if ( event && (! event->IsSet()) ) { - event->SetEventID(evnr); - event->SetB(b); - event->MarkSet(kTRUE); - } - - // ---> Loop over tracks in the current event - for(int itrack=0; itrack= 0) { pid = 1000 * (ichg+2) + ityp; } - else { pid = -1000 * (ichg+2) + ityp; } - - // Convert Unique PID into PDG particle code - if (fParticleTable.find(pid) == fParticleTable.end()) { - LOG(warn) << "FairUrqmdGenerator: PID " << ityp << " charge " - << ichg << " not found in table (" << pid << ")"; - continue; + // ---> Check for input file + if (!fInputFile) { + LOG(error) << "FairUrqmdGenerator: Input file not open! "; + return kFALSE; } - Int_t pdgID = fParticleTable[pid]; - - // Lorentztransformation to lab - Double_t mass = Double_t(m); - Double_t px = Double_t(ppx); - Double_t py = Double_t(ppy); - Double_t pz = Double_t(ppz); - Double_t e = sqrt( mass*mass + px*px + py*py + pz*pz ); - pz = gammaCM * ( pz + betaCM * e ); - Double_t ee = sqrt( mass*mass + px*px + py*py + pz*pz ); - - TVector3 aa(px,py,pz); - TLorentzVector pp; - pp.SetPx( px ); - pp.SetPy( py ); - pp.SetPz( pz); - pp.SetE( ee ); - - // Give track to PrimaryGenerator - primGen->AddTrack(pdgID, px, py, pz, 0., 0., 0.); - } - - return kTRUE; -} -Bool_t FairUrqmdGenerator::SkipEvents(Int_t count) -{ - if (count<=0) { return kTRUE; } - - for(Int_t ii=0; ii Check for input file - if ( ! fInputFile ) { - LOG(error) << "FairUrqmdGenerator: Input file not open! "; - return kFALSE; + // ---> Check for primary generator + if (!primGen) { + LOG(error) << "FairUrqmdGenerator::ReadEvent: " + << "No PrimaryGenerator!"; + return kFALSE; } // ---> Define event variables to be read from file - int evnr=0, ntracks=0, aProj=0, zProj=0, aTarg=0, zTarg=0; + int evnr = 0, ntracks = 0, aProj = 0, zProj = 0, aTarg = 0, zTarg = 0; float b = 0., ekin = 0.; + int ityp = 0, i3 = 0, ichg = 0, pid = 0; + float ppx = 0., ppy = 0., ppz = 0., m = 0.; + // ---> Read and check first event header line from input file char read[200]; skipBytes(read, 200, fInputFile); - if ( feof(fInputFile) ) { - LOG(info) << "FairUrqmdGenerator : End of input file reached."; - fclose(fInputFile); - fInputFile = nullptr; - return kFALSE; + if (feof(fInputFile)) { + LOG(info) << "FairUrqmdGenerator : End of input file reached."; + fclose(fInputFile); + fInputFile = nullptr; + return kFALSE; } - if ( read[0] != 'U' ) { - LOG(error) << "FairUrqmdGenerator: Wrong event header"; - return kFALSE; + if (read[0] != 'U') { + LOG(error) << "FairUrqmdGenerator: Wrong event header"; + return kFALSE; } Int_t retval = 0; @@ -293,66 +149,216 @@ Bool_t FairUrqmdGenerator::SkipEvents(Int_t count) retval = fscanf(fInputFile, "%d", &evnr); CheckReturnValue(retval); skipBytes(read, 200, fInputFile); - for (int iline=0; iline<8; iline++) { skipBytes(read, 200,fInputFile); } + for (int iline = 0; iline < 8; iline++) { + skipBytes(read, 200, fInputFile); + } retval = fscanf(fInputFile, "%d", &ntracks); - if (ntracks < 0 || ntracks > (INT_MAX-1)) LOG(fatal) << "Error reading the number of events from event header."; + if (ntracks < 0 || ntracks > (INT_MAX - 1)) + LOG(fatal) << "Error reading the number of events from event header."; CheckReturnValue(retval); skipBytes(read, 200, fInputFile); skipBytes(read, 200, fInputFile); - LOG(info) << "FairUrqmdGenerator: Event " << evnr << " skipped!"; + // ---> Calculate beta and gamma for Lorentztransformation + TDatabasePDG* pdgDB = TDatabasePDG::Instance(); + TParticlePDG* kProton = pdgDB->GetParticle(2212); + Double_t kProtonMass = kProton->Mass(); + + Double_t eBeam = ekin + kProtonMass; + Double_t pBeam = TMath::Sqrt(eBeam * eBeam - kProtonMass * kProtonMass); + Double_t betaCM = pBeam / (eBeam + kProtonMass); + Double_t gammaCM = TMath::Sqrt(1. / (1. - betaCM * betaCM)); + + LOG(info) << "FairUrqmdGenerator: Event " << evnr << ", b = " << b << " fm, multiplicity " << ntracks + << ", ekin: " << ekin; + + // Set event id and impact parameter in MCEvent if not yet done + FairMCEventHeader* event = primGen->GetEvent(); + if (event && (!event->IsSet())) { + event->SetEventID(evnr); + event->SetB(b); + event->MarkSet(kTRUE); + } // ---> Loop over tracks in the current event - for(int itrack=0; itrack= 0) { + pid = 1000 * (ichg + 2) + ityp; + } else { + pid = -1000 * (ichg + 2) + ityp; + } + + // Convert Unique PID into PDG particle code + if (fParticleTable.find(pid) == fParticleTable.end()) { + LOG(warn) << "FairUrqmdGenerator: PID " << ityp << " charge " << ichg << " not found in table (" << pid + << ")"; + continue; + } + Int_t pdgID = fParticleTable[pid]; + + // Lorentztransformation to lab + Double_t mass = Double_t(m); + Double_t px = Double_t(ppx); + Double_t py = Double_t(ppy); + Double_t pz = Double_t(ppz); + Double_t e = sqrt(mass * mass + px * px + py * py + pz * pz); + pz = gammaCM * (pz + betaCM * e); + Double_t ee = sqrt(mass * mass + px * px + py * py + pz * pz); + + TVector3 aa(px, py, pz); + TLorentzVector pp; + pp.SetPx(px); + pp.SetPy(py); + pp.SetPz(pz); + pp.SetE(ee); + + // Give track to PrimaryGenerator + primGen->AddTrack(pdgID, px, py, pz, 0., 0., 0.); + } + + return kTRUE; +} + +Bool_t FairUrqmdGenerator::SkipEvents(Int_t count) +{ + if (count <= 0) { + return kTRUE; + } - // Read momentum and PID from file - skipBytes(read, 81, fInputFile); - skipBytes(read, 200, fInputFile); + for (Int_t ii = 0; ii < count; ii++) { + // ---> Check for input file + if (!fInputFile) { + LOG(error) << "FairUrqmdGenerator: Input file not open! "; + return kFALSE; + } + + // ---> Define event variables to be read from file + int evnr = 0, ntracks = 0, aProj = 0, zProj = 0, aTarg = 0, zTarg = 0; + float b = 0., ekin = 0.; + + // ---> Read and check first event header line from input file + char read[200]; + skipBytes(read, 200, fInputFile); + if (feof(fInputFile)) { + LOG(info) << "FairUrqmdGenerator : End of input file reached."; + fclose(fInputFile); + fInputFile = nullptr; + return kFALSE; + } + if (read[0] != 'U') { + LOG(error) << "FairUrqmdGenerator: Wrong event header"; + return kFALSE; + } + + Int_t retval = 0; + + // ---> Read rest of event header + skipBytes(read, 26, fInputFile); + retval = fscanf(fInputFile, "%d", &aProj); + CheckReturnValue(retval); + retval = fscanf(fInputFile, "%d", &zProj); + CheckReturnValue(retval); + skipBytes(read, 25, fInputFile); + retval = fscanf(fInputFile, "%d", &aTarg); + CheckReturnValue(retval); + retval = fscanf(fInputFile, "%d", &zTarg); + CheckReturnValue(retval); + skipBytes(read, 200, fInputFile); + skipBytes(read, 200, fInputFile); + skipBytes(read, 36, fInputFile); + retval = fscanf(fInputFile, "%f", &b); + CheckReturnValue(retval); + skipBytes(read, 200, fInputFile); + skipBytes(read, 39, fInputFile); + retval = fscanf(fInputFile, "%e", &ekin); + CheckReturnValue(retval); + skipBytes(read, 200, fInputFile); + skipBytes(read, 7, fInputFile); + retval = fscanf(fInputFile, "%d", &evnr); + CheckReturnValue(retval); + skipBytes(read, 200, fInputFile); + for (int iline = 0; iline < 8; iline++) { + skipBytes(read, 200, fInputFile); + } + retval = fscanf(fInputFile, "%d", &ntracks); + if (ntracks < 0 || ntracks > (INT_MAX - 1)) + LOG(fatal) << "Error reading the number of events from event header."; + CheckReturnValue(retval); + skipBytes(read, 200, fInputFile); + skipBytes(read, 200, fInputFile); + + LOG(info) << "FairUrqmdGenerator: Event " << evnr << " skipped!"; + + // ---> Loop over tracks in the current event + for (int itrack = 0; itrack < ntracks; itrack++) { + + // Read momentum and PID from file + skipBytes(read, 81, fInputFile); + skipBytes(read, 200, fInputFile); + } } - } - return kTRUE; + return kTRUE; } void FairUrqmdGenerator::ReadConversionTable(TString conversion_table) { - TString work = getenv("VMCWORKDIR"); - TString fileName; + TString work = getenv("VMCWORKDIR"); + TString fileName; - if (conversion_table.IsNull()){ - fileName = work + "/input/urqmd_pdg.dat"; - }else{ - fileName= conversion_table.Data(); - } - - std::ifstream* pdgconv = new std::ifstream(fileName.Data()); + if (conversion_table.IsNull()) { + fileName = work + "/input/urqmd_pdg.dat"; + } else { + fileName = conversion_table.Data(); + } - if (!pdgconv->good()) { - LOG(fatal) << "Could not open Urqmd->PDG input file " << fileName; - } + std::ifstream* pdgconv = new std::ifstream(fileName.Data()); - Int_t index = 0; + if (!pdgconv->good()) { + LOG(fatal) << "Could not open Urqmd->PDG input file " << fileName; + } - Int_t pdgId = 0; + Int_t index = 0; - while ( ! pdgconv->eof() ) { - index =pdgId =0 ; - *pdgconv >> index >> pdgId ; - fParticleTable[index] = pdgId; - } + Int_t pdgId = 0; - pdgconv->close(); - delete pdgconv; + while (!pdgconv->eof()) { + index = pdgId = 0; + *pdgconv >> index >> pdgId; + fParticleTable[index] = pdgId; + } - LOG(info) << "FairUrqmdGenerator: Particle table for conversion from " - << "UrQMD loaded"; + pdgconv->close(); + delete pdgconv; + LOG(info) << "FairUrqmdGenerator: Particle table for conversion from " + << "UrQMD loaded"; } void FairUrqmdGenerator::CheckReturnValue(Int_t retval) { - if (1 != retval) { - LOG(error) << "Error when reading variable from input file"; - } + if (1 != retval) { + LOG(error) << "Error when reading variable from input file"; + } } ClassImp(FairUrqmdGenerator); diff --git a/generators/FairUrqmdGenerator.h b/generators/FairUrqmdGenerator.h index 9d4b191c03..5f39e1e18f 100644 --- a/generators/FairUrqmdGenerator.h +++ b/generators/FairUrqmdGenerator.h @@ -23,13 +23,12 @@ #ifndef FAIRURQMDGENERATOR_H #define FAIRURQMDGENERATOR_H -#include "FairGenerator.h" // for FairGenerator +#include "FairGenerator.h" // for FairGenerator -#include // for Int_t, Bool_t, etc +#include // for Int_t, Bool_t, etc #include - -#include // for FILE -#include // for map +#include // for map +#include // for FILE class FairPrimaryGenerator; @@ -49,7 +48,7 @@ class FairUrqmdGenerator : public FairGenerator * @param conversion_table name of conversion table file (from Urqmd->PDG) should use the full path to the file **/ - FairUrqmdGenerator(const char* fileName, const char* conversion_table); + FairUrqmdGenerator(const char* fileName, const char* conversion_table); /** Destructor. **/ ~FairUrqmdGenerator(); @@ -65,16 +64,16 @@ class FairUrqmdGenerator : public FairGenerator Bool_t SkipEvents(Int_t count); private: - FILE* fInputFile; //! Input file + FILE* fInputFile; //! Input file - std::map fParticleTable; //! Map from UrQMD PID to PDGPID + std::map fParticleTable; //! Map from UrQMD PID to PDGPID - const Char_t* fFileName; //! Input file name + const Char_t* fFileName; //! Input file name /** Private method ReadConversionTable. Reads the conversion table from UrQMD particle code to PDG particle code and fills the conversion map. Is called from the constructor. **/ - void ReadConversionTable(TString conversion_table=""); + void ReadConversionTable(TString conversion_table = ""); /** Check return value from fscanf call **/ void CheckReturnValue(Int_t retval); @@ -82,7 +81,7 @@ class FairUrqmdGenerator : public FairGenerator FairUrqmdGenerator(const FairUrqmdGenerator&); FairUrqmdGenerator& operator=(const FairUrqmdGenerator&); - ClassDef(FairUrqmdGenerator,1); + ClassDef(FairUrqmdGenerator, 1); }; #endif diff --git a/generators/FairYPtGenerator.cxx b/generators/FairYPtGenerator.cxx index 9ba31ba46a..c1ff790481 100644 --- a/generators/FairYPtGenerator.cxx +++ b/generators/FairYPtGenerator.cxx @@ -7,80 +7,80 @@ * Warsaw University of Technology, Faculty of Physics */ #include "FairYPtGenerator.h" -#include "FairPrimaryGenerator.h" + #include "FairLogger.h" -#include +#include "FairPrimaryGenerator.h" + #include +#include #include #include -FairYPtGenerator::FairYPtGenerator(): - FairBaseMCGenerator(), - fYPt(){ -} +FairYPtGenerator::FairYPtGenerator() + : FairBaseMCGenerator() + , fYPt() +{} -FairYPtGenerator::FairYPtGenerator(const FairYPtGenerator& base): - FairBaseMCGenerator(base) - { - base.fYPt.Copy(this->fYPt) ; +FairYPtGenerator::FairYPtGenerator(const FairYPtGenerator &base) + : FairBaseMCGenerator(base) +{ + base.fYPt.Copy(this->fYPt); fYPt.SetDirectory(nullptr); } -FairYPtGenerator& FairYPtGenerator::operator=(const FairYPtGenerator&rhs){ - if(&rhs==this) return *this; - FairBaseMCGenerator::operator =(rhs); +FairYPtGenerator &FairYPtGenerator::operator=(const FairYPtGenerator &rhs) +{ + if (&rhs == this) + return *this; + FairBaseMCGenerator::operator=(rhs); rhs.fYPt.Copy(fYPt); fYPt.SetDirectory(nullptr); return *this; } -void FairYPtGenerator::SetYPt(const TH2D &yPt) { - yPt.Copy(fYPt); - fYPt.SetDirectory(nullptr); +void FairYPtGenerator::SetYPt(const TH2D &yPt) +{ + yPt.Copy(fYPt); + fYPt.SetDirectory(nullptr); } -Bool_t FairYPtGenerator::Init() { - if(FairBaseMCGenerator::Init()==kFALSE)return kFALSE; - fYPt.ResetStats(); - for(int i=1;i<=fYPt.GetNbinsX();i++){ - for(int j=1;jUniform(-TMath::Pi(),TMath::Pi()); - Double_t pz = TMath::Sign(e*0.5,y)*TMath::Exp(-y)*(TMath::Exp(2.0*y)-1.0); - Double_t px = pt*TMath::Cos(phi); - Double_t py = pt*TMath::Sin(phi); - LOG(debug)<<"FairYPtGenerator: "<< - Form("PDG %i p=(%.2f, %.2f, %.2f) GeV,",GetPDGType(),px,py,pz); - primGen->AddTrack(GetPDGType(), px, py, pz, fX, fY, fZ); - } - return kTRUE; -} - -FairGenerator* FairYPtGenerator::CloneGenerator() const { - return new FairYPtGenerator(*this); + if (fYPt.GetEntries() == 0) { + LOG(fatal) << "FairYPtGenerator lack entries !"; + } + return kTRUE; } -void FairYPtGenerator::GetYPt(Double_t &y, Double_t &pt) { - fYPt.GetRandom2(y,pt); +Bool_t FairYPtGenerator::ReadEvent(FairPrimaryGenerator *primGen) +{ + Double_t pt, y; + GenerateEventParameters(); + for (int i = 0; i < GetMultiplicity(); i++) { + GetYPt(y, pt); + Double_t e = TMath::Sqrt(pt * pt + GetMass2()); + Double_t phi = gRandom->Uniform(-TMath::Pi(), TMath::Pi()); + Double_t pz = TMath::Sign(e * 0.5, y) * TMath::Exp(-y) * (TMath::Exp(2.0 * y) - 1.0); + Double_t px = pt * TMath::Cos(phi); + Double_t py = pt * TMath::Sin(phi); + LOG(debug) << "FairYPtGenerator: " << Form("PDG %i p=(%.2f, %.2f, %.2f) GeV,", GetPDGType(), px, py, pz); + primGen->AddTrack(GetPDGType(), px, py, pz, fX, fY, fZ); + } + return kTRUE; } -FairYPtGenerator::~FairYPtGenerator() { -} +FairGenerator *FairYPtGenerator::CloneGenerator() const { return new FairYPtGenerator(*this); } +void FairYPtGenerator::GetYPt(Double_t &y, Double_t &pt) { fYPt.GetRandom2(y, pt); } +FairYPtGenerator::~FairYPtGenerator() {} diff --git a/generators/FairYPtGenerator.h b/generators/FairYPtGenerator.h index dc4c1ee5a9..774660fb2d 100644 --- a/generators/FairYPtGenerator.h +++ b/generators/FairYPtGenerator.h @@ -11,25 +11,28 @@ #ifndef FAIRYPTGENERATOR_H_ #define FAIRYPTGENERATOR_H_ -#include "TH2D.h" #include "FairBaseMCGenerator.h" +#include "TH2D.h" -class FairYPtGenerator : public FairBaseMCGenerator{ +class FairYPtGenerator : public FairBaseMCGenerator +{ public: FairYPtGenerator(); - void SetYPt(const TH2D &yPt); + void SetYPt(const TH2D& yPt); virtual Bool_t Init(); virtual Bool_t ReadEvent(FairPrimaryGenerator* primGen); virtual FairGenerator* CloneGenerator() const; virtual ~FairYPtGenerator(); + protected: FairYPtGenerator(const FairYPtGenerator& base); - FairYPtGenerator& operator=(const FairYPtGenerator&rhs); - Double_t GetMass2()const{return GetPDGMass()*GetPDGMass();}; - void GetYPt(Double_t &y, Double_t &pt); + FairYPtGenerator& operator=(const FairYPtGenerator& rhs); + Double_t GetMass2() const { return GetPDGMass() * GetPDGMass(); }; + void GetYPt(Double_t& y, Double_t& pt); + private: - TH2D fYPt;// Y-Pt distribution - ClassDef(FairYPtGenerator,1) + TH2D fYPt; // Y-Pt distribution + ClassDef(FairYPtGenerator, 1) }; #endif /* CBM_NOV_ANALYSIS_CBMFEMTO_HELPERS_FAIRYPTGENERATOR_H_ */ diff --git a/geobase/FairGeoAsciiIo.cxx b/geobase/FairGeoAsciiIo.cxx index a1ed76e39f..c2beca1fa3 100644 --- a/geobase/FairGeoAsciiIo.cxx +++ b/geobase/FairGeoAsciiIo.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ //*-- AUTHOR : Ilse Koenig @@ -16,229 +16,265 @@ /////////////////////////////////////////////////////////////////////////////// #include "FairGeoAsciiIo.h" -#include "FairGeoInterface.h" // for FairGeoInterface -#include "FairGeoIo.h" // for FairGeoIo -#include "FairGeoMedia.h" // for FairGeoMedia -#include "FairGeoSet.h" // for FairGeoSet +#include "FairGeoInterface.h" // for FairGeoInterface +#include "FairGeoIo.h" // for FairGeoIo +#include "FairGeoMedia.h" // for FairGeoMedia +#include "FairGeoSet.h" // for FairGeoSet -#include // for sscanf -#include // for strcmp, strlen, strtok, etc -#include // for cout -#include // for fstream +#include // for fstream +#include // for cout +#include // for sscanf +#include // for strcmp, strlen, strtok, etc using std::cout; using std::endl; using std::ios; -ClassImp(FairGeoAsciiIo) +ClassImp(FairGeoAsciiIo); FairGeoAsciiIo::FairGeoAsciiIo() - : FairGeoIo(), - filename(""), - filedir(""), - writable(kFALSE), - file(nullptr) + : FairGeoIo() + , filename("") + , filedir("") + , writable(kFALSE) + , file(nullptr) { - // Constructor + // Constructor } FairGeoAsciiIo::~FairGeoAsciiIo() { - // Destructor - close(); - delete file; - file=0; + // Destructor + close(); + delete file; + file = 0; } -Bool_t FairGeoAsciiIo::open(const char* fname,const Text_t* status) +Bool_t FairGeoAsciiIo::open(const char* fname, const Text_t* status) { - // Opens the file fname - close(); - if (!file) { file=new std::fstream(); } - else { (file->clear()); } - if (!filedir.IsNull()) { filename=filedir+"/"+fname; } - else { filename=fname; } - filename=filename.Strip(); - if (strcmp(status,"in")==0) { - file->open(filename,ios::in); - writable=kFALSE; - } else { - if (strcmp(status,"out")==0) { - file->open(filename,ios::in); - if (!isOpen()) { - file->close(); - file->clear(); - file->open(filename,ios::out); - writable=kTRUE; - } else { - file->close(); - Error("open","Output file %s exists already and will not be recreated.", - filename.Data()); + // Opens the file fname + close(); + if (!file) { + file = new std::fstream(); + } else { + (file->clear()); + } + if (!filedir.IsNull()) { + filename = filedir + "/" + fname; + } else { + filename = fname; + } + filename = filename.Strip(); + if (strcmp(status, "in") == 0) { + file->open(filename, ios::in); + writable = kFALSE; + } else { + if (strcmp(status, "out") == 0) { + file->open(filename, ios::in); + if (!isOpen()) { + file->close(); + file->clear(); + file->open(filename, ios::out); + writable = kTRUE; + } else { + file->close(); + Error("open", "Output file %s exists already and will not be recreated.", filename.Data()); + return kFALSE; + } + } else { + Error("open", "Invalid file option!"); + } + } + if (file->rdbuf()->is_open() == 0) { + Fatal("open", "Failed to open file %s", filename.Data()); return kFALSE; - } - } else { Error("open","Invalid file option!"); } - } - if (file->rdbuf()->is_open()==0) { - Fatal("open","Failed to open file %s",filename.Data()); - return kFALSE; - } - return kTRUE; + } + return kTRUE; } Bool_t FairGeoAsciiIo::isOpen() { - // Returns kTRUE, if the file is open - if (file && file->rdbuf()->is_open()==1) { return kTRUE; } - return kFALSE; + // Returns kTRUE, if the file is open + if (file && file->rdbuf()->is_open() == 1) { + return kTRUE; + } + return kFALSE; } Bool_t FairGeoAsciiIo::isWritable() { - // Returns kTRUE, if the file is open and writable - if (isOpen() && writable) { return kTRUE; } - return kFALSE; + // Returns kTRUE, if the file is open and writable + if (isOpen() && writable) { + return kTRUE; + } + return kFALSE; } void FairGeoAsciiIo::close() { - // Closes the file - if (isOpen()) { - file->close(); - filename=""; - } + // Closes the file + if (isOpen()) { + file->close(); + filename = ""; + } } void FairGeoAsciiIo::print() { - // Prints file information - if (isOpen()) { - if (writable) { cout<<"Open output file: "<read(*file); - return kTRUE; + // Reads the media from file + if (!isOpen() || writable || media == 0) { + return kFALSE; + } + media->read(*file); + return kTRUE; } -Bool_t FairGeoAsciiIo::read(FairGeoSet* set,FairGeoMedia* media) +Bool_t FairGeoAsciiIo::read(FairGeoSet* set, FairGeoMedia* media) { - // Reads the geometry set from file - if (!isOpen() || writable || set==0) { return kFALSE; } - set->read(*file,media); - return kTRUE; + // Reads the geometry set from file + if (!isOpen() || writable || set == 0) { + return kFALSE; + } + set->read(*file, media); + return kTRUE; } Bool_t FairGeoAsciiIo::write(FairGeoMedia* media) { - // Writes the media to file - if (!isOpen() || !writable || media==0) { return kFALSE; } - media->write(*file); - return kTRUE; + // Writes the media to file + if (!isOpen() || !writable || media == 0) { + return kFALSE; + } + media->write(*file); + return kTRUE; } Bool_t FairGeoAsciiIo::write(FairGeoSet* set) { - // Writes the geometry set to file - if (!isOpen() || !writable || set==0) { return kFALSE; } - set->write(*file); - return kTRUE; + // Writes the geometry set to file + if (!isOpen() || !writable || set == 0) { + return kFALSE; + } + set->write(*file); + return kTRUE; } Bool_t FairGeoAsciiIo::readGeomConfig(FairGeoInterface* interface) { - // Reads the GEANT configuration file - if (!isOpen() || writable || interface==0) { return kFALSE; } - TString buf(256); - TString simRefRun,historyDate; - Int_t k=-1; - while(!(*file).eof()) { - buf.ReadLine(*file); - buf=buf.Strip(buf.kBoth); - if (!buf.IsNull() && buf(0,2)!="//" && buf(0,1)!="*") { - if (buf.Contains(".geo")||buf.Contains("_gdb")) { - interface->addInputFile(buf.Data()); - } else { - if (buf.Contains(".setup")) { - interface->addSetupFile(buf.Data()); - } else { - if (buf.Contains("SimulRefRunDb:")) { - k=buf.Last(' ')+1; - if (k) { simRefRun=buf(k,buf.Length()-k); } - } else { - if (buf.Contains("HistoryDateDb:")) { - k=buf.First(' ')+1; - if (buf.Length()>k) { - historyDate=buf(k,buf.Length()-k); - historyDate=historyDate.Strip(historyDate.kBoth); - } + // Reads the GEANT configuration file + if (!isOpen() || writable || interface == 0) { + return kFALSE; + } + TString buf(256); + TString simRefRun, historyDate; + Int_t k = -1; + while (!(*file).eof()) { + buf.ReadLine(*file); + buf = buf.Strip(buf.kBoth); + if (!buf.IsNull() && buf(0, 2) != "//" && buf(0, 1) != "*") { + if (buf.Contains(".geo") || buf.Contains("_gdb")) { + interface->addInputFile(buf.Data()); + } else { + if (buf.Contains(".setup")) { + interface->addSetupFile(buf.Data()); + } else { + if (buf.Contains("SimulRefRunDb:")) { + k = buf.Last(' ') + 1; + if (k) { + simRefRun = buf(k, buf.Length() - k); + } + } else { + if (buf.Contains("HistoryDateDb:")) { + k = buf.First(' ') + 1; + if (buf.Length() > k) { + historyDate = buf(k, buf.Length() - k); + historyDate = historyDate.Strip(historyDate.kBoth); + } + } + } + } } - } } - } - } - } - Bool_t rc=kTRUE; - FairGeoIo* oraIo=interface->getOraInput(); - if (oraIo) { - if (historyDate.Length()>0) { rc=oraIo->setHistoryDate(historyDate.Data()); } - if (rc&&simRefRun.Length()>0) { rc=oraIo->setSimulRefRun(simRefRun.Data()); } - } - return rc; + } + Bool_t rc = kTRUE; + FairGeoIo* oraIo = interface->getOraInput(); + if (oraIo) { + if (historyDate.Length() > 0) { + rc = oraIo->setHistoryDate(historyDate.Data()); + } + if (rc && simRefRun.Length() > 0) { + rc = oraIo->setSimulRefRun(simRefRun.Data()); + } + } + return rc; } Bool_t FairGeoAsciiIo::readDetectorSetup(FairGeoInterface* interface) { - // Reads the detector setups, needed for create only subsets - if (!isOpen() || writable || interface==0) { return kFALSE; } - const Int_t maxbuf=256; - char buf[maxbuf]; - TString s, det; - FairGeoSet* set=0; - Int_t maxModules=0, secNo=-1; - Int_t* mod=0; - const char d[]=" "; - while(!(*file).eof()) { - (*file).getline(buf,maxbuf); - if (strlen(buf)>=3 && buf[1]!='/') { - if (buf[0]=='[') { - set=0; - delete [] mod; - mod=0; - s=buf; - Ssiz_t n=s.First(']'); - det=s(1,n-1); - det.ToLower(); - set=interface->findSet(det); - if (!set) { - Error("readDetectorSetup","Detector %s not found",det.Data()); - delete [] mod; - return kFALSE; - } - maxModules=set->getMaxModules(); - mod=new Int_t[maxModules]; - } else { - if (set&&mod) { - char* ss=strtok(buf,d); - if (ss&&strlen(ss)>3) { - secNo=static_cast(ss[3]-'0')-1; - for(Int_t i=0; i= 3 && buf[1] != '/') { + if (buf[0] == '[') { + set = 0; + delete[] mod; + mod = 0; + s = buf; + Ssiz_t n = s.First(']'); + det = s(1, n - 1); + det.ToLower(); + set = interface->findSet(det); + if (!set) { + Error("readDetectorSetup", "Detector %s not found", det.Data()); + delete[] mod; + return kFALSE; + } + maxModules = set->getMaxModules(); + mod = new Int_t[maxModules]; + } else { + if (set && mod) { + char* ss = strtok(buf, d); + if (ss && strlen(ss) > 3) { + secNo = static_cast(ss[3] - '0') - 1; + for (Int_t i = 0; i < maxModules && mod; i++) { + ss = strtok(nullptr, d); + if (ss) { + sscanf(ss, "%i", &mod[i]); + } + } + set->setModules(secNo, mod); + } + } else { + delete[] mod; + return kFALSE; + } } - set->setModules(secNo,mod); - } - } else { - delete [] mod; - return kFALSE; } - } } - } - delete [] mod; - return kTRUE; + delete[] mod; + return kTRUE; } diff --git a/geobase/FairGeoAsciiIo.h b/geobase/FairGeoAsciiIo.h index aa94fb7923..7936906035 100644 --- a/geobase/FairGeoAsciiIo.h +++ b/geobase/FairGeoAsciiIo.h @@ -1,18 +1,18 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRGEOASCIIIO_H #define FAIRGEOASCIIIO_H -#include "FairGeoIo.h" // for FairGeoIo +#include "FairGeoIo.h" // for FairGeoIo -#include // for fstream -#include // for Bool_t, etc -#include // for TString +#include // for Bool_t, etc +#include // for TString +#include // for fstream class FairGeoSet; class FairGeoMedia; @@ -22,35 +22,37 @@ class FairGeoInterface; * Class for geometry I/O from ASCII file * @author Ilse Koenig */ -class FairGeoAsciiIo: public FairGeoIo +class FairGeoAsciiIo : public FairGeoIo { - TString filename; - TString filedir; - Bool_t writable; + TString filename; + TString filedir; + Bool_t writable; std::fstream* file; + public: FairGeoAsciiIo(); virtual ~FairGeoAsciiIo(); - void setDirectory(const char* fDir) {filedir=fDir;} - const char* getDirectory() {return filedir.Data();} - const char* getFilename() {return filename.Data();} - Bool_t open(const char*,const Text_t* status="in"); + void setDirectory(const char* fDir) { filedir = fDir; } + const char* getDirectory() { return filedir.Data(); } + const char* getFilename() { return filename.Data(); } + Bool_t open(const char*, const Text_t* status = "in"); Bool_t isOpen(); Bool_t isWritable(); void close(); void print(); Bool_t read(FairGeoMedia*); - Bool_t read(FairGeoSet*,FairGeoMedia*); + Bool_t read(FairGeoSet*, FairGeoMedia*); Bool_t write(FairGeoMedia*); Bool_t write(FairGeoSet* set); Bool_t readGeomConfig(FairGeoInterface*); Bool_t readDetectorSetup(FairGeoInterface*); - Bool_t setSimulRefRun(const char*) {return kTRUE;} - Bool_t setHistoryDate(const char*) {return kTRUE;} + Bool_t setSimulRefRun(const char*) { return kTRUE; } + Bool_t setHistoryDate(const char*) { return kTRUE; } + private: FairGeoAsciiIo(const FairGeoAsciiIo&); FairGeoAsciiIo& operator=(const FairGeoAsciiIo&); - ClassDef(FairGeoAsciiIo,0) // Class for geometry I/O from ASCII file + ClassDef(FairGeoAsciiIo, 0) // Class for geometry I/O from ASCII file }; -#endif /* !FAIRGEOASCIIIO_H */ +#endif /* !FAIRGEOASCIIIO_H */ diff --git a/geobase/FairGeoAssembly.cxx b/geobase/FairGeoAssembly.cxx index 29198e53b8..c60402f902 100644 --- a/geobase/FairGeoAssembly.cxx +++ b/geobase/FairGeoAssembly.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ //*-- AUTHOR : M. Al-Turany 21/04/2009 @@ -15,89 +15,89 @@ ///////////////////////////////////////////////////////////// #include "FairGeoAssembly.h" -#include "FairGeoTransform.h" // for FairGeoTransform -#include "FairGeoVector.h" // for FairGeoVector -#include "FairGeoVolume.h" // for FairGeoVolume +#include "FairGeoTransform.h" // for FairGeoTransform +#include "FairGeoVector.h" // for FairGeoVector +#include "FairGeoVolume.h" // for FairGeoVolume -#include // for TArrayD -#include // for TString - -#include // for printf, sprintf -#include // for strlen -#include // for fstream, etc +#include // for TArrayD +#include // for TString #include +#include // for fstream, etc +#include // for printf, sprintf +#include // for strlen -ClassImp(FairGeoAssembly) +ClassImp(FairGeoAssembly); FairGeoAssembly::FairGeoAssembly() - :FairGeoBasicShape() + : FairGeoBasicShape() { - // constructor - fName="ASSEMBLY"; - nPoints=0; - nParam=0; - param=new TArrayD(nParam); + // constructor + fName = "ASSEMBLY"; + nPoints = 0; + nParam = 0; + param = new TArrayD(nParam); } FairGeoAssembly::~FairGeoAssembly() { - // destructor - if (param) { - delete param; - param=0; - } - if (center) { - delete center; - center=0; - } - if (position) { - delete position; - position=0; - } + // destructor + if (param) { + delete param; + param = 0; + } + if (center) { + delete center; + center = 0; + } + if (position) { + delete position; + position = 0; + } } -Int_t FairGeoAssembly::readPoints(std::fstream*,FairGeoVolume*) +Int_t FairGeoAssembly::readPoints(std::fstream*, FairGeoVolume*) { - //Assemblies has no parameters so just return 1; - return 1; + // Assemblies has no parameters so just return 1; + return 1; } TArrayD* FairGeoAssembly::calcVoluParam(FairGeoVolume*) { - // nothing to calculate + // nothing to calculate - return param; + return param; } -Bool_t FairGeoAssembly::writePoints(std::fstream* pFile,FairGeoVolume* volu) +Bool_t FairGeoAssembly::writePoints(std::fstream* pFile, FairGeoVolume* volu) { - // writes the 4 'points' decribed above to ascii file - if (!pFile) { return kFALSE; } - Text_t buf[155]; - for(Int_t i=0; igetPoint(i)); - sprintf(buf,"%9.3f\n",v(0)); - pFile->write(buf,strlen(buf)); - } - return kTRUE; + // writes the 4 'points' decribed above to ascii file + if (!pFile) { + return kFALSE; + } + Text_t buf[155]; + for (Int_t i = 0; i < nPoints; i++) { + FairGeoVector& v = *(volu->getPoint(i)); + sprintf(buf, "%9.3f\n", v(0)); + pFile->write(buf, strlen(buf)); + } + return kTRUE; } void FairGeoAssembly::printPoints(FairGeoVolume* volu) { - // prints volume points to screen - for(Int_t i=0; igetPoint(i)); - printf("%9.3f\n",v(0)); - } + // prints volume points to screen + for (Int_t i = 0; i < nPoints; i++) { + FairGeoVector& v = *(volu->getPoint(i)); + printf("%9.3f\n", v(0)); + } } -void FairGeoAssembly::calcVoluPosition(FairGeoVolume*, - const FairGeoTransform& dTC,const FairGeoTransform& mTR) +void FairGeoAssembly::calcVoluPosition(FairGeoVolume*, const FairGeoTransform& dTC, const FairGeoTransform& mTR) { - // calls the function posInMother(...) to calculate the position of the - // volume in its mother - Double_t t[3]= {0.,0.,0.}; - center->setTransVector(t); - posInMother(dTC,mTR); + // calls the function posInMother(...) to calculate the position of the + // volume in its mother + Double_t t[3] = {0., 0., 0.}; + center->setTransVector(t); + posInMother(dTC, mTR); } diff --git a/geobase/FairGeoAssembly.h b/geobase/FairGeoAssembly.h index ddf671473d..eafb99a964 100644 --- a/geobase/FairGeoAssembly.h +++ b/geobase/FairGeoAssembly.h @@ -1,17 +1,17 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRGEOASSEMBLY_H #define FAIRGEOASSEMBLY_H -#include "FairGeoBasicShape.h" // for FairGeoBasicShape +#include "FairGeoBasicShape.h" // for FairGeoBasicShape -#include // for fstream -#include // for FairGeoAssembly::Class, etc +#include // for FairGeoAssembly::Class, etc +#include // for fstream class FairGeoTransform; class FairGeoVolume; @@ -23,14 +23,12 @@ class FairGeoAssembly : public FairGeoBasicShape FairGeoAssembly(); ~FairGeoAssembly(); TArrayD* calcVoluParam(FairGeoVolume*); - void calcVoluPosition(FairGeoVolume*, const FairGeoTransform&,const FairGeoTransform&); - Int_t readPoints(std::fstream* pFile,FairGeoVolume* volu); - Bool_t writePoints(std::fstream*,FairGeoVolume*); + void calcVoluPosition(FairGeoVolume*, const FairGeoTransform&, const FairGeoTransform&); + Int_t readPoints(std::fstream* pFile, FairGeoVolume* volu); + Bool_t writePoints(std::fstream*, FairGeoVolume*); void printPoints(FairGeoVolume* volu); - ClassDef(FairGeoAssembly,0) // class for geometry shape ASSEMBLY + ClassDef(FairGeoAssembly, 0) // class for geometry shape ASSEMBLY }; -#endif /* !FAIRGEOASSEMBLY_H */ - - +#endif /* !FAIRGEOASSEMBLY_H */ diff --git a/geobase/FairGeoBasicShape.cxx b/geobase/FairGeoBasicShape.cxx index 09c73a0af0..d467c261f1 100644 --- a/geobase/FairGeoBasicShape.cxx +++ b/geobase/FairGeoBasicShape.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ //*-- AUTHOR : Ilse Koenig @@ -18,123 +18,128 @@ /////////////////////////////////////////////////////////////////////////////// #include "FairGeoBasicShape.h" -#include "FairGeoTransform.h" // for FairGeoTransform -#include "FairGeoVector.h" // for FairGeoVector -#include "FairGeoVolume.h" // for FairGeoVolume +#include "FairGeoTransform.h" // for FairGeoTransform +#include "FairGeoVector.h" // for FairGeoVector +#include "FairGeoVolume.h" // for FairGeoVolume -#include // for TArrayD - -#include // for printf, sprintf, sscanf -#include // for strlen -#include // for cout -#include // for fstream +#include // for TArrayD +#include // for fstream +#include // for cout +#include // for printf, sprintf, sscanf +#include // for strlen using std::cout; -ClassImp(FairGeoBasicShape) +ClassImp(FairGeoBasicShape); FairGeoBasicShape::FairGeoBasicShape() - : TNamed(), - nPoints(0), - nParam(0), - param(0), - center(new FairGeoTransform()), - position(new FairGeoTransform()) + : TNamed() + , nPoints(0) + , nParam(0) + , param(0) + , center(new FairGeoTransform()) + , position(new FairGeoTransform()) { - // default constructor + // default constructor } FairGeoBasicShape::~FairGeoBasicShape() { - // destructor - if (param) { - delete param; - param=0; - } - if (center) { - delete center; - center=0; - } - if (position) { - delete position; - position=0; - } + // destructor + if (param) { + delete param; + param = 0; + } + if (center) { + delete center; + center = 0; + } + if (position) { + delete position; + position = 0; + } } -Int_t FairGeoBasicShape::readPoints(std::fstream* pFile,FairGeoVolume* volu) +Int_t FairGeoBasicShape::readPoints(std::fstream* pFile, FairGeoVolume* volu) { - // reads nPoints with 3 components from Ascii file - // if the array of points is not existing in the volume it is created and - // the values are stored inside - // returns the number of points - if (!pFile) { return 0; } - if (volu->getNumPoints()!=nPoints) { volu->createPoints(nPoints); } - Double_t x,y,z; - const Int_t maxbuf=155; - Text_t buf[maxbuf]; - for(Int_t i=0; igetline(buf,maxbuf); - sscanf(buf,"%lf%lf%lf",&x,&y,&z); - volu->setPoint(i,x,y,z); - } - return nPoints; + // reads nPoints with 3 components from Ascii file + // if the array of points is not existing in the volume it is created and + // the values are stored inside + // returns the number of points + if (!pFile) { + return 0; + } + if (volu->getNumPoints() != nPoints) { + volu->createPoints(nPoints); + } + Double_t x, y, z; + const Int_t maxbuf = 155; + Text_t buf[maxbuf]; + for (Int_t i = 0; i < nPoints; i++) { + pFile->getline(buf, maxbuf); + sscanf(buf, "%lf%lf%lf", &x, &y, &z); + volu->setPoint(i, x, y, z); + } + return nPoints; } -Bool_t FairGeoBasicShape::writePoints(std::fstream* pFile,FairGeoVolume* volu) +Bool_t FairGeoBasicShape::writePoints(std::fstream* pFile, FairGeoVolume* volu) { - // writes nPoints with 3 components to Ascii file - if (!pFile) { return kFALSE; } - Text_t buf[155]; - for(Int_t i=0; igetNumPoints(); i++) { - FairGeoVector& v=*(volu->getPoint(i)); - sprintf(buf,"%9.3f%10.3f%10.3f\n",v(0),v(1),v(2)); - pFile->write(buf,strlen(buf)); - } - return kTRUE; + // writes nPoints with 3 components to Ascii file + if (!pFile) { + return kFALSE; + } + Text_t buf[155]; + for (Int_t i = 0; i < volu->getNumPoints(); i++) { + FairGeoVector& v = *(volu->getPoint(i)); + sprintf(buf, "%9.3f%10.3f%10.3f\n", v(0), v(1), v(2)); + pFile->write(buf, strlen(buf)); + } + return kTRUE; } void FairGeoBasicShape::printPoints(FairGeoVolume* volu) { - // prints nPoints with 3 components to screen - for(Int_t i=0; igetNumPoints(); i++) { - FairGeoVector& v=*(volu->getPoint(i)); - printf("%9.3f%10.3f%10.3f\n",v(0),v(1),v(2)); - } + // prints nPoints with 3 components to screen + for (Int_t i = 0; i < volu->getNumPoints(); i++) { + FairGeoVector& v = *(volu->getPoint(i)); + printf("%9.3f%10.3f%10.3f\n", v(0), v(1), v(2)); + } } -void FairGeoBasicShape::calcVoluPosition(FairGeoVolume* volu, - const FairGeoTransform& mTR) +void FairGeoBasicShape::calcVoluPosition(FairGeoVolume* volu, const FairGeoTransform& mTR) { - // calculates the relevant information to position the corresponding volume - // in its mother and to position later other components inside this volume. - // The transformation mTR describes the position and orientation of the - // mother volume (center) relative to the physical coordinate system of - // the volume from which it was created. - FairGeoTransform& dTC=volu->getTransform(); - calcVoluPosition(volu,dTC,mTR); + // calculates the relevant information to position the corresponding volume + // in its mother and to position later other components inside this volume. + // The transformation mTR describes the position and orientation of the + // mother volume (center) relative to the physical coordinate system of + // the volume from which it was created. + FairGeoTransform& dTC = volu->getTransform(); + calcVoluPosition(volu, dTC, mTR); } -void FairGeoBasicShape::posInMother(const FairGeoTransform& dTC, - const FairGeoTransform& mTR) +void FairGeoBasicShape::posInMother(const FairGeoTransform& dTC, const FairGeoTransform& mTR) { - // calculates the position of the volume inside its mother - // dTC is the coordinate system of the ROOT volume relative to its physical - // coordinate system - // mTR is the coordinate system of the mother volume relative to its - // physical coordinate system - position->setRotMatrix(center->getRotMatrix()); - position->setTransVector(center->getTransVector()); - position->transFrom(dTC); - position->transTo(mTR); - FairGeoVector t(position->getTransVector()); - position->setTransVector(t*=0.1); + // calculates the position of the volume inside its mother + // dTC is the coordinate system of the ROOT volume relative to its physical + // coordinate system + // mTR is the coordinate system of the mother volume relative to its + // physical coordinate system + position->setRotMatrix(center->getRotMatrix()); + position->setTransVector(center->getTransVector()); + position->transFrom(dTC); + position->transTo(mTR); + FairGeoVector t(position->getTransVector()); + position->setTransVector(t *= 0.1); } void FairGeoBasicShape::printParam() { - // prints the parameters of the ROOT shape - if (param) { - for (Int_t i=0; iAt(i)<<" "; } - cout<<'\n'; - } + // prints the parameters of the ROOT shape + if (param) { + for (Int_t i = 0; i < nParam; i++) { + cout << param->At(i) << " "; + } + cout << '\n'; + } } diff --git a/geobase/FairGeoBasicShape.h b/geobase/FairGeoBasicShape.h index 904e63b26c..339b64ad3e 100644 --- a/geobase/FairGeoBasicShape.h +++ b/geobase/FairGeoBasicShape.h @@ -1,17 +1,16 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRGEOBASICSHAPE_H #define FAIRGEOBASICSHAPE_H -#include // for TNamed - -#include // for fstream -#include // for Int_t, etc +#include // for Int_t, etc +#include // for TNamed +#include // for fstream class FairGeoTransform; class FairGeoVolume; @@ -23,34 +22,32 @@ class TArrayD; class FairGeoBasicShape : public TNamed { protected: - Int_t nPoints; // number of points describing the shape - Int_t nParam; // number of parameters needed to create the ROOT shape - TArrayD* param; // parameters needed to create the ROOT shape - FairGeoTransform* center; // position of the volume center in the technical KS - FairGeoTransform* position; // position of the ROOT volume in its ROOT mother + Int_t nPoints; // number of points describing the shape + Int_t nParam; // number of parameters needed to create the ROOT shape + TArrayD* param; // parameters needed to create the ROOT shape + FairGeoTransform* center; // position of the volume center in the technical KS + FairGeoTransform* position; // position of the ROOT volume in its ROOT mother public: FairGeoBasicShape(); virtual ~FairGeoBasicShape(); - Int_t getNumPoints() {return nPoints;} - Int_t getNumParam() {return nParam;} - TArrayD* getParam() {return param;} - FairGeoTransform* getCenterPosition() {return center;} - FairGeoTransform* getVoluPosition() {return position;} - virtual Int_t readPoints(std::fstream*,FairGeoVolume*); - virtual Bool_t writePoints(std::fstream*,FairGeoVolume*); + Int_t getNumPoints() { return nPoints; } + Int_t getNumParam() { return nParam; } + TArrayD* getParam() { return param; } + FairGeoTransform* getCenterPosition() { return center; } + FairGeoTransform* getVoluPosition() { return position; } + virtual Int_t readPoints(std::fstream*, FairGeoVolume*); + virtual Bool_t writePoints(std::fstream*, FairGeoVolume*); virtual void printPoints(FairGeoVolume* volu); - virtual TArrayD* calcVoluParam(FairGeoVolume*) {return 0;} - virtual void calcVoluPosition(FairGeoVolume*,const FairGeoTransform&); - virtual void calcVoluPosition(FairGeoVolume*,const FairGeoTransform&, - const FairGeoTransform&) {return;} + virtual TArrayD* calcVoluParam(FairGeoVolume*) { return 0; } + virtual void calcVoluPosition(FairGeoVolume*, const FairGeoTransform&); + virtual void calcVoluPosition(FairGeoVolume*, const FairGeoTransform&, const FairGeoTransform&) { return; } void printParam(); + protected: - void posInMother(const FairGeoTransform&,const FairGeoTransform&); - ClassDef(FairGeoBasicShape,0) // base class for all shapes - private: - FairGeoBasicShape(const FairGeoBasicShape&); + void posInMother(const FairGeoTransform&, const FairGeoTransform&); + ClassDef(FairGeoBasicShape, 0) // base class for all shapes + private : FairGeoBasicShape(const FairGeoBasicShape&); FairGeoBasicShape& operator=(const FairGeoBasicShape&); - }; -#endif /* !FAIRGEOBASICSHAPE_H */ +#endif /* !FAIRGEOBASICSHAPE_H */ diff --git a/geobase/FairGeoBrik.cxx b/geobase/FairGeoBrik.cxx index 93294be5ea..063b8c36d1 100644 --- a/geobase/FairGeoBrik.cxx +++ b/geobase/FairGeoBrik.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ //*-- AUTHOR : Ilse Koenig @@ -22,60 +22,64 @@ ///////////////////////////////////////////////////////////// #include "FairGeoBrik.h" -#include "FairGeoTransform.h" // for FairGeoTransform -#include "FairGeoVector.h" // for FairGeoVector -#include "FairGeoVolume.h" // for FairGeoVolume +#include "FairGeoTransform.h" // for FairGeoTransform +#include "FairGeoVector.h" // for FairGeoVector +#include "FairGeoVolume.h" // for FairGeoVolume -#include // for TArrayD -#include // for TString +#include // for TArrayD +#include // for TString -ClassImp(FairGeoBrik) +ClassImp(FairGeoBrik); FairGeoBrik::FairGeoBrik() - :FairGeoBasicShape() + : FairGeoBasicShape() { - // constructor - fName="BOX "; - nPoints=8; - nParam=3; - param=new TArrayD(nParam); + // constructor + fName = "BOX "; + nPoints = 8; + nParam = 3; + param = new TArrayD(nParam); } FairGeoBrik::~FairGeoBrik() { - // destructor - if (param) { - delete param; - param=0; - } - if (center) { - delete center; - center=0; - } - if (position) { - delete position; - position=0; - } + // destructor + if (param) { + delete param; + param = 0; + } + if (center) { + delete center; + center = 0; + } + if (position) { + delete position; + position = 0; + } } TArrayD* FairGeoBrik::calcVoluParam(FairGeoVolume* volu) { - // calculates the parameters needed to create the shape - if (!volu) { return 0; } - FairGeoVector v=*(volu->getPoint(5)) - *(volu->getPoint(3)); - v.abs(); - v*=(1/20.); - for(Int_t i=0; iAddAt(v(i),i); } - return param; + // calculates the parameters needed to create the shape + if (!volu) { + return 0; + } + FairGeoVector v = *(volu->getPoint(5)) - *(volu->getPoint(3)); + v.abs(); + v *= (1 / 20.); + for (Int_t i = 0; i < nParam; i++) { + param->AddAt(v(i), i); + } + return param; } -void FairGeoBrik::calcVoluPosition(FairGeoVolume* volu, const FairGeoTransform& dTC,const FairGeoTransform& mTR) +void FairGeoBrik::calcVoluPosition(FairGeoVolume* volu, const FairGeoTransform& dTC, const FairGeoTransform& mTR) { - // calls the function posInMother(...) to calculate the position of the - // volume in its mother - FairGeoVector trans=*(volu->getPoint(5)) + *(volu->getPoint(3)); - trans*=0.5; - center->clear(); - center->setTransVector(trans); - posInMother(dTC,mTR); + // calls the function posInMother(...) to calculate the position of the + // volume in its mother + FairGeoVector trans = *(volu->getPoint(5)) + *(volu->getPoint(3)); + trans *= 0.5; + center->clear(); + center->setTransVector(trans); + posInMother(dTC, mTR); } diff --git a/geobase/FairGeoBrik.h b/geobase/FairGeoBrik.h index 60dd153396..ba4dcf2baa 100644 --- a/geobase/FairGeoBrik.h +++ b/geobase/FairGeoBrik.h @@ -1,16 +1,16 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRGEOBRIK_H #define FAIRGEOBRIK_H -#include "FairGeoBasicShape.h" // for FairGeoBasicShape +#include "FairGeoBasicShape.h" // for FairGeoBasicShape -#include // for FairGeoBrik::Class, etc +#include // for FairGeoBrik::Class, etc class FairGeoTransform; class FairGeoVolume; @@ -22,8 +22,8 @@ class FairGeoBrik : public FairGeoBasicShape FairGeoBrik(); ~FairGeoBrik(); TArrayD* calcVoluParam(FairGeoVolume*); - void calcVoluPosition(FairGeoVolume*, const FairGeoTransform&,const FairGeoTransform&); - ClassDef(FairGeoBrik,0) // class for geometry shape BOX or BRIK + void calcVoluPosition(FairGeoVolume*, const FairGeoTransform&, const FairGeoTransform&); + ClassDef(FairGeoBrik, 0) // class for geometry shape BOX or BRIK }; -#endif /* !FAIRGEOBRIK_H */ +#endif /* !FAIRGEOBRIK_H */ diff --git a/geobase/FairGeoBuilder.cxx b/geobase/FairGeoBuilder.cxx index fc37259c11..28ddcc5994 100644 --- a/geobase/FairGeoBuilder.cxx +++ b/geobase/FairGeoBuilder.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ //*-- AUTHOR : Ilse Koenig @@ -17,20 +17,20 @@ #include "FairGeoBuilder.h" -ClassImp(FairGeoBuilder) +ClassImp(FairGeoBuilder); FairGeoBuilder::FairGeoBuilder() - :TNamed(), - nRot(0), - nMed(0) + : TNamed() + , nRot(0) + , nMed(0) { - // Default constructor + // Default constructor } -FairGeoBuilder::FairGeoBuilder(const char* name,const char* title) - : TNamed(name,title), - nRot(0), - nMed(0) +FairGeoBuilder::FairGeoBuilder(const char* name, const char* title) + : TNamed(name, title) + , nRot(0) + , nMed(0) { - // Constructor + // Constructor } diff --git a/geobase/FairGeoBuilder.h b/geobase/FairGeoBuilder.h index 0b5dbfd0c9..ac485693b2 100644 --- a/geobase/FairGeoBuilder.h +++ b/geobase/FairGeoBuilder.h @@ -1,16 +1,15 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRGEOBUILDER_H #define FAIRGEOBUILDER_H -#include // for TNamed - -#include // for Int_t, etc +#include // for Int_t, etc +#include // for TNamed class FairGeoNode; class FairGeoMedium; @@ -22,19 +21,20 @@ class FairGeoMedium; class FairGeoBuilder : public TNamed { protected: - Int_t nRot; // number of defined rotations - Int_t nMed; // number of defined media + Int_t nRot; // number of defined rotations + Int_t nMed; // number of defined media FairGeoBuilder(); - FairGeoBuilder(const char* name,const char* title); + FairGeoBuilder(const char* name, const char* title); + public: virtual ~FairGeoBuilder() {} - virtual Bool_t createNode(FairGeoNode*, Int_t hadFormat =0)=0; - virtual Int_t createMedium(FairGeoMedium*)=0; + virtual Bool_t createNode(FairGeoNode*, Int_t hadFormat = 0) = 0; + virtual Int_t createMedium(FairGeoMedium*) = 0; virtual void finalize() {} inline const Int_t& GetNMedia() const { return nMed; } inline void SetNMedia(const Int_t& nmed) { nMed = nmed; } - ClassDef(FairGeoBuilder,0) + ClassDef(FairGeoBuilder, 0) }; #endif /* !FAIRGEOBUILDER_H */ diff --git a/geobase/FairGeoCompositeVolume.cxx b/geobase/FairGeoCompositeVolume.cxx index b8d826583a..2f717bd251 100644 --- a/geobase/FairGeoCompositeVolume.cxx +++ b/geobase/FairGeoCompositeVolume.cxx @@ -15,67 +15,80 @@ ///////////////////////////////////////////////////////////// #include "FairGeoCompositeVolume.h" -#include // for TObjArray +#include // for TObjArray -ClassImp(FairGeoCompositeVolume) +ClassImp(FairGeoCompositeVolume); FairGeoCompositeVolume::FairGeoCompositeVolume(Int_t nComp) - : FairGeoVolume(), - components(nullptr) + : FairGeoVolume() + , components(nullptr) { - if (nComp) { - components=new TObjArray(nComp); - for(Int_t i=0; iAddAt(new FairGeoVolume(),i); } - } - + if (nComp) { + components = new TObjArray(nComp); + for (Int_t i = 0; i < nComp; i++) { + components->AddAt(new FairGeoVolume(), i); + } + } } FairGeoCompositeVolume::~FairGeoCompositeVolume() { - if (components) { components->Delete(); } - delete components; + if (components) { + components->Delete(); + } + delete components; } Int_t FairGeoCompositeVolume::getNumComponents() { - if (components) { return components->GetSize(); } - else { return 0; } + if (components) { + return components->GetSize(); + } else { + return 0; + } } FairGeoVolume* FairGeoCompositeVolume::getComponent(const Int_t n) { - return static_cast(components->At(n)); + return static_cast(components->At(n)); } void FairGeoCompositeVolume::createComponents(const Int_t n) { - if (components) { - components->Delete(); - } else { - components=new TObjArray(); - } - components->Expand(n); + if (components) { + components->Delete(); + } else { + components = new TObjArray(); + } + components->Expand(n); } -void FairGeoCompositeVolume::setComponent(FairGeoVolume* v,const Int_t n) +void FairGeoCompositeVolume::setComponent(FairGeoVolume* v, const Int_t n) { - if (components) { components->AddAt(v,n); } - else { Error("FairGeoCompositeVolume::setComponent","no array of components"); } + if (components) { + components->AddAt(v, n); + } else { + Error("FairGeoCompositeVolume::setComponent", "no array of components"); + } } void FairGeoCompositeVolume::clear() { - FairGeoVolume::clear(); - Int_t n=getNumComponents(); - for(Int_t i=0; i(components->At(i)))->clear(); } + FairGeoVolume::clear(); + Int_t n = getNumComponents(); + for (Int_t i = 0; i < n; i++) { + (static_cast(components->At(i)))->clear(); + } } void FairGeoCompositeVolume::print() { - FairGeoVolume::print(); - FairGeoVolume* v; - for(Int_t i=0; iGetSize(); i++) { - v=static_cast(components->At(i)); - if (v) { v->print(); } - } + FairGeoVolume::print(); + FairGeoVolume* v; + for (Int_t i = 0; i < components->GetSize(); i++) { + v = static_cast(components->At(i)); + if (v) { + v->print(); + } + } } diff --git a/geobase/FairGeoCompositeVolume.h b/geobase/FairGeoCompositeVolume.h index 79b03ea780..d5abb59e1a 100644 --- a/geobase/FairGeoCompositeVolume.h +++ b/geobase/FairGeoCompositeVolume.h @@ -1,16 +1,16 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRGEOCOMPOSITEVOLUME_H #define FAIRGEOCOMPOSITEVOLUME_H -#include "FairGeoVolume.h" // for FairGeoVolume +#include "FairGeoVolume.h" // for FairGeoVolume -#include // for Int_t, etc +#include // for Int_t, etc class TObjArray; /** @@ -20,21 +20,20 @@ class TObjArray; class FairGeoCompositeVolume : public FairGeoVolume { protected: - TObjArray* components; // array of components (type FairGeoVolume) + TObjArray* components; // array of components (type FairGeoVolume) public: - FairGeoCompositeVolume(Int_t nComp=0); + FairGeoCompositeVolume(Int_t nComp = 0); ~FairGeoCompositeVolume(); Int_t getNumComponents(); FairGeoVolume* getComponent(const Int_t); void createComponents(const Int_t); - void setComponent(FairGeoVolume*,const Int_t); + void setComponent(FairGeoVolume*, const Int_t); void clear(); void print(); - ClassDef(FairGeoCompositeVolume,1) + ClassDef(FairGeoCompositeVolume, 1) - private: - FairGeoCompositeVolume(const FairGeoCompositeVolume& ); + private : FairGeoCompositeVolume(const FairGeoCompositeVolume&); FairGeoCompositeVolume& operator=(const FairGeoCompositeVolume&); }; diff --git a/geobase/FairGeoCone.cxx b/geobase/FairGeoCone.cxx index 27a6d91d1c..b5ab571f4f 100644 --- a/geobase/FairGeoCone.cxx +++ b/geobase/FairGeoCone.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ //*-- AUTHOR : Ilse Koenig @@ -33,121 +33,131 @@ /////////////////////////////////////////////////////////////////////////////// #include "FairGeoCone.h" -#include "FairGeoTransform.h" // for FairGeoTransform -#include "FairGeoVector.h" // for FairGeoVector -#include "FairGeoVolume.h" // for FairGeoVolume +#include "FairGeoTransform.h" // for FairGeoTransform +#include "FairGeoVector.h" // for FairGeoVector +#include "FairGeoVolume.h" // for FairGeoVolume -#include // for TArrayD -#include // for Abs -#include // for TString - -#include // for printf, sprintf, sscanf -#include // for strlen -#include // for fstream, etc +#include // for TArrayD +#include // for Abs +#include // for TString #include +#include // for fstream, etc +#include // for printf, sprintf, sscanf +#include // for strlen -ClassImp(FairGeoCone) +ClassImp(FairGeoCone); FairGeoCone::FairGeoCone() - :FairGeoBasicShape() + : FairGeoBasicShape() { - // constructor - fName="CONE"; - nPoints=4; - nParam=5; - param=new TArrayD(nParam); + // constructor + fName = "CONE"; + nPoints = 4; + nParam = 5; + param = new TArrayD(nParam); } FairGeoCone::~FairGeoCone() { - // default destructor - if (param) { - delete param; - param=0; - } - if (center) { - delete center; - center=0; - } - if (position) { - delete position; - position=0; - } + // default destructor + if (param) { + delete param; + param = 0; + } + if (center) { + delete center; + center = 0; + } + if (position) { + delete position; + position = 0; + } } -Int_t FairGeoCone::readPoints(std::fstream* pFile,FairGeoVolume* volu) +Int_t FairGeoCone::readPoints(std::fstream* pFile, FairGeoVolume* volu) { - // reads the 4 'points' decribed above from ascii file - // if the array of points is not existing in the volume it is created and - // the values are stored inside - // returns the number of points - if (!pFile) { return 0; } - if (volu->getNumPoints()!=nPoints) { volu->createPoints(nPoints); } - Double_t x,y,z; - const Int_t maxbuf=155; - Text_t buf[maxbuf]; - for(Int_t i=0; igetline(buf,maxbuf); - sscanf(buf,"%lf%lf%lf",&x,&y,&z); - volu->setPoint(i,x,y,z); - i++; - pFile->getline(buf,maxbuf); - sscanf(buf,"%lf%lf",&x,&y); - volu->setPoint(i,x,y,0.0); - } - return nPoints; + // reads the 4 'points' decribed above from ascii file + // if the array of points is not existing in the volume it is created and + // the values are stored inside + // returns the number of points + if (!pFile) { + return 0; + } + if (volu->getNumPoints() != nPoints) { + volu->createPoints(nPoints); + } + Double_t x, y, z; + const Int_t maxbuf = 155; + Text_t buf[maxbuf]; + for (Int_t i = 0; i < nPoints; i++) { + pFile->getline(buf, maxbuf); + sscanf(buf, "%lf%lf%lf", &x, &y, &z); + volu->setPoint(i, x, y, z); + i++; + pFile->getline(buf, maxbuf); + sscanf(buf, "%lf%lf", &x, &y); + volu->setPoint(i, x, y, 0.0); + } + return nPoints; } -Bool_t FairGeoCone::writePoints(std::fstream* pFile,FairGeoVolume* volu) +Bool_t FairGeoCone::writePoints(std::fstream* pFile, FairGeoVolume* volu) { - // writes the 4 'points' decribed above to ascii file - if (!pFile) { return kFALSE; } - Text_t buf[155]; - for(Int_t i=0; igetPoint(i)); - if (i==0 || i==2) { sprintf(buf,"%9.3f%10.3f%10.3f\n",v(0),v(1),v(2)); } - else { sprintf(buf,"%9.3f%10.3f\n",v(0),v(1)); } - pFile->write(buf,strlen(buf)); - } - return kTRUE; + // writes the 4 'points' decribed above to ascii file + if (!pFile) { + return kFALSE; + } + Text_t buf[155]; + for (Int_t i = 0; i < nPoints; i++) { + FairGeoVector& v = *(volu->getPoint(i)); + if (i == 0 || i == 2) { + sprintf(buf, "%9.3f%10.3f%10.3f\n", v(0), v(1), v(2)); + } else { + sprintf(buf, "%9.3f%10.3f\n", v(0), v(1)); + } + pFile->write(buf, strlen(buf)); + } + return kTRUE; } void FairGeoCone::printPoints(FairGeoVolume* volu) { - // prints volume points to screen - for(Int_t i=0; igetPoint(i)); - if (i==0 || i==2) { printf("%9.3f%10.3f%10.3f\n",v(0),v(1),v(2)); } - else { printf("%9.3f%10.3f\n",v(0),v(1)); } - } + // prints volume points to screen + for (Int_t i = 0; i < nPoints; i++) { + FairGeoVector& v = *(volu->getPoint(i)); + if (i == 0 || i == 2) { + printf("%9.3f%10.3f%10.3f\n", v(0), v(1), v(2)); + } else { + printf("%9.3f%10.3f\n", v(0), v(1)); + } + } } TArrayD* FairGeoCone::calcVoluParam(FairGeoVolume* volu) { - // calculates the parameters needed to create the shape CONE - Double_t fac=10.; - FairGeoVector v=*(volu->getPoint(2)) - *(volu->getPoint(0)); - param->AddAt(TMath::Abs(v(2))/fac/2.,0); - FairGeoVector& v1=*(volu->getPoint(1)); - param->AddAt(v1(0)/fac,1); - param->AddAt(v1(1)/fac,2); - FairGeoVector& v3=*(volu->getPoint(3)); - param->AddAt(v3(0)/fac,3); - param->AddAt(v3(1)/fac,4); - return param; + // calculates the parameters needed to create the shape CONE + Double_t fac = 10.; + FairGeoVector v = *(volu->getPoint(2)) - *(volu->getPoint(0)); + param->AddAt(TMath::Abs(v(2)) / fac / 2., 0); + FairGeoVector& v1 = *(volu->getPoint(1)); + param->AddAt(v1(0) / fac, 1); + param->AddAt(v1(1) / fac, 2); + FairGeoVector& v3 = *(volu->getPoint(3)); + param->AddAt(v3(0) / fac, 3); + param->AddAt(v3(1) / fac, 4); + return param; } -void FairGeoCone::calcVoluPosition(FairGeoVolume* volu, - const FairGeoTransform& dTC,const FairGeoTransform& mTR) +void FairGeoCone::calcVoluPosition(FairGeoVolume* volu, const FairGeoTransform& dTC, const FairGeoTransform& mTR) { - // calculates the position of the center of the volume in the intrinsic - // coordinate system and stores it in the data element 'center' - // calls the function posInMother(...) to calculate the position of the - // volume in its mother - Double_t t[3]= {0.,0.,0.}; - FairGeoVector v=*(volu->getPoint(2)) + *(volu->getPoint(0)); - t[2]=v(2)/2.; - center->clear(); - center->setTransVector(t); - posInMother(dTC,mTR); + // calculates the position of the center of the volume in the intrinsic + // coordinate system and stores it in the data element 'center' + // calls the function posInMother(...) to calculate the position of the + // volume in its mother + Double_t t[3] = {0., 0., 0.}; + FairGeoVector v = *(volu->getPoint(2)) + *(volu->getPoint(0)); + t[2] = v(2) / 2.; + center->clear(); + center->setTransVector(t); + posInMother(dTC, mTR); } diff --git a/geobase/FairGeoCone.h b/geobase/FairGeoCone.h index 999749646b..31bf095da9 100644 --- a/geobase/FairGeoCone.h +++ b/geobase/FairGeoCone.h @@ -1,17 +1,17 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRGEOCONE_H #define FAIRGEOCONE_H -#include "FairGeoBasicShape.h" // for FairGeoBasicShape +#include "FairGeoBasicShape.h" // for FairGeoBasicShape -#include // for fstream -#include // for FairGeoCone::Class, Bool_t, etc +#include // for FairGeoCone::Class, Bool_t, etc +#include // for fstream class FairGeoTransform; class FairGeoVolume; @@ -26,12 +26,11 @@ class FairGeoCone : public FairGeoBasicShape FairGeoCone(); ~FairGeoCone(); TArrayD* calcVoluParam(FairGeoVolume*); - void calcVoluPosition(FairGeoVolume*, - const FairGeoTransform&,const FairGeoTransform&); - Int_t readPoints(std::fstream*,FairGeoVolume*); - Bool_t writePoints(std::fstream*,FairGeoVolume*); + void calcVoluPosition(FairGeoVolume*, const FairGeoTransform&, const FairGeoTransform&); + Int_t readPoints(std::fstream*, FairGeoVolume*); + Bool_t writePoints(std::fstream*, FairGeoVolume*); void printPoints(FairGeoVolume* volu); - ClassDef(FairGeoCone,0) // + ClassDef(FairGeoCone, 0) // }; -#endif /* !FAIRGEOCONE_H */ +#endif /* !FAIRGEOCONE_H */ diff --git a/geobase/FairGeoCons.cxx b/geobase/FairGeoCons.cxx index 87cebf5878..44fd490108 100644 --- a/geobase/FairGeoCons.cxx +++ b/geobase/FairGeoCons.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ //*-- AUTHOR : Ilse Koenig @@ -36,125 +36,135 @@ /////////////////////////////////////////////////////////////////////////////// #include "FairGeoCons.h" -#include "FairGeoTransform.h" // for FairGeoTransform -#include "FairGeoVector.h" // for FairGeoVector -#include "FairGeoVolume.h" // for FairGeoVolume +#include "FairGeoTransform.h" // for FairGeoTransform +#include "FairGeoVector.h" // for FairGeoVector +#include "FairGeoVolume.h" // for FairGeoVolume -#include // for TArrayD -#include // for Abs -#include // for TString - -#include // for printf, sprintf, sscanf -#include // for strlen -#include // for fstream, etc +#include // for TArrayD +#include // for Abs +#include // for TString #include +#include // for fstream, etc +#include // for printf, sprintf, sscanf +#include // for strlen -ClassImp(FairGeoCons) +ClassImp(FairGeoCons); FairGeoCons::FairGeoCons() - :FairGeoBasicShape() + : FairGeoBasicShape() { - // constructor - fName="CONS"; - nPoints=5; - nParam=7; - param=new TArrayD(nParam); + // constructor + fName = "CONS"; + nPoints = 5; + nParam = 7; + param = new TArrayD(nParam); } FairGeoCons::~FairGeoCons() { - // default destructor - if (param) { - delete param; - param=0; - } - if (center) { - delete center; - center=0; - } - if (position) { - delete position; - position=0; - } + // default destructor + if (param) { + delete param; + param = 0; + } + if (center) { + delete center; + center = 0; + } + if (position) { + delete position; + position = 0; + } } -Int_t FairGeoCons::readPoints(std::fstream* pFile,FairGeoVolume* volu) +Int_t FairGeoCons::readPoints(std::fstream* pFile, FairGeoVolume* volu) { - // reads the 5 'points' decribed above from ascii file - // if the array of points is not existing in the volume it is created and - // the values are stored inside - // returns the number of points - if (!pFile) { return 0; } - if (volu->getNumPoints()!=nPoints) { volu->createPoints(nPoints); } - Double_t x,y,z; - const Int_t maxbuf=155; - Text_t buf[maxbuf]; - for(Int_t i=0; igetline(buf,maxbuf); - if (i==0 || i==2) { - sscanf(buf,"%lf%lf%lf",&x,&y,&z); - volu->setPoint(i,x,y,z); - } else { - sscanf(buf,"%lf%lf",&x,&y); - volu->setPoint(i,x,y,0.0); + // reads the 5 'points' decribed above from ascii file + // if the array of points is not existing in the volume it is created and + // the values are stored inside + // returns the number of points + if (!pFile) { + return 0; + } + if (volu->getNumPoints() != nPoints) { + volu->createPoints(nPoints); } - } - return nPoints; + Double_t x, y, z; + const Int_t maxbuf = 155; + Text_t buf[maxbuf]; + for (Int_t i = 0; i < nPoints; i++) { + pFile->getline(buf, maxbuf); + if (i == 0 || i == 2) { + sscanf(buf, "%lf%lf%lf", &x, &y, &z); + volu->setPoint(i, x, y, z); + } else { + sscanf(buf, "%lf%lf", &x, &y); + volu->setPoint(i, x, y, 0.0); + } + } + return nPoints; } -Bool_t FairGeoCons::writePoints(std::fstream* pFile,FairGeoVolume* volu) +Bool_t FairGeoCons::writePoints(std::fstream* pFile, FairGeoVolume* volu) { - // writes the 5 'points' decribed above to ascii file - if (!pFile) { return kFALSE; } - Text_t buf[155]; - for(Int_t i=0; igetPoint(i)); - if (i==0 || i==2) { sprintf(buf,"%9.3f%10.3f%10.3f\n",v(0),v(1),v(2)); } - else { sprintf(buf,"%9.3f%10.3f\n",v(0),v(1)); } - pFile->write(buf,strlen(buf)); - } - return kTRUE; + // writes the 5 'points' decribed above to ascii file + if (!pFile) { + return kFALSE; + } + Text_t buf[155]; + for (Int_t i = 0; i < nPoints; i++) { + FairGeoVector& v = *(volu->getPoint(i)); + if (i == 0 || i == 2) { + sprintf(buf, "%9.3f%10.3f%10.3f\n", v(0), v(1), v(2)); + } else { + sprintf(buf, "%9.3f%10.3f\n", v(0), v(1)); + } + pFile->write(buf, strlen(buf)); + } + return kTRUE; } void FairGeoCons::printPoints(FairGeoVolume* volu) { - // prints volume points to screen - for(Int_t i=0; igetPoint(i)); - if (i==0 || i==2) { printf("%9.3f%10.3f%10.3f\n",v(0),v(1),v(2)); } - else { printf("%9.3f%10.3f\n",v(0),v(1)); } - } + // prints volume points to screen + for (Int_t i = 0; i < nPoints; i++) { + FairGeoVector& v = *(volu->getPoint(i)); + if (i == 0 || i == 2) { + printf("%9.3f%10.3f%10.3f\n", v(0), v(1), v(2)); + } else { + printf("%9.3f%10.3f\n", v(0), v(1)); + } + } } TArrayD* FairGeoCons::calcVoluParam(FairGeoVolume* volu) { - // calculates the parameters needed to create the shape CONS - Double_t fac=10.; - FairGeoVector v=*(volu->getPoint(2)) - *(volu->getPoint(0)); - param->AddAt(TMath::Abs(v(2))/fac/2.,0); - FairGeoVector& v1=*(volu->getPoint(1)); - param->AddAt(v1(0)/fac,1); - param->AddAt(v1(1)/fac,2); - FairGeoVector& v3=*(volu->getPoint(3)); - param->AddAt(v3(0)/fac,3); - param->AddAt(v3(1)/fac,4); - FairGeoVector& v4=*(volu->getPoint(4)); - param->AddAt(v4(0),5); - param->AddAt(v4(1),6); - return param; + // calculates the parameters needed to create the shape CONS + Double_t fac = 10.; + FairGeoVector v = *(volu->getPoint(2)) - *(volu->getPoint(0)); + param->AddAt(TMath::Abs(v(2)) / fac / 2., 0); + FairGeoVector& v1 = *(volu->getPoint(1)); + param->AddAt(v1(0) / fac, 1); + param->AddAt(v1(1) / fac, 2); + FairGeoVector& v3 = *(volu->getPoint(3)); + param->AddAt(v3(0) / fac, 3); + param->AddAt(v3(1) / fac, 4); + FairGeoVector& v4 = *(volu->getPoint(4)); + param->AddAt(v4(0), 5); + param->AddAt(v4(1), 6); + return param; } -void FairGeoCons::calcVoluPosition(FairGeoVolume* volu, - const FairGeoTransform& dTC,const FairGeoTransform& mTR) +void FairGeoCons::calcVoluPosition(FairGeoVolume* volu, const FairGeoTransform& dTC, const FairGeoTransform& mTR) { - // calculates the position of the center of the volume in the intrinsic - // coordinate system and stores it in the data element 'center' - // calls the function posInMother(...) to calculate the position of the - // volume in its mother - Double_t t[3]= {0.,0.,0.}; - FairGeoVector v=*(volu->getPoint(2)) + *(volu->getPoint(0)); - t[2]=v(2)/2.; - center->clear(); - center->setTransVector(t); - posInMother(dTC,mTR); + // calculates the position of the center of the volume in the intrinsic + // coordinate system and stores it in the data element 'center' + // calls the function posInMother(...) to calculate the position of the + // volume in its mother + Double_t t[3] = {0., 0., 0.}; + FairGeoVector v = *(volu->getPoint(2)) + *(volu->getPoint(0)); + t[2] = v(2) / 2.; + center->clear(); + center->setTransVector(t); + posInMother(dTC, mTR); } diff --git a/geobase/FairGeoCons.h b/geobase/FairGeoCons.h index 3aa1b2958d..35b6efc657 100644 --- a/geobase/FairGeoCons.h +++ b/geobase/FairGeoCons.h @@ -1,18 +1,17 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRGEOCONS_H #define FAIRGEOCONS_H -#include "FairGeoBasicShape.h" // for FairGeoBasicShape +#include "FairGeoBasicShape.h" // for FairGeoBasicShape -#include // for FairGeoCons::Class, Bool_t, etc - -#include // for fstream +#include // for FairGeoCons::Class, Bool_t, etc +#include // for fstream class FairGeoTransform; class FairGeoVolume; @@ -27,12 +26,11 @@ class FairGeoCons : public FairGeoBasicShape FairGeoCons(); ~FairGeoCons(); TArrayD* calcVoluParam(FairGeoVolume*); - void calcVoluPosition(FairGeoVolume*, - const FairGeoTransform&,const FairGeoTransform&); - Int_t readPoints(std::fstream*,FairGeoVolume*); - Bool_t writePoints(std::fstream*,FairGeoVolume*); + void calcVoluPosition(FairGeoVolume*, const FairGeoTransform&, const FairGeoTransform&); + Int_t readPoints(std::fstream*, FairGeoVolume*); + Bool_t writePoints(std::fstream*, FairGeoVolume*); void printPoints(FairGeoVolume* volu); - ClassDef(FairGeoCons,0) // + ClassDef(FairGeoCons, 0) // }; -#endif /* !FAIRGEOCONS_H */ +#endif /* !FAIRGEOCONS_H */ diff --git a/geobase/FairGeoEltu.cxx b/geobase/FairGeoEltu.cxx index 224bd98713..a37be52ef7 100644 --- a/geobase/FairGeoEltu.cxx +++ b/geobase/FairGeoEltu.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ //*-- AUTHOR : Ilse Koenig @@ -30,119 +30,129 @@ /////////////////////////////////////////////////////////////////////////////// #include "FairGeoEltu.h" -#include "FairGeoTransform.h" // for FairGeoTransform -#include "FairGeoVector.h" // for FairGeoVector -#include "FairGeoVolume.h" // for FairGeoVolume +#include "FairGeoTransform.h" // for FairGeoTransform +#include "FairGeoVector.h" // for FairGeoVector +#include "FairGeoVolume.h" // for FairGeoVolume -#include // for TArrayD -#include // for Abs -#include // for TString - -#include // for printf, sprintf, sscanf -#include // for strlen -#include // for fstream, etc +#include // for TArrayD +#include // for Abs +#include // for TString #include +#include // for fstream, etc +#include // for printf, sprintf, sscanf +#include // for strlen -ClassImp(FairGeoEltu) +ClassImp(FairGeoEltu); FairGeoEltu::FairGeoEltu() - :FairGeoBasicShape() + : FairGeoBasicShape() { - // constructor - fName="ELTU"; - nPoints=3; - nParam=3; - param=new TArrayD(nParam); + // constructor + fName = "ELTU"; + nPoints = 3; + nParam = 3; + param = new TArrayD(nParam); } FairGeoEltu::~FairGeoEltu() { - // default destructor - if (param) { - delete param; - param=0; - } - if (center) { - delete center; - center=0; - } - if (position) { - delete position; - position=0; - } + // default destructor + if (param) { + delete param; + param = 0; + } + if (center) { + delete center; + center = 0; + } + if (position) { + delete position; + position = 0; + } } -Int_t FairGeoEltu::readPoints(std::fstream* pFile,FairGeoVolume* volu) +Int_t FairGeoEltu::readPoints(std::fstream* pFile, FairGeoVolume* volu) { - // reads the 3 'points' decribed above from ascii file - // if the array of points is not existing in the volume it is created and - // the values are stored inside - // returns the number of points - if (!pFile) { return 0; } - if (volu->getNumPoints()!=nPoints) { volu->createPoints(nPoints); } - Double_t x,y,z; - const Int_t maxbuf=155; - Text_t buf[maxbuf]; - for(Int_t i=0; igetline(buf,maxbuf); - if (i!=1) { - sscanf(buf,"%lf%lf%lf",&x,&y,&z); - volu->setPoint(i,x,y,z); - } else { - sscanf(buf,"%lf%lf",&x,&y); - volu->setPoint(i,x,y,0.0); + // reads the 3 'points' decribed above from ascii file + // if the array of points is not existing in the volume it is created and + // the values are stored inside + // returns the number of points + if (!pFile) { + return 0; + } + if (volu->getNumPoints() != nPoints) { + volu->createPoints(nPoints); } - } - return nPoints; + Double_t x, y, z; + const Int_t maxbuf = 155; + Text_t buf[maxbuf]; + for (Int_t i = 0; i < nPoints; i++) { + pFile->getline(buf, maxbuf); + if (i != 1) { + sscanf(buf, "%lf%lf%lf", &x, &y, &z); + volu->setPoint(i, x, y, z); + } else { + sscanf(buf, "%lf%lf", &x, &y); + volu->setPoint(i, x, y, 0.0); + } + } + return nPoints; } -Bool_t FairGeoEltu::writePoints(std::fstream* pFile,FairGeoVolume* volu) +Bool_t FairGeoEltu::writePoints(std::fstream* pFile, FairGeoVolume* volu) { - // writes the 3 'points' decribed above to ascii file - if (!pFile) { return kFALSE; } - Text_t buf[155]; - for(Int_t i=0; igetPoint(i)); - if (i!=1) { sprintf(buf,"%9.3f%10.3f%10.3f\n",v(0),v(1),v(2)); } - else { sprintf(buf,"%9.3f%10.3f\n",v(0),v(1)); } - pFile->write(buf,strlen(buf)); - } - return kTRUE; + // writes the 3 'points' decribed above to ascii file + if (!pFile) { + return kFALSE; + } + Text_t buf[155]; + for (Int_t i = 0; i < nPoints; i++) { + FairGeoVector& v = *(volu->getPoint(i)); + if (i != 1) { + sprintf(buf, "%9.3f%10.3f%10.3f\n", v(0), v(1), v(2)); + } else { + sprintf(buf, "%9.3f%10.3f\n", v(0), v(1)); + } + pFile->write(buf, strlen(buf)); + } + return kTRUE; } void FairGeoEltu::printPoints(FairGeoVolume* volu) { - // prints volume points to screen - for(Int_t i=0; igetPoint(i)); - if (i!=1) { printf("%9.3f%10.3f%10.3f\n",v(0),v(1),v(2)); } - else { printf("%9.3f%10.3f\n",v(0),v(1)); } - } + // prints volume points to screen + for (Int_t i = 0; i < nPoints; i++) { + FairGeoVector& v = *(volu->getPoint(i)); + if (i != 1) { + printf("%9.3f%10.3f%10.3f\n", v(0), v(1), v(2)); + } else { + printf("%9.3f%10.3f\n", v(0), v(1)); + } + } } TArrayD* FairGeoEltu::calcVoluParam(FairGeoVolume* volu) { - // calculates the parameters needed to create the shape ELTU - Double_t fac=10.; - FairGeoVector& v1=*(volu->getPoint(1)); - param->AddAt(v1(0)/fac,0); - param->AddAt(v1(1)/fac,1); - FairGeoVector v=*(volu->getPoint(2)) - *(volu->getPoint(0)); - param->AddAt(TMath::Abs(v(2))/fac/2.,2); - return param; + // calculates the parameters needed to create the shape ELTU + Double_t fac = 10.; + FairGeoVector& v1 = *(volu->getPoint(1)); + param->AddAt(v1(0) / fac, 0); + param->AddAt(v1(1) / fac, 1); + FairGeoVector v = *(volu->getPoint(2)) - *(volu->getPoint(0)); + param->AddAt(TMath::Abs(v(2)) / fac / 2., 2); + return param; } -void FairGeoEltu::calcVoluPosition(FairGeoVolume* volu, - const FairGeoTransform& dTC,const FairGeoTransform& mTR) +void FairGeoEltu::calcVoluPosition(FairGeoVolume* volu, const FairGeoTransform& dTC, const FairGeoTransform& mTR) { - // calculates the position of the center of the volume in the intrinsic - // coordinate system and stores it in the data element 'center' - // calls the function posInMother(...) to calculate the position of the - // volume in its mother - Double_t t[3]= {0.,0.,0.}; - FairGeoVector v=*(volu->getPoint(2)) + *(volu->getPoint(0)); - t[2]=v(2)/2.; - center->clear(); - center->setTransVector(t); - posInMother(dTC,mTR); + // calculates the position of the center of the volume in the intrinsic + // coordinate system and stores it in the data element 'center' + // calls the function posInMother(...) to calculate the position of the + // volume in its mother + Double_t t[3] = {0., 0., 0.}; + FairGeoVector v = *(volu->getPoint(2)) + *(volu->getPoint(0)); + t[2] = v(2) / 2.; + center->clear(); + center->setTransVector(t); + posInMother(dTC, mTR); } diff --git a/geobase/FairGeoEltu.h b/geobase/FairGeoEltu.h index 08da04e6c3..185a6ef52c 100644 --- a/geobase/FairGeoEltu.h +++ b/geobase/FairGeoEltu.h @@ -1,18 +1,17 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRGEOELTU_H #define FAIRGEOELTU_H -#include "FairGeoBasicShape.h" // for FairGeoBasicShape +#include "FairGeoBasicShape.h" // for FairGeoBasicShape -#include // for FairGeoEltu::Class, Bool_t, etc - -#include // for fstream +#include // for FairGeoEltu::Class, Bool_t, etc +#include // for fstream class FairGeoTransform; class FairGeoVolume; @@ -28,12 +27,11 @@ class FairGeoEltu : public FairGeoBasicShape FairGeoEltu(); ~FairGeoEltu(); TArrayD* calcVoluParam(FairGeoVolume*); - void calcVoluPosition(FairGeoVolume*, - const FairGeoTransform&,const FairGeoTransform&); - Int_t readPoints(std::fstream*,FairGeoVolume*); - Bool_t writePoints(std::fstream*,FairGeoVolume*); + void calcVoluPosition(FairGeoVolume*, const FairGeoTransform&, const FairGeoTransform&); + Int_t readPoints(std::fstream*, FairGeoVolume*); + Bool_t writePoints(std::fstream*, FairGeoVolume*); void printPoints(FairGeoVolume* volu); - ClassDef(FairGeoEltu,0) // + ClassDef(FairGeoEltu, 0) // }; -#endif /* !FAIRGEOELTU_H */ +#endif /* !FAIRGEOELTU_H */ diff --git a/geobase/FairGeoInterface.cxx b/geobase/FairGeoInterface.cxx index c7c8b91086..81f7673447 100644 --- a/geobase/FairGeoInterface.cxx +++ b/geobase/FairGeoInterface.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ //*-- AUTHOR : Ilse Koenig @@ -23,97 +23,92 @@ /////////////////////////////////////////////////////////////////////////////// #include "FairGeoInterface.h" -#include "FairGeoAsciiIo.h" // for FairGeoAsciiIo -#include "FairGeoBuilder.h" // for FairGeoBuilder -#include "FairGeoIo.h" // for FairGeoIo -#include "FairGeoMedia.h" // for FairGeoMedia -#include "FairGeoSet.h" // for FairGeoSet -#include "FairGeoShapes.h" // for FairGeoShapes - -#include // for TClass -#include // for TList -#include // for TObjArray - -#include // for sprintf -#include // for strcmp -#include // for time_t -#include // for tm, localtime, time -#include // for operator<<, basic_ostream, etc +#include "FairGeoAsciiIo.h" // for FairGeoAsciiIo +#include "FairGeoBuilder.h" // for FairGeoBuilder +#include "FairGeoIo.h" // for FairGeoIo +#include "FairGeoMedia.h" // for FairGeoMedia +#include "FairGeoSet.h" // for FairGeoSet +#include "FairGeoShapes.h" // for FairGeoShapes + +#include // for TClass +#include // for TList +#include // for TObjArray +#include // for operator<<, basic_ostream, etc +#include // for sprintf +#include // for strcmp +#include // for time_t +#include // for tm, localtime, time using std::cout; using std::endl; -ClassImp(FairGeoInterface) +ClassImp(FairGeoInterface); FairGeoInterface::FairGeoInterface() - :TObject(), - fileInput(nullptr), - oraInput(nullptr), - output(nullptr), - nSets(0), - nActualSets(0), - sets(new TObjArray()), - media(new FairGeoMedia()), - shapes(new FairGeoShapes()), - masterNodes(new TList()), - setupFile(""), - geoBuilder(nullptr) + : TObject() + , fileInput(nullptr) + , oraInput(nullptr) + , output(nullptr) + , nSets(0) + , nActualSets(0) + , sets(new TObjArray()) + , media(new FairGeoMedia()) + , shapes(new FairGeoShapes()) + , masterNodes(new TList()) + , setupFile("") + , geoBuilder(nullptr) { - // Constructor + // Constructor } FairGeoInterface::~FairGeoInterface() { - // Destructor - delete fileInput; - fileInput=0; - delete oraInput; - oraInput=0; - delete output; - output=0; - -// if (geoBuilder) { -// delete geoBuilder; -// geoBuilder=0; -// } - if (masterNodes) { - masterNodes->Delete(); - delete masterNodes; - masterNodes=0; - } - if (sets) { - sets->Delete(); - delete sets; - sets=0; - } - if (media) { - delete media; - media=0; - } - if (shapes) { - delete shapes; - shapes=0; - } + // Destructor + delete fileInput; + fileInput = 0; + delete oraInput; + oraInput = 0; + delete output; + output = 0; + + // if (geoBuilder) { + // delete geoBuilder; + // geoBuilder=0; + // } + if (masterNodes) { + masterNodes->Delete(); + delete masterNodes; + masterNodes = 0; + } + if (sets) { + sets->Delete(); + delete sets; + sets = 0; + } + if (media) { + delete media; + media = 0; + } + if (shapes) { + delete shapes; + shapes = 0; + } } void FairGeoInterface::addGeoModule(FairGeoSet* pSet) { - sets->AddLast(pSet); - pSet->setShapes(shapes); - pSet->setMasterNodes(masterNodes); - nActualSets++; - -} -void FairGeoInterface::setMediaFile(const char* file) -{ - media->setInputFile(file); + sets->AddLast(pSet); + pSet->setShapes(shapes); + pSet->setMasterNodes(masterNodes); + nActualSets++; } +void FairGeoInterface::setMediaFile(const char* file) { media->setInputFile(file); } void FairGeoInterface::addInputFile(const char* file) { - Error("This Methode is not used any more ","Use addGeoModule to add detectors: %s",file); - /* + Error("This Methode is not used any more ", "Use addGeoModule to add detectors: %s", file); + /* // Adds the input file and creates the corresponding detector object FairGeoSet* pSet=0; TString setName(file); @@ -184,14 +179,14 @@ void FairGeoInterface::addInputFile(const char* file) FairGeoSet* FairGeoInterface::findSet(const char* name) { - // Find the detector set in the actual setup - FairGeoSet* pSet=0; - TString setName(name); - TString PSetName; - setName.ToLower(); - Int_t l=setName.Last('/')+1; - setName=setName(l,setName.Length()-l); - /* if (setName.Contains("cave")) pSet=static_cast(sets->At(kFairGeoCave)); + // Find the detector set in the actual setup + FairGeoSet* pSet = 0; + TString setName(name); + TString PSetName; + setName.ToLower(); + Int_t l = setName.Last('/') + 1; + setName = setName(l, setName.Length() - l); + /* if (setName.Contains("cave")) pSet=static_cast(sets->At(kFairGeoCave)); else if (setName.Contains("pipe")) pSet=static_cast(sets->At(kFairGeoPipe)); else if (setName.Contains("target")) pSet=static_cast(sets->At(kFairGeoTarget)); else if (setName.Contains("magnet")) pSet=static_cast(sets->At(kFairGeoMagnet)); @@ -202,276 +197,342 @@ FairGeoSet* FairGeoInterface::findSet(const char* name) else if (setName.Contains("ecal")) pSet=static_cast(sets->At(kFairGeoEcal)); return pSet; */ - for(Int_t i=0; iAt(i)->GetName(); - if (PSetName.Contains(setName.Data())) { - pSet=static_cast(sets->At(i)); - cout << "FairGeoInterface::findSet" <GetName() <At(i)->GetName(); + if (PSetName.Contains(setName.Data())) { + pSet = static_cast(sets->At(i)); + cout << "FairGeoInterface::findSet" << pSet->GetName() << endl; + break; + } } - - } - return pSet; - + return pSet; } Bool_t FairGeoInterface::readSet(FairGeoSet* pSet) { - // Reads the geometry for the detector part - Bool_t rc=kFALSE; - FairGeoIo* input=0; - if (pSet) { - input=connectInput(pSet->getGeomFile()); - if (input) { rc=input->read(pSet,media); } - } - return rc; + // Reads the geometry for the detector part + Bool_t rc = kFALSE; + FairGeoIo* input = 0; + if (pSet) { + input = connectInput(pSet->getGeomFile()); + if (input) { + rc = input->read(pSet, media); + } + } + return rc; } Bool_t FairGeoInterface::writeSet(FairGeoSet* pSet) { - // Writes the geometry for the detector part to output - if (pSet&&connectOutput(pSet->GetName())) { return output->write(pSet); } - return kFALSE; + // Writes the geometry for the detector part to output + if (pSet && connectOutput(pSet->GetName())) { + return output->write(pSet); + } + return kFALSE; } Bool_t FairGeoInterface::writeSet(FairGeoSet* pSet, const char* filename) { - // Writes the geometry for the detector part to file - if (pSet&&output) { - output->open(filename,"out"); - if (output->isOpen()) { return output->write(pSet); } - } - return kFALSE; + // Writes the geometry for the detector part to file + if (pSet && output) { + output->open(filename, "out"); + if (output->isOpen()) { + return output->write(pSet); + } + } + return kFALSE; } void FairGeoInterface::deleteSet(FairGeoSet* pSet) { - // Deletes the set - if (pSet) { - sets->Remove(pSet); - delete pSet; - pSet=0; - } + // Deletes the set + if (pSet) { + sets->Remove(pSet); + delete pSet; + pSet = 0; + } } Bool_t FairGeoInterface::readMedia() { - // Reads the media - Bool_t rc=kFALSE; - FairGeoIo* input=connectInput(media->getInputFile()); - if (input) { - rc=input->read(media); - } - return rc; + // Reads the media + Bool_t rc = kFALSE; + FairGeoIo* input = connectInput(media->getInputFile()); + if (input) { + rc = input->read(media); + } + return rc; } Bool_t FairGeoInterface::writeMedia() { - // Writes the media to output - if (connectOutput("media")) { return output->write(media); } - return kFALSE; + // Writes the media to output + if (connectOutput("media")) { + return output->write(media); + } + return kFALSE; } Bool_t FairGeoInterface::writeMedia(const char* filename) { - // Writes the media to file - if (output) { - output->open(filename,"out"); - if (output->isOpen()) { return output->write(media); } - } - return kFALSE; + // Writes the media to file + if (output) { + output->open(filename, "out"); + if (output->isOpen()) { + return output->write(media); + } + } + return kFALSE; } Bool_t FairGeoInterface::readAll() { - // Reads the media and the whole geometry - Bool_t rc=kTRUE; - if (nActualSets==0&&oraInput) { - rc=oraInput->readGeomConfig(this); -// if (rc) addInputFile("media_gdb"); - if (rc) { addInputFile("media_gdb"); } - } - if(rc) { rc=readSetupFile(); } - if(rc) { rc=readMedia(); } - FairGeoSet* pSet=0; - for(Int_t i=0; i(sets->At(i)); - if (pSet) { - cout<<"Read "<GetName()<readGeomConfig(this); + // if (rc) addInputFile("media_gdb"); + if (rc) { + addInputFile("media_gdb"); + } + } + if (rc) { + rc = readSetupFile(); + } + if (rc) { + rc = readMedia(); } - } - return rc; + FairGeoSet* pSet = 0; + for (Int_t i = 0; i < nSets && rc; i++) { + pSet = static_cast(sets->At(i)); + if (pSet) { + cout << "Read " << pSet->GetName() << endl; + rc = readSet(pSet); + } + } + return rc; } Bool_t FairGeoInterface::writeAll() { - // Reads the media and the whole geometry to output - Bool_t rc=kTRUE; - FairGeoSet* pSet=0; - rc=writeMedia(); - for(Int_t i=0; i(sets->At(i)); - if (pSet) { rc=writeSet(pSet); } - } - return rc; + // Reads the media and the whole geometry to output + Bool_t rc = kTRUE; + FairGeoSet* pSet = 0; + rc = writeMedia(); + for (Int_t i = 0; i < nSets && rc; i++) { + pSet = static_cast(sets->At(i)); + if (pSet) { + rc = writeSet(pSet); + } + } + return rc; } Bool_t FairGeoInterface::createAll(Bool_t withCleanup) { - // Creates the whole geometry - // (if withCleanup==kTRUE, the geometry input is deleted afterwards) - Bool_t rc=kTRUE; - Int_t n=0; - if (geoBuilder) { - FairGeoSet* pSet=0; - for(Int_t i=0; i(sets->At(i)); - if (pSet) { - cout<<"Create "<GetName()<create(geoBuilder); - n++; - if (withCleanup) { - sets->RemoveAt(i); - delete pSet; + // Creates the whole geometry + // (if withCleanup==kTRUE, the geometry input is deleted afterwards) + Bool_t rc = kTRUE; + Int_t n = 0; + if (geoBuilder) { + FairGeoSet* pSet = 0; + for (Int_t i = 0; i < nSets && rc; i++) { + pSet = static_cast(sets->At(i)); + if (pSet) { + cout << "Create " << pSet->GetName() << endl; + rc = pSet->create(geoBuilder); + n++; + if (withCleanup) { + sets->RemoveAt(i); + delete pSet; + } + } } - } + if (rc && n > 0) { + geoBuilder->finalize(); + } + } else { + Error("createAll()", "No Builder"); } - if (rc&&n>0) { geoBuilder->finalize(); } - } else { Error("createAll()","No Builder"); } - return rc; + return rc; } Bool_t FairGeoInterface::createGeometry(Bool_t withCleanup) { - // Reads and creates the whole geometry - // (if withCleanup==kTRUE, the geometry input is deleted after creation) - Bool_t rc=kTRUE; - Int_t n=0; - if (geoBuilder) { - if (nActualSets==0&&oraInput) { - rc=oraInput->readGeomConfig(this); - if (rc) { addInputFile("media_gdb"); } - } - if (rc) { rc=readSetupFile(); } - if (rc) { rc=readMedia(); } - FairGeoSet* pSet=0; - for(Int_t i=0; i(sets->At(i)); - if (pSet) { - cout<<"Read and create "<GetName()<readGeomConfig(this); + if (rc) { + addInputFile("media_gdb"); + } + } + if (rc) { + rc = readSetupFile(); + } if (rc) { - rc=pSet->create(geoBuilder); - n++; + rc = readMedia(); } - if (withCleanup) { - sets->RemoveAt(i); - delete pSet; + FairGeoSet* pSet = 0; + for (Int_t i = 0; i < nSets && rc; i++) { + pSet = static_cast(sets->At(i)); + if (pSet) { + cout << "Read and create " << pSet->GetName() << endl; + rc = readSet(pSet); + if (rc) { + rc = pSet->create(geoBuilder); + n++; + } + if (withCleanup) { + sets->RemoveAt(i); + delete pSet; + } + } } - } + if (rc && n > 0) { + geoBuilder->finalize(); + } + } else { + Error("createAll()", "No Builder"); } - if (rc&&n>0) { geoBuilder->finalize(); } - } else { Error("createAll()","No Builder"); } - return rc; + return rc; } FairGeoIo* FairGeoInterface::connectInput(const char* filename) { - // Connects the input (ASCII or Oracle) - FairGeoIo* currentIo=0; - if (filename) { - TString s(filename); - s=s.Strip(); - if (s.EndsWith(".dat")||s.EndsWith(".geo")||s.EndsWith(".setup")) { - if (!fileInput) { fileInput=new FairGeoAsciiIo(); } - fileInput->open(filename); - currentIo=fileInput; - } else if (s.EndsWith("_gdb")) { currentIo=oraInput; } - } - if (currentIo && currentIo->isOpen()) { return currentIo; } - return 0; + // Connects the input (ASCII or Oracle) + FairGeoIo* currentIo = 0; + if (filename) { + TString s(filename); + s = s.Strip(); + if (s.EndsWith(".dat") || s.EndsWith(".geo") || s.EndsWith(".setup")) { + if (!fileInput) { + fileInput = new FairGeoAsciiIo(); + } + fileInput->open(filename); + currentIo = fileInput; + } else if (s.EndsWith("_gdb")) { + currentIo = oraInput; + } + } + if (currentIo && currentIo->isOpen()) { + return currentIo; + } + return 0; } -Bool_t FairGeoInterface::connectOutput (const char* name) +Bool_t FairGeoInterface::connectOutput(const char* name) { - // Connects the output (ASCII or Oracle) - if (output) { - if (strcmp(output->IsA()->GetName(),"FairGeoAsciiIo")==0) { - TString fName(name); - char buf[80]; - struct tm* newtime; - time_t t; - time(&t); - newtime=localtime(&t); - if (newtime->tm_mday<10) { sprintf(buf,"_0%i",newtime->tm_mday); } - else { sprintf(buf,"_%i",newtime->tm_mday); } - fName=fName+buf; - if (newtime->tm_mon<9) { sprintf(buf,"0%i",newtime->tm_mon+1); } - else { sprintf(buf,"%i",newtime->tm_mon+1); } - fName=fName+buf; - Int_t y=newtime->tm_year-100; - if (y<10) { sprintf(buf,"0%i",y); } - else { sprintf(buf,"%i",y); } - fName=fName+buf; - if (newtime->tm_hour<10) { sprintf(buf,"0%i",newtime->tm_hour); } - else { sprintf(buf,"%i",newtime->tm_hour); } - fName=fName+buf; - if (newtime->tm_min<10) { sprintf(buf,"0%i",newtime->tm_min); } - else { sprintf(buf,"%i",newtime->tm_min); } - fName=fName+buf; - if (newtime->tm_sec<10) { sprintf(buf,"0%i",newtime->tm_sec); } - else { sprintf(buf,"%i",newtime->tm_sec); } - fName=fName+buf+".geo"; - output->open(fName,"out"); - cout<<"Output file for "<(output))->getFilename()<IsA()->GetName(), "FairGeoAsciiIo") == 0) { + TString fName(name); + char buf[80]; + struct tm* newtime; + time_t t; + time(&t); + newtime = localtime(&t); + if (newtime->tm_mday < 10) { + sprintf(buf, "_0%i", newtime->tm_mday); + } else { + sprintf(buf, "_%i", newtime->tm_mday); + } + fName = fName + buf; + if (newtime->tm_mon < 9) { + sprintf(buf, "0%i", newtime->tm_mon + 1); + } else { + sprintf(buf, "%i", newtime->tm_mon + 1); + } + fName = fName + buf; + Int_t y = newtime->tm_year - 100; + if (y < 10) { + sprintf(buf, "0%i", y); + } else { + sprintf(buf, "%i", y); + } + fName = fName + buf; + if (newtime->tm_hour < 10) { + sprintf(buf, "0%i", newtime->tm_hour); + } else { + sprintf(buf, "%i", newtime->tm_hour); + } + fName = fName + buf; + if (newtime->tm_min < 10) { + sprintf(buf, "0%i", newtime->tm_min); + } else { + sprintf(buf, "%i", newtime->tm_min); + } + fName = fName + buf; + if (newtime->tm_sec < 10) { + sprintf(buf, "0%i", newtime->tm_sec); + } else { + sprintf(buf, "%i", newtime->tm_sec); + } + fName = fName + buf + ".geo"; + output->open(fName, "out"); + cout << "Output file for " << name << ": " << (static_cast(output))->getFilename() + << endl; + } + if (output->isOpen() && output->isWritable()) { + return kTRUE; + } + } else { + Error("connectOutput", "No output open"); } - if (output->isOpen()&&output->isWritable()) { return kTRUE; } - } else { Error("connectOutput","No output open"); } - return kFALSE; + return kFALSE; } Bool_t FairGeoInterface::createSet(FairGeoSet* pSet) { - // Creates the geometry of detector part - if (!geoBuilder) { return kFALSE; } - return pSet->create(geoBuilder); + // Creates the geometry of detector part + if (!geoBuilder) { + return kFALSE; + } + return pSet->create(geoBuilder); } void FairGeoInterface::print() { - // Prints the media and the list of detector parts - media->list(); - cout<<"********************************************************************\n"; - cout<<"List of detector parts:\n"; - FairGeoSet* pSet=0; - for(Int_t i=0; i(sets->At(i)); - if (pSet) { cout<<" "<GetName()<<":\t"<getGeomFile()<<'\n'; } - } - cout<<"********************************************************************\n"; + // Prints the media and the list of detector parts + media->list(); + cout << "********************************************************************\n"; + cout << "List of detector parts:\n"; + FairGeoSet* pSet = 0; + for (Int_t i = 0; i < nSets; i++) { + pSet = static_cast(sets->At(i)); + if (pSet) { + cout << " " << pSet->GetName() << ":\t" << pSet->getGeomFile() << '\n'; + } + } + cout << "********************************************************************\n"; } Bool_t FairGeoInterface::readGeomConfig(const char* configFile) { - // Reads the GEANT configuration file - Bool_t rc=kFALSE; - FairGeoIo* input=0; - if (configFile) { - input=connectInput(configFile); - if (input) { rc=input->readGeomConfig(this); } - } - return rc; + // Reads the GEANT configuration file + Bool_t rc = kFALSE; + FairGeoIo* input = 0; + if (configFile) { + input = connectInput(configFile); + if (input) { + rc = input->readGeomConfig(this); + } + } + return rc; } Bool_t FairGeoInterface::readSetupFile() { - // Reads the detector setups, needed for create only subsets - Bool_t rc=kTRUE; - if (setupFile.Length()>0) { - FairGeoAsciiIo* input=static_cast(connectInput(setupFile)); - if (input) { rc=input->readDetectorSetup(this); } - } - return rc; + // Reads the detector setups, needed for create only subsets + Bool_t rc = kTRUE; + if (setupFile.Length() > 0) { + FairGeoAsciiIo* input = static_cast(connectInput(setupFile)); + if (input) { + rc = input->readDetectorSetup(this); + } + } + return rc; } diff --git a/geobase/FairGeoInterface.h b/geobase/FairGeoInterface.h index 475178830e..85cfa78f69 100644 --- a/geobase/FairGeoInterface.h +++ b/geobase/FairGeoInterface.h @@ -1,17 +1,16 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRGEOINTERFACE_H #define FAIRGEOINTERFACE_H -#include // for TObject - -#include // for Bool_t, kFALSE, Int_t, etc -#include // for TString +#include // for Bool_t, kFALSE, Int_t, etc +#include // for TObject +#include // for TString class FairGeoIo; class FairGeoSet; @@ -21,16 +20,17 @@ class FairGeoBuilder; class TObjArray; class TList; -enum EHGeoDetPart { - kFairGeoCave = 0, - kFairGeoPipe = 1, - kFairGeoTarget = 2, - kFairGeoMagnet = 3, - kFairGeoRich = 4, - kFairGeoSts = 5, - kFairGeoTrd = 6, - kFairGeoTof = 7, - kFairGeoEcal = 8 +enum EHGeoDetPart +{ + kFairGeoCave = 0, + kFairGeoPipe = 1, + kFairGeoTarget = 2, + kFairGeoMagnet = 3, + kFairGeoRich = 4, + kFairGeoSts = 5, + kFairGeoTrd = 6, + kFairGeoTof = 7, + kFairGeoEcal = 8 }; /** @@ -40,24 +40,24 @@ enum EHGeoDetPart { */ class FairGeoInterface : public TObject { - FairGeoIo* fileInput; /** ASCII file I/O */ - FairGeoIo* oraInput; /** Oracle input */ - FairGeoIo* output; /** Oracle output */ - Int_t nSets; /** number of geometry sets (detector parts) */ - Int_t nActualSets; /** number of set in actual geometry */ - TObjArray* sets; /** array of geometry sets */ - FairGeoMedia* media; /** list of media */ - FairGeoShapes* shapes; /** list of shapes */ - TList* masterNodes; /** list of mother nodes used by several sets */ - TString setupFile; /** file with detector setups (subsets) */ - FairGeoBuilder* geoBuilder; /** actually used geometry builder */ + FairGeoIo* fileInput; /** ASCII file I/O */ + FairGeoIo* oraInput; /** Oracle input */ + FairGeoIo* output; /** Oracle output */ + Int_t nSets; /** number of geometry sets (detector parts) */ + Int_t nActualSets; /** number of set in actual geometry */ + TObjArray* sets; /** array of geometry sets */ + FairGeoMedia* media; /** list of media */ + FairGeoShapes* shapes; /** list of shapes */ + TList* masterNodes; /** list of mother nodes used by several sets */ + TString setupFile; /** file with detector setups (subsets) */ + FairGeoBuilder* geoBuilder; /** actually used geometry builder */ public: FairGeoInterface(); ~FairGeoInterface(); - void setOracleInput(FairGeoIo* p) {oraInput=p;} - void setOutput(FairGeoIo* p) {output=p;} - void setGeomBuilder(FairGeoBuilder* p) {geoBuilder=p;} + void setOracleInput(FairGeoIo* p) { oraInput = p; } + void setOutput(FairGeoIo* p) { output = p; } + void setGeomBuilder(FairGeoBuilder* p) { geoBuilder = p; } FairGeoIo* getFileInput() { return fileInput; } FairGeoIo* getOraInput() { return oraInput; } FairGeoIo* getOutput() { return output; } @@ -70,7 +70,7 @@ class FairGeoInterface : public TObject FairGeoSet* findSet(const char*); Bool_t readSet(FairGeoSet*); Bool_t writeSet(FairGeoSet*); - Bool_t writeSet(FairGeoSet*,const char*); + Bool_t writeSet(FairGeoSet*, const char*); Bool_t createSet(FairGeoSet*); void deleteSet(FairGeoSet* pSet); Bool_t readMedia(); @@ -78,13 +78,13 @@ class FairGeoInterface : public TObject Bool_t writeMedia(const char*); Bool_t readAll(); Bool_t writeAll(); - Bool_t createAll(Bool_t withCleanup=kFALSE); - Bool_t createGeometry(Bool_t withCleanup=kFALSE); + Bool_t createAll(Bool_t withCleanup = kFALSE); + Bool_t createGeometry(Bool_t withCleanup = kFALSE); Bool_t readGeomConfig(const char*); - void addSetupFile(const char* f) {setupFile=f;} + void addSetupFile(const char* f) { setupFile = f; } Bool_t readSetupFile(); void print(); - void SetNoOfSets(Int_t n) {nSets=n;} // + void SetNoOfSets(Int_t n) { nSets = n; } // private: FairGeoInterface(const FairGeoInterface&); @@ -93,7 +93,7 @@ class FairGeoInterface : public TObject FairGeoIo* connectInput(const char*); Bool_t connectOutput(const char*); - ClassDef(FairGeoInterface,0) // + ClassDef(FairGeoInterface, 0) // }; #endif /* !FAIRGEOINTERFACE_H */ diff --git a/geobase/FairGeoIo.cxx b/geobase/FairGeoIo.cxx index 682f56480c..91ad83b9d7 100644 --- a/geobase/FairGeoIo.cxx +++ b/geobase/FairGeoIo.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ //*-- AUTHOR : Ilse Koenig @@ -17,5 +17,4 @@ #include "FairGeoIo.h" -ClassImp(FairGeoIo) - +ClassImp(FairGeoIo); diff --git a/geobase/FairGeoIo.h b/geobase/FairGeoIo.h index 0d05991895..4c8b61d744 100644 --- a/geobase/FairGeoIo.h +++ b/geobase/FairGeoIo.h @@ -1,16 +1,15 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRGEOIO_H #define FAIRGEOIO_H -#include // for TObject - -#include // for Bool_t, FairGeoIo::Class, etc +#include // for Bool_t, FairGeoIo::Class, etc +#include // for TObject class FairGeoMedia; class FairGeoSet; @@ -23,20 +22,21 @@ class FairGeoInterface; class FairGeoIo : public TObject { public: - virtual Bool_t open(const char*,const Text_t* status="in")=0; - virtual void close()=0; - virtual void print()=0; - virtual Bool_t isOpen()=0; - virtual Bool_t isWritable()=0; - virtual Bool_t read(FairGeoMedia*)=0; - virtual Bool_t read(FairGeoSet*,FairGeoMedia*)=0; - virtual Bool_t write(FairGeoMedia*)=0; - virtual Bool_t write(FairGeoSet*)=0; - virtual Bool_t readGeomConfig(FairGeoInterface*)=0; - virtual Bool_t setSimulRefRun(const char*)=0; - virtual Bool_t setHistoryDate(const char*)=0; + virtual Bool_t open(const char*, const Text_t* status = "in") = 0; + virtual void close() = 0; + virtual void print() = 0; + virtual Bool_t isOpen() = 0; + virtual Bool_t isWritable() = 0; + virtual Bool_t read(FairGeoMedia*) = 0; + virtual Bool_t read(FairGeoSet*, FairGeoMedia*) = 0; + virtual Bool_t write(FairGeoMedia*) = 0; + virtual Bool_t write(FairGeoSet*) = 0; + virtual Bool_t readGeomConfig(FairGeoInterface*) = 0; + virtual Bool_t setSimulRefRun(const char*) = 0; + virtual Bool_t setHistoryDate(const char*) = 0; + private: - ClassDef(FairGeoIo,0) // + ClassDef(FairGeoIo, 0) // }; -#endif /* !FAIRGEOIO_H */ +#endif /* !FAIRGEOIO_H */ diff --git a/geobase/FairGeoLoader.cxx b/geobase/FairGeoLoader.cxx index dcc2418c15..6a135e1c28 100644 --- a/geobase/FairGeoLoader.cxx +++ b/geobase/FairGeoLoader.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /*************************************************************************** @@ -14,61 +14,54 @@ ***************************************************************************/ #include "FairGeoLoader.h" -#include "FairGeoInterface.h" // for FairGeoInterface -#include "FairGeoRootBuilder.h" // for FairGeoRootBuilder +#include "FairGeoInterface.h" // for FairGeoInterface +#include "FairGeoRootBuilder.h" // for FairGeoRootBuilder -#include // for TGeoManager - -#include // for strncmp -#include // for NULL, exit -#include // for cout, endl, operator<<, etc +#include // for TGeoManager +#include // for NULL, exit +#include // for cout, endl, operator<<, etc +#include // for strncmp using std::cout; using std::endl; -FairGeoLoader* FairGeoLoader::fgInstance=0; +FairGeoLoader* FairGeoLoader::fgInstance = 0; -FairGeoLoader* FairGeoLoader::Instance() -{ - return fgInstance; -} +FairGeoLoader* FairGeoLoader::Instance() { return fgInstance; } FairGeoLoader::FairGeoLoader() - :TNamed(), - fInterface(NULL), - fGeoBuilder(NULL) + : TNamed() + , fInterface(NULL) + , fGeoBuilder(NULL) { - fgInstance=this; + fgInstance = this; } FairGeoLoader::FairGeoLoader(const char* Name, const char* title) - :TNamed(Name,title), - fInterface(NULL), - fGeoBuilder(NULL) + : TNamed(Name, title) + , fInterface(NULL) + , fGeoBuilder(NULL) { - if (fgInstance) { - Fatal("FairGeoLoader", "Singleton instance already exists."); - return; - } - fgInstance = this; - fInterface= new FairGeoInterface; - if ( strncmp(Name,"TGeo",4) == 0 ) { - TGeoManager* geom = new TGeoManager("FAIRGeom", "FAIR geometry"); - fGeoBuilder=new FairGeoRootBuilder("TGeo builder","geometry builder"); - (static_cast(fGeoBuilder))->setGeoManager(geom); - } else if ( strncmp(Name,"G3Native",8) == 0) { - cout << "-I- FairGeoLoader() : Native G3 Geometry is used: This option is not supported any more!" << endl; - exit(0); - // gGeoManager = NULL; - // fGeoBuilder=new FairGeoG3Builder("G3 builder","geometry builder"); - } + if (fgInstance) { + Fatal("FairGeoLoader", "Singleton instance already exists."); + return; + } + fgInstance = this; + fInterface = new FairGeoInterface; + if (strncmp(Name, "TGeo", 4) == 0) { + TGeoManager* geom = new TGeoManager("FAIRGeom", "FAIR geometry"); + fGeoBuilder = new FairGeoRootBuilder("TGeo builder", "geometry builder"); + (static_cast(fGeoBuilder))->setGeoManager(geom); + } else if (strncmp(Name, "G3Native", 8) == 0) { + cout << "-I- FairGeoLoader() : Native G3 Geometry is used: This option is not supported any more!" << endl; + exit(0); + // gGeoManager = NULL; + // fGeoBuilder=new FairGeoG3Builder("G3 builder","geometry builder"); + } - fInterface->setGeomBuilder(fGeoBuilder); + fInterface->setGeomBuilder(fGeoBuilder); } -FairGeoLoader::~FairGeoLoader() -{ - delete fInterface; -} +FairGeoLoader::~FairGeoLoader() { delete fInterface; } -ClassImp(FairGeoLoader) +ClassImp(FairGeoLoader); diff --git a/geobase/FairGeoLoader.h b/geobase/FairGeoLoader.h index a7b50f2e44..ff0800a8aa 100644 --- a/geobase/FairGeoLoader.h +++ b/geobase/FairGeoLoader.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /*************************************************************************** @@ -16,9 +16,8 @@ #ifndef FairGeoLOADER_H #define FairGeoLOADER_H -#include // for TNamed - -#include // for FairGeoLoader::Class, etc +#include // for FairGeoLoader::Class, etc +#include // for TNamed class FairGeoInterface; class FairGeoBuilder; @@ -32,19 +31,19 @@ class FairGeoLoader : public TNamed FairGeoLoader(const char* Name, const char* title); FairGeoLoader(); virtual ~FairGeoLoader(); - FairGeoInterface* getGeoInterface() {return fInterface;} - FairGeoBuilder* getGeoBuilder() {return fGeoBuilder; } + FairGeoInterface* getGeoInterface() { return fInterface; } + FairGeoBuilder* getGeoBuilder() { return fGeoBuilder; } /** static access method*/ static FairGeoLoader* Instance(); private: FairGeoLoader(const FairGeoLoader&); FairGeoLoader& operator=(const FairGeoLoader&); - static FairGeoLoader* fgInstance;//! /**Singleton instance*/ - FairGeoInterface* fInterface; //! /** Hades Geometry Interface*/ - FairGeoBuilder* fGeoBuilder; //! /**Geometry builder*/ + static FairGeoLoader* fgInstance; //! /**Singleton instance*/ + FairGeoInterface* fInterface; //! /** Hades Geometry Interface*/ + FairGeoBuilder* fGeoBuilder; //! /**Geometry builder*/ - ClassDef(FairGeoLoader,1) + ClassDef(FairGeoLoader, 1) }; #endif diff --git a/geobase/FairGeoMatrix.cxx b/geobase/FairGeoMatrix.cxx index 7e43244531..7e11183184 100644 --- a/geobase/FairGeoMatrix.cxx +++ b/geobase/FairGeoMatrix.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ //*-- Author : M. Sanchez @@ -10,7 +10,6 @@ #include "FairGeoMatrix.h" - //////////////////////////////////////////////////////// // FairGeoMatrix // @@ -21,41 +20,42 @@ // added as needed ///////////////////////////////////////////////////////// - FairGeoMatrix::FairGeoMatrix(void) - :TObject() + : TObject() { - // Initializes the matrix to 0 - for (int i=0; i<9; i++) { fM[i]=0.0; } + // Initializes the matrix to 0 + for (int i = 0; i < 9; i++) { + fM[i] = 0.0; + } } -FairGeoMatrix::~FairGeoMatrix(void) -{ -} +FairGeoMatrix::~FairGeoMatrix(void) {} Double_t FairGeoMatrix::det(void) { - // Computes de determinat of the 3D matrix - return (fM[0] * fM[4] * fM[8] + fM[1] * fM[5] * fM[6] + fM[3] *fM[7] * fM[2] - - fM[2] * fM[4] * fM[6] - fM[1] * fM[3] * fM[8] - fM[5] *fM[7] * fM[0]); + // Computes de determinat of the 3D matrix + return (fM[0] * fM[4] * fM[8] + fM[1] * fM[5] * fM[6] + fM[3] * fM[7] * fM[2] - fM[2] * fM[4] * fM[6] + - fM[1] * fM[3] * fM[8] - fM[5] * fM[7] * fM[0]); } FairGeoVector FairGeoMatrix::operator*(FairGeoVector& v) { - // Matrix multiplication - FairGeoVector vo; - vo.setX(fM[0] * v.getX() + fM[1] * v.getY() + fM[2] * v.getZ()); - vo.setY(fM[3] * v.getX() + fM[4] * v.getY() + fM[5] * v.getZ()); - vo.setZ(fM[6] * v.getX() + fM[7] * v.getY() + fM[8] * v.getZ()); - return vo; + // Matrix multiplication + FairGeoVector vo; + vo.setX(fM[0] * v.getX() + fM[1] * v.getY() + fM[2] * v.getZ()); + vo.setY(fM[3] * v.getX() + fM[4] * v.getY() + fM[5] * v.getZ()); + vo.setZ(fM[6] * v.getX() + fM[7] * v.getY() + fM[8] * v.getZ()); + return vo; } FairGeoMatrix& FairGeoMatrix::operator/=(Double_t d) { - // Matrix division by a constant. Divides each element on the - //matrix by the constant "d" - for (int i=0; i<9; i++) { fM[i]/=d; } - return *this; + // Matrix division by a constant. Divides each element on the + // matrix by the constant "d" + for (int i = 0; i < 9; i++) { + fM[i] /= d; + } + return *this; } -ClassImp(FairGeoMatrix) +ClassImp(FairGeoMatrix); diff --git a/geobase/FairGeoMatrix.h b/geobase/FairGeoMatrix.h index b1701c1160..14c2515615 100644 --- a/geobase/FairGeoMatrix.h +++ b/geobase/FairGeoMatrix.h @@ -1,18 +1,17 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRGEOMATRIX_H #define FAIRGEOMATRIX_H -#include // for TObject +#include "FairGeoVector.h" // for FairGeoVector -#include "FairGeoVector.h" // for FairGeoVector - -#include // for Double_t, etc +#include // for Double_t, etc +#include // for TObject /** * @author Ilse koenig @@ -21,14 +20,15 @@ class FairGeoMatrix : public TObject { protected: Double_t fM[9]; + public: FairGeoMatrix(void); ~FairGeoMatrix(void); - Double_t& operator()(Int_t i,Int_t j) { return fM[i*3+j]; } + Double_t& operator()(Int_t i, Int_t j) { return fM[i * 3 + j]; } Double_t det(void); FairGeoVector operator*(FairGeoVector& v); FairGeoMatrix& operator/=(Double_t d); - ClassDef(FairGeoMatrix,0) + ClassDef(FairGeoMatrix, 0) }; #endif diff --git a/geobase/FairGeoMedia.cxx b/geobase/FairGeoMedia.cxx index 61a77ffa62..bb1e912942 100644 --- a/geobase/FairGeoMedia.cxx +++ b/geobase/FairGeoMedia.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ //*-- AUTHOR : Ilse Koenig @@ -16,132 +16,148 @@ /////////////////////////////////////////////////////////////////////////////// #include "FairGeoMedia.h" + #include "FairGeoMedium.h" #include "FairLogger.h" #include - #include using std::cout; using std::endl; -ClassImp(FairGeoMedia) +ClassImp(FairGeoMedia); FairGeoMedia::FairGeoMedia() - : TNamed(), - media(new TList()), - inputFile(""), - author(""), - description("") + : TNamed() + , media(new TList()) + , inputFile("") + , author("") + , description("") { - // Constructor + // Constructor } FairGeoMedia::~FairGeoMedia() { - // Destructor - if (media) { - media->Delete(); - delete media; - media=0; - } + // Destructor + if (media) { + media->Delete(); + delete media; + media = 0; + } } FairGeoMedium* FairGeoMedia::getMedium(const char* mediumName) { - // Returns the medium with name mediumName - return static_cast(media->FindObject(mediumName)); + // Returns the medium with name mediumName + return static_cast(media->FindObject(mediumName)); } void FairGeoMedia::addMedium(FairGeoMedium* m) { - // Adds a medium to the list of media - media->Add(m); + // Adds a medium to the list of media + media->Add(m); } void FairGeoMedia::list() { - // Lists all media - cout<<"********************************************************************\n"; - cout<<"List of media:\n"; - TListIter iter(media); - FairGeoMedium* medium; - while((medium=static_cast(iter.Next()))) { - cout<<" "<GetName()<<"\n"; - } + // Lists all media + cout << "********************************************************************\n"; + cout << "List of media:\n"; + TListIter iter(media); + FairGeoMedium* medium; + while ((medium = static_cast(iter.Next()))) { + cout << " " << medium->GetName() << "\n"; + } } void FairGeoMedia::print() { - // Prints the media - if (!author.IsNull()) { cout<<"//Author: "<(iter.Next()))) { - if (medium->getAutoFlag()!=0) { - medium->print(); - i++; + // Prints the media + if (!author.IsNull()) { + cout << "//Author: " << author << '\n'; } - } - if (i!=media->GetSize()) { - iter.Reset(); - cout<<"//----------------------------------------------\n"; - cout<<"AUTONULL\n"; - cout<<"//----------------------------------------------\n"; - while((medium=static_cast(iter.Next()))) { - if (medium->getAutoFlag()==0) { medium->print(); } + if (!description.IsNull()) { + cout << "//Description: " << description << '\n'; + } + cout << "//----------------------------------------------------------\n"; + TListIter iter(media); + FairGeoMedium* medium; + Int_t i = 0; + while ((medium = static_cast(iter.Next()))) { + if (medium->getAutoFlag() != 0) { + medium->print(); + i++; + } + } + if (i != media->GetSize()) { + iter.Reset(); + cout << "//----------------------------------------------\n"; + cout << "AUTONULL\n"; + cout << "//----------------------------------------------\n"; + while ((medium = static_cast(iter.Next()))) { + if (medium->getAutoFlag() == 0) { + medium->print(); + } + } } - } } void FairGeoMedia::read(std::fstream& fin) { - // Reads the media from file - LOG(info) << "FairGeoMedia: Read media "; - const Int_t maxBuf=256; - char buf[maxBuf]; - Int_t autoflag=1; - while(!fin.eof()) { - fin>>buf; - if (buf[0]=='\0' || buf[0]=='/') { fin.getline(buf,maxBuf); } - else if (fin.eof()) { break; } - else { - TString eleName(buf); - if (eleName.CompareTo("AUTONULL")!=0) { - FairGeoMedium* medium=new FairGeoMedium(eleName); - medium->read(fin,autoflag); - media->Add(medium); - } else { autoflag=0; } + // Reads the media from file + LOG(info) << "FairGeoMedia: Read media "; + const Int_t maxBuf = 256; + char buf[maxBuf]; + Int_t autoflag = 1; + while (!fin.eof()) { + fin >> buf; + if (buf[0] == '\0' || buf[0] == '/') { + fin.getline(buf, maxBuf); + } else if (fin.eof()) { + break; + } else { + TString eleName(buf); + if (eleName.CompareTo("AUTONULL") != 0) { + FairGeoMedium* medium = new FairGeoMedium(eleName); + medium->read(fin, autoflag); + media->Add(medium); + } else { + autoflag = 0; + } + } } - } } void FairGeoMedia::write(std::fstream& fout) { - // Writes the media to file - if (!author.IsNull()) { fout<<"//Author: "<(iter.Next()))) { - if (medium->getAutoFlag()!=0) { - medium->write(fout); - i++; + // Writes the media to file + if (!author.IsNull()) { + fout << "//Author: " << author << '\n'; + } + if (!description.IsNull()) { + fout << "//Description: " << description << '\n'; + } + fout << "//----------------------------------------------------------\n"; + TListIter iter(media); + FairGeoMedium* medium; + Int_t i = 0; + while ((medium = static_cast(iter.Next()))) { + if (medium->getAutoFlag() != 0) { + medium->write(fout); + i++; + } } - } - if (i!=media->GetSize()) { - iter.Reset(); - fout<<"//----------------------------------------------\n"; - fout<<"AUTONULL\n"; - fout<<"//----------------------------------------------\n"; - while((medium=static_cast(iter.Next()))) { - if (medium->getAutoFlag()==0) { medium->write(fout); } + if (i != media->GetSize()) { + iter.Reset(); + fout << "//----------------------------------------------\n"; + fout << "AUTONULL\n"; + fout << "//----------------------------------------------\n"; + while ((medium = static_cast(iter.Next()))) { + if (medium->getAutoFlag() == 0) { + medium->write(fout); + } + } } - } } diff --git a/geobase/FairGeoMedia.h b/geobase/FairGeoMedia.h index 78b623cf9a..7034a5e720 100644 --- a/geobase/FairGeoMedia.h +++ b/geobase/FairGeoMedia.h @@ -1,19 +1,17 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRGEOMEDIA_H #define FAIRGEOMEDIA_H -#include // for TNamed - -#include // for FairGeoMedia::Class, etc -#include // for TString - -#include // for fstream +#include // for FairGeoMedia::Class, etc +#include // for TNamed +#include // for TString +#include // for fstream class FairGeoMedium; class TList; @@ -25,31 +23,32 @@ class TList; class FairGeoMedia : public TNamed { private: - TList* media; /** list of media */ - TString inputFile; /** name of input file or Oracle */ - TString author; /** author of the media version */ - TString description; /** description of the version */ + TList* media; /** list of media */ + TString inputFile; /** name of input file or Oracle */ + TString author; /** author of the media version */ + TString description; /** description of the version */ public: FairGeoMedia(); ~FairGeoMedia(); - void setInputFile(const char* file) { inputFile=file; } + void setInputFile(const char* file) { inputFile = file; } const char* getInputFile() { return inputFile; } void addMedium(FairGeoMedium* m); FairGeoMedium* getMedium(const char*); - TList* getListOfMedia() {return media;} + TList* getListOfMedia() { return media; } void read(std::fstream&); void print(); void list(); void write(std::fstream&); - void setAuthor(TString& s) {author=s;} - void setDescription(TString& s) {description=s;} - TString& getAuthor() {return author;} - TString& getDescription() {return description;} + void setAuthor(TString& s) { author = s; } + void setDescription(TString& s) { description = s; } + TString& getAuthor() { return author; } + TString& getDescription() { return description; } + private: FairGeoMedia(const FairGeoMedia&); FairGeoMedia& operator=(const FairGeoMedia&); - ClassDef(FairGeoMedia,0) // + ClassDef(FairGeoMedia, 0) // }; #endif /* !FAIRGEOMEDIA_H */ diff --git a/geobase/FairGeoMedium.cxx b/geobase/FairGeoMedium.cxx index 737d3c8f77..2f51ff30a0 100644 --- a/geobase/FairGeoMedium.cxx +++ b/geobase/FairGeoMedium.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ //*-- ö : Ilse Koenig @@ -15,323 +15,348 @@ //////////////////////////////////////////////////////////////////////////////// #include "FairGeoMedium.h" -#include // for TString - -#include // for pow, log +#include // for TString +#include // for pow, log // IWYU pragma: no_include -#include // for cout -#include // for abs -#include // for INT_MAX -#include // for fstream +#include // for INT_MAX +#include // for fstream +#include // for cout +#include // for abs using std::cout; using std::log; using std::pow; -ClassImp(FairGeoMedium) +ClassImp(FairGeoMedium); FairGeoMedium::FairGeoMedium(const char* name) - : TNamed(name,""), - medId(0), - autoflag(1), - nComponents(0), - weightFac(0), - ca(nullptr), - cz(nullptr), - cw(nullptr), - density(0), - radLen(0), - sensFlag(0), - fldFlag(0), - fld(0), - epsil(0), - madfld(-1), - maxstep(-1), - maxde(-1), - minstep(-1), - npckov(0), - ppckov(nullptr), - absco(nullptr), - effic(nullptr), - rindex(nullptr) -{ - // Constructor for a medium with name and index id -// SetName(name); -}; + : TNamed(name, "") + , medId(0) + , autoflag(1) + , nComponents(0) + , weightFac(0) + , ca(nullptr) + , cz(nullptr) + , cw(nullptr) + , density(0) + , radLen(0) + , sensFlag(0) + , fldFlag(0) + , fld(0) + , epsil(0) + , madfld(-1) + , maxstep(-1) + , maxde(-1) + , minstep(-1) + , npckov(0) + , ppckov(nullptr) + , absco(nullptr) + , effic(nullptr) + , rindex(nullptr){ + // Constructor for a medium with name and index id + // SetName(name); + }; FairGeoMedium::~FairGeoMedium() { - // Destructor - if (nComponents>0) { - delete [] ca; - ca=0; - delete [] cz; - cz=0; - delete [] cw; - cw=0; - nComponents=0; - } - if (npckov>0) { - delete [] ppckov; - ppckov=0; - delete [] absco; - absco=0; - delete [] effic; - effic=0; - delete [] rindex; - rindex=0; - npckov=0; - } + // Destructor + if (nComponents > 0) { + delete[] ca; + ca = 0; + delete[] cz; + cz = 0; + delete[] cw; + cw = 0; + nComponents = 0; + } + if (npckov > 0) { + delete[] ppckov; + ppckov = 0; + delete[] absco; + absco = 0; + delete[] effic; + effic = 0; + delete[] rindex; + rindex = 0; + npckov = 0; + } } void FairGeoMedium::setNComponents(Int_t n) { - // Sets the number of components in the material - if (n==0) { return; } - Int_t k=abs(n); - if (nComponents!=0 && k!=nComponents) { - delete [] ca; - delete [] cz; - delete [] cw; - nComponents=0; - } - if (nComponents==0) { - nComponents=k; - ca=new Double_t[k]; - cz=new Double_t[k]; - cw=new Double_t[k]; - } - weightFac=static_cast(n/nComponents); + // Sets the number of components in the material + if (n == 0) { + return; + } + Int_t k = abs(n); + if (nComponents != 0 && k != nComponents) { + delete[] ca; + delete[] cz; + delete[] cw; + nComponents = 0; + } + if (nComponents == 0) { + nComponents = k; + ca = new Double_t[k]; + cz = new Double_t[k]; + cw = new Double_t[k]; + } + weightFac = static_cast(n / nComponents); } -Bool_t FairGeoMedium::setComponent (Int_t i,Double_t a,Double_t z,Double_t weight) +Bool_t FairGeoMedium::setComponent(Int_t i, Double_t a, Double_t z, Double_t weight) { - // Defines the ith material component - if (i<0||i>=nComponents) { - Error("setNComponents","Wrong index"); - return kFALSE; - } - ca[i]=a; - cz[i]=z; - cw[i]=weight; - return kTRUE; + // Defines the ith material component + if (i < 0 || i >= nComponents) { + Error("setNComponents", "Wrong index"); + return kFALSE; + } + ca[i] = a; + cz[i] = z; + cw[i] = weight; + return kTRUE; } -void FairGeoMedium::getComponent(Int_t i,Double_t* p) +void FairGeoMedium::getComponent(Int_t i, Double_t* p) { - // Returns the ith material component - if (i>=0&&i= 0 && i < nComponents) { + p[0] = ca[i]; + p[1] = cz[i]; + p[2] = cw[i]; + // cout << " -I p: " << p[0] << p[1] << p[2] << endl; + } else { + p[0] = p[1] = p[2] = 0.; + } } -void FairGeoMedium::setNpckov (Int_t n) +void FairGeoMedium::setNpckov(Int_t n) { - // Sets the number of optical parameters for the tracking of Cerenkov light - if (n!=npckov && npckov>0) { - delete [] ppckov; - delete [] absco; - delete [] effic; - delete [] rindex; - } - npckov=n; - if (n>0) { - ppckov=new Double_t[npckov]; - absco=new Double_t[npckov]; - effic=new Double_t[npckov]; - rindex=new Double_t[npckov]; - } + // Sets the number of optical parameters for the tracking of Cerenkov light + if (n != npckov && npckov > 0) { + delete[] ppckov; + delete[] absco; + delete[] effic; + delete[] rindex; + } + npckov = n; + if (n > 0) { + ppckov = new Double_t[npckov]; + absco = new Double_t[npckov]; + effic = new Double_t[npckov]; + rindex = new Double_t[npckov]; + } } -Bool_t FairGeoMedium::setCerenkovPar(Int_t i,Double_t p,Double_t a,Double_t e ,Double_t r) +Bool_t FairGeoMedium::setCerenkovPar(Int_t i, Double_t p, Double_t a, Double_t e, Double_t r) { - // Defines the ith parameter set of the optical parameters - if (i<0 || i>=npckov) { - Error("setNpckov","Wrong index"); - return kFALSE; - } - ppckov[i]=p; - absco[i]=a; - effic[i]=e; - rindex[i]=r; - return kTRUE; + // Defines the ith parameter set of the optical parameters + if (i < 0 || i >= npckov) { + Error("setNpckov", "Wrong index"); + return kFALSE; + } + ppckov[i] = p; + absco[i] = a; + effic[i] = e; + rindex[i] = r; + return kTRUE; } -void FairGeoMedium::getCerenkovPar(Int_t i,Double_t* p) +void FairGeoMedium::getCerenkovPar(Int_t i, Double_t* p) { - // returns the ith parameter set of the optical parameters - if (i>=0&&i= 0 && i < npckov) { + p[0] = ppckov[i]; + p[1] = absco[i]; + p[2] = effic[i]; + p[3] = rindex[i]; + } else { + p[0] = p[1] = p[2] = p[3] = 0.; + } } -void FairGeoMedium::setMediumPar(Int_t sensitivityFlag,Int_t fieldFlag, - Double_t maxField,Double_t precision,Double_t maxDeviation, - Double_t maxStep,Double_t maxDE,Double_t minStep ) +void FairGeoMedium::setMediumPar(Int_t sensitivityFlag, + Int_t fieldFlag, + Double_t maxField, + Double_t precision, + Double_t maxDeviation, + Double_t maxStep, + Double_t maxDE, + Double_t minStep) { - // Sets the medium parameters - sensFlag=sensitivityFlag; - fldFlag=fieldFlag; - fld=maxField; - epsil=precision; - madfld=maxDeviation; - maxstep=maxStep; - maxde=maxDE; - minstep=minStep; + // Sets the medium parameters + sensFlag = sensitivityFlag; + fldFlag = fieldFlag; + fld = maxField; + epsil = precision; + madfld = maxDeviation; + maxstep = maxStep; + maxde = maxDE; + minstep = minStep; } void FairGeoMedium::getMediumPar(Double_t* params) { - // Returns the medium parameters - params[0]=sensFlag; - params[1]=fldFlag; - params[2]=fld; - params[3]=madfld; - params[4]=maxstep; - params[5]=maxde; - params[6]=epsil; - params[7]=minstep; - params[8]=0.; - params[9]=0.; + // Returns the medium parameters + params[0] = sensFlag; + params[1] = fldFlag; + params[2] = fld; + params[3] = madfld; + params[4] = maxstep; + params[5] = maxde; + params[6] = epsil; + params[7] = minstep; + params[8] = 0.; + params[9] = 0.; } -void FairGeoMedium::read(std::fstream& fin, Int_t aflag ) +void FairGeoMedium::read(std::fstream& fin, Int_t aflag) { - // Reads the parameters from file - autoflag=aflag; - Int_t n; - fin>>n; - setNComponents(n); - for(Int_t ik=0; ik>ca[ik]; - } - for(Int_t i=0; i>cz[i]; - } - fin>>density; - if (nComponents==1) { - cw[0]=1.; - calcRadiationLength(); - } else { - for(Int_t i=0; i>cw[i]; + // Reads the parameters from file + autoflag = aflag; + Int_t n; + fin >> n; + setNComponents(n); + for (Int_t ik = 0; ik < nComponents; ik++) { + fin >> ca[ik]; } - } - fin>>sensFlag>>fldFlag>>fld>>epsil ; - if (autoflag<1) { fin>>madfld>>maxstep>>maxde>>minstep; } - else { - //to use this feature one has to set TGeant3::SetAUTO(0), thus if the media does not - // defined these values one can force Geant3 to calculate them by given them a value - // of -1 - madfld=-1; - maxstep=-1; - maxde=-1; - minstep=-1; - } - fin>>n; - if (n>0 && n<(INT_MAX-1)) { - setNpckov(n); -// if (n>0) { - for(Int_t i=0; i>ppckov[i]>>absco[i]>>effic[i]>>rindex[i]; + for (Int_t i = 0; i < nComponents; i++) { + fin >> cz[i]; + } + fin >> density; + if (nComponents == 1) { + cw[0] = 1.; + calcRadiationLength(); + } else { + for (Int_t i = 0; i < nComponents; i++) { + fin >> cw[i]; + } + } + fin >> sensFlag >> fldFlag >> fld >> epsil; + if (autoflag < 1) { + fin >> madfld >> maxstep >> maxde >> minstep; + } else { + // to use this feature one has to set TGeant3::SetAUTO(0), thus if the media does not + // defined these values one can force Geant3 to calculate them by given them a value + // of -1 + madfld = -1; + maxstep = -1; + maxde = -1; + minstep = -1; + } + fin >> n; + if (n > 0 && n < (INT_MAX - 1)) { + setNpckov(n); + // if (n>0) { + for (Int_t i = 0; i < n; i++) { + fin >> ppckov[i] >> absco[i] >> effic[i] >> rindex[i]; + } } - } - } void FairGeoMedium::print() { - // Prints the medium definition - const char* bl=" "; - cout<0) { - for(Int_t i=0; i 0) { + for (Int_t i = 0; i < npckov; i++) { + cout << ppckov[i] << bl << absco[i] << bl << effic[i] << bl << rindex[i] << '\n'; + } } - } - cout<<'\n'; + cout << '\n'; } -void FairGeoMedium::write (std::fstream& fout) +void FairGeoMedium::write(std::fstream& fout) { - // Writes the medium definition into stream - const char* bl=" "; - fout<0) { - for(Int_t i=0; i 0) { + for (Int_t i = 0; i < npckov; i++) { + fout << ppckov[i] << bl << absco[i] << bl << effic[i] << bl << rindex[i] << '\n'; + } + } + fout << '\n'; } Bool_t FairGeoMedium::calcRadiationLength() { - // calculates radiation length - // formula in GEANT manual CONS110 - if (cz[0]<1.e-6) { // VAKUUM$ - radLen=1.e+16; - return kTRUE; - } - Double_t alpha=1/137.; // fine structure constant - Double_t fac=.1912821; // 4*((electron radius)**2)*(avogadro's number) - Double_t z, a, w, az2, fc, y, xi, x0i, amol=0., x0itot=0.; - if (weightFac>0) { amol=1.; } - else { - for (int i=0; i0) { - w=cw[i]/amol; + Double_t alpha = 1 / 137.; // fine structure constant + Double_t fac = .1912821; // 4*((electron radius)**2)*(avogadro's number) + Double_t z, a, w, az2, fc, y, xi, x0i, amol = 0., x0itot = 0.; + if (weightFac > 0) { + amol = 1.; } else { - w=a*cw[i]/amol; + for (int i = 0; i < nComponents; i++) { + amol += cw[i] * ca[i]; + if (amol == 0.) { + Error("calcRadiationLength()", "amol==0 for medium %s", fName.Data()); + return kFALSE; + } + } } - az2=alpha*alpha*z*z; - fc=az2 * (1./(1.+az2) + 0.20206 - 0.0369*az2 + 0.0083*az2*az2 - - .002F*az2*az2*az2); - y=log(183./pow(z,1./3.)) - fc; - xi=static_cast(log(1440./pow(z,2./3.)) / y); - x0i=fac*alpha/a*z*(z+xi)*y; - x0itot+=(x0i*w); - } - if (x0itot==0. || density==0.) { - Error("calcRadiationLength()","x0itot=0 or density=0 for medium %s",fName.Data()); - return kFALSE; - } - radLen=1/density/x0itot; - return kTRUE; + for (int i = 0; i < nComponents; i++) { + z = cz[i]; + a = ca[i]; + if (weightFac > 0) { + w = cw[i] / amol; + } else { + w = a * cw[i] / amol; + } + az2 = alpha * alpha * z * z; + fc = az2 * (1. / (1. + az2) + 0.20206 - 0.0369 * az2 + 0.0083 * az2 * az2 - .002F * az2 * az2 * az2); + y = log(183. / pow(z, 1. / 3.)) - fc; + xi = static_cast(log(1440. / pow(z, 2. / 3.)) / y); + x0i = fac * alpha / a * z * (z + xi) * y; + x0itot += (x0i * w); + } + if (x0itot == 0. || density == 0.) { + Error("calcRadiationLength()", "x0itot=0 or density=0 for medium %s", fName.Data()); + return kFALSE; + } + radLen = 1 / density / x0itot; + return kTRUE; } diff --git a/geobase/FairGeoMedium.h b/geobase/FairGeoMedium.h index 1d86abd00e..fb14460943 100644 --- a/geobase/FairGeoMedium.h +++ b/geobase/FairGeoMedium.h @@ -1,93 +1,101 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRGEOMEDIUM_H #define FAIRGEOMEDIUM_H -#include // for TNamed - -#include // for fstream -#include // for Double_t, Int_t, Bool_t, etc +#include // for Double_t, Int_t, Bool_t, etc +#include // for TNamed +#include // for fstream /** * Class for tracking medium * @author ilse koenig */ -class FairGeoMedium : public TNamed +class FairGeoMedium : public TNamed { private: - Int_t medId; /** Unique number for the material and the medium */ - Int_t autoflag; /** Flag for default values of madfld .. minstep*/ - Int_t nComponents; /** Number of material components */ - Int_t weightFac; /** Factor for weights (1: relative w., -1: w. by number of atoms)*/ - Double_t* ca; //[nComponents] /** Atomic weights for the components*/ - Double_t* cz; //[nComponents] /** Atomic numbers for the components*/ - Double_t* cw; //[nComponents] /** Weights of the components in a mixture*/ - Double_t density; /** Density in g cm(**-3)*/ - Double_t radLen; /** Radiation lenght*/ - Int_t sensFlag; /** Sensitivity flag*/ - Int_t fldFlag; /** Field flag*/ - Double_t fld; /** Maximum field value in kilogauss*/ - Double_t epsil; /** Boundary crossing precision*/ - Double_t madfld; /** Maximum angular deviation due to field*/ - Double_t maxstep; /** Maximum step permitted*/ - Double_t maxde; /** Maximum fractional energy loss*/ - Double_t minstep; /** Minimum value for step*/ - Int_t npckov; /** Number of optical parameters for Cerenkov*/ - Double_t* ppckov; //[npckov] /** Photon momentum*/ - Double_t* absco; //[npckov] /** Absoption length*/ - Double_t* effic; //[npckov] /** Detection efficiency*/ - Double_t* rindex; //[npckov] /** Refraction index*/ + Int_t medId; /** Unique number for the material and the medium */ + Int_t autoflag; /** Flag for default values of madfld .. minstep*/ + Int_t nComponents; /** Number of material components */ + Int_t weightFac; /** Factor for weights (1: relative w., -1: w. by number of atoms)*/ + Double_t* ca; //[nComponents] /** Atomic weights for the components*/ + Double_t* cz; //[nComponents] /** Atomic numbers for the components*/ + Double_t* cw; //[nComponents] /** Weights of the components in a mixture*/ + Double_t density; /** Density in g cm(**-3)*/ + Double_t radLen; /** Radiation lenght*/ + Int_t sensFlag; /** Sensitivity flag*/ + Int_t fldFlag; /** Field flag*/ + Double_t fld; /** Maximum field value in kilogauss*/ + Double_t epsil; /** Boundary crossing precision*/ + Double_t madfld; /** Maximum angular deviation due to field*/ + Double_t maxstep; /** Maximum step permitted*/ + Double_t maxde; /** Maximum fractional energy loss*/ + Double_t minstep; /** Minimum value for step*/ + Int_t npckov; /** Number of optical parameters for Cerenkov*/ + Double_t* ppckov; //[npckov] /** Photon momentum*/ + Double_t* absco; //[npckov] /** Absoption length*/ + Double_t* effic; //[npckov] /** Detection efficiency*/ + Double_t* rindex; //[npckov] /** Refraction index*/ public: - FairGeoMedium(const char* name=""); - FairGeoMedium& operator=(const FairGeoMedium&) {return *this;} + FairGeoMedium(const char* name = ""); + FairGeoMedium& operator=(const FairGeoMedium&) { return *this; } ~FairGeoMedium(); - void setMediumIndex(Int_t i) {medId=i;} - Int_t getMediumIndex() {return medId;} - void setAutoFlag(Int_t i) {autoflag=i;} - Int_t getAutoFlag() {return autoflag;} + void setMediumIndex(Int_t i) { medId = i; } + Int_t getMediumIndex() { return medId; } + void setAutoFlag(Int_t i) { autoflag = i; } + Int_t getAutoFlag() { return autoflag; } void setNComponents(Int_t); - Int_t getNComponents() {return nComponents;} - Bool_t setComponent(Int_t,Double_t,Double_t,Double_t w=1.); - void getComponent(Int_t,Double_t*); - Int_t getWeightFac() {return weightFac;} - void setDensity(Double_t d) {density=d;} - Double_t getDensity() {return density;} - void setRadiationLength(Double_t l) {radLen=l;} - Double_t getRadiationLength() {return radLen;} + Int_t getNComponents() { return nComponents; } + Bool_t setComponent(Int_t, Double_t, Double_t, Double_t w = 1.); + void getComponent(Int_t, Double_t*); + Int_t getWeightFac() { return weightFac; } + void setDensity(Double_t d) { density = d; } + Double_t getDensity() { return density; } + void setRadiationLength(Double_t l) { radLen = l; } + Double_t getRadiationLength() { return radLen; } void setNpckov(Int_t); - Int_t getNpckov() {return npckov;} - Bool_t setCerenkovPar(Int_t,Double_t,Double_t,Double_t,Double_t); - void getCerenkovPar(Int_t,Double_t*); - void setMediumPar(Int_t,Int_t,Double_t,Double_t,Double_t maxDeviation=-1., - Double_t maxStep=-1.,Double_t maxDE=-1., - Double_t minStepDouble_t=-1.); + Int_t getNpckov() { return npckov; } + Bool_t setCerenkovPar(Int_t, Double_t, Double_t, Double_t, Double_t); + void getCerenkovPar(Int_t, Double_t*); + void setMediumPar(Int_t, + Int_t, + Double_t, + Double_t, + Double_t maxDeviation = -1., + Double_t maxStep = -1., + Double_t maxDE = -1., + Double_t minStepDouble_t = -1.); void getMediumPar(Double_t*); inline Bool_t isSensitive(); - Int_t getSensitivityFlag() { return sensFlag;} - Int_t getFieldFlag() {return fldFlag;} - Double_t getField() {return fld;} - Double_t getEpsil() {return epsil;} - void read(std::fstream&, Int_t autoflag ); + Int_t getSensitivityFlag() { return sensFlag; } + Int_t getFieldFlag() { return fldFlag; } + Double_t getField() { return fld; } + Double_t getEpsil() { return epsil; } + void read(std::fstream&, Int_t autoflag); void print(); - void write (std::fstream&); + void write(std::fstream&); Bool_t calcRadiationLength(); + private: FairGeoMedium(const FairGeoMedium&); - //TODO: correct copy constructor for FairGeoMedium + // TODO: correct copy constructor for FairGeoMedium // FairGeoMedium& operator=(const FairGeoMedium&); - ClassDef(FairGeoMedium,1) // + ClassDef(FairGeoMedium, 1) // }; inline Bool_t FairGeoMedium::isSensitive() { - if (sensFlag) { return kTRUE; } - else { return kFALSE; } + if (sensFlag) { + return kTRUE; + } else { + return kFALSE; + } } #endif /* !FAIRGEOMEDIUM_H */ diff --git a/geobase/FairGeoNode.cxx b/geobase/FairGeoNode.cxx index e4758507ff..bec67893c6 100644 --- a/geobase/FairGeoNode.cxx +++ b/geobase/FairGeoNode.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ //*-- AUTHOR : Ilse Koenig @@ -17,99 +17,106 @@ //////////////////////////////////////////////////////////////// #include "FairGeoNode.h" -#include "FairGeoRotation.h" // for FairGeoRotation -#include "FairGeoVector.h" // for FairGeoVector +#include "FairGeoRotation.h" // for FairGeoRotation +#include "FairGeoVector.h" // for FairGeoVector -#include // for TList - -#include // IWYU pragma: keep for abs +#include // for TList +#include // IWYU pragma: keep for abs // IWYU pragma: no_include -#include // for sscanf -#include // for operator<<, basic_ostream, etc +#include // for sscanf #include +#include // for operator<<, basic_ostream, etc using std::cout; using std::endl; -ClassImp(FairGeoNode) +ClassImp(FairGeoNode); FairGeoNode::FairGeoNode() - : FairGeoVolume(), - active(kFALSE), - center(FairGeoTransform()), - volumeType(kFairGeoElement), - created(kFALSE), - copyNode(nullptr), - rootVolume(nullptr), - pShape(0), - pMother(nullptr), - medium(nullptr), - labTransform(nullptr), - fDaughterList(new TObjArray(5)), - fTruncName("") + : FairGeoVolume() + , active(kFALSE) + , center(FairGeoTransform()) + , volumeType(kFairGeoElement) + , created(kFALSE) + , copyNode(nullptr) + , rootVolume(nullptr) + , pShape(0) + , pMother(nullptr) + , medium(nullptr) + , labTransform(nullptr) + , fDaughterList(new TObjArray(5)) + , fTruncName("") { - // Constructor - clear(); + // Constructor + clear(); } FairGeoNode::FairGeoNode(FairGeoNode& r) - :FairGeoVolume(r), - active(kFALSE), - center(r.getCenterPosition()), - volumeType(r.getVolumeType()), - created(kFALSE), - copyNode(r.getCopyNode()), - rootVolume(r.getRootVolume()), - pShape(nullptr), - pMother(nullptr), - medium(nullptr), - labTransform(new FairGeoTransform(*(r.getLabTransform()))), - fDaughterList(new TObjArray(*(r.GetListOfDaughters()))), - fTruncName(r.getTruncName()) + : FairGeoVolume(r) + , active(kFALSE) + , center(r.getCenterPosition()) + , volumeType(r.getVolumeType()) + , created(kFALSE) + , copyNode(r.getCopyNode()) + , rootVolume(r.getRootVolume()) + , pShape(nullptr) + , pMother(nullptr) + , medium(nullptr) + , labTransform(new FairGeoTransform(*(r.getLabTransform()))) + , fDaughterList(new TObjArray(*(r.GetListOfDaughters()))) + , fTruncName(r.getTruncName()) { - // Copy constructor - points=0; - nPoints = 0; - fName=r.GetName(); - setVolumePar(r); - if (r.isActive()) { active=kTRUE; } - if (r.isCreated()) { created=kTRUE; } + // Copy constructor + points = 0; + nPoints = 0; + fName = r.GetName(); + setVolumePar(r); + if (r.isActive()) { + active = kTRUE; + } + if (r.isCreated()) { + created = kTRUE; + } } FairGeoNode::~FairGeoNode() { - // Destructor - if (points) { - for (Int_t i=0; iRemoveAt(i); } - delete points; - points=0; - } - if (labTransform) { - delete labTransform; - labTransform=0; - } - if(fDaughterList) { - fDaughterList->Delete(); - delete fDaughterList; - } + // Destructor + if (points) { + for (Int_t i = 0; i < nPoints; i++) { + points->RemoveAt(i); + } + delete points; + points = 0; + } + if (labTransform) { + delete labTransform; + labTransform = 0; + } + if (fDaughterList) { + fDaughterList->Delete(); + delete fDaughterList; + } } void FairGeoNode::setVolumePar(FairGeoNode& r) { - // Copies all volume parameters except the name - setMother(r.getMotherNode()); - medium=r.getMedium(); - setShape(r.getShapePointer()); - Int_t n=r.getNumPoints(); - createPoints(n); - for (Int_t i=0; i4) { - TString s(fName); - s.Remove(0,4); - sscanf(s.Data(),"%i",&n); - } - } else { + // Returns the copy number + Int_t n = 0; + if (fHadFormat == 1) { + Int_t l = fName.Length(); + if (l > 4) { + TString s(fName); + s.Remove(0, 4); + sscanf(s.Data(), "%i", &n); + } + } else { - Ssiz_t l=fName.Last('#'); - if (l>0) { - TString s(fName); - s.Remove(0,l+1); - sscanf(s.Data(),"%i",&n); + Ssiz_t l = fName.Last('#'); + if (l > 0) { + TString s(fName); + s.Remove(0, l + 1); + sscanf(s.Data(), "%i", &n); + } } - } - return n; + return n; } TArrayD* FairGeoNode::getParameters() { - // Returns the parameters to create a GEANT/ROOT volume - if (pShape) { return pShape->calcVoluParam(this); } - return 0; + // Returns the parameters to create a GEANT/ROOT volume + if (pShape) { + return pShape->calcVoluParam(this); + } + return 0; } FairGeoTransform* FairGeoNode::getPosition() { - // Returns the transformation to position a volume in GEANT/ROOT - if (pShape&&pMother) { - pShape->calcVoluPosition(this,pMother->getCenterPosition()); - center.setTransform(*(pShape->getCenterPosition())); - return pShape->getVoluPosition(); - } - return 0; + // Returns the transformation to position a volume in GEANT/ROOT + if (pShape && pMother) { + pShape->calcVoluPosition(this, pMother->getCenterPosition()); + center.setTransform(*(pShape->getCenterPosition())); + return pShape->getVoluPosition(); + } + return 0; } void FairGeoNode::print() { - // Prints all parameters of a volume - cout<<"//----------------------------------------------------------\n"; - FairGeoVolume::print(); - cout<<"//----------------------------------------------------------\n"; - return; + // Prints all parameters of a volume + cout << "//----------------------------------------------------------\n"; + FairGeoVolume::print(); + cout << "//----------------------------------------------------------\n"; + return; - /* + /* cout<<((const char*)fName)<<'\n'; if (pMother) { cout<<((const char*)mother)<<'\n'; } else { cout<<"-- unknown mother --\n"; } @@ -195,207 +204,229 @@ void FairGeoNode::print() Bool_t FairGeoNode::write(std::fstream& fout) { - // Writes all parameters of a volume to file - fout<(mother.Data()))<<'\n'; } - else { - Error("write","Unknown mother for %s\n",fName.Data()); - return kFALSE; - } - if (!copyNode) { - if (pShape) { fout<<(const_cast(shape.Data()))<<'\n'; } - else { - Error("write","Unknown shape for %s\n",fName.Data()); - return kFALSE; + // Writes all parameters of a volume to file + fout << fName.Data() << '\n'; + if (pMother) { + fout << (const_cast(mother.Data())) << '\n'; + } else { + Error("write", "Unknown mother for %s\n", fName.Data()); + return kFALSE; } - if (medium) { fout<GetName()<<'\n'; } - else { - Error("write","Unknown medium for %s\n",fName.Data()); - return kFALSE; + if (!copyNode) { + if (pShape) { + fout << (const_cast(shape.Data())) << '\n'; + } else { + Error("write", "Unknown shape for %s\n", fName.Data()); + return kFALSE; + } + if (medium) { + fout << medium->GetName() << '\n'; + } else { + Error("write", "Unknown medium for %s\n", fName.Data()); + return kFALSE; + } + if (points && pShape) { + pShape->writePoints(&fout, this); + } else { + Error("write", "No points for %s\n", fName.Data()); + return kFALSE; + } } - if (points && pShape) { pShape->writePoints(&fout,this); } - else { - Error("write","No points for %s\n",fName.Data()); - return kFALSE; + const FairGeoRotation& r = transform.getRotMatrix(); + const FairGeoVector& v = transform.getTransVector(); + fout.precision(3); + fout << v(0) << " " << v(1) << " " << v(2) << '\n'; + fout.precision(7); + for (Int_t i = 0; i < 9; i++) { + fout << r(i) << " "; } - } - const FairGeoRotation& r=transform.getRotMatrix(); - const FairGeoVector& v=transform.getTransVector(); - fout.precision(3); - fout<getMotherNode(); - if (lmother) { tree->Add(lmother); } - v=lmother; - } while (v&&!v->isTopNode()); - return tree; + // Returns the tree of the mother volumes + TList* tree = new TList(); + FairGeoNode* v = this; + FairGeoNode* lmother; + do { + lmother = v->getMotherNode(); + if (lmother) { + tree->Add(lmother); + } + v = lmother; + } while (v && !v->isTopNode()); + return tree; } FairGeoTransform* FairGeoNode::getLabTransform() { - // Returns the lab transformation - if (labTransform) { return labTransform; } - else { return calcLabTransform(); } + // Returns the lab transformation + if (labTransform) { + return labTransform; + } else { + return calcLabTransform(); + } } FairGeoTransform* FairGeoNode::calcLabTransform() { - // Calculates the lab transformation + // Calculates the lab transformation - labTransform=new FairGeoTransform(transform); + labTransform = new FairGeoTransform(transform); - if (!isTopNode()) { - if (!pMother) { - Error("calcLabTransform()","Mother volume of %s not found!",GetName()); - delete labTransform; - return 0; - } - FairGeoTransform* tm=pMother->getLabTransform(); - if (!tm) { - ; - Error("calcLabTransform()", - "Lab Transformation of mother volume of %s not found!",GetName()); - delete labTransform; - return 0; + if (!isTopNode()) { + if (!pMother) { + Error("calcLabTransform()", "Mother volume of %s not found!", GetName()); + delete labTransform; + return 0; + } + FairGeoTransform* tm = pMother->getLabTransform(); + if (!tm) { + ; + Error("calcLabTransform()", "Lab Transformation of mother volume of %s not found!", GetName()); + delete labTransform; + return 0; + } + labTransform->transFrom(*tm); } - labTransform->transFrom(*tm); - } - fLabTransform = *labTransform; - fMedium = *medium; - return labTransform; + fLabTransform = *labTransform; + fMedium = *medium; + return labTransform; } void FairGeoNode::setLabTransform(FairGeoTransform& t) { - // Sets the lab transformation - if (!isTopNode()) { - if (labTransform) { labTransform->setTransform(t); } - else { labTransform=new FairGeoTransform(t); } - if (!pMother) { - Error("calcLabTransform()","Mother volume of %s not found!",GetName()); - delete labTransform; - return; + // Sets the lab transformation + if (!isTopNode()) { + if (labTransform) { + labTransform->setTransform(t); + } else { + labTransform = new FairGeoTransform(t); + } + if (!pMother) { + Error("calcLabTransform()", "Mother volume of %s not found!", GetName()); + delete labTransform; + return; + } + FairGeoTransform* tm = pMother->getLabTransform(); + if (!tm) { + ; + Error("calcLabTransform()", "Lab Transformation of mother volume of %s not found!", GetName()); + delete labTransform; + return; + } + transform = t; + transform.transTo(*tm); } - FairGeoTransform* tm=pMother->getLabTransform(); - if (!tm) { - ; - Error("calcLabTransform()", - "Lab Transformation of mother volume of %s not found!",GetName()); - delete labTransform; - return; - } - transform=t; - transform.transTo(*tm); - } } Bool_t FairGeoNode::calcModuleTransform(FairGeoTransform& modTransform) { - // Calculates the transformation relative to the detectors coordinate system - FairGeoNode* node=this; - modTransform=transform; - while (node&&!node->isModule()) { - FairGeoNode* pm=node->getMotherNode(); - if (!pm) { - Error("calcModuleTransform","Mother volume of %s not found!",node->GetName()); - return kFALSE; + // Calculates the transformation relative to the detectors coordinate system + FairGeoNode* node = this; + modTransform = transform; + while (node && !node->isModule()) { + FairGeoNode* pm = node->getMotherNode(); + if (!pm) { + Error("calcModuleTransform", "Mother volume of %s not found!", node->GetName()); + return kFALSE; + } + modTransform.transFrom(pm->getTransform()); + node = pm; + } + if (isTopNode()) { + return kFALSE; + } else { + return kTRUE; } - modTransform.transFrom(pm->getTransform()); - node=pm; - } - if (isTopNode()) { return kFALSE; } - else { return kTRUE; } } Bool_t FairGeoNode::calcRefPos(FairGeoVector& refPos) { - // Calculates the position in the detectors coordinate system - FairGeoNode* node=this; - refPos=center.getTransVector(); - do { - refPos=node->getTransform().transFrom(refPos); - node=node->getMotherNode(); - if (!node) { - Error("calcModuleTransform","Mother of volume %s not found!",GetName()); - return kFALSE; + // Calculates the position in the detectors coordinate system + FairGeoNode* node = this; + refPos = center.getTransVector(); + do { + refPos = node->getTransform().transFrom(refPos); + node = node->getMotherNode(); + if (!node) { + Error("calcModuleTransform", "Mother of volume %s not found!", GetName()); + return kFALSE; + } + } while (node && !node->isModule()); + if (isTopNode()) { + return kFALSE; + } else { + return kTRUE; } - } while (node&&!node->isModule()); - if (isTopNode()) { return kFALSE; } - else { return kTRUE; } } Int_t FairGeoNode::compare(FairGeoNode& rn) { - // Compares the volume with the volume rn and prints the diagnose - // Returns kTRUE if the volume parameters are the same - Int_t diff[]= {0,0,0,0,0,0}; - Int_t n=0; - cout<GetName(); - if (med.CompareTo(rn.getMedium()->GetName())!=0) { - diff[1]=1; - n++; + // Compares the volume with the volume rn and prints the diagnose + // Returns kTRUE if the volume parameters are the same + Int_t diff[] = {0, 0, 0, 0, 0, 0}; + Int_t n = 0; + cout << fName << '\t'; + if (mother.CompareTo(rn.getMother()) != 0) { + diff[0] = 1; + n++; } - } else { - diff[1]=1; - n++; - } - if (shape.CompareTo(rn.getShape())!=0) { - diff[2]=1; - n++; - } - Int_t np=rn.getNumPoints(); - if (points&&nPoints==np) { - for (Int_t i=0; i=0.001||fabs(v1(1)-v2(1))>=0.001||fabs(v1(1)-v2(1))>=0.001) { - diff[3]=1; + if (medium && rn.getMedium()) { + TString med = medium->GetName(); + if (med.CompareTo(rn.getMedium()->GetName()) != 0) { + diff[1] = 1; + n++; + } + } else { + diff[1] = 1; n++; - break; - } } - } else { - diff[3]=1; - n++; - } - FairGeoVector v1=transform.getTransVector(); - FairGeoVector v2=rn.getTransform().getTransVector(); - if (fabs(v1(0)-v2(0))>=0.001||fabs(v1(1)-v2(1))>=0.001||fabs(v1(1)-v2(1))>=0.001) { - diff[4]=1; - n++; - } - FairGeoRotation r1=transform.getRotMatrix(); - FairGeoRotation r2=rn.getTransform().getRotMatrix(); - for (Int_t i=0; i<9; i++) { - if (fabs(r1(i)-r2(i))>=1.e-7) { - diff[5]=1; - n++; - break; + if (shape.CompareTo(rn.getShape()) != 0) { + diff[2] = 1; + n++; } - } - if (n>0) { - for (Int_t i=0; i<6; i++) { cout<<" "<= 0.001 || fabs(v1(1) - v2(1)) >= 0.001 || fabs(v1(1) - v2(1)) >= 0.001) { + diff[3] = 1; + n++; + break; + } + } + } else { + diff[3] = 1; + n++; + } + FairGeoVector v1 = transform.getTransVector(); + FairGeoVector v2 = rn.getTransform().getTransVector(); + if (fabs(v1(0) - v2(0)) >= 0.001 || fabs(v1(1) - v2(1)) >= 0.001 || fabs(v1(1) - v2(1)) >= 0.001) { + diff[4] = 1; + n++; + } + FairGeoRotation r1 = transform.getRotMatrix(); + FairGeoRotation r2 = rn.getTransform().getRotMatrix(); + for (Int_t i = 0; i < 9; i++) { + if (fabs(r1(i) - r2(i)) >= 1.e-7) { + diff[5] = 1; + n++; + break; + } + } + if (n > 0) { + for (Int_t i = 0; i < 6; i++) { + cout << " " << diff[i] << " "; + } + cout << '\n'; + } else { + cout << " same\n"; + } + return n; } diff --git a/geobase/FairGeoNode.h b/geobase/FairGeoNode.h index 33a286218d..ac634f6c20 100644 --- a/geobase/FairGeoNode.h +++ b/geobase/FairGeoNode.h @@ -1,39 +1,37 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRGEONODE_H #define FAIRGEONODE_H -#include "FairGeoVolume.h" // for FairGeoVolume +#include "FairGeoBasicShape.h" // for FairGeoBasicShape +#include "FairGeoMedium.h" // for FairGeoMedium +#include "FairGeoTransform.h" // for FairGeoTransform +#include "FairGeoVolume.h" // for FairGeoVolume -#include "FairGeoBasicShape.h" // for FairGeoBasicShape -#include "FairGeoMedium.h" // for FairGeoMedium -#include "FairGeoTransform.h" // for FairGeoTransform - -#include // for Bool_t, FairGeoNode::Class, etc -#include // for TObjArray -#include // for TString - -#include // for fstream +#include // for Bool_t, FairGeoNode::Class, etc +#include // for TObjArray +#include // for TString +#include // for fstream class FairGeoVector; class TArrayD; class TGeoVolume; class TList; -enum EFairGeoNodeType { - kFairGeoElement = 0, - kFairGeoKeepin = 1, - kFairGeoModule = 2, - kFairGeoTopNode = 3, - kFairGeoRefNode = 4 +enum EFairGeoNodeType +{ + kFairGeoElement = 0, + kFairGeoKeepin = 1, + kFairGeoModule = 2, + kFairGeoTopNode = 3, + kFairGeoRefNode = 4 }; - /** * basic geometry parameters of a volume * @author Ilse koenig @@ -43,56 +41,58 @@ class FairGeoNode : public FairGeoVolume private: FairGeoNode(const FairGeoNode&); FairGeoNode& operator=(const FairGeoNode&); + protected: - Bool_t active; /** in/out flag for creation */ + Bool_t active; /** in/out flag for creation */ FairGeoTransform center; /** position of the GEANT/ROOT center */ EFairGeoNodeType volumeType; /** type of volume */ - Bool_t created; /** Flag set kTRUE after creation of volume */ - FairGeoNode* copyNode; /** pointer to the reference volume for a copy */ - TGeoVolume* rootVolume; /** pointer to the ROOT node */ - FairGeoBasicShape* pShape; /** pointer to the shape */ - FairGeoNode* pMother; //! /** pointer to the mother volume */ - FairGeoMedium* medium; /** pointer to medium */ + Bool_t created; /** Flag set kTRUE after creation of volume */ + FairGeoNode* copyNode; /** pointer to the reference volume for a copy */ + TGeoVolume* rootVolume; /** pointer to the ROOT node */ + FairGeoBasicShape* pShape; /** pointer to the shape */ + FairGeoNode* pMother; //! /** pointer to the mother volume */ + FairGeoMedium* medium; /** pointer to medium */ FairGeoTransform* labTransform; /** Transformation to the LAB system */ - TObjArray* fDaughterList; /** List of daughter Nodes */ - //const char* fTruncName; // - TString fTruncName; + TObjArray* fDaughterList; /** List of daughter Nodes */ + // const char* fTruncName; // + TString fTruncName; + public: FairGeoNode(); FairGeoNode(FairGeoNode&); virtual ~FairGeoNode(); - void AddDaughter(FairGeoNode* fNode) {fDaughterList->AddLast(fNode);} - TObjArray* GetListOfDaughters() {return fDaughterList;} + void AddDaughter(FairGeoNode* fNode) { fDaughterList->AddLast(fNode); } + TObjArray* GetListOfDaughters() { return fDaughterList; } EFairGeoNodeType getVolumeType() { return volumeType; } - Bool_t isTopNode() { return static_cast((volumeType == kFairGeoTopNode));} - Bool_t isRefNode() { return static_cast((volumeType == kFairGeoRefNode));} - Bool_t isKeepin() { return static_cast((volumeType == kFairGeoKeepin));} - Bool_t isModule() { return static_cast((volumeType == kFairGeoModule));} + Bool_t isTopNode() { return static_cast((volumeType == kFairGeoTopNode)); } + Bool_t isRefNode() { return static_cast((volumeType == kFairGeoRefNode)); } + Bool_t isKeepin() { return static_cast((volumeType == kFairGeoKeepin)); } + Bool_t isModule() { return static_cast((volumeType == kFairGeoModule)); } Int_t getCopyNo(); FairGeoBasicShape* getShapePointer() { return pShape; } - FairGeoNode* getMotherNode() {return pMother;} - FairGeoMedium* getMedium() {return medium;} - Bool_t isActive() {return active;} - FairGeoTransform& getCenterPosition() {return center;} + FairGeoNode* getMotherNode() { return pMother; } + FairGeoMedium* getMedium() { return medium; } + Bool_t isActive() { return active; } + FairGeoTransform& getCenterPosition() { return center; } TArrayD* getParameters(); FairGeoTransform* getPosition(); FairGeoTransform* getLabTransform(); - FairGeoNode* getCopyNode() {return copyNode;} - TGeoVolume* getRootVolume() {return rootVolume;} + FairGeoNode* getCopyNode() { return copyNode; } + TGeoVolume* getRootVolume() { return rootVolume; } TList* getTree(); Bool_t isSensitive(); - Bool_t isCreated() {return created;} - void setCreated() {created=kTRUE;} + Bool_t isCreated() { return created; } + void setCreated() { created = kTRUE; } void setName(const Text_t* s); - void setVolumeType(EFairGeoNodeType t) {volumeType=t;} + void setVolumeType(EFairGeoNodeType t) { volumeType = t; } void setVolumePar(FairGeoNode&); void setShape(FairGeoBasicShape* s); void setMother(FairGeoNode* s); - void setMedium(FairGeoMedium* med) {medium=med; } - void setActive(Bool_t a=kTRUE) {active=a;} - void setCenterPosition(const FairGeoTransform& t) {center=t;} - void setCopyNode(FairGeoNode* p) {copyNode=p;} - void setRootVolume(TGeoVolume* p) {rootVolume=p;} + void setMedium(FairGeoMedium* med) { medium = med; } + void setActive(Bool_t a = kTRUE) { active = a; } + void setCenterPosition(const FairGeoTransform& t) { center = t; } + void setCopyNode(FairGeoNode* p) { copyNode = p; } + void setRootVolume(TGeoVolume* p) { rootVolume = p; } FairGeoTransform* calcLabTransform(); void setLabTransform(FairGeoTransform&); Bool_t calcModuleTransform(FairGeoTransform&); @@ -102,48 +102,54 @@ class FairGeoNode : public FairGeoVolume Bool_t write(std::fstream&); Int_t compare(FairGeoNode&); - - void setTruncName( const char* aName ) { fTruncName = aName;} - const char* getTruncName() { - if (fTruncName.Length()>0) { return fTruncName.Data(); } - else { return GetName(); } + void setTruncName(const char* aName) { fTruncName = aName; } + const char* getTruncName() + { + if (fTruncName.Length() > 0) { + return fTruncName.Data(); + } else { + return GetName(); + } } - ClassDef(FairGeoNode,1) // + ClassDef(FairGeoNode, 1) // }; // -------------------- inlines -------------------------- inline void FairGeoNode::setName(const Text_t* s) { - // Sets the name of the volume - fName=s; - fName.ToUpper(); + // Sets the name of the volume + fName = s; + fName.ToUpper(); } inline void FairGeoNode::setShape(FairGeoBasicShape* s) { - // Sets the shape of the volume - if (s) { - pShape=s; - shape=pShape->GetName(); - } + // Sets the shape of the volume + if (s) { + pShape = s; + shape = pShape->GetName(); + } } inline void FairGeoNode::setMother(FairGeoNode* moth) { - // Sets the mother of the volume - if (moth) { - pMother=moth; - mother=pMother->GetName(); - pMother->AddDaughter(this); - } + // Sets the mother of the volume + if (moth) { + pMother = moth; + mother = pMother->GetName(); + pMother->AddDaughter(this); + } } inline Bool_t FairGeoNode::isSensitive() { - if (medium) { return medium->isSensitive(); } - else { return kFALSE; } + if (medium) { + return medium->isSensitive(); + } else { + return kFALSE; + } } #endif /* !FAIRGEONODE_H */ diff --git a/geobase/FairGeoOldAsciiIo.cxx b/geobase/FairGeoOldAsciiIo.cxx index 7466b13df6..fbec357d43 100644 --- a/geobase/FairGeoOldAsciiIo.cxx +++ b/geobase/FairGeoOldAsciiIo.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ //*-- AUTHOR : Ilse Koenig @@ -17,248 +17,279 @@ /////////////////////////////////////////////////////////////////////////////// #include "FairGeoOldAsciiIo.h" -#include "FairGeoBasicShape.h" // for FairGeoBasicShape -#include "FairGeoMedia.h" // for FairGeoMedia -#include "FairGeoMedium.h" // for FairGeoMedium -#include "FairGeoNode.h" // for FairGeoNode -#include "FairGeoSet.h" // for FairGeoSet -#include "FairGeoShapes.h" // for FairGeoShapes -#include "FairGeoTransform.h" // for FairGeoTransform +#include "FairGeoBasicShape.h" // for FairGeoBasicShape +#include "FairGeoMedia.h" // for FairGeoMedia +#include "FairGeoMedium.h" // for FairGeoMedium +#include "FairGeoNode.h" // for FairGeoNode +#include "FairGeoSet.h" // for FairGeoSet +#include "FairGeoShapes.h" // for FairGeoShapes +#include "FairGeoTransform.h" // for FairGeoTransform -#include // for TList +#include // for TList +#include // for fstream +#include // for cerr, cout +#include // for strcmp -#include // for strcmp -#include // for cerr, cout -#include // for fstream - -using std::cout; using std::cerr; +using std::cout; using std::endl; using std::ios; -ClassImp(FairGeoOldAsciiIo) +ClassImp(FairGeoOldAsciiIo); FairGeoOldAsciiIo::FairGeoOldAsciiIo() - : FairGeoIo(), - filename(""), - filedir(""), - writable(kFALSE), - file(nullptr) + : FairGeoIo() + , filename("") + , filedir("") + , writable(kFALSE) + , file(nullptr) { - // Constructor + // Constructor } FairGeoOldAsciiIo::~FairGeoOldAsciiIo() { - // Destructor - close(); - if (file) { - delete file; - file=0; - } + // Destructor + close(); + if (file) { + delete file; + file = 0; + } } -Bool_t FairGeoOldAsciiIo::open(const char* fname,const Text_t* status) +Bool_t FairGeoOldAsciiIo::open(const char* fname, const Text_t* status) { - // Opens the file fname - close(); - if (!file) { file=new std::fstream(); } - else { (file->clear()); } - if (!filedir.IsNull()) { filename=filedir+"/"+fname; } - else { filename=fname; } - filename=filename.Strip(); - if (strcmp(status,"in")==0) { - file->open(filename,ios::in); - writable=kFALSE; - } else { - if (strcmp(status,"out")==0) { - file->open(filename,ios::in); - if (!isOpen()) { - file->close(); - file->clear(); - file->open(filename,ios::out); - writable=kTRUE; - } else { - file->close(); - Error("open","Output file %s exists already and will not be recreated.", - filename.Data()); + // Opens the file fname + close(); + if (!file) { + file = new std::fstream(); + } else { + (file->clear()); + } + if (!filedir.IsNull()) { + filename = filedir + "/" + fname; + } else { + filename = fname; + } + filename = filename.Strip(); + if (strcmp(status, "in") == 0) { + file->open(filename, ios::in); + writable = kFALSE; + } else { + if (strcmp(status, "out") == 0) { + file->open(filename, ios::in); + if (!isOpen()) { + file->close(); + file->clear(); + file->open(filename, ios::out); + writable = kTRUE; + } else { + file->close(); + Error("open", "Output file %s exists already and will not be recreated.", filename.Data()); + return kFALSE; + } + } else { + Error("open", "Invalid file option!"); + } + } + if (file->rdbuf()->is_open() == 0) { + Error("open", "Failed to open file %s", filename.Data()); return kFALSE; - } - } else { Error("open","Invalid file option!"); } - } - if (file->rdbuf()->is_open()==0) { - Error("open","Failed to open file %s",filename.Data()); - return kFALSE; - } - return kTRUE; + } + return kTRUE; } Bool_t FairGeoOldAsciiIo::isOpen() { - // Returns kTRUE, if the file is open - if (file && file->rdbuf()->is_open()==1) { return kTRUE; } - return kFALSE; + // Returns kTRUE, if the file is open + if (file && file->rdbuf()->is_open() == 1) { + return kTRUE; + } + return kFALSE; } Bool_t FairGeoOldAsciiIo::isWritable() { - // Returns kTRUE, if the file is open and writable - if (isOpen() && writable) { return kTRUE; } - return kFALSE; + // Returns kTRUE, if the file is open and writable + if (isOpen() && writable) { + return kTRUE; + } + return kFALSE; } void FairGeoOldAsciiIo::close() { - // Closes the file - if (isOpen()) { - file->close(); - filename=""; - } + // Closes the file + if (isOpen()) { + file->close(); + filename = ""; + } } void FairGeoOldAsciiIo::print() { - // Prints file information - if (isOpen()) { - if (writable) { cout<<"Open output file: "<getListOfVolumes(); - FairGeoShapes* pShapes=set->getShapes(); - while(!fin.eof()) { - // Read volumeName - TString volumeName = ""; - fin >> volumeName; - if (fin.eof()) { break; } - volu=new FairGeoNode; - volu->SetName(volumeName); - // Read sensitivity - fin >> sensitivity; -// Why this additional integer only in trd file ???????????? - if (sensitivity>0) { fin >> na; } - // Read motherName - TString motherName = ""; - fin >> motherName; - FairGeoNode* mother=0; - if (motherName=="world") { mother=set->getMasterNode("cave"); } - else { mother=set->getVolume(motherName.Data()); } - volu->setMother(mother); - // Read position and rotation matrix - Double_t r[9], t[3]; - fin>>t[0]>>t[1]>>t[2]; - for(Int_t kk=0; kk<3; kk++) { t[kk]*=10.; } - for(Int_t i=0; i<9; i++) { fin>>r[i]; } - FairGeoTransform& tf=volu->getTransform(); - tf.setRotMatrix(r); - tf.setTransVector(t); - // Read material - TString materialName = ""; - fin >> materialName; - FairGeoMedium* medium=media->getMedium(materialName); - if (!medium) { - medium=new FairGeoMedium(materialName); - media->addMedium(medium); - } - volu->setMedium(medium); - // Read shape - TString type = ""; - fin >> type; - FairGeoBasicShape* sh=pShapes->selectShape(type); - if (sh) { volu->setShape(sh); } - else { - cerr << "Shape "<getNumParam(); - Double_t* par = new Double_t[npar](); //() after array default-initialize an array - for (Int_t ik=0; ik> par[ik]; - } - Bool_t rc=calculateShapePoints(par,volu); - delete[] par; - if (!rc) { - cerr << "Conversion for shape "<> control; - if ( control != "#fi" && !fin.eof()) { - cerr << "End of File section is '" << control << "' instead of '#fi'." << endl; - return kFALSE; + std::fstream& fin = *file; + fin.clear(); + fin.seekg(0, ios::beg); + FairGeoNode* volu = 0; + Int_t sensitivity = 0, na = 0; + TList* volumes = set->getListOfVolumes(); + FairGeoShapes* pShapes = set->getShapes(); + while (!fin.eof()) { + // Read volumeName + TString volumeName = ""; + fin >> volumeName; + if (fin.eof()) { + break; + } + volu = new FairGeoNode; + volu->SetName(volumeName); + // Read sensitivity + fin >> sensitivity; + // Why this additional integer only in trd file ???????????? + if (sensitivity > 0) { + fin >> na; + } + // Read motherName + TString motherName = ""; + fin >> motherName; + FairGeoNode* mother = 0; + if (motherName == "world") { + mother = set->getMasterNode("cave"); + } else { + mother = set->getVolume(motherName.Data()); + } + volu->setMother(mother); + // Read position and rotation matrix + Double_t r[9], t[3]; + fin >> t[0] >> t[1] >> t[2]; + for (Int_t kk = 0; kk < 3; kk++) { + t[kk] *= 10.; + } + for (Int_t i = 0; i < 9; i++) { + fin >> r[i]; + } + FairGeoTransform& tf = volu->getTransform(); + tf.setRotMatrix(r); + tf.setTransVector(t); + // Read material + TString materialName = ""; + fin >> materialName; + FairGeoMedium* medium = media->getMedium(materialName); + if (!medium) { + medium = new FairGeoMedium(materialName); + media->addMedium(medium); + } + volu->setMedium(medium); + // Read shape + TString type = ""; + fin >> type; + FairGeoBasicShape* sh = pShapes->selectShape(type); + if (sh) { + volu->setShape(sh); + } else { + cerr << "Shape " << type << " not supported." << endl; + return kFALSE; + } + Int_t npar = sh->getNumParam(); + Double_t* par = new Double_t[npar](); //() after array default-initialize an array + for (Int_t ik = 0; ik < npar; ik++) { + fin >> par[ik]; + } + Bool_t rc = calculateShapePoints(par, volu); + delete[] par; + if (!rc) { + cerr << "Conversion for shape " << type << " not implemented." << endl; + return kFALSE; + } + // Check of volume end + TString control = ""; + fin >> control; + if (control != "#fi" && !fin.eof()) { + cerr << "End of File section is '" << control << "' instead of '#fi'." << endl; + return kFALSE; + } + volu->print(); + volumes->Add(volu); } - volu->print(); - volumes->Add(volu); - } - return kTRUE; + return kTRUE; } -Bool_t FairGeoOldAsciiIo::calculateShapePoints(Double_t* par,FairGeoNode* volu) +Bool_t FairGeoOldAsciiIo::calculateShapePoints(Double_t* par, FairGeoNode* volu) { - FairGeoBasicShape* sh=volu->getShapePointer(); - TString shName=sh->GetName(); - Int_t n=sh->getNumPoints(); - volu->createPoints(n); - Bool_t rc=kTRUE; - if (shName == "BOX ") { - Double_t x=par[0]*10.; - Double_t y=par[1]*10.; - Double_t z=par[2]*10.; - volu->setPoint(0, x,-y,-z); - volu->setPoint(1, x, y,-z); - volu->setPoint(2,-x, y,-z); - volu->setPoint(3,-x,-y,-z); - volu->setPoint(4, x,-y, z); - volu->setPoint(5, x, y, z); - volu->setPoint(6,-x, y, z); - volu->setPoint(7,-x,-y, z); - } else if (shName == "TUBE") { - Double_t z=par[2]*10.; - volu->setPoint(0,0.,0.,-z); - volu->setPoint(1,par[0]*10.,par[1]*10.,0.); - volu->setPoint(2,0.,0.,z); - } else if (shName == "TUBS") { - Double_t z=par[2]*10.; - Double_t a=par[3]/6.28318548*360; - volu->setPoint(0,0.,0.,-z); - volu->setPoint(1,par[0]*10.,par[1]*10.,0.); - volu->setPoint(2,0.,0.,z); - volu->setPoint(3,a,par[4]/6.28318548*360+a,0.); - } else if (shName == "CONE") { - Double_t z=par[4]*10.; - volu->setPoint(0,0.,0.,-z); - volu->setPoint(1,par[0]*10.,par[1]*10.,0.); - volu->setPoint(2,0.,0.,z); - volu->setPoint(3,par[2]*10.,par[3]*10.,0.); - } else if (shName == "CONS") { - Double_t z=par[4]*10.; - Double_t a=par[5]/6.28318548*360; - volu->setPoint(0,0.,0.,-z); - volu->setPoint(1,par[0]*10.,par[1]*10.,0.); - volu->setPoint(2,0.,0.,z); - volu->setPoint(3,par[2]*10.,par[3]*10.,0.); - volu->setPoint(4,a,par[6]/6.28318548*360+a,0.); - } else if (shName == "SPHE") { - Double_t a=par[4]/6.28318548*360; - volu->setPoint(0,par[0]*10.,par[1]*10.,0.); - volu->setPoint(1,par[1],par[2],0.); - volu->setPoint(2,a,par[5]/6.28318548*360+a,0.); - } else if (shName == "ELTU") { - Double_t z=par[2]*10.; - volu->setPoint(0,0.,0.,-z); - volu->setPoint(1,par[0]*10.,par[1]*10.,0.); - volu->setPoint(2,0.,0.,z); - } else { rc=kFALSE; } - return rc; + FairGeoBasicShape* sh = volu->getShapePointer(); + TString shName = sh->GetName(); + Int_t n = sh->getNumPoints(); + volu->createPoints(n); + Bool_t rc = kTRUE; + if (shName == "BOX ") { + Double_t x = par[0] * 10.; + Double_t y = par[1] * 10.; + Double_t z = par[2] * 10.; + volu->setPoint(0, x, -y, -z); + volu->setPoint(1, x, y, -z); + volu->setPoint(2, -x, y, -z); + volu->setPoint(3, -x, -y, -z); + volu->setPoint(4, x, -y, z); + volu->setPoint(5, x, y, z); + volu->setPoint(6, -x, y, z); + volu->setPoint(7, -x, -y, z); + } else if (shName == "TUBE") { + Double_t z = par[2] * 10.; + volu->setPoint(0, 0., 0., -z); + volu->setPoint(1, par[0] * 10., par[1] * 10., 0.); + volu->setPoint(2, 0., 0., z); + } else if (shName == "TUBS") { + Double_t z = par[2] * 10.; + Double_t a = par[3] / 6.28318548 * 360; + volu->setPoint(0, 0., 0., -z); + volu->setPoint(1, par[0] * 10., par[1] * 10., 0.); + volu->setPoint(2, 0., 0., z); + volu->setPoint(3, a, par[4] / 6.28318548 * 360 + a, 0.); + } else if (shName == "CONE") { + Double_t z = par[4] * 10.; + volu->setPoint(0, 0., 0., -z); + volu->setPoint(1, par[0] * 10., par[1] * 10., 0.); + volu->setPoint(2, 0., 0., z); + volu->setPoint(3, par[2] * 10., par[3] * 10., 0.); + } else if (shName == "CONS") { + Double_t z = par[4] * 10.; + Double_t a = par[5] / 6.28318548 * 360; + volu->setPoint(0, 0., 0., -z); + volu->setPoint(1, par[0] * 10., par[1] * 10., 0.); + volu->setPoint(2, 0., 0., z); + volu->setPoint(3, par[2] * 10., par[3] * 10., 0.); + volu->setPoint(4, a, par[6] / 6.28318548 * 360 + a, 0.); + } else if (shName == "SPHE") { + Double_t a = par[4] / 6.28318548 * 360; + volu->setPoint(0, par[0] * 10., par[1] * 10., 0.); + volu->setPoint(1, par[1], par[2], 0.); + volu->setPoint(2, a, par[5] / 6.28318548 * 360 + a, 0.); + } else if (shName == "ELTU") { + Double_t z = par[2] * 10.; + volu->setPoint(0, 0., 0., -z); + volu->setPoint(1, par[0] * 10., par[1] * 10., 0.); + volu->setPoint(2, 0., 0., z); + } else { + rc = kFALSE; + } + return rc; } diff --git a/geobase/FairGeoOldAsciiIo.h b/geobase/FairGeoOldAsciiIo.h index d44b237222..9d70e40878 100644 --- a/geobase/FairGeoOldAsciiIo.h +++ b/geobase/FairGeoOldAsciiIo.h @@ -1,18 +1,18 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRGEOOLDASCIIIO_H #define FAIRGEOOLDASCIIIO_H -#include "FairGeoIo.h" // for FairGeoIo +#include "FairGeoIo.h" // for FairGeoIo -#include // for fstream -#include // for Bool_t, kFALSE, etc -#include // for TString +#include // for Bool_t, kFALSE, etc +#include // for TString +#include // for fstream class FairGeoInterface; class FairGeoMedia; @@ -23,37 +23,39 @@ class FairGeoSet; * Class for geometry I/O from ASCII file in FAIR format * @author Ilse koenig */ -class FairGeoOldAsciiIo: public FairGeoIo +class FairGeoOldAsciiIo : public FairGeoIo { - TString filename; - TString filedir; - Bool_t writable; + TString filename; + TString filedir; + Bool_t writable; std::fstream* file; + public: FairGeoOldAsciiIo(); ~FairGeoOldAsciiIo(); - void setDirectory(const char* fDir) {filedir=fDir;} - const char* getDirectory() {return filedir.Data();} - const char* getFilename() {return filename.Data();} - Bool_t open(const char*,const Text_t* status="in"); + void setDirectory(const char* fDir) { filedir = fDir; } + const char* getDirectory() { return filedir.Data(); } + const char* getFilename() { return filename.Data(); } + Bool_t open(const char*, const Text_t* status = "in"); Bool_t isOpen(); Bool_t isWritable(); void close(); void print(); - Bool_t read(FairGeoMedia*) {return kFALSE;} - Bool_t read(FairGeoSet*,FairGeoMedia*); - Bool_t write(FairGeoMedia*) {return kFALSE;} - Bool_t write(FairGeoSet*) {return kFALSE;} - Bool_t readGeomConfig(FairGeoInterface*) {return kFALSE;} - Bool_t readDetectorSetup(FairGeoInterface*) {return kFALSE;} - Bool_t setSimulRefRun(const char*) {return kTRUE;} - Bool_t setHistoryDate(const char*) {return kTRUE;} + Bool_t read(FairGeoMedia*) { return kFALSE; } + Bool_t read(FairGeoSet*, FairGeoMedia*); + Bool_t write(FairGeoMedia*) { return kFALSE; } + Bool_t write(FairGeoSet*) { return kFALSE; } + Bool_t readGeomConfig(FairGeoInterface*) { return kFALSE; } + Bool_t readDetectorSetup(FairGeoInterface*) { return kFALSE; } + Bool_t setSimulRefRun(const char*) { return kTRUE; } + Bool_t setHistoryDate(const char*) { return kTRUE; } + private: - Bool_t calculateShapePoints(Double_t*,FairGeoNode*); + Bool_t calculateShapePoints(Double_t*, FairGeoNode*); FairGeoOldAsciiIo(const FairGeoOldAsciiIo&); FairGeoOldAsciiIo& operator=(const FairGeoOldAsciiIo&); - ClassDef(FairGeoOldAsciiIo,0) // + ClassDef(FairGeoOldAsciiIo, 0) // }; -#endif /* !FAIRGEOOLDASCIIIO_H */ +#endif /* !FAIRGEOOLDASCIIIO_H */ diff --git a/geobase/FairGeoPcon.cxx b/geobase/FairGeoPcon.cxx index c2c3e11003..842b650829 100644 --- a/geobase/FairGeoPcon.cxx +++ b/geobase/FairGeoPcon.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ //*-- AUTHOR : Ilse Koenig @@ -31,139 +31,147 @@ /////////////////////////////////////////////////////////////////////////////// #include "FairGeoPcon.h" -#include "FairGeoTransform.h" // for FairGeoTransform -#include "FairGeoVector.h" // for FairGeoVector -#include "FairGeoVolume.h" // for FairGeoVolume +#include "FairGeoTransform.h" // for FairGeoTransform +#include "FairGeoVector.h" // for FairGeoVector +#include "FairGeoVolume.h" // for FairGeoVolume -#include // for TArrayD -#include // for TString - -#include // for printf, sprintf, sscanf -#include // for strlen -#include // for fstream, etc +#include // for TArrayD +#include // for TString #include +#include // for fstream, etc +#include // for printf, sprintf, sscanf +#include // for strlen -ClassImp(FairGeoPcon) +ClassImp(FairGeoPcon); FairGeoPcon::FairGeoPcon() - :FairGeoBasicShape() + : FairGeoBasicShape() { - // constructor - fName="PCON"; - nPoints=0; - nParam=0; + // constructor + fName = "PCON"; + nPoints = 0; + nParam = 0; } FairGeoPcon::~FairGeoPcon() { - // default destructor - delete param; - param=0; - delete center; - center=0; - delete position; - position=0; + // default destructor + delete param; + param = 0; + delete center; + center = 0; + delete position; + position = 0; } -Int_t FairGeoPcon::readPoints(std::fstream* pFile,FairGeoVolume* volu) +Int_t FairGeoPcon::readPoints(std::fstream* pFile, FairGeoVolume* volu) { - // reads the 'points' decribed above from ascii file and stores them in the - // array 'points' of the volume - // returns the number of points - if (!pFile) { return 0; } - Double_t x,y,z; - const Int_t maxbuf=155; - Text_t buf[maxbuf]; - pFile->getline(buf,maxbuf); - Int_t n; - sscanf(buf,"%i",&n); - if (n<=0) { return 0; } - nPoints=n+2; - if (volu->getNumPoints()!=nPoints) { volu->createPoints(nPoints); } - volu->setPoint(0,static_cast(n),0.0,0.0); - for(Int_t i=1; igetline(buf,maxbuf); - if (i!=1) { - sscanf(buf,"%lf%lf%lf",&x,&y,&z); - volu->setPoint(i,x,y,z); - } else { - sscanf(buf,"%lf%lf",&x,&y); - volu->setPoint(i,x,y,0.0); + // reads the 'points' decribed above from ascii file and stores them in the + // array 'points' of the volume + // returns the number of points + if (!pFile) { + return 0; + } + Double_t x, y, z; + const Int_t maxbuf = 155; + Text_t buf[maxbuf]; + pFile->getline(buf, maxbuf); + Int_t n; + sscanf(buf, "%i", &n); + if (n <= 0) { + return 0; + } + nPoints = n + 2; + if (volu->getNumPoints() != nPoints) { + volu->createPoints(nPoints); + } + volu->setPoint(0, static_cast(n), 0.0, 0.0); + for (Int_t i = 1; i < nPoints; i++) { + pFile->getline(buf, maxbuf); + if (i != 1) { + sscanf(buf, "%lf%lf%lf", &x, &y, &z); + volu->setPoint(i, x, y, z); + } else { + sscanf(buf, "%lf%lf", &x, &y); + volu->setPoint(i, x, y, 0.0); + } } - } - return nPoints; + return nPoints; } -Bool_t FairGeoPcon::writePoints(std::fstream* pFile,FairGeoVolume* volu) +Bool_t FairGeoPcon::writePoints(std::fstream* pFile, FairGeoVolume* volu) { - // writes the 'points' decribed above to ascii file - if (!pFile) { return kFALSE; } - Text_t buf[155]; - for(Int_t i=0; igetNumPoints(); i++) { - FairGeoVector& v=*(volu->getPoint(i)); - switch(i) { - case 0: - sprintf(buf,"%3i\n",static_cast(v(0))); - break; - case 1: - sprintf(buf,"%9.3f%10.3f\n",v(0),v(1)); - break; - default: - sprintf(buf,"%9.3f%10.3f%10.3f\n",v(0),v(1),v(2)); + // writes the 'points' decribed above to ascii file + if (!pFile) { + return kFALSE; } - pFile->write(buf,strlen(buf)); - } - return kTRUE; + Text_t buf[155]; + for (Int_t i = 0; i < volu->getNumPoints(); i++) { + FairGeoVector& v = *(volu->getPoint(i)); + switch (i) { + case 0: + sprintf(buf, "%3i\n", static_cast(v(0))); + break; + case 1: + sprintf(buf, "%9.3f%10.3f\n", v(0), v(1)); + break; + default: + sprintf(buf, "%9.3f%10.3f%10.3f\n", v(0), v(1), v(2)); + } + pFile->write(buf, strlen(buf)); + } + return kTRUE; } void FairGeoPcon::printPoints(FairGeoVolume* volu) { - // prints volume points to screen - for(Int_t i=0; igetNumPoints(); i++) { - FairGeoVector& v=*(volu->getPoint(i)); - switch(i) { - case 0: - printf("%3i\n",static_cast(v(0))); - break; - case 1: - printf("%9.3f%10.3f\n",v(0),v(1)); - break; - default: - printf("%9.3f%10.3f%10.3f\n",v(0),v(1),v(2)); + // prints volume points to screen + for (Int_t i = 0; i < volu->getNumPoints(); i++) { + FairGeoVector& v = *(volu->getPoint(i)); + switch (i) { + case 0: + printf("%3i\n", static_cast(v(0))); + break; + case 1: + printf("%9.3f%10.3f\n", v(0), v(1)); + break; + default: + printf("%9.3f%10.3f%10.3f\n", v(0), v(1), v(2)); + } } - } } TArrayD* FairGeoPcon::calcVoluParam(FairGeoVolume* volu) { - // calculates the parameters needed to create the shape PCON - Double_t fac=10.; - nPoints=volu->getNumPoints(); - nParam=(nPoints-1)*3; - if (param && param->GetSize()!=nParam) { - delete param; - param=0; - } - if (!param) { param=new TArrayD(nParam); } - FairGeoVector& v1=*(volu->getPoint(1)); - Int_t k=0; - param->AddAt(v1(0),k++); - param->AddAt(v1(1),k++); - param->AddAt((nPoints-2),k++); - for(Int_t i=2; igetPoint(i)); - param->AddAt(v(0)/fac,k++); - param->AddAt(v(1)/fac,k++); - param->AddAt(v(2)/fac,k++); - } - return param; + // calculates the parameters needed to create the shape PCON + Double_t fac = 10.; + nPoints = volu->getNumPoints(); + nParam = (nPoints - 1) * 3; + if (param && param->GetSize() != nParam) { + delete param; + param = 0; + } + if (!param) { + param = new TArrayD(nParam); + } + FairGeoVector& v1 = *(volu->getPoint(1)); + Int_t k = 0; + param->AddAt(v1(0), k++); + param->AddAt(v1(1), k++); + param->AddAt((nPoints - 2), k++); + for (Int_t i = 2; i < nPoints; i++) { + FairGeoVector& v = *(volu->getPoint(i)); + param->AddAt(v(0) / fac, k++); + param->AddAt(v(1) / fac, k++); + param->AddAt(v(2) / fac, k++); + } + return param; } -void FairGeoPcon::calcVoluPosition(FairGeoVolume*, - const FairGeoTransform& dTC,const FairGeoTransform& mTR) +void FairGeoPcon::calcVoluPosition(FairGeoVolume*, const FairGeoTransform& dTC, const FairGeoTransform& mTR) { - // calls the function posInMother(...) to calculate the position of the - // volume in its mother - center->clear(); - posInMother(dTC,mTR); + // calls the function posInMother(...) to calculate the position of the + // volume in its mother + center->clear(); + posInMother(dTC, mTR); } diff --git a/geobase/FairGeoPcon.h b/geobase/FairGeoPcon.h index c75bf02df3..797da2509f 100644 --- a/geobase/FairGeoPcon.h +++ b/geobase/FairGeoPcon.h @@ -1,17 +1,17 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRGEOPCON_H #define FAIRGEOPCON_H -#include "FairGeoBasicShape.h" // for FairGeoBasicShape +#include "FairGeoBasicShape.h" // for FairGeoBasicShape -#include // for fstream -#include // for FairGeoPcon::Class, Bool_t, etc +#include // for FairGeoPcon::Class, Bool_t, etc +#include // for fstream class FairGeoTransform; class FairGeoVolume; @@ -27,11 +27,11 @@ class FairGeoPcon : public FairGeoBasicShape FairGeoPcon(); ~FairGeoPcon(); TArrayD* calcVoluParam(FairGeoVolume*); - void calcVoluPosition(FairGeoVolume*, const FairGeoTransform&,const FairGeoTransform&); - Int_t readPoints(std::fstream*,FairGeoVolume*); - Bool_t writePoints(std::fstream*,FairGeoVolume*); + void calcVoluPosition(FairGeoVolume*, const FairGeoTransform&, const FairGeoTransform&); + Int_t readPoints(std::fstream*, FairGeoVolume*); + Bool_t writePoints(std::fstream*, FairGeoVolume*); void printPoints(FairGeoVolume* volu); - ClassDef(FairGeoPcon,0) // + ClassDef(FairGeoPcon, 0) // }; -#endif /* !FAIRGEOPCON_H */ +#endif /* !FAIRGEOPCON_H */ diff --git a/geobase/FairGeoPgon.cxx b/geobase/FairGeoPgon.cxx index 8b396a3e72..567eb325e7 100644 --- a/geobase/FairGeoPgon.cxx +++ b/geobase/FairGeoPgon.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ //*-- AUTHOR : Ilse Koenig @@ -31,119 +31,133 @@ /////////////////////////////////////////////////////////////////////////////// #include "FairGeoPgon.h" -#include "FairGeoTransform.h" // for FairGeoTransform -#include "FairGeoVector.h" // for FairGeoVector -#include "FairGeoVolume.h" // for FairGeoVolume +#include "FairGeoTransform.h" // for FairGeoTransform +#include "FairGeoVector.h" // for FairGeoVector +#include "FairGeoVolume.h" // for FairGeoVolume -#include // for TArrayD -#include // for TString - -#include // for printf, sprintf, sscanf -#include // for strlen -#include // for basic_ostream::write +#include // for TArrayD +#include // for TString #include +#include // for basic_ostream::write +#include // for printf, sprintf, sscanf +#include // for strlen -ClassImp(FairGeoPgon) +ClassImp(FairGeoPgon); FairGeoPgon::FairGeoPgon() - :FairGeoBasicShape() + : FairGeoBasicShape() { - // constructor - fName="PGON"; - nPoints=0; - nParam=0; + // constructor + fName = "PGON"; + nPoints = 0; + nParam = 0; } FairGeoPgon::~FairGeoPgon() { - // default destructor - delete param; - param=0; - delete center; - center=0; - delete position; - position=0; + // default destructor + delete param; + param = 0; + delete center; + center = 0; + delete position; + position = 0; } -Int_t FairGeoPgon::readPoints(std::fstream* pFile,FairGeoVolume* volu) +Int_t FairGeoPgon::readPoints(std::fstream* pFile, FairGeoVolume* volu) { - // reads the 'points' decribed above from ascii file and stores them in the - // array 'points' of the volume - // returns the number of points - if (!pFile) { return 0; } - Double_t x,y,z; - const Int_t maxbuf=155; - Text_t buf[maxbuf]; - pFile->getline(buf,maxbuf); - Int_t n; - sscanf(buf,"%i",&n); - if (n<=0) { return 0; } - nPoints=n+2; - if (volu->getNumPoints()!=nPoints) { volu->createPoints(nPoints); } - volu->setPoint(0,static_cast(n),0.0,0.0); - for(Int_t i=1; igetline(buf,maxbuf); - sscanf(buf,"%lf%lf%lf",&x,&y,&z); - volu->setPoint(i,x,y,z); - } - return nPoints; + // reads the 'points' decribed above from ascii file and stores them in the + // array 'points' of the volume + // returns the number of points + if (!pFile) { + return 0; + } + Double_t x, y, z; + const Int_t maxbuf = 155; + Text_t buf[maxbuf]; + pFile->getline(buf, maxbuf); + Int_t n; + sscanf(buf, "%i", &n); + if (n <= 0) { + return 0; + } + nPoints = n + 2; + if (volu->getNumPoints() != nPoints) { + volu->createPoints(nPoints); + } + volu->setPoint(0, static_cast(n), 0.0, 0.0); + for (Int_t i = 1; i < nPoints; i++) { + pFile->getline(buf, maxbuf); + sscanf(buf, "%lf%lf%lf", &x, &y, &z); + volu->setPoint(i, x, y, z); + } + return nPoints; } -Bool_t FairGeoPgon::writePoints(std::fstream* pFile,FairGeoVolume* volu) +Bool_t FairGeoPgon::writePoints(std::fstream* pFile, FairGeoVolume* volu) { - // writes the 'points' decribed above to ascii file - if (!pFile) { return kFALSE; } - Text_t buf[155]; - for(Int_t i=0; igetNumPoints(); i++) { - FairGeoVector& v=*(volu->getPoint(i)); - if (i!=0) { sprintf(buf,"%9.3f%10.3f%10.3f\n",v(0),v(1),v(2)); } - else { sprintf(buf,"%3i\n",static_cast(v(0))); } - pFile->write(buf,strlen(buf)); - } - return kTRUE; + // writes the 'points' decribed above to ascii file + if (!pFile) { + return kFALSE; + } + Text_t buf[155]; + for (Int_t i = 0; i < volu->getNumPoints(); i++) { + FairGeoVector& v = *(volu->getPoint(i)); + if (i != 0) { + sprintf(buf, "%9.3f%10.3f%10.3f\n", v(0), v(1), v(2)); + } else { + sprintf(buf, "%3i\n", static_cast(v(0))); + } + pFile->write(buf, strlen(buf)); + } + return kTRUE; } void FairGeoPgon::printPoints(FairGeoVolume* volu) { - // prints volume points to screen - for(Int_t i=0; igetNumPoints(); i++) { - FairGeoVector& v=*(volu->getPoint(i)); - if (i!=0) { printf("%9.3f%10.3f%10.3f\n",v(0),v(1),v(2)); } - else { printf("%3i\n",static_cast(v(0))); } - } + // prints volume points to screen + for (Int_t i = 0; i < volu->getNumPoints(); i++) { + FairGeoVector& v = *(volu->getPoint(i)); + if (i != 0) { + printf("%9.3f%10.3f%10.3f\n", v(0), v(1), v(2)); + } else { + printf("%3i\n", static_cast(v(0))); + } + } } TArrayD* FairGeoPgon::calcVoluParam(FairGeoVolume* volu) { - // calculates the parameters needed to create the shape PGON - Double_t fac=10.; - nPoints=volu->getNumPoints(); - nParam=nPoints*3-2; - if (param && param->GetSize()!=nParam) { - delete param; - param=0; - } - if (!param) { param=new TArrayD(nParam); } - FairGeoVector& v1=*(volu->getPoint(1)); - Int_t k=0; - param->AddAt(v1(0),k++); - param->AddAt(v1(1),k++); - param->AddAt(v1(2),k++); - param->AddAt((nPoints-2),k++); - for (Int_t i=2; igetPoint(i)); - param->AddAt(v(0)/fac,k++); - param->AddAt(v(1)/fac,k++); - param->AddAt(v(2)/fac,k++); - } - return param; + // calculates the parameters needed to create the shape PGON + Double_t fac = 10.; + nPoints = volu->getNumPoints(); + nParam = nPoints * 3 - 2; + if (param && param->GetSize() != nParam) { + delete param; + param = 0; + } + if (!param) { + param = new TArrayD(nParam); + } + FairGeoVector& v1 = *(volu->getPoint(1)); + Int_t k = 0; + param->AddAt(v1(0), k++); + param->AddAt(v1(1), k++); + param->AddAt(v1(2), k++); + param->AddAt((nPoints - 2), k++); + for (Int_t i = 2; i < nPoints; i++) { + FairGeoVector& v = *(volu->getPoint(i)); + param->AddAt(v(0) / fac, k++); + param->AddAt(v(1) / fac, k++); + param->AddAt(v(2) / fac, k++); + } + return param; } -void FairGeoPgon::calcVoluPosition(FairGeoVolume*, - const FairGeoTransform& dTC,const FairGeoTransform& mTR) +void FairGeoPgon::calcVoluPosition(FairGeoVolume*, const FairGeoTransform& dTC, const FairGeoTransform& mTR) { - // calls the function posInMother(...) to calculate the position of the - // volume in its mother - center->clear(); - posInMother(dTC,mTR); + // calls the function posInMother(...) to calculate the position of the + // volume in its mother + center->clear(); + posInMother(dTC, mTR); } diff --git a/geobase/FairGeoPgon.h b/geobase/FairGeoPgon.h index b06c26ec55..638f9737b2 100644 --- a/geobase/FairGeoPgon.h +++ b/geobase/FairGeoPgon.h @@ -1,18 +1,17 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRGEOPGON_H #define FAIRGEOPGON_H -#include "FairGeoBasicShape.h" // for FairGeoBasicShape +#include "FairGeoBasicShape.h" // for FairGeoBasicShape -#include // for FairGeoPcon::Class, Bool_t, etc - -#include // for fstream +#include // for FairGeoPcon::Class, Bool_t, etc +#include // for fstream class FairGeoTransform; class FairGeoVolume; @@ -28,11 +27,11 @@ class FairGeoPgon : public FairGeoBasicShape FairGeoPgon(); ~FairGeoPgon(); TArrayD* calcVoluParam(FairGeoVolume*); - void calcVoluPosition(FairGeoVolume*, const FairGeoTransform&,const FairGeoTransform&); - Int_t readPoints(std::fstream*,FairGeoVolume*); - Bool_t writePoints(std::fstream*,FairGeoVolume*); + void calcVoluPosition(FairGeoVolume*, const FairGeoTransform&, const FairGeoTransform&); + Int_t readPoints(std::fstream*, FairGeoVolume*); + Bool_t writePoints(std::fstream*, FairGeoVolume*); void printPoints(FairGeoVolume* volu); - ClassDef(FairGeoPgon,0) // + ClassDef(FairGeoPgon, 0) // }; -#endif /* !FAIRGEOPGON_H */ +#endif /* !FAIRGEOPGON_H */ diff --git a/geobase/FairGeoRootBuilder.cxx b/geobase/FairGeoRootBuilder.cxx index 785611d3da..932c6550ca 100644 --- a/geobase/FairGeoRootBuilder.cxx +++ b/geobase/FairGeoRootBuilder.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ //*-- AUTHOR : Ilse Koenig @@ -16,176 +16,195 @@ /////////////////////////////////////////////////////////////////////////////// #include "FairGeoRootBuilder.h" -#include "FairGeoMedium.h" // for FairGeoMedium -#include "FairGeoNode.h" // for FairGeoNode -#include "FairGeoRotation.h" // for FairGeoRotation -#include "FairGeoTransform.h" // for FairGeoTransform -#include "FairGeoVector.h" // for FairGeoVector +#include "FairGeoMedium.h" // for FairGeoMedium +#include "FairGeoNode.h" // for FairGeoNode +#include "FairGeoRotation.h" // for FairGeoRotation +#include "FairGeoTransform.h" // for FairGeoTransform +#include "FairGeoVector.h" // for FairGeoVector -#include // for TArrayD -#include // for TGeoManager -#include // for TGeoMixture, TGeoMaterial -#include // for TGeoCombiTrans, etc -#include // for TGeoMedium -#include // for TGeoVolume, etc -#include // for TString - -#include // for sprintf +#include // for TArrayD +#include // for TGeoManager +#include // for TGeoMixture, TGeoMaterial +#include // for TGeoCombiTrans, etc +#include // for TGeoMedium +#include // for TGeoVolume, etc +#include // for TString +#include // for sprintf #include -ClassImp(FairGeoRootBuilder) +ClassImp(FairGeoRootBuilder); FairGeoRootBuilder::FairGeoRootBuilder() - : FairGeoBuilder(), - geoManager(nullptr) + : FairGeoBuilder() + , geoManager(nullptr) { - // Default constructor + // Default constructor } -FairGeoRootBuilder::FairGeoRootBuilder(const char* name,const char* title) - : FairGeoBuilder(name,title), - geoManager(nullptr) +FairGeoRootBuilder::FairGeoRootBuilder(const char* name, const char* title) + : FairGeoBuilder(name, title) + , geoManager(nullptr) { - // Constructor + // Constructor } Bool_t FairGeoRootBuilder::createNode(FairGeoNode* volu, Int_t hadFormat) { - // Creates the volume - if (!geoManager||!volu) { return kFALSE; } - // volu->print(); + // Creates the volume + if (!geoManager || !volu) { + return kFALSE; + } + // volu->print(); - TString nodeName= volu->GetName(); - if ( hadFormat == 1 ) { - volu->setHadFormat( hadFormat ); - nodeName=nodeName(0,4); - } else { - nodeName = (volu->GetName()); - Ssiz_t l=nodeName.Last('#'); - if (l>0) { nodeName=nodeName(0,l); } - } + TString nodeName = volu->GetName(); + if (hadFormat == 1) { + volu->setHadFormat(hadFormat); + nodeName = nodeName(0, 4); + } else { + nodeName = (volu->GetName()); + Ssiz_t l = nodeName.Last('#'); + if (l > 0) { + nodeName = nodeName(0, l); + } + } - FairGeoNode* mother=volu->getMotherNode(); - if (!mother&&!volu->isTopNode()) { - Error("createNode","Mother volume of %s not found\n",volu->GetName()); - return kFALSE; - } + FairGeoNode* mother = volu->getMotherNode(); + if (!mother && !volu->isTopNode()) { + Error("createNode", "Mother volume of %s not found\n", volu->GetName()); + return kFALSE; + } - TGeoVolume* rv=0; - FairGeoNode* cv=volu->getCopyNode(); -// if (cv) cout<<"Copy of "<GetName()<getRootVolume(); } - if (!rv) { - FairGeoMedium* lmedium=volu->getMedium(); - Int_t lnMed=lmedium->getMediumIndex(); - if (lnMed<=0) { lnMed=createMedium(lmedium); } - if (lnMed<=0) { return kFALSE; } - TArrayD* par=volu->getParameters(); - //for (Int_t k=0;kGetSize();k++) cout<At(k)<<" "; - // cout<getShape() << endl; - if (volu->getShape().Contains("TORUS")) { // Torus is missing in the TGeoManager::Volume - // this should solve the problem tell it is implimented in root - TGeoMedium* medium =geoManager->GetMedium(lnMed); - rv = geoManager->MakeTorus(nodeName.Data(),medium,par->At(0),par->At(1),par->At(2),par->At(3),par->At(4)); - // cout << "Create Torus" << nodeName.Data() << endl; - } else if (volu->getShape().Contains("ASSEMBLY")) { - rv=geoManager->MakeVolumeAssembly(nodeName.Data()); + TGeoVolume* rv = 0; + FairGeoNode* cv = volu->getCopyNode(); + // if (cv) cout<<"Copy of "<GetName()<getRootVolume(); + } + if (!rv) { + FairGeoMedium* lmedium = volu->getMedium(); + Int_t lnMed = lmedium->getMediumIndex(); + if (lnMed <= 0) { + lnMed = createMedium(lmedium); + } + if (lnMed <= 0) { + return kFALSE; + } + TArrayD* par = volu->getParameters(); + // for (Int_t k=0;kGetSize();k++) cout<At(k)<<" "; + // cout<getShape() << endl; + if (volu->getShape().Contains("TORUS")) { // Torus is missing in the TGeoManager::Volume + // this should solve the problem tell it is implimented in root + TGeoMedium* medium = geoManager->GetMedium(lnMed); + rv = geoManager->MakeTorus( + nodeName.Data(), medium, par->At(0), par->At(1), par->At(2), par->At(3), par->At(4)); + // cout << "Create Torus" << nodeName.Data() << endl; + } else if (volu->getShape().Contains("ASSEMBLY")) { + rv = geoManager->MakeVolumeAssembly(nodeName.Data()); - } else { - rv=geoManager->Volume(nodeName.Data(),volu->getShape().Data(), - lnMed,par->GetArray(),par->GetSize()); + } else { + rv = geoManager->Volume(nodeName.Data(), volu->getShape().Data(), lnMed, par->GetArray(), par->GetSize()); + } + volu->setCreated(); + if (volu->isModule() && cv) { + cv->setCreated(); + cv->setRootVolume(rv); + cv->getPosition(); + } } - volu->setCreated(); - if (volu->isModule()&&cv) { - cv->setCreated(); - cv->setRootVolume(rv); - cv->getPosition(); + if (!rv) { + return kFALSE; } - } - if (!rv) { return kFALSE; } - volu->setRootVolume(rv); - if (volu->isTopNode()) { - geoManager->SetTopVolume(rv); - } else { - FairGeoTransform* trans=volu->getPosition(); - const FairGeoRotation& rot=trans->getRotMatrix(); - const FairGeoVector& pos=trans->getTransVector(); - TGeoMatrix* tr=0; - if ((const_cast(rot)).isUnitMatrix()) { - tr=new TGeoTranslation(pos.getX(),pos.getY(),pos.getZ()); + volu->setRootVolume(rv); + if (volu->isTopNode()) { + geoManager->SetTopVolume(rv); } else { - nRot++; - char b[10]; - sprintf(b,"R%i",nRot); - TGeoRotation* r=new TGeoRotation(b); - Double_t a[9]; - for (Int_t i=0; i<9; i++) { a[i]=rot(i); } - r->SetMatrix(a); - tr=new TGeoCombiTrans(pos.getX(),pos.getY(),pos.getZ(),r); + FairGeoTransform* trans = volu->getPosition(); + const FairGeoRotation& rot = trans->getRotMatrix(); + const FairGeoVector& pos = trans->getTransVector(); + TGeoMatrix* tr = 0; + if ((const_cast(rot)).isUnitMatrix()) { + tr = new TGeoTranslation(pos.getX(), pos.getY(), pos.getZ()); + } else { + nRot++; + char b[10]; + sprintf(b, "R%i", nRot); + TGeoRotation* r = new TGeoRotation(b); + Double_t a[9]; + for (Int_t i = 0; i < 9; i++) { + a[i] = rot(i); + } + r->SetMatrix(a); + tr = new TGeoCombiTrans(pos.getX(), pos.getY(), pos.getZ(), r); + } + TGeoVolume* mo = mother->getRootVolume(); + if (!mo) { + return kFALSE; + } + mo->AddNode(rv, volu->getCopyNo(), tr); } - TGeoVolume* mo=mother->getRootVolume(); - if (!mo) { return kFALSE; } - mo->AddNode(rv,volu->getCopyNo(),tr); - } - return kTRUE; + return kTRUE; } Int_t FairGeoRootBuilder::createMedium(FairGeoMedium* med) { - // Creates the medium - if (!geoManager&&!med) { return 0; } - Int_t nComp=med->getNComponents(); - Int_t weightFac=med->getWeightFac(); - TGeoMaterial* material=0; - Double_t p[3]; - if (nComp==1) { - med->getComponent(0,p); - material=new TGeoMaterial(med->GetName(),p[0],p[1],med->getDensity(), - med->getRadiationLength()); - // Interaction length not defined!!!!!! - } else { - material=new TGeoMixture(med->GetName(),nComp,med->getDensity()); - Double_t sumWeights=0.; - if (weightFac<0) { - for(Int_t i=0; igetComponent(i,p); - sumWeights+=p[0]*p[2]; - } + // Creates the medium + if (!geoManager && !med) { + return 0; + } + Int_t nComp = med->getNComponents(); + Int_t weightFac = med->getWeightFac(); + TGeoMaterial* material = 0; + Double_t p[3]; + if (nComp == 1) { + med->getComponent(0, p); + material = new TGeoMaterial(med->GetName(), p[0], p[1], med->getDensity(), med->getRadiationLength()); + // Interaction length not defined!!!!!! + } else { + material = new TGeoMixture(med->GetName(), nComp, med->getDensity()); + Double_t sumWeights = 0.; + if (weightFac < 0) { + for (Int_t i = 0; i < nComp; i++) { + med->getComponent(i, p); + sumWeights += p[0] * p[2]; + } + } + for (Int_t i = 0; i < nComp; i++) { + med->getComponent(i, p); + if (weightFac > 0) { + (static_cast(material))->DefineElement(i, p[0], p[1], p[2]); + } else { + (static_cast(material))->DefineElement(i, p[0], p[1], p[0] * p[2] / sumWeights); + } + } } - for(Int_t i=0; igetComponent(i,p); - if (weightFac>0) { - (static_cast(material))->DefineElement(i,p[0],p[1],p[2]); - } else { - (static_cast(material))->DefineElement(i,p[0],p[1],p[0]*p[2]/sumWeights); - } + nMed++; + med->setMediumIndex(nMed); + Double_t mp[10]; + med->getMediumPar(mp); + TGeoMedium* medium = new TGeoMedium(med->GetName(), nMed, material, mp); + if (medium) { + return nMed; + } else { + return 0; } - } - nMed++; - med->setMediumIndex(nMed); - Double_t mp[10]; - med->getMediumPar(mp); - TGeoMedium* medium=new TGeoMedium(med->GetName(),nMed,material,mp); - if (medium) { return nMed; } - else { return 0; } } void FairGeoRootBuilder::finalize() { - // Closes the geometry input in ROOT and draws the cave - if (geoManager) { - geoManager->CloseGeometry(); - geoManager->SetVisLevel(5); - geoManager->GetTopVolume()->Draw(); - } + // Closes the geometry input in ROOT and draws the cave + if (geoManager) { + geoManager->CloseGeometry(); + geoManager->SetVisLevel(5); + geoManager->GetTopVolume()->Draw(); + } } void FairGeoRootBuilder::checkOverlaps(Double_t ovlp) { - // Checks the geometry for overlaps and extrusions wit a default precision of 1 micron - if (geoManager) { - geoManager->CheckOverlaps(ovlp,"SAME"); - geoManager->PrintOverlaps(); - } + // Checks the geometry for overlaps and extrusions wit a default precision of 1 micron + if (geoManager) { + geoManager->CheckOverlaps(ovlp, "SAME"); + geoManager->PrintOverlaps(); + } } diff --git a/geobase/FairGeoRootBuilder.h b/geobase/FairGeoRootBuilder.h index bf5ef98910..365581faa5 100644 --- a/geobase/FairGeoRootBuilder.h +++ b/geobase/FairGeoRootBuilder.h @@ -1,16 +1,16 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRGEOROOTBUILDER_H #define FAIRGEOROOTBUILDER_H -#include "FairGeoBuilder.h" // for FairGeoBuilder +#include "FairGeoBuilder.h" // for FairGeoBuilder -#include // for FairGeoRootBuilder::Class, etc +#include // for FairGeoRootBuilder::Class, etc class FairGeoMedium; class FairGeoNode; @@ -27,18 +27,18 @@ class FairGeoRootBuilder : public FairGeoBuilder FairGeoRootBuilder& operator=(const FairGeoRootBuilder&); protected: - TGeoManager* geoManager; // ROOT geometry manager + TGeoManager* geoManager; // ROOT geometry manager public: FairGeoRootBuilder(); - FairGeoRootBuilder(const char*,const char*); + FairGeoRootBuilder(const char*, const char*); ~FairGeoRootBuilder() {} - void setGeoManager(TGeoManager* me) {geoManager=me;} - Bool_t createNode(FairGeoNode*, Int_t hadFormat=0); + void setGeoManager(TGeoManager* me) { geoManager = me; } + Bool_t createNode(FairGeoNode*, Int_t hadFormat = 0); Int_t createMedium(FairGeoMedium*); void finalize(); - void checkOverlaps(Double_t ovlp=0.0001); - ClassDef(FairGeoRootBuilder,0) // + void checkOverlaps(Double_t ovlp = 0.0001); + ClassDef(FairGeoRootBuilder, 0) // }; #endif /* !FAIRGEOROOTBUILDER_H */ diff --git a/geobase/FairGeoRotation.cxx b/geobase/FairGeoRotation.cxx index 6a0843eae2..48821b0c61 100644 --- a/geobase/FairGeoRotation.cxx +++ b/geobase/FairGeoRotation.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ //*-- AUTHOR : Ilse Koenig @@ -74,60 +74,64 @@ /////////////////////////////////////////////////////////////////////////////// #include "FairGeoRotation.h" -#include // for Cos, Sin -#include // for TRotMatrix +#include // for Cos, Sin +#include // for TRotMatrix -ClassImp(FairGeoRotation) +ClassImp(FairGeoRotation); -FairGeoRotation::FairGeoRotation(const Double_t a,const Double_t b, const Double_t c) - :TObject() +FairGeoRotation::FairGeoRotation(const Double_t a, const Double_t b, const Double_t c) + : TObject() { - // constructor taking three Euler angles - setEulerAngles(a,b,c); + // constructor taking three Euler angles + setEulerAngles(a, b, c); } -void FairGeoRotation::setEulerAngles(const Double_t a,const Double_t b, const Double_t c) +void FairGeoRotation::setEulerAngles(const Double_t a, const Double_t b, const Double_t c) { - // sets the matrix calculating the values from the given Euler angles - const double deg2rad=0.01745329252; - Double_t s0=TMath::Sin(a*deg2rad); - Double_t c0=TMath::Cos(a*deg2rad); - Double_t s1=TMath::Sin(b*deg2rad); - Double_t c1=TMath::Cos(b*deg2rad); - Double_t s2=TMath::Sin(c*deg2rad); - Double_t c2=TMath::Cos(c*deg2rad); - rot[0]=c0*c1*c2 - s0*s2; - rot[1]=-c0*c1*s2 - s0*c2; - rot[2]=c0*s1; - rot[3]=s0*c1*c2 + c0*s2; - rot[4]=c0*c2 - s0*c1*s2; - rot[5]=s0*s1; - rot[6]=-s1*c2; - rot[7]=s1*s2; - rot[8]=c1; + // sets the matrix calculating the values from the given Euler angles + const double deg2rad = 0.01745329252; + Double_t s0 = TMath::Sin(a * deg2rad); + Double_t c0 = TMath::Cos(a * deg2rad); + Double_t s1 = TMath::Sin(b * deg2rad); + Double_t c1 = TMath::Cos(b * deg2rad); + Double_t s2 = TMath::Sin(c * deg2rad); + Double_t c2 = TMath::Cos(c * deg2rad); + rot[0] = c0 * c1 * c2 - s0 * s2; + rot[1] = -c0 * c1 * s2 - s0 * c2; + rot[2] = c0 * s1; + rot[3] = s0 * c1 * c2 + c0 * s2; + rot[4] = c0 * c2 - s0 * c1 * s2; + rot[5] = s0 * s1; + rot[6] = -s1 * c2; + rot[7] = s1 * s2; + rot[8] = c1; } Double_t FairGeoRotation::diff2(const FairGeoRotation& r) const { - // calculates the square of the difference between 2 matrices - Double_t s=0; - for(Int_t i=0; i<9; i++) { - Double_t d=rot[i]-r(i); - s+=d*d; - } - return s; + // calculates the square of the difference between 2 matrices + Double_t s = 0; + for (Int_t i = 0; i < 9; i++) { + Double_t d = rot[i] - r(i); + s += d * d; + } + return s; } -TRotMatrix* FairGeoRotation::createTRotMatrix(const Text_t* name,const Text_t* title) +TRotMatrix* FairGeoRotation::createTRotMatrix(const Text_t* name, const Text_t* title) { - // creates a TRotMatrix - // (uses a new() operator and the user has to take care to free the memory) - TRotMatrix* t=0; - if (isUnitMatrix()==kTRUE) { return t; } - Double_t a[9]; - for(Int_t i=0; i<3; i++) { - for(Int_t j=0; j<3; j++) { a[j+3*i]=rot[i+3*j]; } - } - t=new TRotMatrix(name,title,a); - return t; + // creates a TRotMatrix + // (uses a new() operator and the user has to take care to free the memory) + TRotMatrix* t = 0; + if (isUnitMatrix() == kTRUE) { + return t; + } + Double_t a[9]; + for (Int_t i = 0; i < 3; i++) { + for (Int_t j = 0; j < 3; j++) { + a[j + 3 * i] = rot[i + 3 * j]; + } + } + t = new TRotMatrix(name, title, a); + return t; } diff --git a/geobase/FairGeoRotation.h b/geobase/FairGeoRotation.h index 774642aa3d..4a1cb89c26 100644 --- a/geobase/FairGeoRotation.h +++ b/geobase/FairGeoRotation.h @@ -1,20 +1,18 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRGEOROTATION_H #define FAIRGEOROTATION_H -#include // for TObject +#include "FairGeoVector.h" // for FairGeoVector -#include "FairGeoVector.h" // for FairGeoVector - -#include // for Double_t, Int_t, Bool_t, etc - -#include // for operator<<, cout, ostream, etc +#include // for Double_t, Int_t, Bool_t, etc +#include // for TObject +#include // for operator<<, cout, ostream, etc class TRotMatrix; @@ -31,181 +29,197 @@ class FairGeoRotation : public TObject inline FairGeoRotation(); inline FairGeoRotation(const FairGeoRotation&); inline FairGeoRotation(const Double_t*); - FairGeoRotation(const Double_t,const Double_t,const Double_t); + FairGeoRotation(const Double_t, const Double_t, const Double_t); ~FairGeoRotation() {} inline void setMatrix(const Double_t*); inline void setMatrix(const Float_t*); - void setEulerAngles(const Double_t,const Double_t,const Double_t); - inline void setElement(const Double_t,const Int_t); - inline Double_t operator () (Int_t) const; - inline FairGeoRotation& operator = (const FairGeoRotation&); - inline Bool_t operator == (const FairGeoRotation&); - inline Bool_t operator != (const FairGeoRotation&); - inline FairGeoVector operator * (const FairGeoVector&) const; - inline FairGeoRotation operator * (const FairGeoRotation&) const; - inline FairGeoRotation& operator *= (const FairGeoRotation&); + void setEulerAngles(const Double_t, const Double_t, const Double_t); + inline void setElement(const Double_t, const Int_t); + inline Double_t operator()(Int_t) const; + inline FairGeoRotation& operator=(const FairGeoRotation&); + inline Bool_t operator==(const FairGeoRotation&); + inline Bool_t operator!=(const FairGeoRotation&); + inline FairGeoVector operator*(const FairGeoVector&)const; + inline FairGeoRotation operator*(const FairGeoRotation&)const; + inline FairGeoRotation& operator*=(const FairGeoRotation&); inline FairGeoRotation& transform(const FairGeoRotation&); inline Bool_t isUnitMatrix(); inline FairGeoRotation inverse() const; inline FairGeoRotation& invert(); inline Double_t determinant() const; Double_t diff2(const FairGeoRotation&) const; - inline Double_t getElement(Int_t i,Int_t j) const; + inline Double_t getElement(Int_t i, Int_t j) const; inline void setUnitMatrix(); inline void setZero(); inline void print() const; - TRotMatrix* createTRotMatrix(const Text_t* name="",const Text_t* title=""); + TRotMatrix* createTRotMatrix(const Text_t* name = "", const Text_t* title = ""); - ClassDef(FairGeoRotation,1) // + ClassDef(FairGeoRotation, 1) // }; // -------------------- inlines --------------------------- inline FairGeoRotation::FairGeoRotation() - :TObject() + : TObject() { - rot[0]=rot[4]=rot[8]=1.; - rot[1]=rot[2]=rot[3]=rot[5]=rot[6]=rot[7]=0.; + rot[0] = rot[4] = rot[8] = 1.; + rot[1] = rot[2] = rot[3] = rot[5] = rot[6] = rot[7] = 0.; } -inline Double_t FairGeoRotation::operator () (Int_t i) const +inline Double_t FairGeoRotation::operator()(Int_t i) const { - if (i>=0 && i<9) { return rot[i]; } - Error("operator()","bad index"); - return 0; + if (i >= 0 && i < 9) { + return rot[i]; + } + Error("operator()", "bad index"); + return 0; } inline FairGeoRotation::FairGeoRotation(const FairGeoRotation& r) - :TObject(r) + : TObject(r) { - for(Int_t i=0; i<9; i++) { rot[i]=r(i); } + for (Int_t i = 0; i < 9; i++) { + rot[i] = r(i); + } } inline FairGeoRotation::FairGeoRotation(const Double_t* a) - :TObject() + : TObject() { - for(Int_t i=0; i<9; i++) { rot[i]=a[i]; } + for (Int_t i = 0; i < 9; i++) { + rot[i] = a[i]; + } } inline void FairGeoRotation::setMatrix(const Double_t* a) { - for(Int_t i=0; i<9; i++) { rot[i]=a[i]; } + for (Int_t i = 0; i < 9; i++) { + rot[i] = a[i]; + } } inline void FairGeoRotation::setMatrix(const Float_t* a) { - for(Int_t i=0; i<9; i++) { rot[i]=a[i]; } + for (Int_t i = 0; i < 9; i++) { + rot[i] = a[i]; + } } inline void FairGeoRotation::setElement(const Double_t a, const Int_t i) { - if (i<9) { rot[i]=a; } + if (i < 9) { + rot[i] = a; + } } -inline Double_t FairGeoRotation::getElement(Int_t i,Int_t j) const -{ - return rot[i*3+j]; -} +inline Double_t FairGeoRotation::getElement(Int_t i, Int_t j) const { return rot[i * 3 + j]; } -inline FairGeoRotation& FairGeoRotation::operator = (const FairGeoRotation& r) +inline FairGeoRotation& FairGeoRotation::operator=(const FairGeoRotation& r) { - for(Int_t i=0; i<9; i++) { rot[i]=r(i); } - return *this; + for (Int_t i = 0; i < 9; i++) { + rot[i] = r(i); + } + return *this; } -inline Bool_t FairGeoRotation::operator == (const FairGeoRotation& r) +inline Bool_t FairGeoRotation::operator==(const FairGeoRotation& r) { - Int_t i=0; - while (i<9) { - if (rot[i]!=r(i)) { return kFALSE; } - i++; - } - return kTRUE; + Int_t i = 0; + while (i < 9) { + if (rot[i] != r(i)) { + return kFALSE; + } + i++; + } + return kTRUE; } -inline Bool_t FairGeoRotation::operator != (const FairGeoRotation& r) +inline Bool_t FairGeoRotation::operator!=(const FairGeoRotation& r) { - Int_t i=0; - while (i<9) { - if (rot[i]!=r(i)) { return kTRUE; } - i++; - } - return kFALSE; + Int_t i = 0; + while (i < 9) { + if (rot[i] != r(i)) { + return kTRUE; + } + i++; + } + return kFALSE; } -inline FairGeoVector FairGeoRotation::operator * (const FairGeoVector& v) const +inline FairGeoVector FairGeoRotation::operator*(const FairGeoVector& v) const { - return FairGeoVector(rot[0]*v(0)+rot[1]*v(1)+rot[2]*v(2), - rot[3]*v(0)+rot[4]*v(1)+rot[5]*v(2), - rot[6]*v(0)+rot[7]*v(1)+rot[8]*v(2)); + return FairGeoVector(rot[0] * v(0) + rot[1] * v(1) + rot[2] * v(2), + rot[3] * v(0) + rot[4] * v(1) + rot[5] * v(2), + rot[6] * v(0) + rot[7] * v(1) + rot[8] * v(2)); } -inline FairGeoRotation FairGeoRotation::operator * (const FairGeoRotation& r) const +inline FairGeoRotation FairGeoRotation::operator*(const FairGeoRotation& r) const { - Double_t a[9]; - for(Int_t kk=0; kk<9; kk++) { a[kk]=0; } - for(Int_t i=0; i<3; i++) { - for(Int_t j=0; j<3; j++) { - Int_t n=3*i+j; - for(Int_t k=0; k<3; k++) { a[n]+=rot[3*i+k]*r(3*k+j); } + Double_t a[9]; + for (Int_t kk = 0; kk < 9; kk++) { + a[kk] = 0; + } + for (Int_t i = 0; i < 3; i++) { + for (Int_t j = 0; j < 3; j++) { + Int_t n = 3 * i + j; + for (Int_t k = 0; k < 3; k++) { + a[n] += rot[3 * i + k] * r(3 * k + j); + } + } } - } - return FairGeoRotation(&a[0]); + return FairGeoRotation(&a[0]); } -inline FairGeoRotation& FairGeoRotation::operator *= (const FairGeoRotation& r) -{ - return *this=operator * (r); -} +inline FairGeoRotation& FairGeoRotation::operator*=(const FairGeoRotation& r) { return *this = operator*(r); } -inline FairGeoRotation& FairGeoRotation::transform(const FairGeoRotation& r) -{ - return *this=r*(*this); -} +inline FairGeoRotation& FairGeoRotation::transform(const FairGeoRotation& r) { return *this = r * (*this); } inline Bool_t FairGeoRotation::isUnitMatrix() { - return (rot[0]==1. && rot[1]==0. && rot[2]==0. && - rot[3]==0. && rot[4]==1. && rot[5]==0. && - rot[6]==0. && rot[7]==0. && rot[8]==1.) ? kTRUE : kFALSE; + return (rot[0] == 1. && rot[1] == 0. && rot[2] == 0. && rot[3] == 0. && rot[4] == 1. && rot[5] == 0. && rot[6] == 0. + && rot[7] == 0. && rot[8] == 1.) + ? kTRUE + : kFALSE; } inline FairGeoRotation FairGeoRotation::inverse() const { - Double_t a[9]; - for(Int_t i=0; i<3; i++) { - for(Int_t j=0; j<3; j++) { a[j+3*i]=rot[i+3*j]; } - } - return FairGeoRotation(a); + Double_t a[9]; + for (Int_t i = 0; i < 3; i++) { + for (Int_t j = 0; j < 3; j++) { + a[j + 3 * i] = rot[i + 3 * j]; + } + } + return FairGeoRotation(a); } -inline FairGeoRotation& FairGeoRotation::invert() -{ - return *this=inverse(); -} +inline FairGeoRotation& FairGeoRotation::invert() { return *this = inverse(); } inline Double_t FairGeoRotation::determinant() const { - return rot[0]*(rot[4]*rot[8]-rot[7]*rot[5]) - -rot[3]*(rot[1]*rot[8]-rot[7]*rot[2]) - +rot[6]*(rot[1]*rot[5]-rot[4]*rot[2]); + return rot[0] * (rot[4] * rot[8] - rot[7] * rot[5]) - rot[3] * (rot[1] * rot[8] - rot[7] * rot[2]) + + rot[6] * (rot[1] * rot[5] - rot[4] * rot[2]); } inline void FairGeoRotation::setUnitMatrix() { - rot[0]=rot[4]=rot[8]=1.; - rot[1]=rot[2]=rot[3]=rot[5]=rot[6]=rot[7]=0.; + rot[0] = rot[4] = rot[8] = 1.; + rot[1] = rot[2] = rot[3] = rot[5] = rot[6] = rot[7] = 0.; } inline void FairGeoRotation::setZero() { - for(Int_t i=0; i<9; i++) { rot[i]=0.; } + for (Int_t i = 0; i < 9; i++) { + rot[i] = 0.; + } } inline void FairGeoRotation::print() const { - for(Int_t i=0; i<9; i++) { std::cout< // for TArrayI -#include // for TString, operator<< - -#include // for isalpha -#include // for strcmp -#include // for cout -#include // for fstream +#include // for TArrayI +#include // for TString, operator<< +#include // for isalpha +#include // for fstream +#include // for cout +#include // for strcmp class FairGeoMedium; @@ -37,405 +36,488 @@ using std::cout; using std::endl; using std::ios; -ClassImp(FairGeoSet) +ClassImp(FairGeoSet); FairGeoSet::FairGeoSet() - : TNamed(), - hadesGeo(0), - volumes(new TList()), - masterNodes(nullptr), - maxSectors(0), - maxKeepinVolumes(0), - maxModules(0), - modules(nullptr), - pShapes(nullptr), - geoFile(""), - author(""), - description("") + : TNamed() + , hadesGeo(0) + , volumes(new TList()) + , masterNodes(nullptr) + , maxSectors(0) + , maxKeepinVolumes(0) + , maxModules(0) + , modules(nullptr) + , pShapes(nullptr) + , geoFile("") + , author("") + , description("") { - // Constructor + // Constructor } FairGeoSet::~FairGeoSet() { - // Destructor - delete volumes; - volumes=0; - delete modules; - modules=0; + // Destructor + delete volumes; + volumes = 0; + delete modules; + modules = 0; } -void FairGeoSet::setModules(Int_t s,Int_t* m) +void FairGeoSet::setModules(Int_t s, Int_t* m) { - // Stores the modules given in 'm' as active modules in sector 's' - // May be called with s=-1 for detectors not belonging to a sector - if (!modules) { - if (maxSectors==0&&maxModules>0) { modules=new TArrayI(maxModules); } - if (maxSectors>0&&maxModules>0) { modules=new TArrayI(maxSectors*maxModules); } - } - Int_t sec=0; - if (s>0) { sec=s; } - for(Int_t i=0; iAddAt(m[i],(sec*maxModules+i)); } - } + // Stores the modules given in 'm' as active modules in sector 's' + // May be called with s=-1 for detectors not belonging to a sector + if (!modules) { + if (maxSectors == 0 && maxModules > 0) { + modules = new TArrayI(maxModules); + } + if (maxSectors > 0 && maxModules > 0) { + modules = new TArrayI(maxSectors * maxModules); + } + } + Int_t sec = 0; + if (s > 0) { + sec = s; + } + for (Int_t i = 0; i < maxModules; i++) { + if (modules) { + modules->AddAt(m[i], (sec * maxModules + i)); + } + } } Int_t* FairGeoSet::getModules() { - // Returns a linear array of all modules - if (modules) { return modules->GetArray(); } - return 0; + // Returns a linear array of all modules + if (modules) { + return modules->GetArray(); + } + return 0; } -Int_t FairGeoSet::getModule(Int_t s,Int_t m) +Int_t FairGeoSet::getModule(Int_t s, Int_t m) { - // Returns 1, if the module is not explicitly set inactive - // (in this case it returns 0) - // May be called with s=-1 for detectors not belonging to a sector - if (!modules) { return 1; } - if (m0) { - s1=0; - s2=maxSectors; - } - Bool_t rc=kTRUE; - for (Int_t s=s1; s 0) { + s1 = 0; + s2 = maxSectors; + } + Bool_t rc = kTRUE; + for (Int_t s = s1; s < s2 && rc; s++) { + for (Int_t k = 0; k < maxKeepinVolumes && rc; k++) { + TString keepinName = getKeepinName(s, k); + rc = readKeepIn(fin, media, keepinName); + } } - } - for (Int_t m=0; m>t[0]>>t[1]>>t[2]; - for(Int_t i=0; i<9; i++) { fin>>r[i]; } - tf.setRotMatrix(r); - tf.setTransVector(t); + // Reads the transformation from file + Double_t r[9], t[3]; + fin >> t[0] >> t[1] >> t[2]; + for (Int_t i = 0; i < 9; i++) { + fin >> r[i]; + } + tf.setRotMatrix(r); + tf.setTransVector(t); } -Bool_t FairGeoSet::readVolumeParams(std::fstream& fin,FairGeoMedia* media, - FairGeoNode* volu,TList* refVolumes) +Bool_t FairGeoSet::readVolumeParams(std::fstream& fin, FairGeoMedia* media, FairGeoNode* volu, TList* refVolumes) { - // Reads the volume definition from file -// Int_t hadgeo = 1; - if (volu==0||media==0||refVolumes==0) { return kFALSE; } - const Int_t maxbuf=256; - char buf[maxbuf]; - TString name(volu->GetName()); - Int_t nameLength=name.Length(); - Bool_t isCopy=kFALSE; - fin>>buf; - FairGeoNode* mother=0; - FairGeoCopyNode* refNode=0; - TString refName; + // Reads the volume definition from file + // Int_t hadgeo = 1; + if (volu == 0 || media == 0 || refVolumes == 0) { + return kFALSE; + } + const Int_t maxbuf = 256; + char buf[maxbuf]; + TString name(volu->GetName()); + Int_t nameLength = name.Length(); + Bool_t isCopy = kFALSE; + fin >> buf; + FairGeoNode* mother = 0; + FairGeoCopyNode* refNode = 0; + TString refName; - if (volu->isKeepin()) { mother=getMasterNode(buf); } - else if (volu->isModule()) { - mother=getMasterNode(buf); - if (!mother) { mother=getVolume(buf); } - if (volu->isActive()&&mother) { mother->setActive(); } - } else { - mother=getVolume(buf); - if (!mother) { mother=getMasterNode(buf); } - } + if (volu->isKeepin()) { + mother = getMasterNode(buf); + } else if (volu->isModule()) { + mother = getMasterNode(buf); + if (!mother) { + mother = getVolume(buf); + } + if (volu->isActive() && mother) { + mother->setActive(); + } + } else { + mother = getVolume(buf); + if (!mother) { + mother = getMasterNode(buf); + } + } - volu->setMother(mother); - if (!mother) { Warning("readVolumeParams","Mother volume %s not found!",buf); } + volu->setMother(mother); + if (!mother) { + Warning("readVolumeParams", "Mother volume %s not found!", buf); + } - if ( hadesGeo == 1 ) { - // cout << " read copies in Hades format " << endl; + if (hadesGeo == 1) { + // cout << " read copies in Hades format " << endl; - if (nameLength>4) { - char c=' '; - do { - fin.get(c); - } while (c==' ' || c=='\n'); - Int_t i=static_cast(c); - fin.putback(c); + if (nameLength > 4) { + char c = ' '; + do { + fin.get(c); + } while (c == ' ' || c == '\n'); + Int_t i = static_cast(c); + fin.putback(c); - if (!isalpha(i)) { isCopy=kTRUE; } - refName=name(0,4); - refNode=static_cast(refVolumes->FindObject(refName)); - if (!refNode) { - if (isCopy) { return kFALSE; } - refVolumes->Add(new FairGeoCopyNode(refName.Data(),volu)); - } else { - FairGeoNode* cn=refNode->pNode; - volu->setCopyNode(cn); - volu->setMedium(cn->getMedium()); - volu->setShape(cn->getShapePointer()); - Int_t n=cn->getNumPoints(); - volu->createPoints(n); - for (Int_t k=0; ksetPoint(k,*(cn->getPoint(k))); } - } - } + if (!isalpha(i)) { + isCopy = kTRUE; + } + refName = name(0, 4); + refNode = static_cast(refVolumes->FindObject(refName)); + if (!refNode) { + if (isCopy) { + return kFALSE; + } + refVolumes->Add(new FairGeoCopyNode(refName.Data(), volu)); + } else { + FairGeoNode* cn = refNode->pNode; + volu->setCopyNode(cn); + volu->setMedium(cn->getMedium()); + volu->setShape(cn->getShapePointer()); + Int_t n = cn->getNumPoints(); + volu->createPoints(n); + for (Int_t k = 0; k < n; k++) { + volu->setPoint(k, *(cn->getPoint(k))); + } + } + } - } else { - // cbm format - Ssiz_t l=name.Last('#'); - if (l>0) { - char c; - do { - fin.get(c); - } while (c==' ' || c=='\n'); - Int_t i=static_cast(c); - fin.putback(c); - if (!isalpha(i)) { isCopy=kTRUE; } - refName=name(0,l); - refNode=static_cast(refVolumes->FindObject(refName)); - if (!refNode) { - if (isCopy) { return kFALSE; } - refVolumes->Add(new FairGeoCopyNode(refName.Data(),volu)); - } else { - FairGeoNode* cn=refNode->pNode; - volu->setCopyNode(cn); - volu->setMedium(cn->getMedium()); - volu->setShape(cn->getShapePointer()); - Int_t n=cn->getNumPoints(); - volu->createPoints(n); - for (Int_t k=0; ksetPoint(k,*(cn->getPoint(k))); } - } + } else { + // cbm format + Ssiz_t l = name.Last('#'); + if (l > 0) { + char c; + do { + fin.get(c); + } while (c == ' ' || c == '\n'); + Int_t i = static_cast(c); + fin.putback(c); + if (!isalpha(i)) { + isCopy = kTRUE; + } + refName = name(0, l); + refNode = static_cast(refVolumes->FindObject(refName)); + if (!refNode) { + if (isCopy) { + return kFALSE; + } + refVolumes->Add(new FairGeoCopyNode(refName.Data(), volu)); + } else { + FairGeoNode* cn = refNode->pNode; + volu->setCopyNode(cn); + volu->setMedium(cn->getMedium()); + volu->setShape(cn->getShapePointer()); + Int_t n = cn->getNumPoints(); + volu->createPoints(n); + for (Int_t k = 0; k < n; k++) { + volu->setPoint(k, *(cn->getPoint(k))); + } + } + } } - } - - if (!isCopy) { - fin>>buf; - FairGeoBasicShape* sh=pShapes->selectShape(buf); - if (sh) { volu->setShape(sh); } - else { return kFALSE; } - fin>>buf; - FairGeoMedium* medium=media->getMedium(buf); - if (!medium) { - Error("readVolumeParams","Medium %s not found in list of media",buf); - return kFALSE; + if (!isCopy) { + fin >> buf; + FairGeoBasicShape* sh = pShapes->selectShape(buf); + if (sh) { + volu->setShape(sh); + } else { + return kFALSE; + } + fin >> buf; + FairGeoMedium* medium = media->getMedium(buf); + if (!medium) { + Error("readVolumeParams", "Medium %s not found in list of media", buf); + return kFALSE; + } + volu->setMedium(medium); + Int_t n = 0; + fin.getline(buf, maxbuf); // to read the end of line + if (sh) { + n = sh->readPoints(&fin, volu); + } + if (n <= 0) { + return kFALSE; + } } - volu->setMedium(medium); - Int_t n=0; - fin.getline(buf,maxbuf); // to read the end of line - if (sh) { n=sh->readPoints(&fin,volu); } - if (n<=0) { return kFALSE; } - } - readTransform(fin,volu->getTransform()); - return kTRUE; + readTransform(fin, volu->getTransform()); + return kTRUE; } -Bool_t FairGeoSet::readKeepIn(std::fstream& fin,FairGeoMedia* media,TString& name) +Bool_t FairGeoSet::readKeepIn(std::fstream& fin, FairGeoMedia* media, TString& name) { - // Reads the keepin volume from file - fin.clear(); - fin.seekg(0, ios::beg); - FairGeoNode* volu=0; - Bool_t rc=kTRUE; - TList refVolumes; - const Int_t maxbuf=256; - char buf[maxbuf]; - while(rc && !volu && !fin.eof()) { - fin>>buf; - if (buf[0]=='/') { fin.getline(buf,maxbuf); } - else if (!fin.eof()) { - if (strcmp(buf,name)==0) { - volu=new FairGeoNode; - volu->SetName(buf); - volu->setVolumeType(kFairGeoKeepin); - readInout(fin); - rc=readVolumeParams(fin,media,volu,&refVolumes); - } else { - do { - fin.getline(buf,maxbuf); - } while(!fin.eof()&&buf[0]!='/'); - } + // Reads the keepin volume from file + fin.clear(); + fin.seekg(0, ios::beg); + FairGeoNode* volu = 0; + Bool_t rc = kTRUE; + TList refVolumes; + const Int_t maxbuf = 256; + char buf[maxbuf]; + while (rc && !volu && !fin.eof()) { + fin >> buf; + if (buf[0] == '/') { + fin.getline(buf, maxbuf); + } else if (!fin.eof()) { + if (strcmp(buf, name) == 0) { + volu = new FairGeoNode; + volu->SetName(buf); + volu->setVolumeType(kFairGeoKeepin); + readInout(fin); + rc = readVolumeParams(fin, media, volu, &refVolumes); + } else { + do { + fin.getline(buf, maxbuf); + } while (!fin.eof() && buf[0] != '/'); + } + } } - } - if (rc) { volumes->Add(volu); } - else { - delete volu; - volu=0; - } - refVolumes.Delete(); - return rc; + if (rc) { + volumes->Add(volu); + } else { + delete volu; + volu = 0; + } + refVolumes.Delete(); + return rc; } -Bool_t FairGeoSet::readModule(std::fstream& fin,FairGeoMedia* media,TString& modName, - TString& eleName,Bool_t containsActiveMod) +Bool_t FairGeoSet::readModule(std::fstream& fin, + FairGeoMedia* media, + TString& modName, + TString& eleName, + Bool_t containsActiveMod) { - // Reads the whole geometry of a module from file - const Int_t maxbuf=256; - Text_t buf[maxbuf]; - fin.clear(); - fin.seekg(0,ios::beg); - FairGeoNode* volu=0; - Bool_t rc=kTRUE; - TList refVolumes; - TString name; - while(rc && !fin.eof()) { - fin>>buf; - if (buf[0]=='/') { fin.getline(buf,maxbuf); } - else if (!fin.eof()) { - //TString name(buf); - name=buf; - if (name.BeginsWith(modName)) { - volu=new FairGeoNode; - volu->SetName(buf); - volu->setVolumeType(kFairGeoModule); - Int_t a=getModule(getSecNumInMod(buf),getModNumInMod(buf)); - if (a>0) { volu->setActive(kTRUE); } - else { volu->setActive(kFALSE); } - readInout(fin); - rc=readVolumeParams(fin,media,volu,&refVolumes); - if (rc) { volumes->Add(volu); } - else { - Error("readModule","Failed for module %s\n",volu->GetName()); - delete volu; - volu=0; - } - } else if (!eleName.IsNull()&&name.BeginsWith(eleName)) { - volu=new FairGeoNode; - volu->SetName(buf); - volu->setVolumeType(kFairGeoElement); - volu->setActive(containsActiveMod); - rc=readVolumeParams(fin,media,volu,&refVolumes); - if (rc) { volumes->Add(volu); } - else { - Error("readModule","Failed for %s\n",volu->GetName()); - delete volu; - volu=0; + // Reads the whole geometry of a module from file + const Int_t maxbuf = 256; + Text_t buf[maxbuf]; + fin.clear(); + fin.seekg(0, ios::beg); + FairGeoNode* volu = 0; + Bool_t rc = kTRUE; + TList refVolumes; + TString name; + while (rc && !fin.eof()) { + fin >> buf; + if (buf[0] == '/') { + fin.getline(buf, maxbuf); + } else if (!fin.eof()) { + // TString name(buf); + name = buf; + if (name.BeginsWith(modName)) { + volu = new FairGeoNode; + volu->SetName(buf); + volu->setVolumeType(kFairGeoModule); + Int_t a = getModule(getSecNumInMod(buf), getModNumInMod(buf)); + if (a > 0) { + volu->setActive(kTRUE); + } else { + volu->setActive(kFALSE); + } + readInout(fin); + rc = readVolumeParams(fin, media, volu, &refVolumes); + if (rc) { + volumes->Add(volu); + } else { + Error("readModule", "Failed for module %s\n", volu->GetName()); + delete volu; + volu = 0; + } + } else if (!eleName.IsNull() && name.BeginsWith(eleName)) { + volu = new FairGeoNode; + volu->SetName(buf); + volu->setVolumeType(kFairGeoElement); + volu->setActive(containsActiveMod); + rc = readVolumeParams(fin, media, volu, &refVolumes); + if (rc) { + volumes->Add(volu); + } else { + Error("readModule", "Failed for %s\n", volu->GetName()); + delete volu; + volu = 0; + } + } else { + do { + fin.getline(buf, maxbuf); + } while (!fin.eof() && buf[0] != '/'); + } } - } else { - do { - fin.getline(buf,maxbuf); - } while(!fin.eof()&&buf[0]!='/'); - } } - } - refVolumes.Delete(); - return rc; + refVolumes.Delete(); + return rc; } void FairGeoSet::print() { - // Prints the geometry - if (!author.IsNull()) { cout<<"//Author: "<(iter.Next()))) { - volu->print(); - } - cout.setf(tmp); + // Prints the geometry + if (!author.IsNull()) { + cout << "//Author: " << author << '\n'; + } + if (!description.IsNull()) { + cout << "//Description: " << description << '\n'; + } + if (!description.IsNull()) { + cout << "//----------------------------------------------------------\n"; + } + std::ios_base::fmtflags tmp = cout.setf(ios::fixed, ios::floatfield); + TListIter iter(volumes); + FairGeoNode* volu; + while ((volu = static_cast(iter.Next()))) { + volu->print(); + } + cout.setf(tmp); } void FairGeoSet::write(std::fstream& fout) { - // Writes the volumes to file - if (!author.IsNull()) { fout<<"//Author: "<(iter.Next()))&&rc) { - rc=volu->write(fout); - } - fout.setf(tmp); + // Writes the volumes to file + if (!author.IsNull()) { + fout << "//Author: " << author << '\n'; + } + if (!description.IsNull()) { + fout << "//Description: " << description << '\n'; + } + fout << "//----------------------------------------------------------\n"; + std::ios_base::fmtflags tmp = fout.setf(ios::fixed, ios::floatfield); + TListIter iter(volumes); + FairGeoNode* volu; + Bool_t rc = kTRUE; + while ((volu = static_cast(iter.Next())) && rc) { + rc = volu->write(fout); + } + fout.setf(tmp); } Bool_t FairGeoSet::create(FairGeoBuilder* builder) { - // Creates the geometry - if (!builder) { return kFALSE; } - TListIter iter(volumes); - FairGeoNode* volu; - Bool_t rc=kTRUE; - while((volu=static_cast(iter.Next()))&&rc) { - if (volu->isActive()) { + // Creates the geometry + if (!builder) { + return kFALSE; + } + TListIter iter(volumes); + FairGeoNode* volu; + Bool_t rc = kTRUE; + while ((volu = static_cast(iter.Next())) && rc) { + if (volu->isActive()) { - if (hadesGeo == 1) { rc=builder->createNode(volu, hadesGeo); } - else { rc=builder->createNode(volu) ; } - if (rc) { - if (volu->isTopNode()||volu->isRefNode()) { - FairGeoNode* n=getMasterNode(volu->GetName()); - if (n) { - n->setCenterPosition(volu->getCenterPosition()); - n->setRootVolume(volu->getRootVolume()); - } + if (hadesGeo == 1) { + rc = builder->createNode(volu, hadesGeo); + } else { + rc = builder->createNode(volu); + } + if (rc) { + if (volu->isTopNode() || volu->isRefNode()) { + FairGeoNode* n = getMasterNode(volu->GetName()); + if (n) { + n->setCenterPosition(volu->getCenterPosition()); + n->setRootVolume(volu->getRootVolume()); + } + } + } else { + Error("create", "Creation of %s failed!", volu->GetName()); + } } - } else { Error("create","Creation of %s failed!",volu->GetName()); } } - } - return rc; + return rc; } void FairGeoSet::compare(FairGeoSet& rset) { - // Compares the geometry parameters and print a diagnose - if (fName.CompareTo(rset.GetName())!=0) { - Error("compare","Sets have different type"); - return; - } - TListIter iter(volumes); - FairGeoNode* volu; - Int_t n=0, nnf=0, nDiff=0; - cout<<"name\t mother medium shape points pos rot\n"; - cout<<"------------------------------------------------\n"; - while((volu=static_cast(iter.Next()))) { - n++; - FairGeoNode* rNode=rset.getVolume(volu->GetName()); - if (!rNode) { nnf++; } - else if (volu->compare(*rNode)>0) { nDiff++; } - } - cout<<"Number of volumes in first list: "<GetSize()!=(n-nnf)) { - nnf=0; - TListIter riter(rlist); - while((volu=static_cast(riter.Next()))) { - FairGeoNode* rNode=getVolume(volu->GetName()); - if (!rNode) { nnf++; } + // Compares the geometry parameters and print a diagnose + if (fName.CompareTo(rset.GetName()) != 0) { + Error("compare", "Sets have different type"); + return; + } + TListIter iter(volumes); + FairGeoNode* volu; + Int_t n = 0, nnf = 0, nDiff = 0; + cout << "name\t mother medium shape points pos rot\n"; + cout << "------------------------------------------------\n"; + while ((volu = static_cast(iter.Next()))) { + n++; + FairGeoNode* rNode = rset.getVolume(volu->GetName()); + if (!rNode) { + nnf++; + } else if (volu->compare(*rNode) > 0) { + nDiff++; + } + } + cout << "Number of volumes in first list: " << n << '\n'; + cout << "Number of different volumes: " << nDiff << endl; + cout << "Number of volumes not found in second list: " << nnf << '\n'; + TList* rlist = rset.getListOfVolumes(); + if (rlist->GetSize() != (n - nnf)) { + nnf = 0; + TListIter riter(rlist); + while ((volu = static_cast(riter.Next()))) { + FairGeoNode* rNode = getVolume(volu->GetName()); + if (!rNode) { + nnf++; + } + } + } else { + nnf = 0; } - } else { nnf=0; } - cout<<"Number of additional volumes in second list: "< // for TNamed -#include // for Int_t, Bool_t, etc - -#include // for fstream -#include // for TList -#include // for TString +#include // for Int_t, Bool_t, etc +#include // for TList +#include // for TNamed +#include // for TString +#include // for fstream -//class FairGeoNode; +// class FairGeoNode; class FairGeoShapes; class FairGeoMedia; class FairGeoBuilder; @@ -29,7 +27,7 @@ class TArrayI; * Base class for geometry of detector parts * @author Ilse koenig */ -class FairGeoSet : public TNamed +class FairGeoSet : public TNamed { protected: Int_t hadesGeo; @@ -38,8 +36,10 @@ class FairGeoSet : public TNamed { public: FairGeoNode* pNode; - FairGeoCopyNode(const char* name,FairGeoNode* node) - : TNamed(name,""), pNode(node) {} + FairGeoCopyNode(const char* name, FairGeoNode* node) + : TNamed(name, "") + , pNode(node) + {} // SetName(name); // // } @@ -56,55 +56,53 @@ class FairGeoSet : public TNamed Int_t maxKeepinVolumes; /** maximum number of keepin volumes per sector*/ Int_t maxModules; /** maximum number of modules per sector*/ TArrayI* modules; /** Module's array.*/ - FairGeoShapes* pShapes; /** pointer to the class FairGeoShapes*/ + FairGeoShapes* pShapes; /** pointer to the class FairGeoShapes*/ TString geoFile; /** name of geometry input file or Oracle*/ TString author; /** author of the media version*/ TString description; /** description of the version*/ FairGeoSet(); void readInout(std::fstream&); - void readTransform(std::fstream&,FairGeoTransform&); - Bool_t readVolumeParams(std::fstream&,FairGeoMedia*,FairGeoNode*,TList* l=0); - Bool_t readKeepIn(std::fstream&,FairGeoMedia*,TString&); - Bool_t readModule(std::fstream&,FairGeoMedia*,TString&,TString&,Bool_t a=kFALSE); + void readTransform(std::fstream&, FairGeoTransform&); + Bool_t readVolumeParams(std::fstream&, FairGeoMedia*, FairGeoNode*, TList* l = 0); + Bool_t readKeepIn(std::fstream&, FairGeoMedia*, TString&); + Bool_t readModule(std::fstream&, FairGeoMedia*, TString&, TString&, Bool_t a = kFALSE); - public : + public: virtual ~FairGeoSet(); - void setShapes(FairGeoShapes* s) {pShapes=s;} - void setMasterNodes(TList* m) {masterNodes=m;} - void setGeomFile(const char* filename) {geoFile=filename;} + void setShapes(FairGeoShapes* s) { pShapes = s; } + void setMasterNodes(TList* m) { masterNodes = m; } + void setGeomFile(const char* filename) { geoFile = filename; } const char* getGeomFile() { return geoFile.Data(); } - Int_t getMaxSectors(void) {return maxSectors;} - Int_t getMaxModules(void) {return maxModules;} - Int_t getMaxKeepinVolumes(void) {return maxKeepinVolumes;} - void setModules(Int_t,Int_t*); + Int_t getMaxSectors(void) { return maxSectors; } + Int_t getMaxModules(void) { return maxModules; } + Int_t getMaxKeepinVolumes(void) { return maxKeepinVolumes; } + void setModules(Int_t, Int_t*); Int_t* getModules(void); - Int_t getModule(Int_t,Int_t); - FairGeoNode* getVolume(const char* name) {return dynamic_cast(volumes->FindObject(name));} - FairGeoNode* getMasterNode(const char* name) {return dynamic_cast(masterNodes->FindObject(name));} - TList* getListOfVolumes() {return volumes;} - FairGeoShapes* getShapes() {return pShapes;} - void setAuthor(TString& s) {author=s;} - void setDescription(TString& s) {description=s;} - TString& getAuthor() {return author;} - TString& getDescription() {return description;} - virtual const char* getKeepinName(Int_t,Int_t) {return 0;} - virtual const char* getModuleName(Int_t) {return 0;} - virtual const char* getEleName(Int_t) {return 0;} - virtual Int_t getSecNumInMod(const TString&) {return -1;} - virtual Int_t getModNumInMod(const TString&) {return 0;} - virtual Bool_t read(std::fstream&,FairGeoMedia*); + Int_t getModule(Int_t, Int_t); + FairGeoNode* getVolume(const char* name) { return dynamic_cast(volumes->FindObject(name)); } + FairGeoNode* getMasterNode(const char* name) { return dynamic_cast(masterNodes->FindObject(name)); } + TList* getListOfVolumes() { return volumes; } + FairGeoShapes* getShapes() { return pShapes; } + void setAuthor(TString& s) { author = s; } + void setDescription(TString& s) { description = s; } + TString& getAuthor() { return author; } + TString& getDescription() { return description; } + virtual const char* getKeepinName(Int_t, Int_t) { return 0; } + virtual const char* getModuleName(Int_t) { return 0; } + virtual const char* getEleName(Int_t) { return 0; } + virtual Int_t getSecNumInMod(const TString&) { return -1; } + virtual Int_t getModNumInMod(const TString&) { return 0; } + virtual Bool_t read(std::fstream&, FairGeoMedia*); virtual void addRefNodes() {} virtual void write(std::fstream&); virtual void print(); virtual Bool_t create(FairGeoBuilder*); void compare(FairGeoSet&); - ClassDef(FairGeoSet,0) // + ClassDef(FairGeoSet, 0) // - private: - FairGeoSet(const FairGeoSet&); + private : FairGeoSet(const FairGeoSet&); FairGeoSet& operator=(const FairGeoSet&); }; - -#endif /* !FAIRGEOSET_H */ +#endif /* !FAIRGEOSET_H */ diff --git a/geobase/FairGeoShapes.cxx b/geobase/FairGeoShapes.cxx index e8125a76fc..d7157d43b1 100644 --- a/geobase/FairGeoShapes.cxx +++ b/geobase/FairGeoShapes.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ //*-- AUTHOR : Ilse Koenig @@ -34,131 +34,166 @@ #include "FairGeoShapes.h" -#include "FairGeoVolume.h" +#include "FairGeoAssembly.h" #include "FairGeoBasicShape.h" #include "FairGeoBrik.h" -#include "FairGeoTrap.h" -#include "FairGeoTrd1.h" -#include "FairGeoPgon.h" -#include "FairGeoPcon.h" -#include "FairGeoTube.h" -#include "FairGeoTubs.h" #include "FairGeoCone.h" #include "FairGeoCons.h" -#include "FairGeoSphe.h" #include "FairGeoEltu.h" +#include "FairGeoPcon.h" +#include "FairGeoPgon.h" +#include "FairGeoSphe.h" #include "FairGeoTorus.h" -#include "FairGeoAssembly.h" +#include "FairGeoTrap.h" +#include "FairGeoTrd1.h" +#include "FairGeoTube.h" +#include "FairGeoTubs.h" +#include "FairGeoVolume.h" #include +#include // for fstream -#include // for fstream - -ClassImp(FairGeoShapes) +ClassImp(FairGeoShapes); FairGeoShapes::FairGeoShapes() - : TObject(), - shapes(new TList()) + : TObject() + , shapes(new TList()) { - // constructor creates empty list of shapes - + // constructor creates empty list of shapes } - FairGeoShapes::~FairGeoShapes() { - // destructor deletes all shapes - shapes->Delete(); - delete shapes; + // destructor deletes all shapes + shapes->Delete(); + delete shapes; } - FairGeoBasicShape* FairGeoShapes::selectShape(FairGeoVolume* volu) { - // returns a pointer to the shape used in the given volume - // calls internally selectShape(TString&) with the name of the shape - // returns NULL if the corresponding shape class is not implemented - const TString& name(volu->getShape()); - return selectShape(name); + // returns a pointer to the shape used in the given volume + // calls internally selectShape(TString&) with the name of the shape + // returns NULL if the corresponding shape class is not implemented + const TString& name(volu->getShape()); + return selectShape(name); } - FairGeoBasicShape* FairGeoShapes::selectShape(const TString& name) { - // returns a pointer to the shape given by name - // creates a shape object and adds it to the list of shapes if - // not existing - // returns NULL if the corresponding shape class is not implemented - TString allShapes[13]= {"BOX ","TRAP","TRD1","PGON","PCON","TUBE","TUBS", - "CONE","CONS","SPHE","ELTU","TORUS", "ASSEMBLY" - }; - TString sName(name); - if (sName.Length()==3) { sName+=" "; } - FairGeoBasicShape* s=static_cast(shapes->FindObject(sName)); - if (s) { return s; } - Int_t no=-1; - for(Int_t i=0; i<13; i++) {if (sName.CompareTo(allShapes[i])==0) { no=i; }} - switch(no) { - case 0: - {s= new FairGeoBrik(); break;} - case 1: - {s= new FairGeoTrap(); break;} - case 2: - {s= new FairGeoTrd1(); break;} - case 3: - {s= new FairGeoPgon(); break;} - case 4: - {s= new FairGeoPcon(); break;} - case 5: - {s= new FairGeoTube(); break;} - case 6: - {s= new FairGeoTubs(); break;} - case 7: - {s= new FairGeoCone(); break;} - case 8: - {s= new FairGeoCons(); break;} - case 9: - {s= new FairGeoSphe(); break;} - case 10: - {s= new FairGeoEltu(); break;} - case 11: - {s= new FairGeoTorus(); break;} - case 12: - {s= new FairGeoAssembly(); break;} - default: { - Error("selectShape","shape %s not implemented",name.Data()); - } - } - if (s) { shapes->Add(s); } - return s; + // returns a pointer to the shape given by name + // creates a shape object and adds it to the list of shapes if + // not existing + // returns NULL if the corresponding shape class is not implemented + TString allShapes[13] = { + "BOX ", "TRAP", "TRD1", "PGON", "PCON", "TUBE", "TUBS", "CONE", "CONS", "SPHE", "ELTU", "TORUS", "ASSEMBLY"}; + TString sName(name); + if (sName.Length() == 3) { + sName += " "; + } + FairGeoBasicShape* s = static_cast(shapes->FindObject(sName)); + if (s) { + return s; + } + Int_t no = -1; + for (Int_t i = 0; i < 13; i++) { + if (sName.CompareTo(allShapes[i]) == 0) { + no = i; + } + } + switch (no) { + case 0: { + s = new FairGeoBrik(); + break; + } + case 1: { + s = new FairGeoTrap(); + break; + } + case 2: { + s = new FairGeoTrd1(); + break; + } + case 3: { + s = new FairGeoPgon(); + break; + } + case 4: { + s = new FairGeoPcon(); + break; + } + case 5: { + s = new FairGeoTube(); + break; + } + case 6: { + s = new FairGeoTubs(); + break; + } + case 7: { + s = new FairGeoCone(); + break; + } + case 8: { + s = new FairGeoCons(); + break; + } + case 9: { + s = new FairGeoSphe(); + break; + } + case 10: { + s = new FairGeoEltu(); + break; + } + case 11: { + s = new FairGeoTorus(); + break; + } + case 12: { + s = new FairGeoAssembly(); + break; + } + default: { + Error("selectShape", "shape %s not implemented", name.Data()); + } + } + if (s) { + shapes->Add(s); + } + return s; } - -Int_t FairGeoShapes::readPoints(std::fstream* pFile,FairGeoVolume* volu) +Int_t FairGeoShapes::readPoints(std::fstream* pFile, FairGeoVolume* volu) { - // reads the points of the given volume from the Ascii file - // returns the number of points read - // returns 0 if if the corresponding shape class is not implemented - FairGeoBasicShape* s=selectShape(volu); - if (s) { return s->readPoints(pFile,volu); } - else { return 0; } + // reads the points of the given volume from the Ascii file + // returns the number of points read + // returns 0 if if the corresponding shape class is not implemented + FairGeoBasicShape* s = selectShape(volu); + if (s) { + return s->readPoints(pFile, volu); + } else { + return 0; + } } - -Bool_t FairGeoShapes::writePoints(std::fstream* pFile,FairGeoVolume* volu) +Bool_t FairGeoShapes::writePoints(std::fstream* pFile, FairGeoVolume* volu) { - // writes the points of the given volume to the Ascii file - // return kFALSE if the corresponding shape class is not implemented - FairGeoBasicShape* s=selectShape(volu); - if (s) { return s->writePoints(pFile,volu); } - else { return kFALSE; } + // writes the points of the given volume to the Ascii file + // return kFALSE if the corresponding shape class is not implemented + FairGeoBasicShape* s = selectShape(volu); + if (s) { + return s->writePoints(pFile, volu); + } else { + return kFALSE; + } } - void FairGeoShapes::printPoints(FairGeoVolume* volu) { - // writes the points of the given volume to the Ascii file - // return kFALSE if the corresponding shape class is not implemented - FairGeoBasicShape* s=selectShape(volu); - if (s) { return s->printPoints(volu); } + // writes the points of the given volume to the Ascii file + // return kFALSE if the corresponding shape class is not implemented + FairGeoBasicShape* s = selectShape(volu); + if (s) { + return s->printPoints(volu); + } } diff --git a/geobase/FairGeoShapes.h b/geobase/FairGeoShapes.h index c335d0dfe2..c090b5b6bc 100644 --- a/geobase/FairGeoShapes.h +++ b/geobase/FairGeoShapes.h @@ -1,18 +1,17 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRGEOSHAPES_H #define FAIRGEOSHAPES_H -#include // for TObject - -#include // for fstream -#include // for FairGeoShapes::Class, etc -#include // for TString +#include // for FairGeoShapes::Class, etc +#include // for TObject +#include // for TString +#include // for fstream class FairGeoVolume; class FairGeoBasicShape; @@ -21,24 +20,24 @@ class TList; * manager class for geometry shapes * @author Ilse koenig */ -class FairGeoShapes : public TObject +class FairGeoShapes : public TObject { private: FairGeoShapes(const FairGeoShapes&); FairGeoShapes& operator=(const FairGeoShapes&); protected: - TList* shapes; // list of already created shape classes + TList* shapes; // list of already created shape classes - public : + public: FairGeoShapes(); ~FairGeoShapes(); FairGeoBasicShape* selectShape(FairGeoVolume*); FairGeoBasicShape* selectShape(const TString&); - Int_t readPoints(std::fstream*,FairGeoVolume*); - Bool_t writePoints(std::fstream*,FairGeoVolume*); + Int_t readPoints(std::fstream*, FairGeoVolume*); + Bool_t writePoints(std::fstream*, FairGeoVolume*); void printPoints(FairGeoVolume* volu); - ClassDef(FairGeoShapes,0) // + ClassDef(FairGeoShapes, 0) // }; -#endif /* !FAIRGEOSHAPES_H */ +#endif /* !FAIRGEOSHAPES_H */ diff --git a/geobase/FairGeoSphe.cxx b/geobase/FairGeoSphe.cxx index cb5145e0c4..e58d32d3c0 100644 --- a/geobase/FairGeoSphe.cxx +++ b/geobase/FairGeoSphe.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ //*-- AUTHOR : Ilse Koenig @@ -29,112 +29,108 @@ /////////////////////////////////////////////////////////////////////////////// #include "FairGeoSphe.h" -#include "FairGeoTransform.h" // for FairGeoTransform -#include "FairGeoVector.h" // for FairGeoVector -#include "FairGeoVolume.h" // for FairGeoVolume +#include "FairGeoTransform.h" // for FairGeoTransform +#include "FairGeoVector.h" // for FairGeoVector +#include "FairGeoVolume.h" // for FairGeoVolume -#include // for TArrayD -#include // for TString - -#include // for printf, sprintf, sscanf -#include // for strlen -#include // for basic_ostream::write +#include // for TArrayD +#include // for TString #include +#include // for basic_ostream::write +#include // for printf, sprintf, sscanf +#include // for strlen -ClassImp(FairGeoSphe) +ClassImp(FairGeoSphe); FairGeoSphe::FairGeoSphe() - :FairGeoBasicShape() + : FairGeoBasicShape() { - // constructor - fName="SPHE"; - nPoints=3; - nParam=6; - param=new TArrayD(nParam); + // constructor + fName = "SPHE"; + nPoints = 3; + nParam = 6; + param = new TArrayD(nParam); } - FairGeoSphe::~FairGeoSphe() { - // default destructor - delete param; - param=0; - delete center; - center=0; - delete position; - position=0; + // default destructor + delete param; + param = 0; + delete center; + center = 0; + delete position; + position = 0; } - -Int_t FairGeoSphe::readPoints(std::fstream* pFile,FairGeoVolume* volu) +Int_t FairGeoSphe::readPoints(std::fstream* pFile, FairGeoVolume* volu) { - // reads the 3 'points' decribed above from ascii file - // if the array of points is not existing in the volume it is created and - // the values are stored inside - // returns the number of points - if (!pFile) { return 0; } - if (volu->getNumPoints()!=nPoints) { volu->createPoints(nPoints); } - Double_t x,y; - const Int_t maxbuf=155; - Text_t buf[maxbuf]; - for(Int_t i=0; igetline(buf,maxbuf); - sscanf(buf,"%lf%lf",&x,&y); - volu->setPoint(i,x,y,0.0); - } - return nPoints; + // reads the 3 'points' decribed above from ascii file + // if the array of points is not existing in the volume it is created and + // the values are stored inside + // returns the number of points + if (!pFile) { + return 0; + } + if (volu->getNumPoints() != nPoints) { + volu->createPoints(nPoints); + } + Double_t x, y; + const Int_t maxbuf = 155; + Text_t buf[maxbuf]; + for (Int_t i = 0; i < nPoints; i++) { + pFile->getline(buf, maxbuf); + sscanf(buf, "%lf%lf", &x, &y); + volu->setPoint(i, x, y, 0.0); + } + return nPoints; } - -Bool_t FairGeoSphe::writePoints(std::fstream* pFile,FairGeoVolume* volu) +Bool_t FairGeoSphe::writePoints(std::fstream* pFile, FairGeoVolume* volu) { - // writes the 3 'points' decribed above to ascii file - if (!pFile) { - return kFALSE; - } else { - Text_t buf[155]; - for(Int_t i=0; igetPoint(i)); - sprintf(buf,"%9.3f%10.3f\n",v(0),v(1)); - pFile->write(buf,strlen(buf)); + // writes the 3 'points' decribed above to ascii file + if (!pFile) { + return kFALSE; + } else { + Text_t buf[155]; + for (Int_t i = 0; i < nPoints; i++) { + FairGeoVector& v = *(volu->getPoint(i)); + sprintf(buf, "%9.3f%10.3f\n", v(0), v(1)); + pFile->write(buf, strlen(buf)); + } + return kTRUE; } - return kTRUE; - } } - void FairGeoSphe::printPoints(FairGeoVolume* volu) { - // prints volume points to screen - for(Int_t i=0; igetPoint(i)); - printf("%9.3f%10.3f\n",v(0),v(1)); - } + // prints volume points to screen + for (Int_t i = 0; i < nPoints; i++) { + FairGeoVector& v = *(volu->getPoint(i)); + printf("%9.3f%10.3f\n", v(0), v(1)); + } } - TArrayD* FairGeoSphe::calcVoluParam(FairGeoVolume* volu) { - // calculates the parameters needed to create the shape SPHE - Double_t fac=10.; - FairGeoVector& v0=*(volu->getPoint(0)); - FairGeoVector& v1=*(volu->getPoint(1)); - FairGeoVector& v2=*(volu->getPoint(2)); - param->AddAt(v0(0)/fac,0); - param->AddAt(v0(1)/fac,1); - param->AddAt(v1(0),2); - param->AddAt(v1(1),3); - param->AddAt(v2(0),4); - param->AddAt(v2(1),5); - return param; + // calculates the parameters needed to create the shape SPHE + Double_t fac = 10.; + FairGeoVector& v0 = *(volu->getPoint(0)); + FairGeoVector& v1 = *(volu->getPoint(1)); + FairGeoVector& v2 = *(volu->getPoint(2)); + param->AddAt(v0(0) / fac, 0); + param->AddAt(v0(1) / fac, 1); + param->AddAt(v1(0), 2); + param->AddAt(v1(1), 3); + param->AddAt(v2(0), 4); + param->AddAt(v2(1), 5); + return param; } - -void FairGeoSphe::calcVoluPosition(FairGeoVolume*, - const FairGeoTransform& dTC,const FairGeoTransform& mTR) +void FairGeoSphe::calcVoluPosition(FairGeoVolume*, const FairGeoTransform& dTC, const FairGeoTransform& mTR) { - // calls the function posInMother(...) to calculate the position of the - // volume in its mother - center->clear(); - posInMother(dTC,mTR); + // calls the function posInMother(...) to calculate the position of the + // volume in its mother + center->clear(); + posInMother(dTC, mTR); } diff --git a/geobase/FairGeoSphe.h b/geobase/FairGeoSphe.h index c2c712f8a3..8c5df6e7c5 100644 --- a/geobase/FairGeoSphe.h +++ b/geobase/FairGeoSphe.h @@ -1,18 +1,17 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRGEOSPHE_H #define FAIRGEOSPHE_H -#include "FairGeoBasicShape.h" // for FairGeoBasicShape +#include "FairGeoBasicShape.h" // for FairGeoBasicShape -#include // for FairGeoPcon::Class, Bool_t, etc - -#include // for fstream +#include // for FairGeoPcon::Class, Bool_t, etc +#include // for fstream class FairGeoTransform; class FairGeoVolume; @@ -28,11 +27,11 @@ class FairGeoSphe : public FairGeoBasicShape FairGeoSphe(); ~FairGeoSphe(); TArrayD* calcVoluParam(FairGeoVolume*); - void calcVoluPosition(FairGeoVolume*, const FairGeoTransform&,const FairGeoTransform&); - Int_t readPoints(std::fstream*,FairGeoVolume*); - Bool_t writePoints(std::fstream*,FairGeoVolume*); + void calcVoluPosition(FairGeoVolume*, const FairGeoTransform&, const FairGeoTransform&); + Int_t readPoints(std::fstream*, FairGeoVolume*); + Bool_t writePoints(std::fstream*, FairGeoVolume*); void printPoints(FairGeoVolume* volu); - ClassDef(FairGeoSphe,0) // + ClassDef(FairGeoSphe, 0) // }; -#endif /* !FAIRGEOSPHE_H */ +#endif /* !FAIRGEOSPHE_H */ diff --git a/geobase/FairGeoTorus.cxx b/geobase/FairGeoTorus.cxx index f28d608cb2..8b22e20f3d 100644 --- a/geobase/FairGeoTorus.cxx +++ b/geobase/FairGeoTorus.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ //*-- AUTHOR : M. Al-Turany 06/11/2006 @@ -21,111 +21,116 @@ ///////////////////////////////////////////////////////////// #include "FairGeoTorus.h" -#include "FairGeoTransform.h" // for FairGeoTransform -#include "FairGeoVector.h" // for FairGeoVector -#include "FairGeoVolume.h" // for FairGeoVolume +#include "FairGeoTransform.h" // for FairGeoTransform +#include "FairGeoVector.h" // for FairGeoVector +#include "FairGeoVolume.h" // for FairGeoVolume -#include // for TArrayD -#include // for TString - -#include // for printf, sprintf, sscanf -#include // for strlen -#include // for basic_ostream::write +#include // for TArrayD +#include // for TString #include +#include // for basic_ostream::write +#include // for printf, sprintf, sscanf +#include // for strlen -ClassImp(FairGeoTorus) +ClassImp(FairGeoTorus); FairGeoTorus::FairGeoTorus() - :FairGeoBasicShape() + : FairGeoBasicShape() { - // constructor - fName="TORUS"; - nPoints=5; - nParam=5; - param=new TArrayD(nParam); + // constructor + fName = "TORUS"; + nPoints = 5; + nParam = 5; + param = new TArrayD(nParam); } FairGeoTorus::~FairGeoTorus() { - // destructor - if (param) { - delete param; - param=0; - } - if (center) { - delete center; - center=0; - } - if (position) { - delete position; - position=0; - } + // destructor + if (param) { + delete param; + param = 0; + } + if (center) { + delete center; + center = 0; + } + if (position) { + delete position; + position = 0; + } } -Int_t FairGeoTorus::readPoints(std::fstream* pFile,FairGeoVolume* volu) +Int_t FairGeoTorus::readPoints(std::fstream* pFile, FairGeoVolume* volu) { - // reads nPoints with 3 components from Ascii file - // if the array of points is not existing in the volume it is created and - // the values are stored inside - // returns the number of points - if (!pFile) { return 0; } - if (volu->getNumPoints()!=nPoints) { volu->createPoints(nPoints); } - Double_t x; - const Int_t maxbuf=155; - Text_t buf[maxbuf]; - for(Int_t i=0; igetline(buf,maxbuf); - sscanf(buf,"%lf",&x); - volu->setPoint(i,x,0,0); - } - return nPoints; + // reads nPoints with 3 components from Ascii file + // if the array of points is not existing in the volume it is created and + // the values are stored inside + // returns the number of points + if (!pFile) { + return 0; + } + if (volu->getNumPoints() != nPoints) { + volu->createPoints(nPoints); + } + Double_t x; + const Int_t maxbuf = 155; + Text_t buf[maxbuf]; + for (Int_t i = 0; i < nPoints; i++) { + pFile->getline(buf, maxbuf); + sscanf(buf, "%lf", &x); + volu->setPoint(i, x, 0, 0); + } + return nPoints; } TArrayD* FairGeoTorus::calcVoluParam(FairGeoVolume* volu) { - // calculates the parameters needed to create the shape + // calculates the parameters needed to create the shape - for(Int_t i=0; i<3; i++) { - FairGeoVector v=*(volu->getPoint(i)); - v*=(1/10.); - param->AddAt(v(0),i); - } - FairGeoVector v=*(volu->getPoint(3)); - param->AddAt(v(0),3); + for (Int_t i = 0; i < 3; i++) { + FairGeoVector v = *(volu->getPoint(i)); + v *= (1 / 10.); + param->AddAt(v(0), i); + } + FairGeoVector v = *(volu->getPoint(3)); + param->AddAt(v(0), 3); - v=*(volu->getPoint(4)); - param->AddAt(v(0),4); + v = *(volu->getPoint(4)); + param->AddAt(v(0), 4); - return param; + return param; } -Bool_t FairGeoTorus::writePoints(std::fstream* pFile,FairGeoVolume* volu) +Bool_t FairGeoTorus::writePoints(std::fstream* pFile, FairGeoVolume* volu) { - // writes the 4 'points' decribed above to ascii file - if (!pFile) { return kFALSE; } - Text_t buf[155]; - for(Int_t i=0; igetPoint(i)); - sprintf(buf,"%9.3f\n",v(0)); - pFile->write(buf,strlen(buf)); - } - return kTRUE; + // writes the 4 'points' decribed above to ascii file + if (!pFile) { + return kFALSE; + } + Text_t buf[155]; + for (Int_t i = 0; i < nPoints; i++) { + FairGeoVector& v = *(volu->getPoint(i)); + sprintf(buf, "%9.3f\n", v(0)); + pFile->write(buf, strlen(buf)); + } + return kTRUE; } void FairGeoTorus::printPoints(FairGeoVolume* volu) { - // prints volume points to screen - for(Int_t i=0; igetPoint(i)); - printf("%9.3f\n",v(0)); - } + // prints volume points to screen + for (Int_t i = 0; i < nPoints; i++) { + FairGeoVector& v = *(volu->getPoint(i)); + printf("%9.3f\n", v(0)); + } } -void FairGeoTorus::calcVoluPosition(FairGeoVolume*, const FairGeoTransform& dTC,const FairGeoTransform& mTR) +void FairGeoTorus::calcVoluPosition(FairGeoVolume*, const FairGeoTransform& dTC, const FairGeoTransform& mTR) { - // calls the function posInMother(...) to calculate the position of the - // volume in its mother - Double_t t[3]= {0.,0.,0.}; - center->setTransVector(t); - posInMother(dTC,mTR); + // calls the function posInMother(...) to calculate the position of the + // volume in its mother + Double_t t[3] = {0., 0., 0.}; + center->setTransVector(t); + posInMother(dTC, mTR); } diff --git a/geobase/FairGeoTorus.h b/geobase/FairGeoTorus.h index 9ceb2dd77e..9235b534f4 100644 --- a/geobase/FairGeoTorus.h +++ b/geobase/FairGeoTorus.h @@ -1,18 +1,17 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRGEOTORUS_H #define FAIRGEOTORUS_H -#include "FairGeoBasicShape.h" // for FairGeoBasicShape +#include "FairGeoBasicShape.h" // for FairGeoBasicShape -#include // for FairGeoPcon::Class, Bool_t, etc - -#include // for fstream +#include // for FairGeoPcon::Class, Bool_t, etc +#include // for fstream class FairGeoTransform; class FairGeoVolume; @@ -24,12 +23,12 @@ class FairGeoTorus : public FairGeoBasicShape FairGeoTorus(); ~FairGeoTorus(); TArrayD* calcVoluParam(FairGeoVolume*); - void calcVoluPosition(FairGeoVolume*, const FairGeoTransform&,const FairGeoTransform&); - Int_t readPoints(std::fstream* pFile,FairGeoVolume* volu); - Bool_t writePoints(std::fstream*,FairGeoVolume*); + void calcVoluPosition(FairGeoVolume*, const FairGeoTransform&, const FairGeoTransform&); + Int_t readPoints(std::fstream* pFile, FairGeoVolume* volu); + Bool_t writePoints(std::fstream*, FairGeoVolume*); void printPoints(FairGeoVolume* volu); - ClassDef(FairGeoTorus,0) // class for geometry shape TORUS + ClassDef(FairGeoTorus, 0) // class for geometry shape TORUS }; -#endif /* !FAIRGEOTORUS_H */ +#endif /* !FAIRGEOTORUS_H */ diff --git a/geobase/FairGeoTransform.cxx b/geobase/FairGeoTransform.cxx index 94c355bc32..2e366c612f 100644 --- a/geobase/FairGeoTransform.cxx +++ b/geobase/FairGeoTransform.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ //*-- AUTHOR : Ilse Koenig @@ -51,90 +51,93 @@ //#include //#include "math.h" -ClassImp(FairGeoTransform) +ClassImp(FairGeoTransform); + FairGeoTransform::FairGeoTransform() - : TObject(), - rot(FairGeoRotation(0,0,0)), - trans(FairGeoVector(0,0,0)), - trans_cm(FairGeoVector(0,0,0)) -{ -} + : TObject() + , rot(FairGeoRotation(0, 0, 0)) + , trans(FairGeoVector(0, 0, 0)) + , trans_cm(FairGeoVector(0, 0, 0)) +{} FairGeoTransform& FairGeoTransform::operator=(const FairGeoTransform& t) { - rot=t.getRotMatrix(); - trans=t.getTransVector(); + rot = t.getRotMatrix(); + trans = t.getTransVector(); - return *this; + return *this; } FairGeoVector FairGeoTransform::transFrom(const FairGeoVector& p) const { - // Transforms a vector (point) given in its own coordinate - // system (2) into the reference coordinate system (1) - // e.g. v2 is a vector (point) in the detector coordinate system; - // it can be transformed to a vector v2 the lab system with - // FairGeoVector v2=mo.transFrom(v1) - // where mo is the coordinate system of the mother - return rot*p+trans; + // Transforms a vector (point) given in its own coordinate + // system (2) into the reference coordinate system (1) + // e.g. v2 is a vector (point) in the detector coordinate system; + // it can be transformed to a vector v2 the lab system with + // FairGeoVector v2=mo.transFrom(v1) + // where mo is the coordinate system of the mother + return rot * p + trans; } FairGeoVector FairGeoTransform::transTo(const FairGeoVector& p) const { - // Transforms a vector (point) given in the reference system (1) - // into the local coordinate system (2) - // e.g. v1 is a vector (point) in the lab system; it can be transformed to - // a vector v2 the detector coordinate system with - // FairGeoVector v2=mo.transTo(v1) - // where mo is the coordinate system of the mother - return rot.inverse()*(p-trans); + // Transforms a vector (point) given in the reference system (1) + // into the local coordinate system (2) + // e.g. v1 is a vector (point) in the lab system; it can be transformed to + // a vector v2 the detector coordinate system with + // FairGeoVector v2=mo.transTo(v1) + // where mo is the coordinate system of the mother + return rot.inverse() * (p - trans); } void FairGeoTransform::transTo(const FairGeoTransform& s) { - // Transforms the coordinate system into the coordinate system - // described by s. Both transformations must have the same reference - // system e.g. the lab system - // This function is e.g. used to transform a daughter coordinate system - // with a transformation relative to the lab into the detector coordinate - // system. - const FairGeoRotation& rm=s.getRotMatrix(); - FairGeoRotation rt(rm.inverse()); - if (rm.diff2(rot)<0.000001) { rot.setUnitMatrix(); } - else { rot.transform(rt); } - trans-=s.getTransVector(); - trans=rt*trans; - // trans.round(3); // rounds to 3 digits (precision 1 micrometer) + // Transforms the coordinate system into the coordinate system + // described by s. Both transformations must have the same reference + // system e.g. the lab system + // This function is e.g. used to transform a daughter coordinate system + // with a transformation relative to the lab into the detector coordinate + // system. + const FairGeoRotation& rm = s.getRotMatrix(); + FairGeoRotation rt(rm.inverse()); + if (rm.diff2(rot) < 0.000001) { + rot.setUnitMatrix(); + } else { + rot.transform(rt); + } + trans -= s.getTransVector(); + trans = rt * trans; + // trans.round(3); // rounds to 3 digits (precision 1 micrometer) } void FairGeoTransform::transFrom(const FairGeoTransform& s) { - // Transforms the coordinate system described by s into the local - // coordinate system - // This function is e.g. used to transform a daughter coordinate system - // with a transformation relative to its mother into the lab system. - // e.g. daughterDetTransform.transFrom(motherLabTransform) - const FairGeoRotation& r=s.getRotMatrix(); - rot.transform(r); - trans=r*trans; - trans+=s.getTransVector(); + // Transforms the coordinate system described by s into the local + // coordinate system + // This function is e.g. used to transform a daughter coordinate system + // with a transformation relative to its mother into the lab system. + // e.g. daughterDetTransform.transFrom(motherLabTransform) + const FairGeoRotation& r = s.getRotMatrix(); + rot.transform(r); + trans = r * trans; + trans += s.getTransVector(); } void FairGeoTransform::clear() { - trans.clear(); - rot.setUnitMatrix(); + trans.clear(); + rot.setUnitMatrix(); } void FairGeoTransform::print() { - rot.print(); - trans.print(); + rot.print(); + trans.print(); } void FairGeoTransform::invert(void) { - rot.invert(); - trans = rot*trans; - trans *= -1.; + rot.invert(); + trans = rot * trans; + trans *= -1.; } diff --git a/geobase/FairGeoTransform.h b/geobase/FairGeoTransform.h index bf3009ea24..b0053931b2 100644 --- a/geobase/FairGeoTransform.h +++ b/geobase/FairGeoTransform.h @@ -1,19 +1,18 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRGEOTRANSFORM_H #define FAIRGEOTRANSFORM_H -#include // for TObject +#include "FairGeoRotation.h" // for FairGeoRotation +#include "FairGeoVector.h" // for FairGeoVector -#include "FairGeoRotation.h" // for FairGeoRotation -#include "FairGeoVector.h" // for FairGeoVector - -#include // for Double_t, etc +#include // for Double_t, etc +#include // for TObject /** * basic geometry transformation class @@ -21,9 +20,9 @@ class FairGeoTransform : public TObject { protected: - FairGeoRotation rot; /** rotation matrix, describing the orientation*/ - FairGeoVector trans; /** translation vector, describing the position*/ - FairGeoVector trans_cm; /** translation vector, describing the position in cm*/ + FairGeoRotation rot; /** rotation matrix, describing the orientation*/ + FairGeoVector trans; /** translation vector, describing the position*/ + FairGeoVector trans_cm; /** translation vector, describing the position in cm*/ public: FairGeoTransform(); @@ -32,10 +31,10 @@ class FairGeoTransform : public TObject FairGeoTransform& operator=(const FairGeoTransform& t); const FairGeoRotation& getRotMatrix() const { return rot; } const FairGeoVector& getTransVector() const { return trans; } - void setRotMatrix(const FairGeoRotation& r) { rot=r; } + void setRotMatrix(const FairGeoRotation& r) { rot = r; } void setRotMatrix(const Double_t* a) { rot.setMatrix(a); } void setRotMatrix(const Float_t* a) { rot.setMatrix(a); } - void setTransVector(const FairGeoVector& t) { trans=t; } + void setTransVector(const FairGeoVector& t) { trans = t; } void setTransVector(const Double_t* a) { trans.setVector(a); } void setTransVector(const Float_t* a) { trans.setVector(a); } FairGeoVector transFrom(const FairGeoVector& p) const; @@ -45,30 +44,30 @@ class FairGeoTransform : public TObject void invert(void); void clear(); void print(); - const FairGeoVector& getTranslation() { - const double fac = 10.; - trans_cm=trans; - return (trans_cm/=fac); + const FairGeoVector& getTranslation() + { + const double fac = 10.; + trans_cm = trans; + return (trans_cm /= fac); } const FairGeoRotation& getRotation() const { return rot; } inline void setTransform(const FairGeoTransform& t); - ClassDef(FairGeoTransform,1) // + ClassDef(FairGeoTransform, 1) // }; inline FairGeoTransform::FairGeoTransform(const FairGeoTransform& t) - : TObject(t), - rot(t.getRotMatrix()), - trans(t.getTransVector()), - trans_cm(FairGeoVector(0,0,0)) -{ -} + : TObject(t) + , rot(t.getRotMatrix()) + , trans(t.getTransVector()) + , trans_cm(FairGeoVector(0, 0, 0)) +{} inline void FairGeoTransform::setTransform(const FairGeoTransform& t) { - rot=t.getRotMatrix(); - trans=t.getTransVector(); + rot = t.getRotMatrix(); + trans = t.getTransVector(); } #endif /* !FAIRGEOTRANSFORM_H */ diff --git a/geobase/FairGeoTrap.cxx b/geobase/FairGeoTrap.cxx index 3fe08f7d4d..cff559e8d8 100644 --- a/geobase/FairGeoTrap.cxx +++ b/geobase/FairGeoTrap.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ //*-- AUTHOR : Ilse Koenig @@ -30,127 +30,138 @@ ///////////////////////////////////////////////////////////// #include "FairGeoTrap.h" -#include "FairGeoTransform.h" // for FairGeoTransform -#include "FairGeoVector.h" // for FairGeoVector -#include "FairGeoVolume.h" // for FairGeoVolume +#include "FairGeoTransform.h" // for FairGeoTransform +#include "FairGeoVector.h" // for FairGeoVector +#include "FairGeoVolume.h" // for FairGeoVolume -#include // for TArrayD -#include // for ATan, Pi, Sqrt, atan -#include // for Abs -#include // for TString - -#include // for operator<<, cout, etc +#include // for TArrayD +#include // for ATan, Pi, Sqrt, atan +#include // for Abs +#include // for TString +#include // for operator<<, cout, etc using std::cout; -ClassImp(FairGeoTrap) +ClassImp(FairGeoTrap); FairGeoTrap::FairGeoTrap() - :FairGeoBasicShape(), - intrinsicRot(FairGeoRotation()) + : FairGeoBasicShape() + , intrinsicRot(FairGeoRotation()) { - // constructor - fName="TRAP"; - nPoints=8; - nParam=11; - param=new TArrayD(nParam); - intrinsicRot.setElement(-1.,0); - intrinsicRot.setElement(-1.,4); + // constructor + fName = "TRAP"; + nPoints = 8; + nParam = 11; + param = new TArrayD(nParam); + intrinsicRot.setElement(-1., 0); + intrinsicRot.setElement(-1., 4); } - FairGeoTrap::~FairGeoTrap() { - // destructor - delete param; - param=0; - delete center; - center=0; - delete position; - position=0; + // destructor + delete param; + param = 0; + delete center; + center = 0; + delete position; + position = 0; } - TArrayD* FairGeoTrap::calcVoluParam(FairGeoVolume* volu) { - // calculates the parameters needed to create the shape - const Double_t fac=20.; - const Double_t raddeg=180./TMath::Pi(); - Double_t alpha, beta; - FairGeoVector cb, ct, dc; - for(Int_t i=0; i<4; i++) { cb+=*(volu->getPoint(i)); } // bottom plane - for(Int_t j=4; j<8; j++) { ct+=*(volu->getPoint(j)); } // top plane - dc=(ct-cb); -// cout << dc <<" "<< ct <<" "<< cb <<" "<< endl; - dc*=0.25; // vector from bottom to top plane - dc.setX(-dc(0)); // GEANT coordinate system - dc.setY(-dc(1)); - param->AddAt(TMath::Abs(dc(2))/fac,0); - alpha=TMath::ATan(TMath::Sqrt(dc(0)*dc(0)+dc(1)*dc(1))/dc(2))*raddeg; - if (TMath::Abs(alpha)<0.0001) { - alpha=0.0; - beta=0.0; - } else { - if (TMath::Abs(dc(0))<0.0001) { - if (dc(1)>0) { beta=90.0; } - else { beta=270.0; } + // calculates the parameters needed to create the shape + const Double_t fac = 20.; + const Double_t raddeg = 180. / TMath::Pi(); + Double_t alpha, beta; + FairGeoVector cb, ct, dc; + for (Int_t i = 0; i < 4; i++) { + cb += *(volu->getPoint(i)); + } // bottom plane + for (Int_t j = 4; j < 8; j++) { + ct += *(volu->getPoint(j)); + } // top plane + dc = (ct - cb); + // cout << dc <<" "<< ct <<" "<< cb <<" "<< endl; + dc *= 0.25; // vector from bottom to top plane + dc.setX(-dc(0)); // GEANT coordinate system + dc.setY(-dc(1)); + param->AddAt(TMath::Abs(dc(2)) / fac, 0); + alpha = TMath::ATan(TMath::Sqrt(dc(0) * dc(0) + dc(1) * dc(1)) / dc(2)) * raddeg; + if (TMath::Abs(alpha) < 0.0001) { + alpha = 0.0; + beta = 0.0; } else { - beta=atan(dc(1)/dc(0))*raddeg; - if (dc(0)<0) { beta=180.0 + beta; } - if (beta<0) { beta=360.0 + beta; } + if (TMath::Abs(dc(0)) < 0.0001) { + if (dc(1) > 0) { + beta = 90.0; + } else { + beta = 270.0; + } + } else { + beta = atan(dc(1) / dc(0)) * raddeg; + if (dc(0) < 0) { + beta = 180.0 + beta; + } + if (beta < 0) { + beta = 360.0 + beta; + } + } } - } - param->AddAt(alpha,1); - param->AddAt(beta,2); - param->AddAt(((*(volu->getPoint(1)))(1)-(*(volu->getPoint(0)))(1))/fac,3); - param->AddAt(((*(volu->getPoint(1)))(0)-(*(volu->getPoint(2)))(0))/fac,4); - param->AddAt(((*(volu->getPoint(0)))(0)-(*(volu->getPoint(3)))(0))/fac,5); - - Double_t a=TMath::ATan(((*(volu->getPoint(1)))(0) - - (*(volu->getPoint(0)))(0) - + (*(volu->getPoint(2)))(0) - - (*(volu->getPoint(3)))(0))/40./param->At(3) - )*raddeg; - if (TMath::Abs(a)<=0.0001) { param->AddAt(0.,6); } - else { param->AddAt(a,6); } - param->AddAt(((*(volu->getPoint(5)))(1)-(*(volu->getPoint(4)))(1))/fac,7); - param->AddAt(((*(volu->getPoint(5)))(0)-(*(volu->getPoint(6)))(0))/fac,8); - param->AddAt(((*(volu->getPoint(4)))(0)-(*(volu->getPoint(7)))(0))/fac,9); - a=TMath::ATan(((*(volu->getPoint(5)))(0) - - (*(volu->getPoint(4)))(0) - + (*(volu->getPoint(6)))(0) - - (*(volu->getPoint(7)))(0))/40./param->At(7))*raddeg; - if (TMath::Abs(a)<=0.0001) { param->AddAt(0.,10); } - else { param->AddAt(a,10); } -// check if coplanar - Double_t dx=(param->At(4) - param->At(5)) / param->At(3) * param->At(7) - - (param->At(8) - param->At(9)); - if (TMath::Abs(dx)>=0.001) { - cout << "top and bottom plane are not coplanar for shape TRAP\n"; - cout << "lenght in x-direction of top plane is changed\n"; - cout << "old values: " << param->At(8) << " " << param->At(9) << "\n"; - param->AddAt(param->At(8) + dx/2.,8); - param->AddAt(param->At(9) - dx/2.,9); - cout << "new values: " << param->At(8) << " " << param->At(9) << "\n"; - } - return param; + param->AddAt(alpha, 1); + param->AddAt(beta, 2); + param->AddAt(((*(volu->getPoint(1)))(1) - (*(volu->getPoint(0)))(1)) / fac, 3); + param->AddAt(((*(volu->getPoint(1)))(0) - (*(volu->getPoint(2)))(0)) / fac, 4); + param->AddAt(((*(volu->getPoint(0)))(0) - (*(volu->getPoint(3)))(0)) / fac, 5); + + Double_t a = TMath::ATan(((*(volu->getPoint(1)))(0) - (*(volu->getPoint(0)))(0) + (*(volu->getPoint(2)))(0) + - (*(volu->getPoint(3)))(0)) + / 40. / param->At(3)) + * raddeg; + if (TMath::Abs(a) <= 0.0001) { + param->AddAt(0., 6); + } else { + param->AddAt(a, 6); + } + param->AddAt(((*(volu->getPoint(5)))(1) - (*(volu->getPoint(4)))(1)) / fac, 7); + param->AddAt(((*(volu->getPoint(5)))(0) - (*(volu->getPoint(6)))(0)) / fac, 8); + param->AddAt(((*(volu->getPoint(4)))(0) - (*(volu->getPoint(7)))(0)) / fac, 9); + a = TMath::ATan(((*(volu->getPoint(5)))(0) - (*(volu->getPoint(4)))(0) + (*(volu->getPoint(6)))(0) + - (*(volu->getPoint(7)))(0)) + / 40. / param->At(7)) + * raddeg; + if (TMath::Abs(a) <= 0.0001) { + param->AddAt(0., 10); + } else { + param->AddAt(a, 10); + } + // check if coplanar + Double_t dx = (param->At(4) - param->At(5)) / param->At(3) * param->At(7) - (param->At(8) - param->At(9)); + if (TMath::Abs(dx) >= 0.001) { + cout << "top and bottom plane are not coplanar for shape TRAP\n"; + cout << "lenght in x-direction of top plane is changed\n"; + cout << "old values: " << param->At(8) << " " << param->At(9) << "\n"; + param->AddAt(param->At(8) + dx / 2., 8); + param->AddAt(param->At(9) - dx / 2., 9); + cout << "new values: " << param->At(8) << " " << param->At(9) << "\n"; + } + return param; } - -void FairGeoTrap::calcVoluPosition(FairGeoVolume* volu, - const FairGeoTransform& dTC,const FairGeoTransform& mTR) +void FairGeoTrap::calcVoluPosition(FairGeoVolume* volu, const FairGeoTransform& dTC, const FairGeoTransform& mTR) { - // calls the function posInMother(...) to calculate the position of the - // volume in its mother - Double_t t[3]= {0.,0.,0.}; - for(Int_t i=0; i<8; i++) { t[0]+=(*(volu->getPoint(i)))(0); } - t[0]/=8.; - t[1]=((*(volu->getPoint(1)))(1) + (*(volu->getPoint(0)))(1) + - (*(volu->getPoint(5)))(1) + (*(volu->getPoint(4)))(1))/4.; - t[2]=((*(volu->getPoint(4)))(2) + (*(volu->getPoint(0)))(2))/2.; - center->setTransVector(t); - center->setRotMatrix(intrinsicRot); - posInMother(dTC,mTR); + // calls the function posInMother(...) to calculate the position of the + // volume in its mother + Double_t t[3] = {0., 0., 0.}; + for (Int_t i = 0; i < 8; i++) { + t[0] += (*(volu->getPoint(i)))(0); + } + t[0] /= 8.; + t[1] = + ((*(volu->getPoint(1)))(1) + (*(volu->getPoint(0)))(1) + (*(volu->getPoint(5)))(1) + (*(volu->getPoint(4)))(1)) + / 4.; + t[2] = ((*(volu->getPoint(4)))(2) + (*(volu->getPoint(0)))(2)) / 2.; + center->setTransVector(t); + center->setRotMatrix(intrinsicRot); + posInMother(dTC, mTR); } - - diff --git a/geobase/FairGeoTrap.h b/geobase/FairGeoTrap.h index 4f4b1949d5..97cebbe448 100644 --- a/geobase/FairGeoTrap.h +++ b/geobase/FairGeoTrap.h @@ -8,11 +8,10 @@ #ifndef FAIRGEOTRAP_H #define FAIRGEOTRAP_H -#include "FairGeoBasicShape.h" // for FairGeoBasicShape +#include "FairGeoBasicShape.h" // for FairGeoBasicShape +#include "FairGeoRotation.h" // for FairGeoRotation -#include "FairGeoRotation.h" // for FairGeoRotation - -#include // for FairGeoPcon::Class, Bool_t, etc +#include // for FairGeoPcon::Class, Bool_t, etc class FairGeoTransform; class FairGeoVolume; @@ -27,8 +26,8 @@ class FairGeoTrap : public FairGeoBasicShape FairGeoTrap(); ~FairGeoTrap(); TArrayD* calcVoluParam(FairGeoVolume*); - void calcVoluPosition(FairGeoVolume*, const FairGeoTransform&,const FairGeoTransform&); - ClassDef(FairGeoTrap,0) // class for geometry shape TRAP + void calcVoluPosition(FairGeoVolume*, const FairGeoTransform&, const FairGeoTransform&); + ClassDef(FairGeoTrap, 0) // class for geometry shape TRAP }; -#endif /* !FAIRGEOTRAP_H */ +#endif /* !FAIRGEOTRAP_H */ diff --git a/geobase/FairGeoTrd1.cxx b/geobase/FairGeoTrd1.cxx index bec904a3b7..4dc63e7647 100644 --- a/geobase/FairGeoTrd1.cxx +++ b/geobase/FairGeoTrd1.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ //*-- AUTHOR : Ilse Koenig @@ -30,71 +30,73 @@ ///////////////////////////////////////////////////////////// #include "FairGeoTrd1.h" -#include "FairGeoTransform.h" // for FairGeoTransform -#include "FairGeoVector.h" // for FairGeoVector -#include "FairGeoVolume.h" // for FairGeoVolume +#include "FairGeoTransform.h" // for FairGeoTransform +#include "FairGeoVector.h" // for FairGeoVector +#include "FairGeoVolume.h" // for FairGeoVolume -#include // for TArrayD -#include // for Abs -#include // for TString +#include // for TArrayD +#include // for Abs +#include // for TString -ClassImp(FairGeoTrd1) +ClassImp(FairGeoTrd1); FairGeoTrd1::FairGeoTrd1() - :FairGeoBasicShape(), - intrinsicRot(FairGeoRotation()) + : FairGeoBasicShape() + , intrinsicRot(FairGeoRotation()) { - // constructor - fName="TRD1"; - nPoints=8; - nParam=4; - param=new TArrayD(nParam); - intrinsicRot.setZero(); - intrinsicRot.setElement(-1.,0); - intrinsicRot.setElement(1.,5); - intrinsicRot.setElement(1.,7); + // constructor + fName = "TRD1"; + nPoints = 8; + nParam = 4; + param = new TArrayD(nParam); + intrinsicRot.setZero(); + intrinsicRot.setElement(-1., 0); + intrinsicRot.setElement(1., 5); + intrinsicRot.setElement(1., 7); } FairGeoTrd1::~FairGeoTrd1() { - // destructor - delete param; - param=0; - delete center; - center=0; - delete position; - position=0; + // destructor + delete param; + param = 0; + delete center; + center = 0; + delete position; + position = 0; } TArrayD* FairGeoTrd1::calcVoluParam(FairGeoVolume* volu) { - // calculates the parameters needed to create the shape - Double_t fac=20.; - FairGeoVector& v0=*(volu->getPoint(0)); - FairGeoVector& v1=*(volu->getPoint(1)); - FairGeoVector& v2=*(volu->getPoint(2)); - FairGeoVector& v3=*(volu->getPoint(3)); - FairGeoVector& v4=*(volu->getPoint(4)); - param->AddAt(TMath::Abs((v0(0)-v3(0))/fac),0); - param->AddAt((v1(0)-v2(0))/fac,1); - param->AddAt((v4(2)-v0(2))/fac,2); - param->AddAt((v1(1)-v0(1))/fac,3); - return param; + // calculates the parameters needed to create the shape + Double_t fac = 20.; + FairGeoVector& v0 = *(volu->getPoint(0)); + FairGeoVector& v1 = *(volu->getPoint(1)); + FairGeoVector& v2 = *(volu->getPoint(2)); + FairGeoVector& v3 = *(volu->getPoint(3)); + FairGeoVector& v4 = *(volu->getPoint(4)); + param->AddAt(TMath::Abs((v0(0) - v3(0)) / fac), 0); + param->AddAt((v1(0) - v2(0)) / fac, 1); + param->AddAt((v4(2) - v0(2)) / fac, 2); + param->AddAt((v1(1) - v0(1)) / fac, 3); + return param; } -void FairGeoTrd1::calcVoluPosition(FairGeoVolume* volu, const FairGeoTransform& dTC,const FairGeoTransform& mTR) +void FairGeoTrd1::calcVoluPosition(FairGeoVolume* volu, const FairGeoTransform& dTC, const FairGeoTransform& mTR) { - // calls the function posInMother(...) to calculate the position of the - // volume in its mother - Double_t t[3]= {0.,0.,0.}; - for(Int_t i=0; i<4; i++) { t[0]+=(*(volu->getPoint(i)))(0); } - t[0]/=4.; - FairGeoVector& v0=*(volu->getPoint(0)); - FairGeoVector& v1=*(volu->getPoint(1)); - FairGeoVector& v4=*(volu->getPoint(4)); - t[1]=(v1(1)+v0(1))/2.; - t[2]=(v4(2)+v0(2))/2.; - center->setTransVector(t); - center->setRotMatrix(intrinsicRot); - posInMother(dTC,mTR); + // calls the function posInMother(...) to calculate the position of the + // volume in its mother + Double_t t[3] = {0., 0., 0.}; + for (Int_t i = 0; i < 4; i++) { + t[0] += (*(volu->getPoint(i)))(0); + } + t[0] /= 4.; + FairGeoVector& v0 = *(volu->getPoint(0)); + FairGeoVector& v1 = *(volu->getPoint(1)); + FairGeoVector& v4 = *(volu->getPoint(4)); + t[1] = (v1(1) + v0(1)) / 2.; + t[2] = (v4(2) + v0(2)) / 2.; + center->setTransVector(t); + center->setRotMatrix(intrinsicRot); + posInMother(dTC, mTR); } diff --git a/geobase/FairGeoTrd1.h b/geobase/FairGeoTrd1.h index 533cef09b0..9169c75990 100644 --- a/geobase/FairGeoTrd1.h +++ b/geobase/FairGeoTrd1.h @@ -1,18 +1,17 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRGEOTRD1_H #define FAIRGEOTRD1_H -#include "FairGeoBasicShape.h" // for FairGeoBasicShape +#include "FairGeoBasicShape.h" // for FairGeoBasicShape +#include "FairGeoRotation.h" // for FairGeoRotation -#include "FairGeoRotation.h" // for FairGeoRotation - -#include // for FairGeoPcon::Class, Bool_t, etc +#include // for FairGeoPcon::Class, Bool_t, etc class FairGeoTransform; class FairGeoVolume; @@ -27,9 +26,9 @@ class FairGeoTrd1 : public FairGeoBasicShape FairGeoTrd1(); ~FairGeoTrd1(); TArrayD* calcVoluParam(FairGeoVolume*); - void calcVoluPosition(FairGeoVolume*, const FairGeoTransform&,const FairGeoTransform&); + void calcVoluPosition(FairGeoVolume*, const FairGeoTransform&, const FairGeoTransform&); - ClassDef(FairGeoTrd1,0) // class for geometry shape TRD1 + ClassDef(FairGeoTrd1, 0) // class for geometry shape TRD1 }; -#endif /* !FAIRGEOTRD1_H */ +#endif /* !FAIRGEOTRD1_H */ diff --git a/geobase/FairGeoTube.cxx b/geobase/FairGeoTube.cxx index d23070efc7..8744b6e3a7 100644 --- a/geobase/FairGeoTube.cxx +++ b/geobase/FairGeoTube.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ //*-- AUTHOR : Ilse Koenig @@ -30,113 +30,123 @@ /////////////////////////////////////////////////////////////////////////////// #include "FairGeoTube.h" -#include "FairGeoTransform.h" // for FairGeoTransform -#include "FairGeoVector.h" // for FairGeoVector -#include "FairGeoVolume.h" // for FairGeoVolume +#include "FairGeoTransform.h" // for FairGeoTransform +#include "FairGeoVector.h" // for FairGeoVector +#include "FairGeoVolume.h" // for FairGeoVolume -#include // for TArrayD -#include // for Abs -#include // for TString - -#include // for printf, sprintf, sscanf -#include // for strlen -#include // for basic_ostream::write +#include // for TArrayD +#include // for Abs +#include // for TString #include +#include // for basic_ostream::write +#include // for printf, sprintf, sscanf +#include // for strlen -ClassImp(FairGeoTube) +ClassImp(FairGeoTube); FairGeoTube::FairGeoTube() - :FairGeoBasicShape() + : FairGeoBasicShape() { - // constructor - fName="TUBE"; - nPoints=3; - nParam=3; - param=new TArrayD(nParam); + // constructor + fName = "TUBE"; + nPoints = 3; + nParam = 3; + param = new TArrayD(nParam); } FairGeoTube::~FairGeoTube() { - // default destructor - delete param; - param=0; - delete center; - center=0; - delete position; - position=0; + // default destructor + delete param; + param = 0; + delete center; + center = 0; + delete position; + position = 0; } -Int_t FairGeoTube::readPoints(std::fstream* pFile,FairGeoVolume* volu) +Int_t FairGeoTube::readPoints(std::fstream* pFile, FairGeoVolume* volu) { - // reads the 3 'points' decribed above from ascii file - // if the array of points is not existing in the volume it is created and - // the values are stored inside - // returns the number of points - if (!pFile) { return 0; } - if (volu->getNumPoints()!=nPoints) { volu->createPoints(nPoints); } - Double_t x,y,z; - const Int_t maxbuf=155; - Text_t buf[maxbuf]; - for(Int_t i=0; igetline(buf,maxbuf); - if (i!=1) { - sscanf(buf,"%lf%lf%lf",&x,&y,&z); - volu->setPoint(i,x,y,z); - } else { - sscanf(buf,"%lf%lf",&x,&y); - volu->setPoint(i,x,y,0.0); + // reads the 3 'points' decribed above from ascii file + // if the array of points is not existing in the volume it is created and + // the values are stored inside + // returns the number of points + if (!pFile) { + return 0; + } + if (volu->getNumPoints() != nPoints) { + volu->createPoints(nPoints); + } + Double_t x, y, z; + const Int_t maxbuf = 155; + Text_t buf[maxbuf]; + for (Int_t i = 0; i < nPoints; i++) { + pFile->getline(buf, maxbuf); + if (i != 1) { + sscanf(buf, "%lf%lf%lf", &x, &y, &z); + volu->setPoint(i, x, y, z); + } else { + sscanf(buf, "%lf%lf", &x, &y); + volu->setPoint(i, x, y, 0.0); + } } - } - return nPoints; + return nPoints; } -Bool_t FairGeoTube::writePoints(std::fstream* pFile,FairGeoVolume* volu) +Bool_t FairGeoTube::writePoints(std::fstream* pFile, FairGeoVolume* volu) { - // writes the 3 'points' decribed above to ascii file - if (!pFile) { return kFALSE; } - Text_t buf[155]; - for(Int_t i=0; igetPoint(i)); - if (i!=1) { sprintf(buf,"%9.3f%10.3f%10.3f\n",v(0),v(1),v(2)); } - else { sprintf(buf,"%9.3f%10.3f\n",v(0),v(1)); } - pFile->write(buf,strlen(buf)); - } - return kTRUE; + // writes the 3 'points' decribed above to ascii file + if (!pFile) { + return kFALSE; + } + Text_t buf[155]; + for (Int_t i = 0; i < nPoints; i++) { + FairGeoVector& v = *(volu->getPoint(i)); + if (i != 1) { + sprintf(buf, "%9.3f%10.3f%10.3f\n", v(0), v(1), v(2)); + } else { + sprintf(buf, "%9.3f%10.3f\n", v(0), v(1)); + } + pFile->write(buf, strlen(buf)); + } + return kTRUE; } void FairGeoTube::printPoints(FairGeoVolume* volu) { - // prints volume points to screen - for(Int_t i=0; igetPoint(i)); - if (i!=1) { printf("%9.3f%10.3f%10.3f\n",v(0),v(1),v(2)); } - else { printf("%9.3f%10.3f\n",v(0),v(1)); } - } + // prints volume points to screen + for (Int_t i = 0; i < nPoints; i++) { + FairGeoVector& v = *(volu->getPoint(i)); + if (i != 1) { + printf("%9.3f%10.3f%10.3f\n", v(0), v(1), v(2)); + } else { + printf("%9.3f%10.3f\n", v(0), v(1)); + } + } } TArrayD* FairGeoTube::calcVoluParam(FairGeoVolume* volu) { - // calculates the parameters needed to create the shape TUBE - Double_t fac=10.; - FairGeoVector& v1=*(volu->getPoint(1)); - param->AddAt(v1(0)/fac,0); - param->AddAt(v1(1)/fac,1); - FairGeoVector v=*(volu->getPoint(2)) - *(volu->getPoint(0)); - param->AddAt(TMath::Abs(v(2))/fac/2.,2); - return param; + // calculates the parameters needed to create the shape TUBE + Double_t fac = 10.; + FairGeoVector& v1 = *(volu->getPoint(1)); + param->AddAt(v1(0) / fac, 0); + param->AddAt(v1(1) / fac, 1); + FairGeoVector v = *(volu->getPoint(2)) - *(volu->getPoint(0)); + param->AddAt(TMath::Abs(v(2)) / fac / 2., 2); + return param; } -void FairGeoTube::calcVoluPosition(FairGeoVolume* volu, - const FairGeoTransform& dTC,const FairGeoTransform& mTR) +void FairGeoTube::calcVoluPosition(FairGeoVolume* volu, const FairGeoTransform& dTC, const FairGeoTransform& mTR) { - // calculates the position of the center of the ROOT volume in the intrinsic - // coordinate system and stores it in the data element 'center' - // calls the function posInMother(...) to calculate the position of the - // volume in its mother - Double_t t[3]= {0.,0.,0.}; - FairGeoVector v=*(volu->getPoint(2)) + *(volu->getPoint(0)); - t[2]=v(2)/2.; - center->clear(); - center->setTransVector(t); - posInMother(dTC,mTR); + // calculates the position of the center of the ROOT volume in the intrinsic + // coordinate system and stores it in the data element 'center' + // calls the function posInMother(...) to calculate the position of the + // volume in its mother + Double_t t[3] = {0., 0., 0.}; + FairGeoVector v = *(volu->getPoint(2)) + *(volu->getPoint(0)); + t[2] = v(2) / 2.; + center->clear(); + center->setTransVector(t); + posInMother(dTC, mTR); } diff --git a/geobase/FairGeoTube.h b/geobase/FairGeoTube.h index 3d1b121931..832948b2bc 100644 --- a/geobase/FairGeoTube.h +++ b/geobase/FairGeoTube.h @@ -1,18 +1,17 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRGEOTUBE_H #define FAIRGEOTUBE_H -#include "FairGeoBasicShape.h" // for FairGeoBasicShape +#include "FairGeoBasicShape.h" // for FairGeoBasicShape -#include // for FairGeoPcon::Class, Bool_t, etc - -#include // for fstream +#include // for FairGeoPcon::Class, Bool_t, etc +#include // for fstream class FairGeoTransform; class FairGeoVolume; @@ -24,11 +23,11 @@ class FairGeoTube : public FairGeoBasicShape FairGeoTube(); ~FairGeoTube(); TArrayD* calcVoluParam(FairGeoVolume*); - void calcVoluPosition(FairGeoVolume*, const FairGeoTransform&,const FairGeoTransform&); - Int_t readPoints(std::fstream*,FairGeoVolume*); - Bool_t writePoints(std::fstream*,FairGeoVolume*); + void calcVoluPosition(FairGeoVolume*, const FairGeoTransform&, const FairGeoTransform&); + Int_t readPoints(std::fstream*, FairGeoVolume*); + Bool_t writePoints(std::fstream*, FairGeoVolume*); void printPoints(FairGeoVolume* volu); - ClassDef(FairGeoTube,0) // class for geometry shape TUBE + ClassDef(FairGeoTube, 0) // class for geometry shape TUBE }; -#endif /* !FAIRGEOTUBE_H */ +#endif /* !FAIRGEOTUBE_H */ diff --git a/geobase/FairGeoTubs.cxx b/geobase/FairGeoTubs.cxx index b4c3c57949..553f7a00a6 100644 --- a/geobase/FairGeoTubs.cxx +++ b/geobase/FairGeoTubs.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ //*-- AUTHOR : Ilse Koenig @@ -33,114 +33,125 @@ /////////////////////////////////////////////////////////////////////////////// #include "FairGeoTubs.h" -#include "FairGeoTransform.h" // for FairGeoTransform -#include "FairGeoVector.h" // for FairGeoVector -#include "FairGeoVolume.h" // for FairGeoVolume +#include "FairGeoTransform.h" // for FairGeoTransform +#include "FairGeoVector.h" // for FairGeoVector +#include "FairGeoVolume.h" // for FairGeoVolume -#include // for TArrayD -#include // for Abs -#include // for TString - -#include // for printf, sprintf, sscanf -#include // for strlen -#include // for basic_ostream::write +#include // for TArrayD +#include // for Abs +#include // for TString #include +#include // for basic_ostream::write +#include // for printf, sprintf, sscanf +#include // for strlen -ClassImp(FairGeoTubs) +ClassImp(FairGeoTubs); FairGeoTubs::FairGeoTubs() - :FairGeoBasicShape() + : FairGeoBasicShape() { - // constructor - fName="TUBS"; - nPoints=4; - nParam=5; - param=new TArrayD(nParam); + // constructor + fName = "TUBS"; + nPoints = 4; + nParam = 5; + param = new TArrayD(nParam); } FairGeoTubs::~FairGeoTubs() { - // default destructor - delete param; - param=0; - delete center; - center=0; - delete position; - position=0; + // default destructor + delete param; + param = 0; + delete center; + center = 0; + delete position; + position = 0; } -Int_t FairGeoTubs::readPoints(std::fstream* pFile,FairGeoVolume* volu) +Int_t FairGeoTubs::readPoints(std::fstream* pFile, FairGeoVolume* volu) { - // reads the 4 'points' decribed above from ascii file - // if the array of points is not existing in the volume it is created and - // the values are stored inside - // returns the number of points - if (!pFile) { return 0; } - if (volu->getNumPoints()!=nPoints) { volu->createPoints(nPoints); } - Double_t x,y,z; - const Int_t maxbuf=155; - Text_t buf[maxbuf]; - for(Int_t i=0; igetline(buf,maxbuf); - sscanf(buf,"%lf%lf%lf",&x,&y,&z); - volu->setPoint(i,x,y,z); - i++; - pFile->getline(buf,maxbuf); - sscanf(buf,"%lf%lf",&x,&y); - volu->setPoint(i,x,y,0.0); - } - return nPoints; + // reads the 4 'points' decribed above from ascii file + // if the array of points is not existing in the volume it is created and + // the values are stored inside + // returns the number of points + if (!pFile) { + return 0; + } + if (volu->getNumPoints() != nPoints) { + volu->createPoints(nPoints); + } + Double_t x, y, z; + const Int_t maxbuf = 155; + Text_t buf[maxbuf]; + for (Int_t i = 0; i < nPoints; i++) { + pFile->getline(buf, maxbuf); + sscanf(buf, "%lf%lf%lf", &x, &y, &z); + volu->setPoint(i, x, y, z); + i++; + pFile->getline(buf, maxbuf); + sscanf(buf, "%lf%lf", &x, &y); + volu->setPoint(i, x, y, 0.0); + } + return nPoints; } -Bool_t FairGeoTubs::writePoints(std::fstream* pFile,FairGeoVolume* volu) +Bool_t FairGeoTubs::writePoints(std::fstream* pFile, FairGeoVolume* volu) { - // writes the 4 'points' decribed above to ascii file - if (!pFile) { return kFALSE; } - Text_t buf[155]; - for(Int_t i=0; igetPoint(i)); - if (i==0 || i==2) { sprintf(buf,"%9.3f%10.3f%10.3f\n",v(0),v(1),v(2)); } - else { sprintf(buf,"%9.3f%10.3f\n",v(0),v(1)); } - pFile->write(buf,strlen(buf)); - } - return kTRUE; + // writes the 4 'points' decribed above to ascii file + if (!pFile) { + return kFALSE; + } + Text_t buf[155]; + for (Int_t i = 0; i < nPoints; i++) { + FairGeoVector& v = *(volu->getPoint(i)); + if (i == 0 || i == 2) { + sprintf(buf, "%9.3f%10.3f%10.3f\n", v(0), v(1), v(2)); + } else { + sprintf(buf, "%9.3f%10.3f\n", v(0), v(1)); + } + pFile->write(buf, strlen(buf)); + } + return kTRUE; } void FairGeoTubs::printPoints(FairGeoVolume* volu) { - // prints volume points to screen - for(Int_t i=0; igetPoint(i)); - if (i==0 || i==2) { printf("%9.3f%10.3f%10.3f\n",v(0),v(1),v(2)); } - else { printf("%9.3f%10.3f\n",v(0),v(1)); } - } + // prints volume points to screen + for (Int_t i = 0; i < nPoints; i++) { + FairGeoVector& v = *(volu->getPoint(i)); + if (i == 0 || i == 2) { + printf("%9.3f%10.3f%10.3f\n", v(0), v(1), v(2)); + } else { + printf("%9.3f%10.3f\n", v(0), v(1)); + } + } } TArrayD* FairGeoTubs::calcVoluParam(FairGeoVolume* volu) { - // calculates the parameters needed to create the shape TUBS - Double_t fac=10.; - FairGeoVector& v1=*(volu->getPoint(1)); - param->AddAt(v1(0)/fac,0); - param->AddAt(v1(1)/fac,1); - FairGeoVector v=*(volu->getPoint(2)) - *(volu->getPoint(0)); - param->AddAt(TMath::Abs(v(2))/fac/2.,2); - FairGeoVector& v3=*(volu->getPoint(3)); - param->AddAt(v3(0),3); - param->AddAt(v3(1),4); - return param; + // calculates the parameters needed to create the shape TUBS + Double_t fac = 10.; + FairGeoVector& v1 = *(volu->getPoint(1)); + param->AddAt(v1(0) / fac, 0); + param->AddAt(v1(1) / fac, 1); + FairGeoVector v = *(volu->getPoint(2)) - *(volu->getPoint(0)); + param->AddAt(TMath::Abs(v(2)) / fac / 2., 2); + FairGeoVector& v3 = *(volu->getPoint(3)); + param->AddAt(v3(0), 3); + param->AddAt(v3(1), 4); + return param; } -void FairGeoTubs::calcVoluPosition(FairGeoVolume* volu, const FairGeoTransform& dTC,const FairGeoTransform& mTR) +void FairGeoTubs::calcVoluPosition(FairGeoVolume* volu, const FairGeoTransform& dTC, const FairGeoTransform& mTR) { - // calculates the position of the center of the volume in the intrinsic - // coordinate system and stores it in the data element 'center' - // calls the function posInMother(...) to calculate the position of the - // volume in its mother - Double_t t[3]= {0.,0.,0.}; - FairGeoVector v=*(volu->getPoint(2)) + *(volu->getPoint(0)); - t[2]=v(2)/2.; - center->clear(); - center->setTransVector(t); - posInMother(dTC,mTR); + // calculates the position of the center of the volume in the intrinsic + // coordinate system and stores it in the data element 'center' + // calls the function posInMother(...) to calculate the position of the + // volume in its mother + Double_t t[3] = {0., 0., 0.}; + FairGeoVector v = *(volu->getPoint(2)) + *(volu->getPoint(0)); + t[2] = v(2) / 2.; + center->clear(); + center->setTransVector(t); + posInMother(dTC, mTR); } diff --git a/geobase/FairGeoTubs.h b/geobase/FairGeoTubs.h index 2d494d1c17..4f773a12fd 100644 --- a/geobase/FairGeoTubs.h +++ b/geobase/FairGeoTubs.h @@ -1,18 +1,17 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRGEOTUBS_H #define FAIRGEOTUBS_H -#include "FairGeoBasicShape.h" // for FairGeoBasicShape +#include "FairGeoBasicShape.h" // for FairGeoBasicShape -#include // for FairGeoPcon::Class, Bool_t, etc - -#include // for fstream +#include // for FairGeoPcon::Class, Bool_t, etc +#include // for fstream class FairGeoTransform; class FairGeoVolume; @@ -24,11 +23,11 @@ class FairGeoTubs : public FairGeoBasicShape FairGeoTubs(); ~FairGeoTubs(); TArrayD* calcVoluParam(FairGeoVolume*); - void calcVoluPosition(FairGeoVolume*, const FairGeoTransform&,const FairGeoTransform&); - Int_t readPoints(std::fstream*,FairGeoVolume*); - Bool_t writePoints(std::fstream*,FairGeoVolume*); + void calcVoluPosition(FairGeoVolume*, const FairGeoTransform&, const FairGeoTransform&); + Int_t readPoints(std::fstream*, FairGeoVolume*); + Bool_t writePoints(std::fstream*, FairGeoVolume*); void printPoints(FairGeoVolume* volu); - ClassDef(FairGeoTubs,0) // class for geometry shape TUBS + ClassDef(FairGeoTubs, 0) // class for geometry shape TUBS }; -#endif /* !FAIRGEOTUBS_H */ +#endif /* !FAIRGEOTUBS_H */ diff --git a/geobase/FairGeoVector.cxx b/geobase/FairGeoVector.cxx index a44c5da30a..f0ae32517b 100644 --- a/geobase/FairGeoVector.cxx +++ b/geobase/FairGeoVector.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ //*-- AUTHOR : Ilse Koenig @@ -92,4 +92,4 @@ #include "FairGeoVector.h" -ClassImp(FairGeoVector) +ClassImp(FairGeoVector); diff --git a/geobase/FairGeoVector.h b/geobase/FairGeoVector.h index 0f37579777..c142d8f86c 100644 --- a/geobase/FairGeoVector.h +++ b/geobase/FairGeoVector.h @@ -1,22 +1,20 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRGEOVECTOR_H #define FAIRGEOVECTOR_H -#include // for TObject - -#include // for Double_t, Bool_t, Int_t, etc -#include // for pow, floor, sqrt -#include // for Abs - -#include // for printf -#include // for operator<<, ostream, etc +#include // for Double_t, Bool_t, Int_t, etc +#include // for pow, floor, sqrt +#include // for Abs +#include // for TObject #include +#include // for operator<<, ostream, etc +#include // for printf class FairGeoVector : public TObject { @@ -24,264 +22,257 @@ class FairGeoVector : public TObject Double_t x; Double_t y; Double_t z; - inline void round(Double_t d,Int_t n); + inline void round(Double_t d, Int_t n); public: - FairGeoVector(Double_t dx=0,Double_t dy=0,Double_t dz=0) - : TObject(),x(dx),y(dy),z(dz) {} + FairGeoVector(Double_t dx = 0, Double_t dy = 0, Double_t dz = 0) + : TObject() + , x(dx) + , y(dy) + , z(dz) + {} FairGeoVector(const FairGeoVector& v) - : TObject(v),x(v.getX()), y(v.getY()), z(v.getZ()) {} + : TObject(v) + , x(v.getX()) + , y(v.getY()) + , z(v.getZ()) + {} ~FairGeoVector() {} - Double_t& X() {return x;} - Double_t& Y() {return y;} - Double_t& Z() {return z;} - Double_t getX() const {return x;} - Double_t getY() const {return y;} - Double_t getZ() const {return z;} - - Double_t getValues(Int_t i ) { - if ( i<0 || i>2 ) { - std::cout << " -E- Vector index is 0 1 2 only ! " << std::endl; - } - if ( i == 0 ) { return x; } - if ( i == 1 ) { return y; } - if ( i == 2 ) { return z; } - return -1; + Double_t& X() { return x; } + Double_t& Y() { return y; } + Double_t& Z() { return z; } + Double_t getX() const { return x; } + Double_t getY() const { return y; } + Double_t getZ() const { return z; } + + Double_t getValues(Int_t i) + { + if (i < 0 || i > 2) { + std::cout << " -E- Vector index is 0 1 2 only ! " << std::endl; + } + if (i == 0) { + return x; + } + if (i == 1) { + return y; + } + if (i == 2) { + return z; + } + return -1; } - void setXYZ(const Double_t xx,const Double_t yy,const Double_t zz) { - x=xx; - y=yy; - z=zz; + void setXYZ(const Double_t xx, const Double_t yy, const Double_t zz) + { + x = xx; + y = yy; + z = zz; } - void setX(const Double_t a) {x=a;} - void setY(const Double_t a) {y=a;} - void setZ(const Double_t a) {z=a;} + void setX(const Double_t a) { x = a; } + void setY(const Double_t a) { y = a; } + void setZ(const Double_t a) { z = a; } inline void setVector(const Double_t* a); inline void setVector(const Float_t* a); - inline Double_t operator() (const Int_t i) const; - inline FairGeoVector operator - () const; - inline FairGeoVector& operator = (const FairGeoVector& v); - inline Bool_t operator == (const FairGeoVector& v) const; - inline Bool_t operator != (const FairGeoVector& v) const; - inline Bool_t operator < (const Double_t a); - inline Bool_t operator <= (const Double_t a); - inline Bool_t operator > (const Double_t a); - inline Bool_t operator >= (const Double_t a); - inline FairGeoVector& operator += (const Double_t a); - inline FairGeoVector& operator -= (const Double_t a); - inline FairGeoVector& operator *= (const Double_t a); - inline FairGeoVector& operator /= (const Double_t a); - inline FairGeoVector& operator += (const FairGeoVector& v); - inline FairGeoVector& operator -= (const FairGeoVector& v); - inline FairGeoVector operator + (const FairGeoVector& v) const; - inline FairGeoVector operator - (const FairGeoVector& v) const; + inline Double_t operator()(const Int_t i) const; + inline FairGeoVector operator-() const; + inline FairGeoVector& operator=(const FairGeoVector& v); + inline Bool_t operator==(const FairGeoVector& v) const; + inline Bool_t operator!=(const FairGeoVector& v) const; + inline Bool_t operator<(const Double_t a); + inline Bool_t operator<=(const Double_t a); + inline Bool_t operator>(const Double_t a); + inline Bool_t operator>=(const Double_t a); + inline FairGeoVector& operator+=(const Double_t a); + inline FairGeoVector& operator-=(const Double_t a); + inline FairGeoVector& operator*=(const Double_t a); + inline FairGeoVector& operator/=(const Double_t a); + inline FairGeoVector& operator+=(const FairGeoVector& v); + inline FairGeoVector& operator-=(const FairGeoVector& v); + inline FairGeoVector operator+(const FairGeoVector& v) const; + inline FairGeoVector operator-(const FairGeoVector& v) const; inline FairGeoVector& abs(); inline Double_t scalarProduct(const FairGeoVector& v) const; inline FairGeoVector vectorProduct(const FairGeoVector& v) const; - Double_t length() const {return sqrt(x*x+y*y+z*z);} - void clear() {x=y=z=0.;} - void print() const {printf("%10.3f%10.3f%10.3f\n",x,y,z);} + Double_t length() const { return sqrt(x * x + y * y + z * z); } + void clear() { x = y = z = 0.; } + void print() const { printf("%10.3f%10.3f%10.3f\n", x, y, z); } inline void round(Int_t n); - inline friend std::ostream& operator << (std::ostream& put,const FairGeoVector& v); - inline friend std::istream& operator >> (std::istream& get,FairGeoVector& v); - ClassDef(FairGeoVector,1) // vector with 3 components + inline friend std::ostream& operator<<(std::ostream& put, const FairGeoVector& v); + inline friend std::istream& operator>>(std::istream& get, FairGeoVector& v); + ClassDef(FairGeoVector, 1) // vector with 3 components }; // -------------------- inlines --------------------------- inline void FairGeoVector::setVector(const Double_t* a) { - x=a[0]; - y=a[1]; - z=a[2]; + x = a[0]; + y = a[1]; + z = a[2]; } inline void FairGeoVector::setVector(const Float_t* a) { - x=a[0]; - y=a[1]; - z=a[2]; + x = a[0]; + y = a[1]; + z = a[2]; } -inline Double_t FairGeoVector::operator() (const Int_t i) const +inline Double_t FairGeoVector::operator()(const Int_t i) const { - switch (i) { - case 0: - return x; - case 1: - return y; - case 2: - return z; - default: - Error("operator()","bad index"); - } - return 0; + switch (i) { + case 0: + return x; + case 1: + return y; + case 2: + return z; + default: + Error("operator()", "bad index"); + } + return 0; } -inline FairGeoVector FairGeoVector::operator - () const +inline FairGeoVector FairGeoVector::operator-() const { - FairGeoVector p(-x,-y,-z); - return p; + FairGeoVector p(-x, -y, -z); + return p; } -inline FairGeoVector& FairGeoVector::operator = (const FairGeoVector& v) +inline FairGeoVector& FairGeoVector::operator=(const FairGeoVector& v) { - x=v.getX(); - y=v.getY(); - z=v.getZ(); - return *this; + x = v.getX(); + y = v.getY(); + z = v.getZ(); + return *this; } -inline Bool_t FairGeoVector::operator == (const FairGeoVector& v) const +inline Bool_t FairGeoVector::operator==(const FairGeoVector& v) const { - return ((v.getX()!=x || v.getY()!=y || v.getZ()!=z) ? kFALSE : kTRUE); + return ((v.getX() != x || v.getY() != y || v.getZ() != z) ? kFALSE : kTRUE); } -inline Bool_t FairGeoVector::operator != (const FairGeoVector& v) const +inline Bool_t FairGeoVector::operator!=(const FairGeoVector& v) const { - return (v.getX()!=x || v.getY()!=y || v.getZ()!=z) ? kTRUE : kFALSE; + return (v.getX() != x || v.getY() != y || v.getZ() != z) ? kTRUE : kFALSE; } /// check with ilse -inline Bool_t FairGeoVector::operator < (const Double_t a) -{ - return (x>=a || y>=a || z>=a) ? kFALSE : kTRUE; -} +inline Bool_t FairGeoVector::operator<(const Double_t a) { return (x >= a || y >= a || z >= a) ? kFALSE : kTRUE; } -inline Bool_t FairGeoVector::operator <= (const Double_t a) -{ - return (x>a || y>a || z>a) ? kFALSE : kTRUE; -} +inline Bool_t FairGeoVector::operator<=(const Double_t a) { return (x > a || y > a || z > a) ? kFALSE : kTRUE; } -inline Bool_t FairGeoVector::operator > (const Double_t a) -{ - return (x<=a || y<=a || z<=a) ? kFALSE : kTRUE; -} +inline Bool_t FairGeoVector::operator>(const Double_t a) { return (x <= a || y <= a || z <= a) ? kFALSE : kTRUE; } -inline Bool_t FairGeoVector::operator >= (const Double_t a) -{ - return (x=(const Double_t a) { return (x < a || y < a || z < a) ? kFALSE : kTRUE; } -inline FairGeoVector& FairGeoVector::operator += (const Double_t a) +inline FairGeoVector& FairGeoVector::operator+=(const Double_t a) { - x+=a; - y+=a; - z+=a; - return *this; + x += a; + y += a; + z += a; + return *this; } -inline FairGeoVector& FairGeoVector::operator -= (const Double_t a) +inline FairGeoVector& FairGeoVector::operator-=(const Double_t a) { - x-=a; - y-=a; - z-=a; - return *this; + x -= a; + y -= a; + z -= a; + return *this; } -inline FairGeoVector& FairGeoVector::operator *= (const Double_t a) +inline FairGeoVector& FairGeoVector::operator*=(const Double_t a) { - x*=a; - y*=a; - z*=a; - return *this; + x *= a; + y *= a; + z *= a; + return *this; } -inline FairGeoVector& FairGeoVector::operator /= (const Double_t a) +inline FairGeoVector& FairGeoVector::operator/=(const Double_t a) { - x/=a; - y/=a; - z/=a; - return *this; + x /= a; + y /= a; + z /= a; + return *this; } -inline FairGeoVector& FairGeoVector::operator += (const FairGeoVector& v) +inline FairGeoVector& FairGeoVector::operator+=(const FairGeoVector& v) { - x+=v.getX(); - y+=v.getY(); - z+=v.getZ(); - return *this; + x += v.getX(); + y += v.getY(); + z += v.getZ(); + return *this; } -inline FairGeoVector& FairGeoVector::operator -= (const FairGeoVector& v) +inline FairGeoVector& FairGeoVector::operator-=(const FairGeoVector& v) { - x-=v.getX(); - y-=v.getY(); - z-=v.getZ(); - return *this; + x -= v.getX(); + y -= v.getY(); + z -= v.getZ(); + return *this; } -inline FairGeoVector FairGeoVector::operator + (const FairGeoVector& v) const +inline FairGeoVector FairGeoVector::operator+(const FairGeoVector& v) const { - FairGeoVector p(*this); - return p+=v; + FairGeoVector p(*this); + return p += v; } -inline FairGeoVector FairGeoVector::operator - (const FairGeoVector& v) const +inline FairGeoVector FairGeoVector::operator-(const FairGeoVector& v) const { - FairGeoVector p(*this); - return p-=v; + FairGeoVector p(*this); + return p -= v; } inline FairGeoVector& FairGeoVector::abs() { - x=TMath::Abs(x); - y=TMath::Abs(y); - z=TMath::Abs(z); - return *this; + x = TMath::Abs(x); + y = TMath::Abs(y); + z = TMath::Abs(z); + return *this; } inline Double_t FairGeoVector::scalarProduct(const FairGeoVector& v) const { - return (x*v.getX()+y*v.getY()+z*v.getZ()); + return (x * v.getX() + y * v.getY() + z * v.getZ()); } inline FairGeoVector FairGeoVector::vectorProduct(const FairGeoVector& v) const { - FairGeoVector p(y*v.getZ()-z*v.getY(),z*v.getX()-x*v.getZ(), - x*v.getY()-y*v.getX()); - return p; + FairGeoVector p(y * v.getZ() - z * v.getY(), z * v.getX() - x * v.getZ(), x * v.getY() - y * v.getX()); + return p; } -inline void FairGeoVector::round(Double_t d,Int_t n) +inline void FairGeoVector::round(Double_t d, Int_t n) { - // rounds d to a precision with n digits - if(d>0) { d=floor(d*pow(10.,n)+0.5)/pow(10.,n); } - else { d=-floor((-d)*pow(10.,n)+0.5)/pow(10.,n); } + // rounds d to a precision with n digits + if (d > 0) { + d = floor(d * pow(10., n) + 0.5) / pow(10., n); + } else { + d = -floor((-d) * pow(10., n) + 0.5) / pow(10., n); + } } inline void FairGeoVector::round(Int_t n) { - // rounds every component to a precision with n digits - round(x,n); - round(y,n); - round(z,n); + // rounds every component to a precision with n digits + round(x, n); + round(y, n); + round(z, n); } -inline std::ostream& operator << (std::ostream& put,const FairGeoVector& v) +inline std::ostream& operator<<(std::ostream& put, const FairGeoVector& v) { - return put<> (std::istream& get,FairGeoVector& v) +inline std::istream& operator>>(std::istream& get, FairGeoVector& v) { - Double_t x[3]; - get>>x[0]>>x[1]>>x[2]; - v.setVector(x); - return get; + Double_t x[3]; + get >> x[0] >> x[1] >> x[2]; + v.setVector(x); + return get; } #endif /* !FAIRGEOVECTOR_H */ - - - - - - - - - - - - - diff --git a/geobase/FairGeoVolume.cxx b/geobase/FairGeoVolume.cxx index 3c9bf4fcea..85b57fad81 100644 --- a/geobase/FairGeoVolume.cxx +++ b/geobase/FairGeoVolume.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ //*-- AUTHOR : Ilse Koenig @@ -28,126 +28,137 @@ ///////////////////////////////////////////////////////////// #include "FairGeoVolume.h" -#include // for operator<<, basic_ostream, etc +#include // for operator<<, basic_ostream, etc using std::cout; using std::endl; -ClassImp(FairGeoVolume) +ClassImp(FairGeoVolume); FairGeoVolume::FairGeoVolume(FairGeoVolume& r) - : TNamed(r), - shape(""), - mother(""), - points(NULL), - transform(FairGeoTransform()), - fLabTransform(FairGeoTransform()), - fMedium(0), - nPoints(0), - fHadFormat(0), - fgMCid(0) + : TNamed(r) + , shape("") + , mother("") + , points(NULL) + , transform(FairGeoTransform()) + , fLabTransform(FairGeoTransform()) + , fMedium(0) + , nPoints(0) + , fHadFormat(0) + , fgMCid(0) { - // copy constructor - // fName=r.GetName(); - setVolumePar(r); + // copy constructor + // fName=r.GetName(); + setVolumePar(r); } void FairGeoVolume::setVolumePar(FairGeoVolume& r) { - // copies all volume parameters except the name - shape=r.getShape(); - mother=r.getMother(); - Int_t n=r.getNumPoints(); - createPoints(n); - for (Int_t i=0; i0) { - if (points!=0) { - points->Delete(); - delete points; - } - points=new TObjArray(n); - for(Int_t i=0; iAddAt(new FairGeoVector(),i); } - } else { - if (points) { points->Delete(); } - delete points; - points=0; + // Creates n Points (objects of class FairGeoVector). + // If the array exists already and the size is different from n it is + // deleted and recreated with the new size n. + // If n==0 the points are deleted. + if (n != nPoints) { + nPoints = n; + if (n > 0) { + if (points != 0) { + points->Delete(); + delete points; + } + points = new TObjArray(n); + for (Int_t i = 0; i < n; i++) { + points->AddAt(new FairGeoVector(), i); + } + } else { + if (points) { + points->Delete(); + } + delete points; + points = 0; + } } - } } -void FairGeoVolume::setPoint(const Int_t n,const Double_t x, - const Double_t y,const Double_t z) +void FairGeoVolume::setPoint(const Int_t n, const Double_t x, const Double_t y, const Double_t z) { - // set the 3 values of the point with index n - if (points && n(points->At(n)); - v->setX(x); - v->setY(y); - v->setZ(z); - } + // set the 3 values of the point with index n + if (points && n < nPoints) { + FairGeoVector* v = static_cast(points->At(n)); + v->setX(x); + v->setY(y); + v->setZ(z); + } } -void FairGeoVolume::setPoint(const Int_t n,const FairGeoVector& p) +void FairGeoVolume::setPoint(const Int_t n, const FairGeoVector& p) { - // sets point with index n by copying the 3 components of point p - if (points && n(points->At(n))); - v=p; - } + // sets point with index n by copying the 3 components of point p + if (points && n < nPoints) { + FairGeoVector& v = *(static_cast(points->At(n))); + v = p; + } } void FairGeoVolume::clear() { - // clears the volume - // deletes the points - shape=""; - mother=""; - if (points) { points->Delete(); } - delete points; - points=0; - nPoints=0; - transform.clear(); + // clears the volume + // deletes the points + shape = ""; + mother = ""; + if (points) { + points->Delete(); + } + delete points; + points = 0; + nPoints = 0; + transform.clear(); } void FairGeoVolume::print() { - // prints all parameters of a volume - cout<<"Volume: " <<(const_cast(fName.Data()))<<" Shape: "<<(const_cast(shape.Data()))<<" Mother: " - <<(const_cast(mother.Data()))<<'\n'; - cout << "Points definition " << endl; - if (points) { - for (Int_t i=0; i(points->At(i)))); + // prints all parameters of a volume + cout << "Volume: " << (const_cast(fName.Data())) + << " Shape: " << (const_cast(shape.Data())) + << " Mother: " << (const_cast(mother.Data())) << '\n'; + cout << "Points definition " << endl; + if (points) { + for (Int_t i = 0; i < nPoints; i++) { + cout << (*(static_cast(points->At(i)))); + } } - } - cout << "Lab Transform " << endl; - fLabTransform.print(); - cout<<'\n'; + cout << "Lab Transform " << endl; + fLabTransform.print(); + cout << '\n'; } -Double_t FairGeoVolume::getVolParameter( Int_t nPoint, Int_t pos ) +Double_t FairGeoVolume::getVolParameter(Int_t nPoint, Int_t pos) { - FairGeoVector* vec = static_cast( points->At( nPoint )); - if ( vec ) { return vec->getValues( pos ); } - else { return -1; } + FairGeoVector* vec = static_cast(points->At(nPoint)); + if (vec) { + return vec->getValues(pos); + } else { + return -1; + } } FairGeoVolume::~FairGeoVolume() { - if (points) { - points->Delete(); - delete points; - points=0; - } + if (points) { + points->Delete(); + delete points; + points = 0; + } } diff --git a/geobase/FairGeoVolume.h b/geobase/FairGeoVolume.h index 7c43e498dd..bfdf14899c 100644 --- a/geobase/FairGeoVolume.h +++ b/geobase/FairGeoVolume.h @@ -1,24 +1,22 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRGEOVOLUME_H #define FAIRGEOVOLUME_H -#include // for TNamed +#include "FairGeoMedium.h" // for FairGeoMedium +#include "FairGeoTransform.h" // for FairGeoTransform +#include "FairGeoVector.h" // for FairGeoVector -#include "FairGeoMedium.h" // for FairGeoMedium -#include "FairGeoTransform.h" // for FairGeoTransform -#include "FairGeoVector.h" // for FairGeoVector - -#include // for Int_t, Text_t, Double_t, etc -#include // for TObjArray -#include // for TString - -#include // for NULL +#include // for Int_t, Text_t, Double_t, etc +#include // for TNamed +#include // for TObjArray +#include // for TString +#include // for NULL /** * basic geometry parameters of a volume @@ -27,18 +25,18 @@ class FairGeoVolume : public TNamed { private: - FairGeoVolume& operator=(const FairGeoVolume&); + FairGeoVolume& operator=(const FairGeoVolume&); protected: - TString shape; /**eant shape of the volume*/ - TString mother; /** Name of the mother volume*/ - TObjArray* points; /** array of points (type FairGeoVector)*/ - FairGeoTransform transform; /** transformation relative to the mother system */ + TString shape; /**eant shape of the volume*/ + TString mother; /** Name of the mother volume*/ + TObjArray* points; /** array of points (type FairGeoVector)*/ + FairGeoTransform transform; /** transformation relative to the mother system */ FairGeoTransform fLabTransform; /** transformation to the LAB system; */ - FairGeoMedium fMedium; /** medium properties */ - Int_t nPoints; /** number of points */ - Int_t fHadFormat; // - Int_t fgMCid; /** Volume Id given by MC*/ + FairGeoMedium fMedium; /** medium properties */ + Int_t nPoints; /** number of points */ + Int_t fHadFormat; // + Int_t fgMCid; /** Volume Id given by MC*/ public: inline FairGeoVolume(); @@ -48,66 +46,67 @@ class FairGeoVolume : public TNamed const TString& getShape() const { return shape; } const TString& getMother() const { return mother; } FairGeoTransform& getTransform() { return transform; } - FairGeoTransform& getLabTransform() { return fLabTransform;} - FairGeoMedium& getMedium() { return fMedium;} - Int_t getNumPoints() { return nPoints;} + FairGeoTransform& getLabTransform() { return fLabTransform; } + FairGeoMedium& getMedium() { return fMedium; } + Int_t getNumPoints() { return nPoints; } inline FairGeoVector* getPoint(const Int_t n); inline void setName(const Text_t* s); void setVolumePar(FairGeoVolume&); inline void setShape(const Text_t* s); inline void setMother(const Text_t* s); void createPoints(const Int_t); - void setPoint(const Int_t,const Double_t,const Double_t,const Double_t); - void setPoint(const Int_t,const FairGeoVector&); + void setPoint(const Int_t, const Double_t, const Double_t, const Double_t); + void setPoint(const Int_t, const FairGeoVector&); virtual void clear(); virtual void print(); - virtual void setHadFormat( Int_t i ) { fHadFormat=i;} - Double_t getVolParameter( Int_t nPoint, Int_t pos ); - Int_t getMCid() {return fgMCid;} - void setMCid(Int_t MCid) {fgMCid=MCid;} + virtual void setHadFormat(Int_t i) { fHadFormat = i; } + Double_t getVolParameter(Int_t nPoint, Int_t pos); + Int_t getMCid() { return fgMCid; } + void setMCid(Int_t MCid) { fgMCid = MCid; } - ClassDef(FairGeoVolume,1) // + ClassDef(FairGeoVolume, 1) // }; // -------------------- inlines -------------------------- inline FairGeoVolume::FairGeoVolume() - :TNamed(), - shape(""), - mother(""), - points(NULL), - transform(FairGeoTransform()), - fLabTransform(FairGeoTransform()), - fMedium(0), - nPoints(0), - fHadFormat(0), - fgMCid(0) -{ -} - + : TNamed() + , shape("") + , mother("") + , points(NULL) + , transform(FairGeoTransform()) + , fLabTransform(FairGeoTransform()) + , fMedium(0) + , nPoints(0) + , fHadFormat(0) + , fgMCid(0) +{} inline FairGeoVector* FairGeoVolume::getPoint(const Int_t n) { - if (points && n(points->At(n)); } - else { return 0; } + if (points && n < nPoints) { + return static_cast(points->At(n)); + } else { + return 0; + } } inline void FairGeoVolume::setName(const Text_t* s) { - fName=s; - fName.ToUpper(); + fName = s; + fName.ToUpper(); } inline void FairGeoVolume::setShape(const Text_t* s) { - shape=s; - shape.ToUpper(); + shape = s; + shape.ToUpper(); } inline void FairGeoVolume::setMother(const Text_t* s) { - mother=s; - mother.ToUpper(); + mother = s; + mother.ToUpper(); } #endif /* !FAIRGEOVOLUME_H */ diff --git a/parbase/FairContFact.cxx b/parbase/FairContFact.cxx index 49cc2d0232..613c37d759 100644 --- a/parbase/FairContFact.cxx +++ b/parbase/FairContFact.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #//*-- AUTHOR : Ilse Koenig @@ -18,183 +18,203 @@ #include "FairContFact.h" -#include "FairLogger.h" // for FairLogger -#include "FairRuntimeDb.h" // for FairRuntimeDb +#include "FairLogger.h" // for FairLogger +#include "FairRuntimeDb.h" // for FairRuntimeDb -#include // for TIter -#include // for TObjString - -#include // for strlen -#include // for operator<<, ostream, cout, etc +#include // for TIter +#include // for TObjString +#include // for operator<<, ostream, cout, etc +#include // for strlen using std::cout; -ClassImp(FairContainer) -ClassImp(FairContFact) +ClassImp(FairContainer); +ClassImp(FairContFact); FairContainer::FairContainer() - :TNamed(), - contexts(nullptr), - actualContext(""), - fLogger(FairLogger::GetLogger()) -{ -} + : TNamed() + , contexts(nullptr) + , actualContext("") + , fLogger(FairLogger::GetLogger()) +{} // Default constructor -FairContainer::FairContainer(const char* name, const char* title, - const char* defContext) - : TNamed(name, title), - contexts(new TList()), - actualContext(""), - fLogger(FairLogger::GetLogger()) +FairContainer::FairContainer(const char* name, const char* title, const char* defContext) + : TNamed(name, title) + , contexts(new TList()) + , actualContext("") + , fLogger(FairLogger::GetLogger()) { - // Constructor - // Arguments: name = name of the corresponding parameter container - // title = title of this parameter container - // defContext = default context of this parameter container - addContext(defContext); + // Constructor + // Arguments: name = name of the corresponding parameter container + // title = title of this parameter container + // defContext = default context of this parameter container + addContext(defContext); } FairContainer::~FairContainer() { - // Destructor deletes the list of accepted contexts - if (contexts) { - contexts->Delete(); - delete contexts; - } + // Destructor deletes the list of accepted contexts + if (contexts) { + contexts->Delete(); + delete contexts; + } } void FairContainer::addContext(const char* name) { - // Adds a context to the list of accepted contexts - TObjString* c=new TObjString(name); - contexts->Add(c); + // Adds a context to the list of accepted contexts + TObjString* c = new TObjString(name); + contexts->Add(c); } Bool_t FairContainer::setActualContext(const char* c) { - // The function sets the actual context for the container, if it is in the list of - // accepted contexts. When the actual context was already set before, it prints a warning - // and ignores the second setting. - // The function returns kFALSE, when the context is not in the list. - if (contexts->FindObject(c)) { - if (actualContext.IsNull()) { actualContext=c; } - else Warning("addContext", - "Actual context of parameter container %s already defined as %s", - GetName(),actualContext.Data()); - return kTRUE; - } - return kFALSE; + // The function sets the actual context for the container, if it is in the list of + // accepted contexts. When the actual context was already set before, it prints a warning + // and ignores the second setting. + // The function returns kFALSE, when the context is not in the list. + if (contexts->FindObject(c)) { + if (actualContext.IsNull()) { + actualContext = c; + } else + Warning("addContext", + "Actual context of parameter container %s already defined as %s", + GetName(), + actualContext.Data()); + return kTRUE; + } + return kFALSE; } const char* FairContainer::getDefaultContext() { - // Returns the default context - return (static_cast(contexts->At(0)))->String().Data(); + // Returns the default context + return (static_cast(contexts->At(0)))->String().Data(); } void FairContainer::print() { - // prints the name, title of the container together with the actual context set - // or all possible contexts, when the actual context was not set - cout<(next()))) { - if (c->String().IsNull()) { cout<<" \"\""; } - else { cout<<" "<String(); } - if (i==0) { cout<<"\t default"; } - cout<<"\n"; - i++; + // prints the name, title of the container together with the actual context set + // or all possible contexts, when the actual context was not set + cout << fName << "\t" << fTitle << "\n"; + if (!actualContext.IsNull()) { + cout << " actual context: " << actualContext << "\n"; + } else { + TIter next(contexts); + Int_t i = 0; + TObjString* c; + cout << " all contexts:" + << "\n"; + while ((c = static_cast(next()))) { + if (c->String().IsNull()) { + cout << " \"\""; + } else { + cout << " " << c->String(); + } + if (i == 0) { + cout << "\t default"; + } + cout << "\n"; + i++; + } } - } } TString FairContainer::getConcatName() { - // Returns the name of the parameter container used in the constructor and the - // runtime database. - // When the parameter container supportes different contexts (not only an empty string) - // and the actual context set is not the default context, the new name of the parameter - // container is concatinated as - // original container name + _ + actualcontext - TString cn=fName; - if (!actualContext.IsNull() && actualContext!=(static_cast(contexts->At(0)))->String()) { - cn+="_"; - cn+=actualContext; - } - return cn; + // Returns the name of the parameter container used in the constructor and the + // runtime database. + // When the parameter container supportes different contexts (not only an empty string) + // and the actual context set is not the default context, the new name of the parameter + // container is concatinated as + // original container name + _ + actualcontext + TString cn = fName; + if (!actualContext.IsNull() && actualContext != (static_cast(contexts->At(0)))->String()) { + cn += "_"; + cn += actualContext; + } + return cn; } const char* FairContainer::getContext() { - // return the actual context, if set, or the default context - if (!actualContext.IsNull()) { return actualContext.Data(); } - else { return getDefaultContext(); } + // return the actual context, if set, or the default context + if (!actualContext.IsNull()) { + return actualContext.Data(); + } else { + return getDefaultContext(); + } } FairContFact::FairContFact() - : TNamed(), - containers(new TList), - fLogger(FairLogger::GetLogger()) + : TNamed() + , containers(new TList) + , fLogger(FairLogger::GetLogger()) { - // Constructor creates a list to store objects of type FairContainer - // containers=new TList; + // Constructor creates a list to store objects of type FairContainer + // containers=new TList; } FairContFact::~FairContFact() { - // Destructor deletes the container list and its elements - FairRuntimeDb::instance()->removeContFactory(this); - containers->Delete(); - delete containers; + // Destructor deletes the container list and its elements + FairRuntimeDb::instance()->removeContFactory(this); + containers->Delete(); + delete containers; } Bool_t FairContFact::addContext(const char* name) { - // Set the actual context in all containers, which accept this context - FairContainer* c=0; - Bool_t found=kFALSE; - TIter next(containers); - while ((c=static_cast(next()))) { - if (c->setActualContext(name)) { found=kTRUE; } - } - return found; + // Set the actual context in all containers, which accept this context + FairContainer* c = 0; + Bool_t found = kFALSE; + TIter next(containers); + while ((c = static_cast(next()))) { + if (c->setActualContext(name)) { + found = kTRUE; + } + } + return found; } FairParSet* FairContFact::getContainer(const char* name) { - // Returns the pointer to the parameter container in the runtime database - // If this parameter container does not yet exit, it calls the function - // createContainer(FairContainer*), which is implemented in the derived classes - // and calls the corresponding constructor. Then the pointer it added in the - // runtime database. - FairContainer* c=static_cast((containers->FindObject(name))); - - FairParSet* cont=0; - if (c) { - TString cn=c->getConcatName(); - FairRuntimeDb* rtdb = FairRuntimeDb::instance(); - if (!(cont=rtdb->findContainer(c->getConcatName().Data()))) { - if (strlen(c->getActualContext())==0) { c->setActualContext(c->getDefaultContext()); } - cont=createContainer(c); - if (cont) { rtdb->addContainer(cont); } + // Returns the pointer to the parameter container in the runtime database + // If this parameter container does not yet exit, it calls the function + // createContainer(FairContainer*), which is implemented in the derived classes + // and calls the corresponding constructor. Then the pointer it added in the + // runtime database. + FairContainer* c = static_cast((containers->FindObject(name))); + + FairParSet* cont = 0; + if (c) { + TString cn = c->getConcatName(); + FairRuntimeDb* rtdb = FairRuntimeDb::instance(); + if (!(cont = rtdb->findContainer(c->getConcatName().Data()))) { + if (strlen(c->getActualContext()) == 0) { + c->setActualContext(c->getDefaultContext()); + } + cont = createContainer(c); + if (cont) { + rtdb->addContainer(cont); + } + } } - } - return cont; + return cont; } void FairContFact::print() { - // Loops over all containers in the list and calls their print() function - cout<<"---------------------------------------------------------------------------"<<"\n"; - cout<(next()))) { c->print(); } + // Loops over all containers in the list and calls their print() function + cout << "---------------------------------------------------------------------------" + << "\n"; + cout << GetName() << ": " << GetTitle() << "\n"; + cout << "---------------------------------------------------------------------------" + << "\n"; + FairContainer* c; + TIter next(containers); + while ((c = static_cast(next()))) { + c->print(); + } } diff --git a/parbase/FairContFact.h b/parbase/FairContFact.h index 2c2c3eb6a7..c838be38e9 100644 --- a/parbase/FairContFact.h +++ b/parbase/FairContFact.h @@ -1,18 +1,17 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRCONTFACT_H #define FAIRCONTFACT_H -#include // for TNamed - -#include // for Bool_t, ClassDef, etc -#include // for TList -#include // for TString +#include // for Bool_t, ClassDef, etc +#include // for TList +#include // for TNamed +#include // for TString class FairLogger; class FairParIo; @@ -31,10 +30,10 @@ class FairContainer : public TNamed /** actual context set by the user */ TString actualContext; /** Fair Logger */ - FairLogger* fLogger;//! + FairLogger* fLogger; //! public: - FairContainer( const char*, const char*, const char*); + FairContainer(const char*, const char*, const char*); ~FairContainer(); void addContext(const char*); Bool_t setActualContext(const char* c); @@ -43,7 +42,7 @@ class FairContainer : public TNamed void print(); TString getConcatName(); const char* getContext(); - ClassDef(FairContainer,0) // class for list elements in class FairContFact + ClassDef(FairContainer, 0) // class for list elements in class FairContFact }; class FairContFact : public TNamed @@ -54,21 +53,21 @@ class FairContFact : public TNamed Bool_t addContext(const char* name); void print(); FairParSet* getContainer(const char*); - virtual FairParSet* createContainer(FairContainer*) {return 0;} + virtual FairParSet* createContainer(FairContainer*) { return 0; } virtual void activateParIo(FairParIo*) {} protected: TList* containers; // all parameter containers managed by this factory - const char* getActualContext(const char* name) { - return (static_cast(containers->FindObject(name)))->getActualContext(); + const char* getActualContext(const char* name) + { + return (static_cast(containers->FindObject(name)))->getActualContext(); } /** Fair Logger */ - FairLogger* fLogger;//! - ClassDef(FairContFact,0) // base class of all factories for parameter containers + FairLogger* fLogger; //! + ClassDef(FairContFact, 0) // base class of all factories for parameter containers - private: - FairContFact(const FairContFact&); + private : FairContFact(const FairContFact&); FairContFact& operator=(const FairContFact&); }; -#endif /* !FAIRCONTFACT_H */ +#endif /* !FAIRCONTFACT_H */ diff --git a/parbase/FairDetParAsciiFileIo.cxx b/parbase/FairDetParAsciiFileIo.cxx index 850ef808b7..4f60863bb1 100644 --- a/parbase/FairDetParAsciiFileIo.cxx +++ b/parbase/FairDetParAsciiFileIo.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ //*-- AUTHOR : Ilse Koenig @@ -18,22 +18,22 @@ #include "FairDetParAsciiFileIo.h" -#include "FairParSet.h" // for FairParSet +#include "FairParSet.h" // for FairParSet -#include // for printf, sprintf -#include // for strlen, strncmp -#include // for fstream +#include // for fstream +#include // for printf, sprintf +#include // for strlen, strncmp using std::ios; FairDetParAsciiFileIo::FairDetParAsciiFileIo(std::fstream* f) - :FairDetParIo(), - fHeader(""), - sepLine("##############################################################################\n"), - pFile(f) + : FairDetParIo() + , fHeader("") + , sepLine("##############################################################################\n") + , pFile(f) { - // constructor - /* pFile=f; + // constructor + /* pFile=f; sepLine= "##############################################################################\n"; */ @@ -41,175 +41,200 @@ FairDetParAsciiFileIo::FairDetParAsciiFileIo(std::fstream* f) Bool_t FairDetParAsciiFileIo::findContainer(const Text_t* name) { - // searches the container in the file - const Int_t maxbuf=4000; - Text_t buf[maxbuf]; - Text_t buf2[maxbuf]; - sprintf(buf2,"%s%s%s","[",name,"]"); - //cout << " buf2 " << buf2 << endl; - pFile->clear(); - pFile->seekg(0,ios::beg); - while (!pFile->eof()) { - pFile->getline(buf,maxbuf); - if (buf[0]!='[') { continue; } - //cout << " buf: " << buf << endl; - if (!strncmp(buf,buf2,strlen(buf2))) { break; } - } - if (pFile->eof()) { return kFALSE; } - return kTRUE; + // searches the container in the file + const Int_t maxbuf = 4000; + Text_t buf[maxbuf]; + Text_t buf2[maxbuf]; + sprintf(buf2, "%s%s%s", "[", name, "]"); + // cout << " buf2 " << buf2 << endl; + pFile->clear(); + pFile->seekg(0, ios::beg); + while (!pFile->eof()) { + pFile->getline(buf, maxbuf); + if (buf[0] != '[') { + continue; + } + // cout << " buf: " << buf << endl; + if (!strncmp(buf, buf2, strlen(buf2))) { + break; + } + } + if (pFile->eof()) { + return kFALSE; + } + return kTRUE; } Bool_t FairDetParAsciiFileIo::checkAllFound(Int_t* set, Int_t setSize) { - // checks if all modules have been initialized - Bool_t allFound=kTRUE; - for(Int_t i=0; iwrite(sepLine,strlen(sepLine)); - pFile->write(fHeader.Data(),fHeader.Length()); - pFile->write(sepLine,strlen(sepLine)); - *pFile<<"["<0) { *pFile<<"// Parameter Context: "<0) { *pFile<<"author: "<write(sepLine, strlen(sepLine)); + pFile->write(fHeader.Data(), fHeader.Length()); + pFile->write(sepLine, strlen(sepLine)); + *pFile << "[" << name << "]\n"; + if (strlen(context) > 0) { + *pFile << "// Parameter Context: " << context << "\n"; + } + if (strlen(author) > 0) { + *pFile << "author: " << author << "\n"; + } + TString t = description; + if (!t.IsNull()) { + t = t.ReplaceAll("\n", " \\\n"); + *pFile << "description: " << t << "\n"; + } + *pFile << "//-----------------------------------------------------------" + "-----------------\n"; } void FairDetParAsciiFileIo::readComment(const Char_t* lastBuf, FairParSet* pPar) { - // reads the author or the description - const Int_t maxbuf=4000; - Text_t buf[maxbuf]; - TString s=lastBuf; - TString pName, pVal; - Ssiz_t n=s.First(':'); - Ssiz_t m=s.Last('\\'); - pName=s(0,n); - if (m>0) { pVal=s(n+1,m-n-1); } - else { pVal=s(n+1,s.Length()-n-1); } - pVal=pVal.Strip(pVal.kLeading); - while (m>0) { - pVal+="\n"; - pFile->getline(buf,maxbuf); - if (buf[0]!='/') { - s=buf; - m=s.Last('\\'); - if (m>0) { pVal+=s(0,m); } - else { pVal+=s; } + // reads the author or the description + const Int_t maxbuf = 4000; + Text_t buf[maxbuf]; + TString s = lastBuf; + TString pName, pVal; + Ssiz_t n = s.First(':'); + Ssiz_t m = s.Last('\\'); + pName = s(0, n); + if (m > 0) { + pVal = s(n + 1, m - n - 1); + } else { + pVal = s(n + 1, s.Length() - n - 1); + } + pVal = pVal.Strip(pVal.kLeading); + while (m > 0) { + pVal += "\n"; + pFile->getline(buf, maxbuf); + if (buf[0] != '/') { + s = buf; + m = s.Last('\\'); + if (m > 0) { + pVal += s(0, m); + } else { + pVal += s; + } + } + } + if (pName.CompareTo("author") == 0) { + pPar->setAuthor(pVal.Data()); + } else if (pName.CompareTo("description") == 0) { + pPar->setDescription(pVal.Data()); } - } - if (pName.CompareTo("author")==0) { pPar->setAuthor(pVal.Data()); } - else if ( pName.CompareTo("description")==0) { pPar->setDescription(pVal.Data()); } } void FairDetParAsciiFileIo::writeComment(FairParSet* pPar) { - TString t=pPar->getAuthor(); - if (!t.IsNull()) { *pFile<<"author: "<getDescription(); - if (!t.IsNull()) { - t=t.ReplaceAll("\n"," \\\n"); - *pFile<<"description: "<getAuthor(); + if (!t.IsNull()) { + *pFile << "author: " << t << "\n"; + } + t = pPar->getDescription(); + if (!t.IsNull()) { + t = t.ReplaceAll("\n", " \\\n"); + *pFile << "description: " << t << "\n"; + } } -ClassImp(FairDetParAsciiFileIo) +ClassImp(FairDetParAsciiFileIo); /* FairDetParAsciiFileIo::FairDetParAsciiFileIo(std::fstream* f) { - // constructor - pFile=f; - sepLine= - "##############################################################################\n"; +// constructor +pFile=f; +sepLine= +"##############################################################################\n"; } Bool_t FairDetParAsciiFileIo::findContainer(const Text_t* name) { - // searches the container in the file - const Int_t maxbuf=4000; - Text_t buf[maxbuf]; - Text_t buf2[maxbuf]; - sprintf(buf2,"%s%s%s","[",name,"]"); - pFile->clear(); - pFile->seekg(0,ios::beg); - while (!pFile->eof()) { - pFile->getline(buf,maxbuf); - if (buf[0]!='[') continue; - if (!strncmp(buf,buf2,strlen(buf2))) break; - } - if (pFile->eof()) return kFALSE; - return kTRUE; +// searches the container in the file +const Int_t maxbuf=4000; +Text_t buf[maxbuf]; +Text_t buf2[maxbuf]; +sprintf(buf2,"%s%s%s","[",name,"]"); +pFile->clear(); +pFile->seekg(0,ios::beg); +while (!pFile->eof()) { +pFile->getline(buf,maxbuf); +if (buf[0]!='[') continue; +if (!strncmp(buf,buf2,strlen(buf2))) break; +} +if (pFile->eof()) return kFALSE; +return kTRUE; } void FairDetParAsciiFileIo::writeHeader(const Text_t* name, const Text_t* context, - const Text_t* author, const Text_t* description) { - // calls the function putAsciiHeader(...) of the parameter container - // class and writes the header to the file - pFile->write(sepLine,strlen(sepLine)); - pFile->write(fHeader.Data(),fHeader.Length()); - pFile->write(sepLine,strlen(sepLine)); - *pFile<<"["<0) *pFile<<"// Parameter Context: "<0) *pFile<<"author: "<write(sepLine,strlen(sepLine)); +pFile->write(fHeader.Data(),fHeader.Length()); +pFile->write(sepLine,strlen(sepLine)); +*pFile<<"["<0) *pFile<<"// Parameter Context: "<0) *pFile<<"author: "<0) pVal=s(n+1,m-n-1); - else pVal=s(n+1,s.Length()-n-1); - pVal=pVal.Strip(pVal.kLeading); - while (m>0) { - pVal+="\n"; - pFile->getline(buf,maxbuf); - if (buf[0]!='/') { - s=buf; - m=s.Last('\\'); - if (m>0) pVal+=s(0,m); - else pVal+=s; - } - } - if (pName.CompareTo("author")==0) pPar->setAuthor(pVal.Data()); - else if ( pName.CompareTo("description")==0) pPar->setDescription(pVal.Data()); +// reads the author or the description +const Int_t maxbuf=4000; +Text_t buf[maxbuf]; +TString s=lastBuf; +TString pName, pVal; +Ssiz_t n=s.First(':'); +Ssiz_t m=s.Last('\\'); +pName=s(0,n); +if (m>0) pVal=s(n+1,m-n-1); +else pVal=s(n+1,s.Length()-n-1); +pVal=pVal.Strip(pVal.kLeading); +while (m>0) { +pVal+="\n"; +pFile->getline(buf,maxbuf); +if (buf[0]!='/') { + s=buf; + m=s.Last('\\'); + if (m>0) pVal+=s(0,m); + else pVal+=s; +} +} +if (pName.CompareTo("author")==0) pPar->setAuthor(pVal.Data()); +else if ( pName.CompareTo("description")==0) pPar->setDescription(pVal.Data()); } void FairDetParAsciiFileIo::writeComment(FairParSet* pPar) { - TString t=pPar->getAuthor(); - if (!t.IsNull()) *pFile<<"author: "<getDescription(); - if (!t.IsNull()) { - t=t.ReplaceAll("\n"," \\\n"); - *pFile<<"description: "<getAuthor(); +if (!t.IsNull()) *pFile<<"author: "<getDescription(); +if (!t.IsNull()) { +t=t.ReplaceAll("\n"," \\\n"); +*pFile<<"description: "< // for fstream -#include // for Text_t, Bool_t, etc -#include // for TString +#include // for Text_t, Bool_t, etc +#include // for TString +#include // for fstream class FairParSet; class FairDetParAsciiFileIo : public FairDetParIo { protected: - TString fHeader; //! header of container output in file - TString sepLine; //! comment line + TString fHeader; //! header of container output in file + TString sepLine; //! comment line std::fstream* pFile; //! pointer to ascii file // virtual Bool_t write(HDetector*) {return kTRUE;} Bool_t findContainer(const Text_t* name); - Bool_t checkAllFound(Int_t*,Int_t); - void writeHeader(const Text_t*, const Text_t* context="", - const Text_t* author="", const Text_t* description=""); + Bool_t checkAllFound(Int_t*, Int_t); + void writeHeader(const Text_t*, + const Text_t* context = "", + const Text_t* author = "", + const Text_t* description = ""); void writeComment(FairParSet*); void readComment(const Char_t*, FairParSet*); // Bool_t readLabPositions(const Text_t*,HDetGeomPar*,Int_t*,Int_t,Int_t); @@ -46,7 +48,7 @@ class FairDetParAsciiFileIo : public FairDetParIo FairDetParAsciiFileIo& operator=(const FairDetParAsciiFileIo&); FairDetParAsciiFileIo(const FairDetParAsciiFileIo&); - ClassDef(FairDetParAsciiFileIo,0) // Class for detector parameter I/O from ascii file + ClassDef(FairDetParAsciiFileIo, 0) // Class for detector parameter I/O from ascii file }; -#endif /* !FAIRDETPARASCIIFILEIO_H */ +#endif /* !FAIRDETPARASCIIFILEIO_H */ diff --git a/parbase/FairDetParIo.cxx b/parbase/FairDetParIo.cxx index 67e643427b..3087ec0747 100644 --- a/parbase/FairDetParIo.cxx +++ b/parbase/FairDetParIo.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ //*-- AUTHOR : Ilse Koenig @@ -15,10 +15,8 @@ // detector ///////////////////////////////////////////////////////////// FairDetParIo::FairDetParIo() - :TNamed(), - inputNumber(0) -{ -} - -ClassImp(FairDetParIo) + : TNamed() + , inputNumber(0) +{} +ClassImp(FairDetParIo); diff --git a/parbase/FairDetParIo.h b/parbase/FairDetParIo.h index ada3253190..5a17599dd7 100644 --- a/parbase/FairDetParIo.h +++ b/parbase/FairDetParIo.h @@ -1,41 +1,40 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRDETPARIO_H #define FAIRDETPARIO_H -#include // for TNamed - -#include // for Int_t, FairDetParIo::Class, etc +#include // for Int_t, FairDetParIo::Class, etc +#include // for TNamed class FairParSet; class FairDetParIo : public TNamed { protected: - Int_t inputNumber; // input number (first or second input in runtime database) + Int_t inputNumber; // input number (first or second input in runtime database) public: FairDetParIo(); - virtual ~FairDetParIo() {;} + virtual ~FairDetParIo() { ; } // sets the input number - void setInputNumber(Int_t n) {inputNumber=n;} + void setInputNumber(Int_t n) { inputNumber = n; } // returns the input number - Int_t getInputNumber() {return inputNumber;} + Int_t getInputNumber() { return inputNumber; } // initializes parameter container - virtual Bool_t init(FairParSet*) {return kFALSE;} + virtual Bool_t init(FairParSet*) { return kFALSE; } // writes parameter container to output - virtual Int_t write(FairParSet*) {return kFALSE;} + virtual Int_t write(FairParSet*) { return kFALSE; } - ClassDef(FairDetParIo,0) // Base class for detector parameter IO + ClassDef(FairDetParIo, 0) // Base class for detector parameter IO }; -#endif /* !HDETPARIO_H */ +#endif /* !HDETPARIO_H */ diff --git a/parbase/FairDetParRootFileIo.cxx b/parbase/FairDetParRootFileIo.cxx index 48938dd344..497c711e38 100644 --- a/parbase/FairDetParRootFileIo.cxx +++ b/parbase/FairDetParRootFileIo.cxx @@ -2,7 +2,7 @@ * 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, * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ //*-- AUTHOR : Ilse Koenig @@ -22,122 +22,125 @@ /////////////////////////////////////////////////////////////////////////////// #include "FairDetParRootFileIo.h" -#include "FairParRootFileIo.h" // for FairParRootFile -#include "FairParSet.h" // for FairParSet -#include "FairRtdbRun.h" // for FairParVersion, FairRtdbRun -#include "FairRuntimeDb.h" // for FairRuntimeDb +#include "FairParRootFileIo.h" // for FairParRootFile +#include "FairParSet.h" // for FairParSet +#include "FairRtdbRun.h" // for FairParVersion, FairRtdbRun +#include "FairRuntimeDb.h" // for FairRuntimeDb -#include // for TDirectory, gDirectory -#include // for TKey -#include // for TROOT, gROOT - -#include // for sprintf -#include // for operator<<, basic_ostream, etc +#include // for TDirectory, gDirectory +#include // for TKey +#include // for TROOT, gROOT +#include // for operator<<, basic_ostream, etc +#include // for sprintf class TObject; using std::cout; using std::endl; -ClassImp(FairDetParRootFileIo) +ClassImp(FairDetParRootFileIo); FairDetParRootFileIo::FairDetParRootFileIo(FairParRootFile *f) - : FairDetParIo(), pFile(f) { - // Constructor takes a pointer to the parameter ROOT file - // pFile=f; + : FairDetParIo() + , pFile(f) +{ + // Constructor takes a pointer to the parameter ROOT file + // pFile=f; } -Bool_t FairDetParRootFileIo::read(FairParSet *pPar) { - // generic read function for parameter containers - Text_t *name = const_cast(pPar->GetName()); - Int_t version = findInputVersion(name); +Bool_t FairDetParRootFileIo::read(FairParSet *pPar) +{ + // generic read function for parameter containers + Text_t *name = const_cast(pPar->GetName()); + Int_t version = findInputVersion(name); + + // cout << "-I- FairDetParRootFileIo# " << name << " : " << version << endl; + + if (version <= 0) { + pPar->setInputVersion(-1, inputNumber); + return kFALSE; + } - // cout << "-I- FairDetParRootFileIo# " << name << " : " << version << endl; + if (pPar->getInputVersion(inputNumber) == version && pPar->getInputVersion(inputNumber) != -1) { + return kTRUE; + } - if (version <= 0) { + TKey *key = dynamic_cast(gDirectory->GetKey(name, version)); + if (key) { + pPar->clear(); + key->Read(pPar); + pPar->setInputVersion(version, inputNumber); + pPar->setChanged(); + cout << "Container " << pPar->GetName() << " initialized from ROOT file." << endl; + return kTRUE; + } pPar->setInputVersion(-1, inputNumber); return kFALSE; - } - - if (pPar->getInputVersion(inputNumber) == version && - pPar->getInputVersion(inputNumber) != -1) { - return kTRUE; - } - - TKey *key = dynamic_cast(gDirectory->GetKey(name, version)); - if (key) { - pPar->clear(); - key->Read(pPar); - pPar->setInputVersion(version, inputNumber); - pPar->setChanged(); - cout << "Container " << pPar->GetName() << " initialized from ROOT file." - << endl; - return kTRUE; - } - pPar->setInputVersion(-1, inputNumber); - return kFALSE; } -Int_t FairDetParRootFileIo::write(FairParSet *pPar) { - // writes a parameter container to the ROOT file and returns the new version - // number (returns -1 if the file is not writable) - if (pFile) { - pFile->cd(); - if (pFile->IsWritable()) { - Text_t *name = const_cast(pPar->GetName()); - pPar->Write(name); - pPar->setChanged(kFALSE); - FairRuntimeDb::instance()->setVersionsChanged(kTRUE); - return getMaxVersion(name); - } else { - Error(":write", "Output is not writable"); +Int_t FairDetParRootFileIo::write(FairParSet *pPar) +{ + // writes a parameter container to the ROOT file and returns the new version + // number (returns -1 if the file is not writable) + if (pFile) { + pFile->cd(); + if (pFile->IsWritable()) { + Text_t *name = const_cast(pPar->GetName()); + pPar->Write(name); + pPar->setChanged(kFALSE); + FairRuntimeDb::instance()->setVersionsChanged(kTRUE); + return getMaxVersion(name); + } else { + Error(":write", "Output is not writable"); + } } - } - Error(":write", "No output open"); - return -1; + Error(":write", "No output open"); + return -1; } -Int_t FairDetParRootFileIo::getMaxVersion(Text_t *name) { - // returns the maximum version of the container given by name in the ROOT - // file (return -1 if not found) - TKey *key = pFile->GetKey(name); - if (key) { - return key->GetCycle(); - } else { - return -1; - } +Int_t FairDetParRootFileIo::getMaxVersion(Text_t *name) +{ + // returns the maximum version of the container given by name in the ROOT + // file (return -1 if not found) + TKey *key = pFile->GetKey(name); + if (key) { + return key->GetCycle(); + } else { + return -1; + } } -Int_t FairDetParRootFileIo::findInputVersion(Text_t *name) { - // finds the input version to initialize the container given by name; - // returns -1 if the version cannot be determined - FairParVersion *currVers = - FairRuntimeDb::instance()->getCurrentRun()->getParVersion(name); - Int_t v = currVers->getInputVersion(inputNumber); - if (v > 0) { - return v; - } // predefined - FairRtdbRun *r = pFile->getRun(); - // cout << "-I- FairDetParRootFileIo::findInputVersion " << r << endl; - if (!r) { - return -1; - } // run not in ROOT file - FairParVersion *vers = r->getParVersion(name); - if (!vers) { - return -1; - } // container not in ROOT file - return vers->getRootVersion(); +Int_t FairDetParRootFileIo::findInputVersion(Text_t *name) +{ + // finds the input version to initialize the container given by name; + // returns -1 if the version cannot be determined + FairParVersion *currVers = FairRuntimeDb::instance()->getCurrentRun()->getParVersion(name); + Int_t v = currVers->getInputVersion(inputNumber); + if (v > 0) { + return v; + } // predefined + FairRtdbRun *r = pFile->getRun(); + // cout << "-I- FairDetParRootFileIo::findInputVersion " << r << endl; + if (!r) { + return -1; + } // run not in ROOT file + FairParVersion *vers = r->getParVersion(name); + if (!vers) { + return -1; + } // container not in ROOT file + return vers->getRootVersion(); } -TObject *FairDetParRootFileIo::findContainer(Text_t *name, Int_t vers) { - // finds the parameter container given by its name with a special version in - // the ROOT file (returns 0 if not successful) - // This funtion uses internally the ROOT function FindObject(Text_t*), which - // creates a new object. The calling function must therefore delete the - // object after usage! - Text_t cn[80]; - sprintf(cn, "%s;%i", name, vers); - pFile->cd(); - TObject *p = gROOT->FindObject(cn); - return p; +TObject *FairDetParRootFileIo::findContainer(Text_t *name, Int_t vers) +{ + // finds the parameter container given by its name with a special version in + // the ROOT file (returns 0 if not successful) + // This funtion uses internally the ROOT function FindObject(Text_t*), which + // creates a new object. The calling function must therefore delete the + // object after usage! + Text_t cn[80]; + sprintf(cn, "%s;%i", name, vers); + pFile->cd(); + TObject *p = gROOT->FindObject(cn); + return p; } diff --git a/parbase/FairDetParRootFileIo.h b/parbase/FairDetParRootFileIo.h index bcc8bc546e..e5280e6026 100644 --- a/parbase/FairDetParRootFileIo.h +++ b/parbase/FairDetParRootFileIo.h @@ -1,16 +1,16 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRDETPARROOTFILEIO_H #define FAIRDETPARROOTFILEIO_H -#include "FairDetParIo.h" // for FairDetParIo +#include "FairDetParIo.h" // for FairDetParIo -#include // for Int_t, Text_t, etc +#include // for Int_t, Text_t, etc class FairParRootFile; class FairParSet; @@ -19,7 +19,7 @@ class TObject; class FairDetParRootFileIo : public FairDetParIo { protected: - FairParRootFile* pFile; // pointer to parameter ROOT file + FairParRootFile* pFile; // pointer to parameter ROOT file public: FairDetParRootFileIo(FairParRootFile* f); @@ -35,10 +35,9 @@ class FairDetParRootFileIo : public FairDetParIo private: FairDetParRootFileIo(const FairDetParRootFileIo&); - FairDetParRootFileIo& operator= (const FairDetParRootFileIo&); + FairDetParRootFileIo& operator=(const FairDetParRootFileIo&); - ClassDef(FairDetParRootFileIo,0) // detector base class for parameter I/O from ROOT file + ClassDef(FairDetParRootFileIo, 0) // detector base class for parameter I/O from ROOT file }; -#endif /* !FAIRDETPARROOTFILEIO_H */ - +#endif /* !FAIRDETPARROOTFILEIO_H */ diff --git a/parbase/FairGenericParAsciiFileIo.cxx b/parbase/FairGenericParAsciiFileIo.cxx index 2df875f9fd..e4fe144a58 100644 --- a/parbase/FairGenericParAsciiFileIo.cxx +++ b/parbase/FairGenericParAsciiFileIo.cxx @@ -18,314 +18,317 @@ #include "FairGenericParAsciiFileIo.h" -#include "FairParGenericSet.h" // for FairParGenericSet -#include "FairParSet.h" // for FairParSet -#include "FairParamList.h" // for FairParamObj, FairParamList +#include "FairParGenericSet.h" // for FairParGenericSet +#include "FairParSet.h" // for FairParSet +#include "FairParamList.h" // for FairParamObj, FairParamList -#include // for TIter -#include // for THashTable -#include // for TString, operator<< - -#include // for printf, sscanf -#include // for strcmp, memcpy, strtok, etc -#include // for fstream +#include // for TIter +#include // for THashTable +#include // for TString, operator<< +#include // for fstream +#include // for printf, sscanf +#include // for strcmp, memcpy, strtok, etc using std::ios; -ClassImp(FairGenericParAsciiFileIo) +ClassImp(FairGenericParAsciiFileIo); FairGenericParAsciiFileIo::FairGenericParAsciiFileIo(std::fstream *f) - : FairDetParAsciiFileIo(f) { - // constructor - // sets the name of the I/O class "FairGenericParIo" - // gets the pointer to the ASCII file - fName = "FairGenericParIo"; + : FairDetParAsciiFileIo(f) +{ + // constructor + // sets the name of the I/O class "FairGenericParIo" + // gets the pointer to the ASCII file + fName = "FairGenericParIo"; } -Bool_t FairGenericParAsciiFileIo::init(FairParSet *pPar) { - // initializes the parameter container from ASCII file - if (!pFile) { - return kFALSE; - } +Bool_t FairGenericParAsciiFileIo::init(FairParSet *pPar) +{ + // initializes the parameter container from ASCII file + if (!pFile) { + return kFALSE; + } - if (pPar->InheritsFrom("FairParGenericSet")) { - return readGenericSet(static_cast(pPar)); - } + if (pPar->InheritsFrom("FairParGenericSet")) { + return readGenericSet(static_cast(pPar)); + } - Error("init(FairParSet*)", "%s does not inherit from FairParGenericSet", - pPar->GetName()); - return kFALSE; + Error("init(FairParSet*)", "%s does not inherit from FairParGenericSet", pPar->GetName()); + return kFALSE; } -Int_t FairGenericParAsciiFileIo::write(FairParSet *pPar) { - // writes the parameter container to ASCII file - if (!pFile) { +Int_t FairGenericParAsciiFileIo::write(FairParSet *pPar) +{ + // writes the parameter container to ASCII file + if (!pFile) { + return -1; + } + if (pPar->InheritsFrom("FairParGenericSet")) { + return writeGenericSet(static_cast(pPar)); + } + Error("write(FairParSet*)", "%s does not inherit from FairParGenericSet", pPar->GetName()); return -1; - } - if (pPar->InheritsFrom("FairParGenericSet")) { - return writeGenericSet(static_cast(pPar)); - } - Error("write(FairParSet*)", "%s does not inherit from FairParGenericSet", - pPar->GetName()); - return -1; } -template -const UChar_t *FairGenericParAsciiFileIo::readData(type t, const Char_t *format, - TString &line, - Int_t &length) { - // reads c-type single data and arrays - const Int_t st = sizeof(t); - const Int_t maxbuf = 8000; - const Int_t bufSizeExt = 10000 * st; - const Char_t d[] = " \t"; - Text_t buf[maxbuf]; - TString s; - Int_t l = 0, bufSize = bufSizeExt; - UChar_t *val = new UChar_t[bufSize]; - Ssiz_t m = line.Last('\\'); - if (m < 0) { - sscanf(line.Data(), format, &t); - memcpy(&val[l], &t, st); - length = st; - } else { - do { - pFile->getline(buf, maxbuf); - if (buf[0] != '/' && buf[0] != '#') { - s = buf; - m = s.Last('\\'); - if (m > 0 && m < s.Length()) { - s = s(0, m - 1); - } - if ((bufSize - 1000) < l) { - bufSize += bufSizeExt; - UChar_t *va = new UChar_t[bufSize]; - memcpy(va, val, l); - delete[] val; - val = va; - } - Char_t *ss = strtok(const_cast(s.Data()), d); - while (ss != 0) { - sscanf(ss, format, &t); - memcpy(&val[l], &t, st); - l += st; - ss = strtok(NULL, d); - } - } - } while (buf[0] != '#' && !pFile->eof() && m > 0); - length = l; - } - return val; +template +const UChar_t *FairGenericParAsciiFileIo::readData(type t, const Char_t *format, TString &line, Int_t &length) +{ + // reads c-type single data and arrays + const Int_t st = sizeof(t); + const Int_t maxbuf = 8000; + const Int_t bufSizeExt = 10000 * st; + const Char_t d[] = " \t"; + Text_t buf[maxbuf]; + TString s; + Int_t l = 0, bufSize = bufSizeExt; + UChar_t *val = new UChar_t[bufSize]; + Ssiz_t m = line.Last('\\'); + if (m < 0) { + sscanf(line.Data(), format, &t); + memcpy(&val[l], &t, st); + length = st; + } else { + do { + pFile->getline(buf, maxbuf); + if (buf[0] != '/' && buf[0] != '#') { + s = buf; + m = s.Last('\\'); + if (m > 0 && m < s.Length()) { + s = s(0, m - 1); + } + if ((bufSize - 1000) < l) { + bufSize += bufSizeExt; + UChar_t *va = new UChar_t[bufSize]; + memcpy(va, val, l); + delete[] val; + val = va; + } + Char_t *ss = strtok(const_cast(s.Data()), d); + while (ss != 0) { + sscanf(ss, format, &t); + memcpy(&val[l], &t, st); + l += st; + ss = strtok(NULL, d); + } + } + } while (buf[0] != '#' && !pFile->eof() && m > 0); + length = l; + } + return val; } -template -void FairGenericParAsciiFileIo::writeData(type *val, Int_t nParams) { - // writes c-type arrays - Int_t i = 0, k = 0; - while (k < nParams) { - if (i == 10) { - *pFile << " \\\n "; - i = 0; +template +void FairGenericParAsciiFileIo::writeData(type *val, Int_t nParams) +{ + // writes c-type arrays + Int_t i = 0, k = 0; + while (k < nParams) { + if (i == 10) { + *pFile << " \\\n "; + i = 0; + } + *pFile << val[k] << " "; + i++; + k++; } - *pFile << val[k] << " "; - i++; - k++; - } - *pFile << std::endl; + *pFile << std::endl; } -Bool_t FairGenericParAsciiFileIo::readGenericSet(FairParGenericSet *pPar) { - // reads condition-stype parameter containers from ASCII file - if (!pFile) { - return kFALSE; - } - pFile->clear(); - pFile->seekg(0, ios::beg); - const Text_t *name = (pPar->GetName()); - - if (!findContainer(name)) { - return kFALSE; - } +Bool_t FairGenericParAsciiFileIo::readGenericSet(FairParGenericSet *pPar) +{ + // reads condition-stype parameter containers from ASCII file + if (!pFile) { + return kFALSE; + } + pFile->clear(); + pFile->seekg(0, ios::beg); + const Text_t *name = (pPar->GetName()); - const Char_t d[] = " \t"; - FairParamList *paramList = new FairParamList; - const Int_t maxbuf = 8000; - Text_t buf[maxbuf]; - buf[0] = '\0'; - TString s, pName, pVal, pType; - Ssiz_t n, m; - while (buf[0] != '#' && !pFile->eof()) { - pFile->getline(buf, maxbuf); - if (buf[0] != '/' && buf[0] != '#') { - s = buf; - n = s.First(':'); - // Check if empty buffer - if (s.IsNull()) continue; - if (n == -1) { - Error("readCond(FairParGenericSet*)", - "%s:\n Missing backslash for parameter %s", name, pName.Data()); - delete paramList; + if (!findContainer(name)) { return kFALSE; - } - pName = s(0, n); - s = s(n + 1, s.Length() - n - 1); - s = s.Strip(s.kLeading); - if (pName.CompareTo("author") == 0 || - pName.CompareTo("description") == 0) { - m = s.Last('\\'); - if (m <= 0) { - pVal = s; - } else { - pVal = s(0, m); - pVal += "\n"; - while (m > 0) { - pFile->getline(buf, maxbuf); - if (buf[0] != '/') { - s = buf; - m = s.Last('\\'); - if (m > 0) { - pVal += s(0, m); - pVal += "\n"; - } else { - pVal += s; - } + } + + const Char_t d[] = " \t"; + FairParamList *paramList = new FairParamList; + const Int_t maxbuf = 8000; + Text_t buf[maxbuf]; + buf[0] = '\0'; + TString s, pName, pVal, pType; + Ssiz_t n, m; + while (buf[0] != '#' && !pFile->eof()) { + pFile->getline(buf, maxbuf); + if (buf[0] != '/' && buf[0] != '#') { + s = buf; + n = s.First(':'); + // Check if empty buffer + if (s.IsNull()) + continue; + if (n == -1) { + Error("readCond(FairParGenericSet*)", "%s:\n Missing backslash for parameter %s", name, pName.Data()); + delete paramList; + return kFALSE; } - } - } - if (pName.CompareTo("author") == 0) { - pPar->setAuthor(pVal.Data()); - } else if (pName.CompareTo("description") == 0) { - pPar->setDescription(pVal.Data()); - } - } else { - Char_t *ss = strtok(const_cast(s.Data()), d); - pType = TString(ss); - Int_t mt = s.Index(pType); - s = s(mt + pType.Length() + 1, s.Length() - mt - pType.Length() - 1); - if (pType.CompareTo("Text_t") == 0) { - m = s.Last('\\'); - if (m < 0) { - pVal = s; - } else { - pVal = ""; - while (m >= 0) { - pFile->getline(buf, maxbuf); - if (buf[0] != '/') { - s = buf; + pName = s(0, n); + s = s(n + 1, s.Length() - n - 1); + s = s.Strip(s.kLeading); + if (pName.CompareTo("author") == 0 || pName.CompareTo("description") == 0) { m = s.Last('\\'); - if (m > 0) { - pVal += s(0, m); - pVal += "\n"; + if (m <= 0) { + pVal = s; + } else { + pVal = s(0, m); + pVal += "\n"; + while (m > 0) { + pFile->getline(buf, maxbuf); + if (buf[0] != '/') { + s = buf; + m = s.Last('\\'); + if (m > 0) { + pVal += s(0, m); + pVal += "\n"; + } else { + pVal += s; + } + } + } + } + if (pName.CompareTo("author") == 0) { + pPar->setAuthor(pVal.Data()); + } else if (pName.CompareTo("description") == 0) { + pPar->setDescription(pVal.Data()); + } + } else { + Char_t *ss = strtok(const_cast(s.Data()), d); + pType = TString(ss); + Int_t mt = s.Index(pType); + s = s(mt + pType.Length() + 1, s.Length() - mt - pType.Length() - 1); + if (pType.CompareTo("Text_t") == 0) { + m = s.Last('\\'); + if (m < 0) { + pVal = s; + } else { + pVal = ""; + while (m >= 0) { + pFile->getline(buf, maxbuf); + if (buf[0] != '/') { + s = buf; + m = s.Last('\\'); + if (m > 0) { + pVal += s(0, m); + pVal += "\n"; + } else { + pVal += s; + } + } + } + } + pVal = pVal.Strip(pVal.kLeading); + if (pVal.Length() > 0) { + paramList->add(pName.Data(), pVal.Data()); + } } else { - pVal += s; + const UChar_t *val = 0; + Int_t length = 0; + if (pType.CompareTo("Int_t") == 0) { + Int_t v = 0; + val = readData(v, "%i", s, length); + } else if (pType.CompareTo("Float_t") == 0) { + Float_t v = 0.F; + val = readData(v, "%f", s, length); + } else if (pType.CompareTo("Double_t") == 0) { + Double_t v = 0.; + val = readData(v, "%lf", s, length); + } else if (pType.CompareTo("Char_t") == 0) { + Char_t v = '0'; + val = readData(v, "%c", s, length); + } else { + Error("readCond(FairParGenericSet*)", + "%s:\n Parameter %s with unsupported type %s", + name, + pName.Data(), + pType.Data()); + delete paramList; + return kFALSE; + } + FairParamObj *obj = new FairParamObj(pName.Data()); + obj->setParamType(pType.Data()); + UChar_t *pValue = obj->setLength(length); + memcpy(pValue, val, length); + paramList->getList()->Add(obj); + delete[] val; } - } } - } - pVal = pVal.Strip(pVal.kLeading); - if (pVal.Length() > 0) { - paramList->add(pName.Data(), pVal.Data()); - } - } else { - const UChar_t *val = 0; - Int_t length = 0; - if (pType.CompareTo("Int_t") == 0) { - Int_t v = 0; - val = readData(v, "%i", s, length); - } else if (pType.CompareTo("Float_t") == 0) { - Float_t v = 0.F; - val = readData(v, "%f", s, length); - } else if (pType.CompareTo("Double_t") == 0) { - Double_t v = 0.; - val = readData(v, "%lf", s, length); - } else if (pType.CompareTo("Char_t") == 0) { - Char_t v = '0'; - val = readData(v, "%c", s, length); - } else { - Error("readCond(FairParGenericSet*)", - "%s:\n Parameter %s with unsupported type %s", name, - pName.Data(), pType.Data()); - delete paramList; - return kFALSE; - } - FairParamObj *obj = new FairParamObj(pName.Data()); - obj->setParamType(pType.Data()); - UChar_t *pValue = obj->setLength(length); - memcpy(pValue, val, length); - paramList->getList()->Add(obj); - delete[] val; } - } } - } - Bool_t allFound = pPar->getParams(paramList); - if (allFound) { - pPar->setInputVersion(1, inputNumber); - pPar->setChanged(); - printf("%s initialized from Ascii file\n", name); - } else { - pPar->setInputVersion(-1, inputNumber); - } - delete paramList; - return allFound; + Bool_t allFound = pPar->getParams(paramList); + if (allFound) { + pPar->setInputVersion(1, inputNumber); + pPar->setChanged(); + printf("%s initialized from Ascii file\n", name); + } else { + pPar->setInputVersion(-1, inputNumber); + } + delete paramList; + return allFound; } -Int_t FairGenericParAsciiFileIo::writeGenericSet(FairParGenericSet *pPar) { - // writes condition-stype parameter containers to ASCII file - if (pFile) { - // Int_t version=1; - const Text_t *name = pPar->GetName(); - const Text_t *context = pPar->getParamContext(); - *pFile << sepLine; - *pFile << "# Class: " << name << "\n# Context: " << context << "\n"; - *pFile << sepLine; - *pFile << "[" << name << "]\n"; - writeComment(pPar); - *pFile << "//-----------------------------------------------------------" - "-----------------\n"; - FairParamList *paramList = new FairParamList; - pPar->putParams(paramList); - THashTable *pList = paramList->getList(); - TIter next(pList); - FairParamObj *po; - while ((po = static_cast(next()))) { - const Char_t *pType = po->getParamType(); - UChar_t *pValue = po->getParamValue(); - if (po->isBasicType() && strcmp(pType, "UChar_t") != 0) { - if (strcmp(pType, "Text_t") == 0) { - TString val(reinterpret_cast(pValue), po->getLength()); - val.ReplaceAll("\n", " \\\n"); - *pFile << po->GetName() << ": " << pType << " \\\n " << val.Data() - << std::endl; - } else { - Int_t nParams = po->getNumParams(); - if (nParams == 1) { - *pFile << po->GetName() << ": " << pType << " "; - } else { - *pFile << po->GetName() << ": " << pType << " \\\n "; - } - if (strcmp(pType, "Char_t") == 0) { - writeData(reinterpret_cast(pValue), nParams); - } else if (strcmp(pType, "Int_t") == 0) { - writeData(reinterpret_cast(pValue), nParams); - } else if (strcmp(pType, "Float_t") == 0) { - writeData(reinterpret_cast(pValue), nParams); - } else if (strcmp(pType, "Double_t") == 0) { - writeData(reinterpret_cast(pValue), nParams); - } +Int_t FairGenericParAsciiFileIo::writeGenericSet(FairParGenericSet *pPar) +{ + // writes condition-stype parameter containers to ASCII file + if (pFile) { + // Int_t version=1; + const Text_t *name = pPar->GetName(); + const Text_t *context = pPar->getParamContext(); + *pFile << sepLine; + *pFile << "# Class: " << name << "\n# Context: " << context << "\n"; + *pFile << sepLine; + *pFile << "[" << name << "]\n"; + writeComment(pPar); + *pFile << "//-----------------------------------------------------------" + "-----------------\n"; + FairParamList *paramList = new FairParamList; + pPar->putParams(paramList); + THashTable *pList = paramList->getList(); + TIter next(pList); + FairParamObj *po; + while ((po = static_cast(next()))) { + const Char_t *pType = po->getParamType(); + UChar_t *pValue = po->getParamValue(); + if (po->isBasicType() && strcmp(pType, "UChar_t") != 0) { + if (strcmp(pType, "Text_t") == 0) { + TString val(reinterpret_cast(pValue), po->getLength()); + val.ReplaceAll("\n", " \\\n"); + *pFile << po->GetName() << ": " << pType << " \\\n " << val.Data() << std::endl; + } else { + Int_t nParams = po->getNumParams(); + if (nParams == 1) { + *pFile << po->GetName() << ": " << pType << " "; + } else { + *pFile << po->GetName() << ": " << pType << " \\\n "; + } + if (strcmp(pType, "Char_t") == 0) { + writeData(reinterpret_cast(pValue), nParams); + } else if (strcmp(pType, "Int_t") == 0) { + writeData(reinterpret_cast(pValue), nParams); + } else if (strcmp(pType, "Float_t") == 0) { + writeData(reinterpret_cast(pValue), nParams); + } else if (strcmp(pType, "Double_t") == 0) { + writeData(reinterpret_cast(pValue), nParams); + } + } + } else { + Error("writeCond(FairParGenericSet*)", + "Type %s of parameter %s not supported by ASCII I/O", + pType, + po->GetName()); + // version=-1; + } } - } else { - Error("writeCond(FairParGenericSet*)", - "Type %s of parameter %s not supported by ASCII I/O", pType, - po->GetName()); - // version=-1; - } + *pFile << sepLine; + delete paramList; + pPar->setChanged(kFALSE); + return 1; } - *pFile << sepLine; - delete paramList; - pPar->setChanged(kFALSE); - return 1; - } - Error("writeCond(FairParGenericSet*)", "Output is not writable"); - return -1; + Error("writeCond(FairParGenericSet*)", "Output is not writable"); + return -1; } diff --git a/parbase/FairGenericParAsciiFileIo.h b/parbase/FairGenericParAsciiFileIo.h index 9a017c55e6..4dfa5f4611 100644 --- a/parbase/FairGenericParAsciiFileIo.h +++ b/parbase/FairGenericParAsciiFileIo.h @@ -1,17 +1,17 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRGENERICPARASCIIFILEIO_H #define FAIRGENERICPARASCIIFILEIO_H -#include "FairDetParAsciiFileIo.h" // for FairDetParAsciiFileIo +#include "FairDetParAsciiFileIo.h" // for FairDetParAsciiFileIo -#include // for fstream -#include // for Int_t, Bool_t, etc +#include // for Int_t, Bool_t, etc +#include // for fstream class FairParGenericSet; class FairParSet; @@ -20,18 +20,21 @@ class TString; class FairGenericParAsciiFileIo : public FairDetParAsciiFileIo { public: - FairGenericParAsciiFileIo(std::fstream* f=0); + FairGenericParAsciiFileIo(std::fstream* f = 0); ~FairGenericParAsciiFileIo() {} Bool_t init(FairParSet*); Int_t write(FairParSet*); private: - ClassDef(FairGenericParAsciiFileIo,0) // I/O from Ascii file for parameter containers derived from FairParGenericSet - Bool_t readGenericSet(FairParGenericSet* pPar); + ClassDef(FairGenericParAsciiFileIo, + 0) // I/O from Ascii file for parameter containers derived from FairParGenericSet + Bool_t readGenericSet(FairParGenericSet* pPar); Int_t writeGenericSet(FairParGenericSet* pPar); - template const UChar_t* readData(type,const Char_t*,TString&,Int_t&); - template void writeData(type*,Int_t); + template + const UChar_t* readData(type, const Char_t*, TString&, Int_t&); + template + void writeData(type*, Int_t); }; -#endif /* !FAIRGENERICPARASCIIFILEIO_H */ +#endif /* !FAIRGENERICPARASCIIFILEIO_H */ diff --git a/parbase/FairGenericParRootFileIo.cxx b/parbase/FairGenericParRootFileIo.cxx index 9851523ea2..fc6303815a 100644 --- a/parbase/FairGenericParRootFileIo.cxx +++ b/parbase/FairGenericParRootFileIo.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ //*-- AUTHOR : Ilse Koenig @@ -17,23 +17,26 @@ #include "FairGenericParRootFileIo.h" -#include // for TString +#include // for TString class FairParSet; -ClassImp(FairGenericParRootFileIo) +ClassImp(FairGenericParRootFileIo); -FairGenericParRootFileIo::FairGenericParRootFileIo(FairParRootFile* f) : FairDetParRootFileIo(f) +FairGenericParRootFileIo::FairGenericParRootFileIo(FairParRootFile* f) + : FairDetParRootFileIo(f) { - // constructor - // sets the name of the I/O class "FairGenericParIo" - // gets the pointer to the ROOT file - fName="FairGenericParIo"; + // constructor + // sets the name of the I/O class "FairGenericParIo" + // gets the pointer to the ROOT file + fName = "FairGenericParIo"; } Bool_t FairGenericParRootFileIo::init(FairParSet* pPar) { - // calls FairDetParRootFileIo"::read(FairParSet*) - if (!pFile) { return kFALSE; } - return FairDetParRootFileIo::read(pPar); + // calls FairDetParRootFileIo"::read(FairParSet*) + if (!pFile) { + return kFALSE; + } + return FairDetParRootFileIo::read(pPar); } diff --git a/parbase/FairGenericParRootFileIo.h b/parbase/FairGenericParRootFileIo.h index edc1eeb277..6883cc88d8 100644 --- a/parbase/FairGenericParRootFileIo.h +++ b/parbase/FairGenericParRootFileIo.h @@ -1,16 +1,16 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRGENERICPARROOTFILEIO_H #define FAIRGENERICPARROOTFILEIO_H -#include "FairDetParRootFileIo.h" // for FairDetParRootFileIo +#include "FairDetParRootFileIo.h" // for FairDetParRootFileIo -#include // for ClassDef macro +#include // for ClassDef macro class FairParRootFile; class FairParSet; @@ -18,10 +18,11 @@ class FairParSet; class FairGenericParRootFileIo : public FairDetParRootFileIo { public: - FairGenericParRootFileIo(FairParRootFile* f=0); + FairGenericParRootFileIo(FairParRootFile* f = 0); ~FairGenericParRootFileIo() {} Bool_t init(FairParSet*); - ClassDef(FairGenericParRootFileIo,0) // I/O from ROOT file for parameter containers derived from FairParGenericSet + ClassDef(FairGenericParRootFileIo, + 0) // I/O from ROOT file for parameter containers derived from FairParGenericSet }; -#endif /* !FAIRGENERICPARROOTFILEIO_H */ +#endif /* !FAIRGENERICPARROOTFILEIO_H */ diff --git a/parbase/FairParAsciiFileIo.cxx b/parbase/FairParAsciiFileIo.cxx index c070a1f214..00f92210d4 100644 --- a/parbase/FairParAsciiFileIo.cxx +++ b/parbase/FairParAsciiFileIo.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ //*-- AUTHOR : Ilse Koenig @@ -19,131 +19,139 @@ /////////////////////////////////////////////////////////////////////////////// #include "FairParAsciiFileIo.h" -#include "FairDetParIo.h" // for FairDetParIo -#include "FairRuntimeDb.h" // for FairRuntimeDb +#include "FairDetParIo.h" // for FairDetParIo #include "FairLogger.h" +#include "FairRuntimeDb.h" // for FairRuntimeDb -#include // for TIter -#include // for TList, TListIter -#include // for TObjString -#include // for TString, operator<< -#include // for TSystem, gSystem +#include // for TIter +#include // for TList, TListIter +#include // for TObjString +#include // for TString, operator<< +#include // for TSystem, gSystem +#include // for cout, cerr +#include // for strcmp -#include // for strcmp -#include // for cout, cerr - -using std::cout; using std::cerr; +using std::cout; using std::endl; -using std::ios; using std::filebuf; +using std::ios; -ClassImp(FairParAsciiFileIo) +ClassImp(FairParAsciiFileIo); FairParAsciiFileIo::FairParAsciiFileIo() - :FairParIo(), - file(nullptr) + : FairParIo() + , file(nullptr) { - // default destructor - // file=0; + // default destructor + // file=0; } FairParAsciiFileIo::~FairParAsciiFileIo() { - // default destructor closes an open file and deletes list of I/Os - close(); + // default destructor closes an open file and deletes list of I/Os + close(); } Bool_t FairParAsciiFileIo::open(const Text_t* fname, const Text_t* status) { - // opens file - // if a file is already open, this file will be closed - // activates detector I/Os - close(); - if (!((strcmp(status,"in")==0) || (strcmp(status,"out")==0))) { - cout<<"Put the right stream option for file "<open(fname, ios::in); + }; + if (strcmp(status, "out") == 0) { + file->open(fname, ios::out); + }; + filebuf* buf = file->rdbuf(); + if (file && (buf->is_open() == 1)) { + filename = fname; + FairRuntimeDb::instance()->activateParIo(this); + return kTRUE; + } + cerr << "-E- Could not open input file " << fname << endl; + Fatal("open", "Could not open input file"); return kFALSE; - } - file=new std::fstream(); - if(strcmp(status,"in")==0) {file->open(fname, ios::in);}; - if(strcmp(status,"out")==0) {file->open(fname, ios::out);}; - filebuf* buf = file->rdbuf(); - if (file && (buf->is_open()==1)) { - filename=fname; - FairRuntimeDb::instance()->activateParIo(this); - return kTRUE; - } - cerr << "-E- Could not open input file " << fname << endl; - Fatal("open","Could not open input file"); - return kFALSE; } Bool_t FairParAsciiFileIo::open(const TList* fnamelist, const Text_t* status) { - if (0 == fnamelist->GetEntries()) { - LOG(error) << "The defined list of parameter files is empty. There are no parameters initialized from the ASCII files."; - return kFALSE; - } - TString outFileName = gSystem->WorkingDirectory(); - - outFileName += "/all_"; - Int_t pid = gSystem->GetPid(); - outFileName += pid; - outFileName += ".par"; - TString catCommand = "cat "; - TObjString* string; - TListIter myIter(fnamelist); - while((string = static_cast(myIter.Next()))) { - // check if the file exist - // if file exist return value is false - TString strParPath = string->GetString(); - gSystem->ExpandPathName(strParPath); - if (gSystem->AccessPathName(strParPath)) - LOG(fatal) << "Parameter file " << strParPath << " does not exist."; - // cout << string->GetString() <GetString(); - catCommand += " "; - } - catCommand += "> "; - catCommand += outFileName; - - // cout <<"CAT: "<Exec(catCommand); - - return open(outFileName, status); + if (0 == fnamelist->GetEntries()) { + LOG(error) << "The defined list of parameter files is empty. There are no parameters initialized from the " + "ASCII files."; + return kFALSE; + } + TString outFileName = gSystem->WorkingDirectory(); + + outFileName += "/all_"; + Int_t pid = gSystem->GetPid(); + outFileName += pid; + outFileName += ".par"; + TString catCommand = "cat "; + TObjString* string; + TListIter myIter(fnamelist); + while ((string = static_cast(myIter.Next()))) { + // check if the file exist + // if file exist return value is false + TString strParPath = string->GetString(); + gSystem->ExpandPathName(strParPath); + if (gSystem->AccessPathName(strParPath)) + LOG(fatal) << "Parameter file " << strParPath << " does not exist."; + // cout << string->GetString() <GetString(); + catCommand += " "; + } + catCommand += "> "; + catCommand += outFileName; + + // cout <<"CAT: "<Exec(catCommand); + + return open(outFileName, status); } void FairParAsciiFileIo::close() { - // closes the file and deletes the detector I/Os - if (file) { - file->close(); - delete file; - file=0; - filename=""; - } - if (detParIoList) { detParIoList->Delete(); } + // closes the file and deletes the detector I/Os + if (file) { + file->close(); + delete file; + file = 0; + filename = ""; + } + if (detParIoList) { + detParIoList->Delete(); + } } void FairParAsciiFileIo::print() { - // prints information about the file and the detector I/Os - if (check()) { - cout<<"Ascii I/O "<(next()))) { - cout<<" "<GetName(); + // prints information about the file and the detector I/Os + if (check()) { + cout << "Ascii I/O " << filename << " is open\n"; + TIter next(detParIoList); + FairDetParIo* io; + cout << "detector I/Os: "; + while ((io = static_cast(next()))) { + cout << " " << io->GetName(); + } + cout << '\n'; + } else { + cout << "No file open\n"; } - cout<<'\n'; - } else { cout<<"No file open\n"; } } std::fstream* FairParAsciiFileIo::getFile() { - // returns the file pointer - return file; + // returns the file pointer + return file; } diff --git a/parbase/FairParAsciiFileIo.h b/parbase/FairParAsciiFileIo.h index 3e3ad54fe4..e935226561 100644 --- a/parbase/FairParAsciiFileIo.h +++ b/parbase/FairParAsciiFileIo.h @@ -1,25 +1,24 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRPARASCIFILEIIO_H #define FAIRPARASCIFILEIIO_H -#include "FairParIo.h" // for FairParIo +#include "FairParIo.h" // for FairParIo -#include // for Bool_t, Text_t, etc - -#include // for fstream, etc +#include // for Bool_t, Text_t, etc +#include // for fstream, etc class TList; class FairParAsciiFileIo : public FairParIo { protected: - std::fstream* file; // pointer to a file + std::fstream* file; // pointer to a file public: FairParAsciiFileIo(); @@ -30,21 +29,25 @@ class FairParAsciiFileIo : public FairParIo // opens file // if a file is already open, this file will be closed // activates detector I/Os - Bool_t open(const Text_t* fname, const Text_t* status="in"); + Bool_t open(const Text_t* fname, const Text_t* status = "in"); // concatenate files whose names are stored in the TList // TList holds list od TObjStrings // create file all.par in local working directory // calls open to open the generated file all.par - Bool_t open(const TList* fnamelist, const Text_t* status="in"); + Bool_t open(const TList* fnamelist, const Text_t* status = "in"); // closes file void close(); // returns kTRUE if file is open - Bool_t check() { - if (file) { return (file->rdbuf()->is_open()==1); } - else { return kFALSE; } + Bool_t check() + { + if (file) { + return (file->rdbuf()->is_open() == 1); + } else { + return kFALSE; + } } // prints information about the file and the detector I/Os @@ -56,8 +59,7 @@ class FairParAsciiFileIo : public FairParIo FairParAsciiFileIo(const FairParAsciiFileIo&); FairParAsciiFileIo& operator=(const FairParAsciiFileIo&); - ClassDef(FairParAsciiFileIo,0) // Parameter I/O from ASCII files + ClassDef(FairParAsciiFileIo, 0) // Parameter I/O from ASCII files }; -#endif /* !FAIRPARASCIIFILEIO_H */ - +#endif /* !FAIRPARASCIIFILEIO_H */ diff --git a/parbase/FairParGenericSet.cxx b/parbase/FairParGenericSet.cxx index 51436ee218..5d2f53e183 100644 --- a/parbase/FairParGenericSet.cxx +++ b/parbase/FairParGenericSet.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ //*-- AUTHOR : Ilse Koenig @@ -28,44 +28,53 @@ /////////////////////////////////////////////////////////////////////////// #include "FairParGenericSet.h" -#include "FairDetParIo.h" // for FairDetParIo -#include "FairParIo.h" // for FairParIo -#include "FairParamList.h" // for FairParamList +#include "FairDetParIo.h" // for FairDetParIo +#include "FairParIo.h" // for FairParIo +#include "FairParamList.h" // for FairParamList -#include // for operator<<, TString +#include // for operator<<, TString +#include // for operator<<, ostream, cout, etc -#include // for operator<<, ostream, cout, etc - -ClassImp(FairParGenericSet) +ClassImp(FairParGenericSet); Bool_t FairParGenericSet::init(FairParIo* inp) { - // intitializes the container from an input - FairDetParIo* input=inp->getDetParIo("FairGenericParIo"); - if (input) { return (input->init(this)); } - return kFALSE; + // intitializes the container from an input + FairDetParIo* input = inp->getDetParIo("FairGenericParIo"); + if (input) { + return (input->init(this)); + } + return kFALSE; } Int_t FairParGenericSet::write(FairParIo* output) { - // writes the container to an output - FairDetParIo* out=output->getDetParIo("FairGenericParIo"); - if (out) { return out->write(this); } - return -1; + // writes the container to an output + FairDetParIo* out = output->getDetParIo("FairGenericParIo"); + if (out) { + return out->write(this); + } + return -1; } void FairParGenericSet::printParams() { - // prints information about the container - std::cout<<"\n---------------------------------------------\n"; - std::cout<<"----- "<print(); - std::cout<<"---------------------------------------------\n\n"; - delete condList; + // prints information about the container + std::cout << "\n---------------------------------------------\n"; + std::cout << "----- " << GetName() << " -----\n"; + if (!paramContext.IsNull()) { + std::cout << "-- Context/Purpose: " << paramContext << '\n'; + } + if (!author.IsNull()) { + std::cout << "-- Author: " << author << '\n'; + } + if (!description.IsNull()) { + std::cout << "-- Description: " << description << '\n'; + } + std::cout << "---------------------------------------------\n"; + FairParamList* condList = new FairParamList; + putParams(condList); + condList->print(); + std::cout << "---------------------------------------------\n\n"; + delete condList; } diff --git a/parbase/FairParGenericSet.h b/parbase/FairParGenericSet.h index 68f2aa86da..5a98cc18f5 100644 --- a/parbase/FairParGenericSet.h +++ b/parbase/FairParGenericSet.h @@ -1,16 +1,16 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRPARGENERICSET_H #define FAIRPARGENERICSET_H -#include "FairParSet.h" // for FairParSet +#include "FairParSet.h" // for FairParSet -#include // for Bool_t, etc +#include // for Bool_t, etc class FairParIo; class FairParamList; @@ -18,24 +18,26 @@ class FairParamList; class FairParGenericSet : public FairParSet { public: - FairParGenericSet(const char* name,const char* title,const char* context, Bool_t ownership=kFALSE) - : FairParSet(name,title,context,ownership) {} + FairParGenericSet(const char* name, const char* title, const char* context, Bool_t ownership = kFALSE) + : FairParSet(name, title, context, ownership) + {} virtual ~FairParGenericSet() {} - virtual void putParams(FairParamList*)=0; - virtual Bool_t getParams(FairParamList*)=0; + virtual void putParams(FairParamList*) = 0; + virtual Bool_t getParams(FairParamList*) = 0; virtual void printParams(); Bool_t init(FairParIo* inp); - Int_t write(FairParIo* output); + Int_t write(FairParIo* output); - // DB add on - void fill(UInt_t) {}; - void store(UInt_t) {}; + // DB add on + void fill(UInt_t){}; + void store(UInt_t){}; protected: FairParGenericSet() - : FairParSet() {} - ClassDef(FairParGenericSet,1) // Base class for generic-style parameter containers + : FairParSet() + {} + ClassDef(FairParGenericSet, 1) // Base class for generic-style parameter containers }; -#endif /* !FAIRPARGENERICSET_H */ +#endif /* !FAIRPARGENERICSET_H */ diff --git a/parbase/FairParIo.cxx b/parbase/FairParIo.cxx index bd91ea6a8c..d896cb3606 100644 --- a/parbase/FairParIo.cxx +++ b/parbase/FairParIo.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ //*-- AUTHOR : Ilse Koenig @@ -18,65 +18,67 @@ #include "FairParIo.h" -#include "FairDetParIo.h" // for FairDetParIo +#include "FairDetParIo.h" // for FairDetParIo -#include // for TIter -#include // for TList +#include // for TIter +#include // for TList using namespace std; -ClassImp(FairParIo) +ClassImp(FairParIo); FairParIo::FairParIo() - :TObject(), - detParIoList(new TList()), - autoWritable(kTRUE), - filename("") + : TObject() + , detParIoList(new TList()) + , autoWritable(kTRUE) + , filename("") { - //default constructor creates an empty list of detector I/Os - // detParIoList=new TList(); - // autoWritable=kTRUE; + // default constructor creates an empty list of detector I/Os + // detParIoList=new TList(); + // autoWritable=kTRUE; } FairParIo::~FairParIo() { - // default destructor - if(detParIoList) { - detParIoList->Delete(); - delete detParIoList; - detParIoList=0; - } + // default destructor + if (detParIoList) { + detParIoList->Delete(); + delete detParIoList; + detParIoList = 0; + } } void FairParIo::setDetParIo(FairDetParIo* detParIo) { - // stores pointer of the input/output class for a detector - // used for I/O from ROOT file or Ascii file - const Text_t* detName=detParIo->GetName(); - if (!detParIoList->FindObject(detName)) { detParIoList->Add(detParIo); } + // stores pointer of the input/output class for a detector + // used for I/O from ROOT file or Ascii file + const Text_t* detName = detParIo->GetName(); + if (!detParIoList->FindObject(detName)) { + detParIoList->Add(detParIo); + } } void FairParIo::setInputNumber(Int_t num) { - // sets in all detector I/Os the number of the input - TIter next(detParIoList); - FairDetParIo* io; - while ((io=static_cast(next()))) { - io->setInputNumber(num); - } + // sets in all detector I/Os the number of the input + TIter next(detParIoList); + FairDetParIo* io; + while ((io = static_cast(next()))) { + io->setInputNumber(num); + } } FairDetParIo* FairParIo::getDetParIo(const Text_t* detName) { - // returns pointer to input/output class for a detector - //std::cout << " DetParIO # " << detName << detParIoList->GetEntries() << std::endl; - return (static_cast(detParIoList->FindObject(detName))); + // returns pointer to input/output class for a detector + // std::cout << " DetParIO # " << detName << detParIoList->GetEntries() << std::endl; + return (static_cast(detParIoList->FindObject(detName))); } void FairParIo::removeDetParIo(Text_t* detName) { - // removes input/output class for a detector - TObject* p=detParIoList->FindObject(detName); - delete p; - p=0; + // removes input/output class for a detector + TObject* p = detParIoList->FindObject(detName); + delete p; + p = 0; } diff --git a/parbase/FairParIo.h b/parbase/FairParIo.h index 9635354e5e..3a7bf2dc60 100644 --- a/parbase/FairParIo.h +++ b/parbase/FairParIo.h @@ -1,17 +1,16 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRPARIO_H #define FAIRPARIO_H -#include // for TObject - -#include // for Bool_t, Text_t, etc -#include // for TString +#include // for Bool_t, Text_t, etc +#include // for TObject +#include // for TString class FairDetParIo; class FairRtdbRun; @@ -20,8 +19,8 @@ class TList; class FairParIo : public TObject { protected: - TList* detParIoList; // list of detector I/Os - Bool_t autoWritable; // flag indicating if automatic write is possible + TList* detParIoList; // list of detector I/Os + Bool_t autoWritable; // flag indicating if automatic write is possible TString filename; public: @@ -31,42 +30,38 @@ class FairParIo : public TObject virtual void setDetParIo(FairDetParIo*); virtual void removeDetParIo(Text_t*); void setInputNumber(Int_t); - virtual void close() {;} + virtual void close() { ; } // returns the filename - const char* getFilename() {return filename.Data();} + const char* getFilename() { return filename.Data(); } // creates input/output class for a special detector and stores pointer // used only for Oracle input/output // (code in class OraIo) - virtual void setDetParIo(Text_t*) {;} + virtual void setDetParIo(Text_t*) { ; } // prints information about input/output - virtual void print() {;} + virtual void print() { ; } // checks if the input/output is open virtual Bool_t check() { return kFALSE; } // reads versions of parameter containers for an event file - virtual void readVersions(FairRtdbRun*) {;} + virtual void readVersions(FairRtdbRun*) { ; } // sets global file pointer in ROOT if input/output is a ROOT-file // (code in FairParRootFileIo) - virtual void cd() {;} + virtual void cd() { ; } // set and get for flag autoWritable - void setAutoWritable(Bool_t f=kTRUE) {autoWritable=f;} - Bool_t isAutoWritable() {return autoWritable;} + void setAutoWritable(Bool_t f = kTRUE) { autoWritable = f; } + Bool_t isAutoWritable() { return autoWritable; } private: FairParIo(const FairParIo&); FairParIo& operator=(const FairParIo&); - ClassDef(FairParIo,0) // Base class for all parameter I/Os + ClassDef(FairParIo, 0) // Base class for all parameter I/Os }; -#endif /* !FAIRPARIO_H */ - - - - +#endif /* !FAIRPARIO_H */ diff --git a/parbase/FairParRootFileIo.cxx b/parbase/FairParRootFileIo.cxx index 640421e6bc..b609ed9363 100644 --- a/parbase/FairParRootFileIo.cxx +++ b/parbase/FairParRootFileIo.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ //*-- AUTHOR : Ilse Koenig @@ -23,252 +23,245 @@ // base type FairDetParRootFileIo. Every detector has its own interface class. ////////////////////////////////////////////////////////////////////////////// #include "FairParRootFileIo.h" -#include "FairDetParIo.h" // for FairDetParIo -#include "FairRtdbRun.h" // for FairRtdbRun -#include "FairRuntimeDb.h" // for FairRuntimeDb -#include // for TIter -#include // for TDatime -#include // for TKey -#include // for TListIter, TList -#include // for TObject -#include // for TObjString -#include // for TString, Form +#include "FairDetParIo.h" // for FairDetParIo +#include "FairRtdbRun.h" // for FairRtdbRun +#include "FairRuntimeDb.h" // for FairRuntimeDb -#include // for operator<<, basic_ostream, etc +#include // for TIter +#include // for TDatime +#include // for TKey +#include // for TListIter, TList +#include // for TObjString +#include // for TObject +#include // for TString, Form +#include // for operator<<, basic_ostream, etc -using std::cout; using std::cerr; +using std::cout; using std::endl; -ClassImp(FairParRootFile) -ClassImp(FairParRootFileIo) +ClassImp(FairParRootFile); +ClassImp(FairParRootFileIo); -FairParRootFile::FairParRootFile(const Text_t* fname, Option_t* option, - const Text_t* ftitle, Int_t compress) - :TNamed(fname, ftitle), - run(nullptr), - RootFile(TFile::Open(fname,option,ftitle,compress)) +FairParRootFile::FairParRootFile(const Text_t* fname, Option_t* option, const Text_t* ftitle, Int_t compress) + : TNamed(fname, ftitle) + , run(nullptr) + , RootFile(TFile::Open(fname, option, ftitle, compress)) { -// : TFile(fname,option,ftitle,compress) { - // constructor opens a ROOT file - // RootFile=TFile::Open(fname,option,ftitle,compress); - //run=0; + // : TFile(fname,option,ftitle,compress) { + // constructor opens a ROOT file + // RootFile=TFile::Open(fname,option,ftitle,compress); + // run=0; } FairParRootFile::FairParRootFile(TFile* f) - :TNamed(f->GetName(), f->GetTitle()), - run(nullptr), - RootFile(f) + : TNamed(f->GetName(), f->GetTitle()) + , run(nullptr) + , RootFile(f) { -// :TFile(f->GetName(),"UPDATE"){ - // constructor opens a ROOT file - //RootFile=TFile::Open(f->GetName(),"UPDATE"); - // RootFile=f; - // run=0; + // :TFile(f->GetName(),"UPDATE"){ + // constructor opens a ROOT file + // RootFile=TFile::Open(f->GetName(),"UPDATE"); + // RootFile=f; + // run=0; } FairParRootFile::~FairParRootFile() { - // destructor - delete run; - run=0; - //TODO: What about the file? Should it be closed or not + // destructor + delete run; + run = 0; + // TODO: What about the file? Should it be closed or not } void FairParRootFile::readVersions(FairRtdbRun* currentRun) { - // finds the current run containing the parameter container versions - // in the ROOT file - delete run; + // finds the current run containing the parameter container versions + // in the ROOT file + delete run; - run=static_cast(RootFile->Get((const_cast(currentRun->GetName())))); - //cout << "-I- FairParRootFile :: readversions " << currentRun->GetName() << " : " << run << endl; + run = static_cast(RootFile->Get((const_cast(currentRun->GetName())))); + // cout << "-I- FairParRootFile :: readversions " << currentRun->GetName() << " : " << run << endl; } FairParRootFileIo::FairParRootFileIo() - :FairParIo(), - file(nullptr), - fMerging(kFALSE) + : FairParIo() + , file(nullptr) + , fMerging(kFALSE) { - // constructor - // file=0; - // fMerging=kFALSE; + // constructor + // file=0; + // fMerging=kFALSE; } FairParRootFileIo::FairParRootFileIo(Bool_t merged) - :FairParIo(), - file(nullptr), - fMerging(merged) + : FairParIo() + , file(nullptr) + , fMerging(merged) { - // constructor - // file=0; - // fMerging=merged; - + // constructor + // file=0; + // fMerging=merged; } FairParRootFileIo::~FairParRootFileIo() { - // destructor closes an open file - close(); + // destructor closes an open file + close(); } -Bool_t FairParRootFileIo::open(const Text_t* fname, Option_t* option, - const Text_t* ftitle, Int_t compress) +Bool_t FairParRootFileIo::open(const Text_t* fname, Option_t* option, const Text_t* ftitle, Int_t compress) { - // It opens a ROOT file (default option "READ"). An open file will be closed. - // The detector I/Os for all detectors defined in the setup are activated. - - //DB, lock file for NFS in case of mulitple access - //gDirectory->ReadKeys(); - close(); - if (fMerging ) { - // used test merging - std::fstream* f = new std::fstream(fname); - if (f->good()) { - // check if file already exists - option = "UPDATE"; - } else { - // if file doesn't exist recreate option is used - option = "RECREATE"; + // It opens a ROOT file (default option "READ"). An open file will be closed. + // The detector I/Os for all detectors defined in the setup are activated. + + // DB, lock file for NFS in case of mulitple access + // gDirectory->ReadKeys(); + close(); + if (fMerging) { + // used test merging + std::fstream* f = new std::fstream(fname); + if (f->good()) { + // check if file already exists + option = "UPDATE"; + } else { + // if file doesn't exist recreate option is used + option = "RECREATE"; + } + f->close(); + delete f; + } + + file = new FairParRootFile(fname, option, ftitle, compress); + + if (file && file->IsOpen()) { + filename = fname; + FairRuntimeDb::instance()->activateParIo(this); + return kTRUE; } - f->close(); - delete f; - } - - file=new FairParRootFile(fname,option,ftitle,compress); - - if (file && file->IsOpen()) { - filename = fname; - FairRuntimeDb::instance()->activateParIo(this); - return kTRUE; - } - cerr << "-E- Could not open input file " << fname << endl; - Fatal("open","Could not open input file"); - return kFALSE; + cerr << "-E- Could not open input file " << fname << endl; + Fatal("open", "Could not open input file"); + return kFALSE; } -Bool_t FairParRootFileIo::open(const TList* fnamelist, Option_t* option, - const Text_t* ftitle, Int_t compress) +Bool_t FairParRootFileIo::open(const TList* fnamelist, Option_t* option, const Text_t* ftitle, Int_t compress) { - TDatime currentDate; - TString newParFileName = ""; - TFile* newParFile=0; + TDatime currentDate; + TString newParFileName = ""; + TFile* newParFile = 0; - TObjString* string; - TListIter myIter(fnamelist); + TObjString* string; + TListIter myIter(fnamelist); - TKey* inpKey; + TKey* inpKey; - TFile* inFile; + TFile* inFile; - Int_t nofFiles = 0; - while((string = static_cast(myIter.Next()))) { - inFile = TFile::Open(string->GetString().Data()); - if ( !inFile ) { - cout << "-W- File \"" << string->GetString().Data() << "\" does not exist" << endl; - continue; - } + Int_t nofFiles = 0; + while ((string = static_cast(myIter.Next()))) { + inFile = TFile::Open(string->GetString().Data()); + if (!inFile) { + cout << "-W- File \"" << string->GetString().Data() << "\" does not exist" << endl; + continue; + } - if ( nofFiles == 0 ) { - newParFileName = string->GetString(); - newParFileName.Replace(newParFileName.Last('/')+1, - newParFileName.Length(),""); - newParFileName = Form("%sallParams_%d_%06d.root", - newParFileName.Data(), - currentDate.GetDate(), - currentDate.GetTime()); - newParFile = TFile::Open(newParFileName.Data(),"RECREATE"); - } + if (nofFiles == 0) { + newParFileName = string->GetString(); + newParFileName.Replace(newParFileName.Last('/') + 1, newParFileName.Length(), ""); + newParFileName = + Form("%sallParams_%d_%06d.root", newParFileName.Data(), currentDate.GetDate(), currentDate.GetTime()); + newParFile = TFile::Open(newParFileName.Data(), "RECREATE"); + } + + TList* inputKeys = static_cast(inFile->GetListOfKeys()); - TList* inputKeys = static_cast(inFile->GetListOfKeys()); + TListIter keyIter(inputKeys); + while ((inpKey = static_cast(keyIter.Next()))) { + TObject* tempObj = inFile->Get(inpKey->GetName()); - TListIter keyIter(inputKeys); - while((inpKey = static_cast(keyIter.Next()))) { - TObject* tempObj = inFile->Get(inpKey->GetName()); + newParFile->cd(); + tempObj->Write(); + } + inFile->Close(); - newParFile->cd(); - tempObj->Write(); + nofFiles++; } - inFile->Close(); - - nofFiles++; - } - if(newParFile!=0){ - newParFile->Close(); - }else{ - std::cout << "****NO file to close file = \"" << std::endl; - } - std::cout << "**** merged file = \"" << newParFileName.Data() << "\"" << std::endl; - - return this->open(newParFileName,option,ftitle,compress); + if (newParFile != 0) { + newParFile->Close(); + } else { + std::cout << "****NO file to close file = \"" << std::endl; + } + std::cout << "**** merged file = \"" << newParFileName.Data() << "\"" << std::endl; + + return this->open(newParFileName, option, ftitle, compress); } Bool_t FairParRootFileIo::open(TFile* f) { - // It opens a ROOT file (default option "READ"). An open file will be closed. - // The detector I/Os for all detectors defined in the setup are activated. - // close(); - file=new FairParRootFile(f); - if (file && file->IsOpen()) { - filename = file->GetName(); - FairRuntimeDb::instance()->activateParIo(this); - return kTRUE; - } - return kFALSE; + // It opens a ROOT file (default option "READ"). An open file will be closed. + // The detector I/Os for all detectors defined in the setup are activated. + // close(); + file = new FairParRootFile(f); + if (file && file->IsOpen()) { + filename = file->GetName(); + FairRuntimeDb::instance()->activateParIo(this); + return kTRUE; + } + return kFALSE; } void FairParRootFileIo::close() { - // closes an open ROOT file and deletes the detector I/Os - if (file) { - file->Close(); - delete file; - file=0; - } - if (detParIoList) { - detParIoList->Delete(); - } + // closes an open ROOT file and deletes the detector I/Os + if (file) { + file->Close(); + delete file; + file = 0; + } + if (detParIoList) { + detParIoList->Delete(); + } } void FairParRootFileIo::print() { - // prints the content of a open ROOT file and the list of detector I/Os - if (file) { - file->ls(); - TIter next(detParIoList); - FairDetParIo* io; - cout<<"Root file I/O "<GetName()<<" is open\n"; - cout<<"detector I/Os: "; - while ((io=static_cast(next()))) { - cout<<" "<GetName(); + // prints the content of a open ROOT file and the list of detector I/Os + if (file) { + file->ls(); + TIter next(detParIoList); + FairDetParIo* io; + cout << "Root file I/O " << file->GetName() << " is open\n"; + cout << "detector I/Os: "; + while ((io = static_cast(next()))) { + cout << " " << io->GetName(); + } + cout << '\n'; + } else { + cout << "No ROOT file open\n"; } - cout<<'\n'; - } else { - cout<<"No ROOT file open\n"; - } } FairParRootFile* FairParRootFileIo::getParRootFile() { - // returns a pointer to the current ROOT file - return file; + // returns a pointer to the current ROOT file + return file; } void FairParRootFileIo::readVersions(FairRtdbRun* currentRun) { - // reads the parameter container versions for the current run from - // the ROOT file - if (file) { - file->readVersions(currentRun); - } + // reads the parameter container versions for the current run from + // the ROOT file + if (file) { + file->readVersions(currentRun); + } } TList* FairParRootFileIo::getKeys() { - // returns the list of keys found in the ROOT file - if (file) { - return file->GetListOfKeys(); - } - return 0; + // returns the list of keys found in the ROOT file + if (file) { + return file->GetListOfKeys(); + } + return 0; } diff --git a/parbase/FairParRootFileIo.h b/parbase/FairParRootFileIo.h index 30eb34efb0..675241fce2 100644 --- a/parbase/FairParRootFileIo.h +++ b/parbase/FairParRootFileIo.h @@ -1,19 +1,18 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRPARROOTFILEIO_H #define FAIRPARROOTFILEIO_H -#include "FairParIo.h" // for FairParIo - -#include // for Bool_t, Text_t, Int_t, etc -#include // for TFile -#include // for TNamed +#include "FairParIo.h" // for FairParIo +#include // for Bool_t, Text_t, Int_t, etc +#include // for TFile +#include // for TNamed #include using std::fstream; @@ -24,21 +23,20 @@ class TList; class FairParRootFile : public TNamed { public: - FairRtdbRun* run; //! pointer to current run in ROOT file - FairParRootFile(const Text_t* fname, Option_t* option="READ", - const Text_t* ftitle="",Int_t compress=1); + FairRtdbRun* run; //! pointer to current run in ROOT file + FairParRootFile(const Text_t* fname, Option_t* option = "READ", const Text_t* ftitle = "", Int_t compress = 1); FairParRootFile(TFile* f); ~FairParRootFile(); - FairRtdbRun* getRun() {return run;} + FairRtdbRun* getRun() { return run; } void readVersions(FairRtdbRun*); - Bool_t IsOpen() {return RootFile->IsOpen();} - void cd() {RootFile->cd();} - Bool_t IsWritable() {return RootFile->IsWritable();} + Bool_t IsOpen() { return RootFile->IsOpen(); } + void cd() { RootFile->cd(); } + Bool_t IsWritable() { return RootFile->IsWritable(); } - TKey* GetKey(Text_t* t) { return RootFile->GetKey(t);} - TList* GetListOfKeys() { return RootFile->GetListOfKeys();} - void Close() {RootFile->Close();} + TKey* GetKey(Text_t* t) { return RootFile->GetKey(t); } + TList* GetListOfKeys() { return RootFile->GetListOfKeys(); } + void Close() { RootFile->Close(); } protected: TFile* RootFile; @@ -47,48 +45,53 @@ class FairParRootFile : public TNamed FairParRootFile(const FairParRootFile&); FairParRootFile& operator=(const FairParRootFile&); - ClassDef(FairParRootFile,0) // ROOT file for Parameter I/O + ClassDef(FairParRootFile, 0) // ROOT file for Parameter I/O }; class FairParRootFileIo : public FairParIo { protected: - FairParRootFile* file; // pointer to ROOT file + FairParRootFile* file; // pointer to ROOT file Bool_t fMerging; public: FairParRootFileIo(); FairParRootFileIo(Bool_t merged); ~FairParRootFileIo(); - Bool_t open(const Text_t* fname, Option_t* option="READ", - const Text_t* ftitle="",Int_t compress=1); - Bool_t open(const TList* fnamelist, Option_t* option="READ", - const Text_t* ftitle="",Int_t compress=1); + Bool_t open(const Text_t* fname, Option_t* option = "READ", const Text_t* ftitle = "", Int_t compress = 1); + Bool_t open(const TList* fnamelist, Option_t* option = "READ", const Text_t* ftitle = "", Int_t compress = 1); void close(); void print(); FairParRootFile* getParRootFile(); void readVersions(FairRtdbRun*); TList* getKeys(); - Bool_t check() { - // returns kTRUE if file is open - if (file) { return file->IsOpen(); } - else { return kFALSE; } + Bool_t check() + { + // returns kTRUE if file is open + if (file) { + return file->IsOpen(); + } else { + return kFALSE; + } } - void cd() { - // sets the global ROOT file pointer gFile - if (file) { file->cd(); } + void cd() + { + // sets the global ROOT file pointer gFile + if (file) { + file->cd(); + } } /** Open an existing root file for IO */ Bool_t open(TFile* f); - void setMerging( Bool_t io ) { fMerging=io;} + void setMerging(Bool_t io) { fMerging = io; } private: FairParRootFileIo(const FairParRootFileIo&); FairParRootFileIo& operator=(const FairParRootFileIo&); - ClassDef(FairParRootFileIo,0) // Parameter I/O from ROOT files + ClassDef(FairParRootFileIo, 0) // Parameter I/O from ROOT files }; -#endif /* !FAIRPARROOTFILEIO_H */ +#endif /* !FAIRPARROOTFILEIO_H */ diff --git a/parbase/FairParSet.cxx b/parbase/FairParSet.cxx index fbb22aa717..2a7909cb17 100644 --- a/parbase/FairParSet.cxx +++ b/parbase/FairParSet.cxx @@ -15,115 +15,142 @@ ///////////////////////////////////////////////////////////// #include "FairParSet.h" -#include "FairLogger.h" // for FairLogger, MESSAGE_ORIGIN -#include "FairRuntimeDb.h" // for FairRuntimeDb +#include "FairLogger.h" // for FairLogger, MESSAGE_ORIGIN +#include "FairRuntimeDb.h" // for FairRuntimeDb -#include // for operator<<, ostream, etc +#include // for operator<<, ostream, etc using std::cout; -ClassImp(FairParSet) +ClassImp(FairParSet); -FairParSet::FairParSet(const char* name,const char* title,const char* context, Bool_t owner) - : TObject(), - fName(name), - fTitle(title), - detName(""), - versions(), - status(kFALSE), - changed(kFALSE), - owned(owner), - paramContext(context), - author(""), - description(""), - fLogger(FairLogger::GetLogger()) +FairParSet::FairParSet(const char* name, const char* title, const char* context, Bool_t owner) + : TObject() + , fName(name) + , fTitle(title) + , detName("") + , versions() + , status(kFALSE) + , changed(kFALSE) + , owned(owner) + , paramContext(context) + , author("") + , description("") + , fLogger(FairLogger::GetLogger()) { - for(Int_t i=0; i<3; i++) {versions[i]=-1;} + for (Int_t i = 0; i < 3; i++) { + versions[i] = -1; + } } Bool_t FairParSet::init() { - // intitializes the container from an input in run time - // database. If this is not successful it is initialized from - // the second input. If this failes too, it returns an error. - // (calls internally the init function in the derived class) - FairRuntimeDb* rtdb=FairRuntimeDb::instance(); - //FairRunAna* fRun =FairRunAna::Instance(); -// cout << "-I- FairParSet::init() " << GetName() << endl; + // intitializes the container from an input in run time + // database. If this is not successful it is initialized from + // the second input. If this failes too, it returns an error. + // (calls internally the init function in the derived class) + FairRuntimeDb* rtdb = FairRuntimeDb::instance(); + // FairRunAna* fRun =FairRunAna::Instance(); + // cout << "-I- FairParSet::init() " << GetName() << endl; - Bool_t allFound=kFALSE; - FairParIo* io=0; - if (rtdb) { - io=rtdb->getFirstInput(); - if (io) { allFound=init(io); } - if (!allFound) { - io=rtdb->getSecondInput(); - //cout << "-I FairParSet::init() 2 " << io << std::endl; - if (io) { allFound=init(io); } - } else { setInputVersion(-1,2); } - } - if (allFound) { return kTRUE; } - LOG(error) << "init() " << GetName() << " not initialized"; - return kFALSE; + Bool_t allFound = kFALSE; + FairParIo* io = 0; + if (rtdb) { + io = rtdb->getFirstInput(); + if (io) { + allFound = init(io); + } + if (!allFound) { + io = rtdb->getSecondInput(); + // cout << "-I FairParSet::init() 2 " << io << std::endl; + if (io) { + allFound = init(io); + } + } else { + setInputVersion(-1, 2); + } + } + if (allFound) { + return kTRUE; + } + LOG(error) << "init() " << GetName() << " not initialized"; + return kFALSE; } Int_t FairParSet::write() { - // writes the container to the output defined in the runtime database - // returns the output version in the ROOT file - // returns -1 if error occured - // (calls internally the init function in the derived class) - FairParIo* output=FairRuntimeDb::instance()->getOutput(); - if (output) { return write(output); } - LOG(error) << "write() " << GetName() << " could not be written to output"; - return -1; + // writes the container to the output defined in the runtime database + // returns the output version in the ROOT file + // returns -1 if error occured + // (calls internally the init function in the derived class) + FairParIo* output = FairRuntimeDb::instance()->getOutput(); + if (output) { + return write(output); + } + LOG(error) << "write() " << GetName() << " could not be written to output"; + return -1; } void FairParSet::print() { - // prints information about container (versions,status,hasChanged...) - cout<<"----- "< // for Int_t, Bool_t, etc -#include // for TString +#include // for Int_t, Bool_t, etc #include +#include // for TString class FairLogger; class FairParIo; @@ -18,25 +18,25 @@ class FairParIo; class FairParSet : public TObject { protected: - TString fName; // - TString fTitle; // - TString detName; //! name of the detector the container belongs to - Int_t versions[3]; //! versions of container in the 2 possible inputs - Bool_t status; //! static flag - Bool_t changed; //! flag is kTRUE if parameters have changed - Bool_t owned; //! if flag is KTRUE FairDB has the par. class ownership - TString paramContext; // Context/purpose for parameters and conditions - TString author; // Author of parameters - TString description ; // Description of parameters + TString fName; // + TString fTitle; // + TString detName; //! name of the detector the container belongs to + Int_t versions[3]; //! versions of container in the 2 possible inputs + Bool_t status; //! static flag + Bool_t changed; //! flag is kTRUE if parameters have changed + Bool_t owned; //! if flag is KTRUE FairDB has the par. class ownership + TString paramContext; // Context/purpose for parameters and conditions + TString author; // Author of parameters + TString description; // Description of parameters /** Fair Logger */ - FairLogger* fLogger; //! + FairLogger* fLogger; //! public: - FairParSet(const char* name="",const char* title="",const char* context="", Bool_t owner=kFALSE); + FairParSet(const char* name = "", const char* title = "", const char* context = "", Bool_t owner = kFALSE); virtual ~FairParSet() {} - virtual const char* GetName() const {return static_cast(fName.Data());} - virtual const char* GetTitle() const {return static_cast(fTitle.Data());} + virtual const char* GetName() const { return static_cast(fName.Data()); } + virtual const char* GetTitle() const { return static_cast(fTitle.Data()); } virtual Bool_t init(); virtual Bool_t init(FairParIo*) { return kFALSE; } @@ -45,46 +45,54 @@ class FairParSet : public TObject virtual void clear() {} virtual void print(); - const char* getDetectorName() {return detName.Data();} + const char* getDetectorName() { return detName.Data(); } void resetInputVersions(); - void setInputVersion(Int_t v=-1,Int_t i=0) { - if (i>=0 && i<3) { versions[i]=v; } + void setInputVersion(Int_t v = -1, Int_t i = 0) + { + if (i >= 0 && i < 3) { + versions[i] = v; + } } - Int_t getInputVersion(Int_t i) { - if (i>=0 && i<3) { return versions[i]; } - else { return 0; } + Int_t getInputVersion(Int_t i) + { + if (i >= 0 && i < 3) { + return versions[i]; + } else { + return 0; + } } - void setStatic(Bool_t flag=kTRUE) {status=flag;} - Bool_t isStatic() {return status;} + void setStatic(Bool_t flag = kTRUE) { status = flag; } + Bool_t isStatic() { return status; } - void setOwnership(Bool_t flag=kTRUE) {owned=flag;} - Bool_t isOwned() {return owned;} + void setOwnership(Bool_t flag = kTRUE) { owned = flag; } + Bool_t isOwned() { return owned; } - void setChanged(Bool_t flag=kTRUE) {changed=flag;} - Bool_t hasChanged() {return changed;} + void setChanged(Bool_t flag = kTRUE) { changed = flag; } + Bool_t hasChanged() { return changed; } const char* getParamContext() const { return paramContext.Data(); } - void setAuthor(const char* s) {author=s;} + void setAuthor(const char* s) { author = s; } const char* getAuthor() const { return author.Data(); } - void setDescription(const char* s) {description=s;} + void setDescription(const char* s) { description = s; } const char* getDescription() const { return description.Data(); } - void copyComment(FairParSet& r) { - author=r.getAuthor(); - description=r.getDescription(); + void copyComment(FairParSet& r) + { + author = r.getAuthor(); + description = r.getDescription(); } - virtual void fill(UInt_t) {}; - virtual void store(UInt_t) {}; + virtual void fill(UInt_t){}; + virtual void store(UInt_t){}; FairParSet& operator=(const FairParSet&); FairParSet(const FairParSet&); - ClassDef(FairParSet,2) // Base class for all parameter containers + ClassDef(FairParSet, 2) // Base class for all parameter containers }; -#endif /* !FAIRPARSET_H */ +#endif /* !FAIRPARSET_H */ diff --git a/parbase/FairParamList.cxx b/parbase/FairParamList.cxx index 596c3af17c..c4307af4a2 100644 --- a/parbase/FairParamList.cxx +++ b/parbase/FairParamList.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ //*-- AUTHOR : Ilse Koenig @@ -10,19 +10,18 @@ #include "FairParamList.h" -#include "FairLogger.h" // for FairLogger, MESSAGE_ORIGIN +#include "FairLogger.h" // for FairLogger, MESSAGE_ORIGIN -#include // for TArrayD -#include // for TArrayF -#include // for TArrayI -#include // for TBuffer, etc -#include // for TBufferFile -#include // for TClass -#include // for TIter -#include // for TStreamerInfo - -#include // for memcpy, strcmp, strlen -#include // for operator<<, ostream, cout, etc +#include // for TArrayD +#include // for TArrayF +#include // for TArrayI +#include // for TBuffer, etc +#include // for TBufferFile +#include // for TClass +#include // for TIter +#include // for TStreamerInfo +#include // for operator<<, ostream, cout, etc +#include // for memcpy, strcmp, strlen //_HADES_CLASS_DESCRIPTION ///////////////////////////////////////////////////////////////////////////////////////// @@ -90,843 +89,875 @@ // ////////////////////////////////////////////////////////////////////////////////////// -ClassImp(FairParamObj) -ClassImp(FairParamList) +ClassImp(FairParamObj); +ClassImp(FairParamList); FairParamObj::FairParamObj(const Text_t* name) - :TNamed(name,""), - paramValue(nullptr), - arraySize(0), - paramType("UChar_t"), - basicType(kFALSE), - bytesPerValue(1), - classVersion(-1), - streamerInfo(nullptr), - streamerInfoSize(0) -{ -} + : TNamed(name, "") + , paramValue(nullptr) + , arraySize(0) + , paramType("UChar_t") + , basicType(kFALSE) + , bytesPerValue(1) + , classVersion(-1) + , streamerInfo(nullptr) + , streamerInfoSize(0) +{} FairParamObj::FairParamObj(FairParamObj& o) - :TNamed(o), - paramValue(nullptr), - arraySize(o.arraySize), - paramType(o.paramType), - basicType(o.basicType), - bytesPerValue(o.bytesPerValue), - classVersion(o.classVersion), - streamerInfo(nullptr), - streamerInfoSize(o.streamerInfoSize) -{ - paramValue=new UChar_t[arraySize]; - memcpy(paramValue,o.getParamValue(),arraySize); - if (streamerInfoSize>0) { - streamerInfo = new UChar_t[streamerInfoSize]; - memcpy(streamerInfo,o.getStreamerInfo(),streamerInfoSize); - } -} - -FairParamObj::FairParamObj(const Text_t* name,Int_t value) - :TNamed(name,""), - paramValue(nullptr), - arraySize(sizeof(Int_t)), - paramType("Int_t"), - basicType(kTRUE), - bytesPerValue(sizeof(Int_t)), - classVersion(-1), - streamerInfo(nullptr), - streamerInfoSize(0) -{ - // Constructor for a Int_t value - paramValue=new UChar_t[arraySize]; - memcpy(paramValue,&value,arraySize); -} - -FairParamObj::FairParamObj(const Text_t* name,Bool_t value) - :TNamed(name,""), - paramValue(nullptr), - arraySize(sizeof(Bool_t)), - paramType("Bool_t"), - basicType(kTRUE), - bytesPerValue(sizeof(Bool_t)), - classVersion(-1), - streamerInfo(nullptr), - streamerInfoSize(0) -{ - // Constructor for a Int_t value - paramValue=new UChar_t[arraySize]; - memcpy(paramValue,&value,arraySize); -} - -FairParamObj::FairParamObj(const Text_t* name,UInt_t value) - :TNamed(name,""), - paramValue(nullptr), - arraySize(sizeof(UInt_t)), - paramType("UInt_t"), - basicType(kTRUE), - bytesPerValue(sizeof(UInt_t)), - classVersion(-1), - streamerInfo(nullptr), - streamerInfoSize(0) -{ - // Constructor for a Int_t value - paramValue=new UChar_t[arraySize]; - memcpy(paramValue,&value,arraySize); -} - -FairParamObj::FairParamObj(const Text_t* name,Float_t value) - :TNamed(name,""), - paramValue(nullptr), - arraySize(sizeof(Float_t)), - paramType("Float_t"), - basicType(kTRUE), - bytesPerValue(sizeof(Float_t)), - classVersion(-1), - streamerInfo(nullptr), - streamerInfoSize(0) -{ - // Constructor for a Float_t value - paramValue=new UChar_t[arraySize]; - memcpy(paramValue,&value,arraySize); -} - -FairParamObj::FairParamObj(const Text_t* name,Double_t value) - :TNamed(name,""), - paramValue(nullptr), - arraySize(sizeof(Double_t)), - paramType("Double_t"), - basicType(kTRUE), - bytesPerValue(sizeof(Double_t)), - classVersion(-1), - streamerInfo(nullptr), - streamerInfoSize(0) -{ - // Constructor for a Double_t value - paramValue=new UChar_t[arraySize]; - memcpy(paramValue,&value,arraySize); -} - -FairParamObj::FairParamObj(const Text_t* name,const Int_t* value,const Int_t nValues) - :TNamed(name,""), - paramValue(nullptr), - arraySize(sizeof(Int_t)*nValues), - paramType("Int_t"), - basicType(kTRUE), - bytesPerValue(sizeof(Int_t)), - classVersion(-1), - streamerInfo(nullptr), - streamerInfoSize(0) -{ - // Constructor for an array with nValues elements of type Int_t - paramValue=new UChar_t[arraySize]; - memcpy(paramValue,value,arraySize); -} - -FairParamObj::FairParamObj(const Text_t* name,const UInt_t* value,const Int_t nValues) -:TNamed(name,""), -paramValue(nullptr), -arraySize(sizeof(UInt_t)*nValues), -paramType("UInt_t"), -basicType(kTRUE), -bytesPerValue(sizeof(UInt_t)), -classVersion(-1), -streamerInfo(nullptr), -streamerInfoSize(0) -{ - // Constructor for an array with nValues elements of type UInt_t - paramValue=new UChar_t[arraySize]; - memcpy(paramValue,value,arraySize); -} - - -FairParamObj::FairParamObj(const Text_t* name,const Float_t* value,const Int_t nValues) - :TNamed(name,""), - paramValue(nullptr), - arraySize(sizeof(Float_t)*nValues), - paramType("Float_t"), - basicType(kTRUE), - bytesPerValue(sizeof(Float_t)), - classVersion(-1), - streamerInfo(nullptr), - streamerInfoSize(0) -{ - // Constructor for an array with nValues elements of type Float_t - paramValue=new UChar_t[arraySize]; - memcpy(paramValue,value,arraySize); -} - -FairParamObj::FairParamObj(const Text_t* name,const Double_t* value,const Int_t nValues) - :TNamed(name,""), - paramValue(nullptr), - arraySize(sizeof(Double_t)*nValues), - paramType("Double_t"), - basicType(kTRUE), - bytesPerValue(sizeof(Double_t)), - classVersion(-1), - streamerInfo(nullptr), - streamerInfoSize(0) -{ - // Constructor for an array with nValues elements of type Double_t - paramValue=new UChar_t[arraySize]; - memcpy(paramValue,value,arraySize); -} - -FairParamObj::FairParamObj(const Text_t* name,const Text_t* value) - :TNamed(name,""), - paramValue(nullptr), - arraySize(strlen(value)), - paramType("Text_t"), - basicType(kTRUE), - bytesPerValue(sizeof(Char_t)), - classVersion(-1), - streamerInfo(nullptr), - streamerInfoSize(0) -{ - // Constructor for a string value - paramValue=new UChar_t[arraySize+1]; - memcpy(paramValue,value,arraySize); -} - - -FairParamObj::FairParamObj(const Text_t* name,const Char_t* value,const Int_t nValues) - :TNamed(name,""), - paramValue(nullptr), - arraySize(sizeof(Char_t)*nValues), - paramType("Char_t"), - basicType(kTRUE), - bytesPerValue(sizeof(Char_t)), - classVersion(-1), - streamerInfo(nullptr), - streamerInfoSize(0) -{ - // Constructor for an array with nValues elements of type Char_t - paramValue=new UChar_t[arraySize]; - memcpy(paramValue,value,arraySize); -} - -FairParamObj::FairParamObj(const Text_t* name,const UChar_t* value,const Int_t nValues) - :TNamed(name,""), - paramValue(nullptr), - arraySize(sizeof(UChar_t)*nValues), - paramType("UChar_t"), - basicType(kTRUE), - bytesPerValue(sizeof(UChar_t)), - classVersion(-1), - streamerInfo(nullptr), - streamerInfoSize(0) -{ - paramValue=new UChar_t[arraySize]; - memcpy(paramValue,value,arraySize); + : TNamed(o) + , paramValue(nullptr) + , arraySize(o.arraySize) + , paramType(o.paramType) + , basicType(o.basicType) + , bytesPerValue(o.bytesPerValue) + , classVersion(o.classVersion) + , streamerInfo(nullptr) + , streamerInfoSize(o.streamerInfoSize) +{ + paramValue = new UChar_t[arraySize]; + memcpy(paramValue, o.getParamValue(), arraySize); + if (streamerInfoSize > 0) { + streamerInfo = new UChar_t[streamerInfoSize]; + memcpy(streamerInfo, o.getStreamerInfo(), streamerInfoSize); + } +} + +FairParamObj::FairParamObj(const Text_t* name, Int_t value) + : TNamed(name, "") + , paramValue(nullptr) + , arraySize(sizeof(Int_t)) + , paramType("Int_t") + , basicType(kTRUE) + , bytesPerValue(sizeof(Int_t)) + , classVersion(-1) + , streamerInfo(nullptr) + , streamerInfoSize(0) +{ + // Constructor for a Int_t value + paramValue = new UChar_t[arraySize]; + memcpy(paramValue, &value, arraySize); +} + +FairParamObj::FairParamObj(const Text_t* name, Bool_t value) + : TNamed(name, "") + , paramValue(nullptr) + , arraySize(sizeof(Bool_t)) + , paramType("Bool_t") + , basicType(kTRUE) + , bytesPerValue(sizeof(Bool_t)) + , classVersion(-1) + , streamerInfo(nullptr) + , streamerInfoSize(0) +{ + // Constructor for a Int_t value + paramValue = new UChar_t[arraySize]; + memcpy(paramValue, &value, arraySize); +} + +FairParamObj::FairParamObj(const Text_t* name, UInt_t value) + : TNamed(name, "") + , paramValue(nullptr) + , arraySize(sizeof(UInt_t)) + , paramType("UInt_t") + , basicType(kTRUE) + , bytesPerValue(sizeof(UInt_t)) + , classVersion(-1) + , streamerInfo(nullptr) + , streamerInfoSize(0) +{ + // Constructor for a Int_t value + paramValue = new UChar_t[arraySize]; + memcpy(paramValue, &value, arraySize); +} + +FairParamObj::FairParamObj(const Text_t* name, Float_t value) + : TNamed(name, "") + , paramValue(nullptr) + , arraySize(sizeof(Float_t)) + , paramType("Float_t") + , basicType(kTRUE) + , bytesPerValue(sizeof(Float_t)) + , classVersion(-1) + , streamerInfo(nullptr) + , streamerInfoSize(0) +{ + // Constructor for a Float_t value + paramValue = new UChar_t[arraySize]; + memcpy(paramValue, &value, arraySize); +} + +FairParamObj::FairParamObj(const Text_t* name, Double_t value) + : TNamed(name, "") + , paramValue(nullptr) + , arraySize(sizeof(Double_t)) + , paramType("Double_t") + , basicType(kTRUE) + , bytesPerValue(sizeof(Double_t)) + , classVersion(-1) + , streamerInfo(nullptr) + , streamerInfoSize(0) +{ + // Constructor for a Double_t value + paramValue = new UChar_t[arraySize]; + memcpy(paramValue, &value, arraySize); +} + +FairParamObj::FairParamObj(const Text_t* name, const Int_t* value, const Int_t nValues) + : TNamed(name, "") + , paramValue(nullptr) + , arraySize(sizeof(Int_t) * nValues) + , paramType("Int_t") + , basicType(kTRUE) + , bytesPerValue(sizeof(Int_t)) + , classVersion(-1) + , streamerInfo(nullptr) + , streamerInfoSize(0) +{ + // Constructor for an array with nValues elements of type Int_t + paramValue = new UChar_t[arraySize]; + memcpy(paramValue, value, arraySize); +} + +FairParamObj::FairParamObj(const Text_t* name, const UInt_t* value, const Int_t nValues) + : TNamed(name, "") + , paramValue(nullptr) + , arraySize(sizeof(UInt_t) * nValues) + , paramType("UInt_t") + , basicType(kTRUE) + , bytesPerValue(sizeof(UInt_t)) + , classVersion(-1) + , streamerInfo(nullptr) + , streamerInfoSize(0) +{ + // Constructor for an array with nValues elements of type UInt_t + paramValue = new UChar_t[arraySize]; + memcpy(paramValue, value, arraySize); +} + +FairParamObj::FairParamObj(const Text_t* name, const Float_t* value, const Int_t nValues) + : TNamed(name, "") + , paramValue(nullptr) + , arraySize(sizeof(Float_t) * nValues) + , paramType("Float_t") + , basicType(kTRUE) + , bytesPerValue(sizeof(Float_t)) + , classVersion(-1) + , streamerInfo(nullptr) + , streamerInfoSize(0) +{ + // Constructor for an array with nValues elements of type Float_t + paramValue = new UChar_t[arraySize]; + memcpy(paramValue, value, arraySize); +} + +FairParamObj::FairParamObj(const Text_t* name, const Double_t* value, const Int_t nValues) + : TNamed(name, "") + , paramValue(nullptr) + , arraySize(sizeof(Double_t) * nValues) + , paramType("Double_t") + , basicType(kTRUE) + , bytesPerValue(sizeof(Double_t)) + , classVersion(-1) + , streamerInfo(nullptr) + , streamerInfoSize(0) +{ + // Constructor for an array with nValues elements of type Double_t + paramValue = new UChar_t[arraySize]; + memcpy(paramValue, value, arraySize); +} + +FairParamObj::FairParamObj(const Text_t* name, const Text_t* value) + : TNamed(name, "") + , paramValue(nullptr) + , arraySize(strlen(value)) + , paramType("Text_t") + , basicType(kTRUE) + , bytesPerValue(sizeof(Char_t)) + , classVersion(-1) + , streamerInfo(nullptr) + , streamerInfoSize(0) +{ + // Constructor for a string value + paramValue = new UChar_t[arraySize + 1]; + memcpy(paramValue, value, arraySize); +} + +FairParamObj::FairParamObj(const Text_t* name, const Char_t* value, const Int_t nValues) + : TNamed(name, "") + , paramValue(nullptr) + , arraySize(sizeof(Char_t) * nValues) + , paramType("Char_t") + , basicType(kTRUE) + , bytesPerValue(sizeof(Char_t)) + , classVersion(-1) + , streamerInfo(nullptr) + , streamerInfoSize(0) +{ + // Constructor for an array with nValues elements of type Char_t + paramValue = new UChar_t[arraySize]; + memcpy(paramValue, value, arraySize); +} + +FairParamObj::FairParamObj(const Text_t* name, const UChar_t* value, const Int_t nValues) + : TNamed(name, "") + , paramValue(nullptr) + , arraySize(sizeof(UChar_t) * nValues) + , paramType("UChar_t") + , basicType(kTRUE) + , bytesPerValue(sizeof(UChar_t)) + , classVersion(-1) + , streamerInfo(nullptr) + , streamerInfoSize(0) +{ + paramValue = new UChar_t[arraySize]; + memcpy(paramValue, value, arraySize); } FairParamObj::~FairParamObj() { - // Destructor - delete [] paramValue; - paramValue=0; - delete [] streamerInfo; - streamerInfo=0; + // Destructor + delete[] paramValue; + paramValue = 0; + delete[] streamerInfo; + streamerInfo = 0; } void FairParamObj::setParamType(const Text_t* t) { - // Sets the parameter type. Accepted type names are: - // UChar_t (default) - // Char_t - // Int_t - // Float_t - // Double_t - // Text_t - // class name - paramType=t; - if (strcmp(t,"Char_t")==0) { - basicType=kTRUE; - bytesPerValue=sizeof(Char_t); - } else if (strcmp(t,"Int_t")==0) { - basicType=kTRUE; - bytesPerValue=sizeof(Int_t); - } else if (strcmp(t,"Float_t")==0) { - basicType=kTRUE; - bytesPerValue=sizeof(Float_t); - } else if (strcmp(t,"Double_t")==0) { - basicType=kTRUE; - bytesPerValue=sizeof(Double_t); - } else if (strcmp(t,"Text_t")==0) { - basicType=kTRUE; - bytesPerValue=sizeof(Char_t); - } else { - basicType=kFALSE; - bytesPerValue=1; - } - if (basicType==kTRUE) { - classVersion=-1; - streamerInfoSize=0; - streamerInfo=0; - } + // Sets the parameter type. Accepted type names are: + // UChar_t (default) + // Char_t + // Int_t + // Float_t + // Double_t + // Text_t + // class name + paramType = t; + if (strcmp(t, "Char_t") == 0) { + basicType = kTRUE; + bytesPerValue = sizeof(Char_t); + } else if (strcmp(t, "Int_t") == 0) { + basicType = kTRUE; + bytesPerValue = sizeof(Int_t); + } else if (strcmp(t, "Float_t") == 0) { + basicType = kTRUE; + bytesPerValue = sizeof(Float_t); + } else if (strcmp(t, "Double_t") == 0) { + basicType = kTRUE; + bytesPerValue = sizeof(Double_t); + } else if (strcmp(t, "Text_t") == 0) { + basicType = kTRUE; + bytesPerValue = sizeof(Char_t); + } else { + basicType = kFALSE; + bytesPerValue = 1; + } + if (basicType == kTRUE) { + classVersion = -1; + streamerInfoSize = 0; + streamerInfo = 0; + } } UChar_t* FairParamObj::setLength(Int_t l) { - // Sets the length of the binary array - delete [] paramValue; - arraySize=l; - if (l>0) { - paramValue=new UChar_t[arraySize]; - } else { - paramValue=0; - } - return paramValue; + // Sets the length of the binary array + delete[] paramValue; + arraySize = l; + if (l > 0) { + paramValue = new UChar_t[arraySize]; + } else { + paramValue = 0; + } + return paramValue; } -void FairParamObj::setParamValue(UChar_t* value,const Int_t length) +void FairParamObj::setParamValue(UChar_t* value, const Int_t length) { - // Sets the parameter value (the array is not copied!) - delete [] paramValue; - arraySize=length; - paramValue=value; + // Sets the parameter value (the array is not copied!) + delete[] paramValue; + arraySize = length; + paramValue = value; } UChar_t* FairParamObj::setStreamerInfoSize(Int_t l) { - // Sets the length of the streamer info - delete [] streamerInfo; - streamerInfoSize=l; - if (l>0) { - streamerInfo=new UChar_t[streamerInfoSize]; - } else { - streamerInfo=0; - } - return streamerInfo; + // Sets the length of the streamer info + delete[] streamerInfo; + streamerInfoSize = l; + if (l > 0) { + streamerInfo = new UChar_t[streamerInfoSize]; + } else { + streamerInfo = 0; + } + return streamerInfo; } -void FairParamObj::setStreamerInfo(UChar_t* array,const Int_t length) +void FairParamObj::setStreamerInfo(UChar_t* array, const Int_t length) { - // Sets the streamer info of ROOT classes (the array is not copied!) - delete [] streamerInfo; - streamerInfoSize=length; - streamerInfo=array; + // Sets the streamer info of ROOT classes (the array is not copied!) + delete[] streamerInfo; + streamerInfoSize = length; + streamerInfo = array; } Int_t FairParamObj::getNumParams() { - // Returns the number of values in the array, respectively 1 for classes and strings - Int_t n=1; - if (basicType) { - n=arraySize/bytesPerValue; - } - return n; + // Returns the number of values in the array, respectively 1 for classes and strings + Int_t n = 1; + if (basicType) { + n = arraySize / bytesPerValue; + } + return n; } void FairParamObj::print() { - // Prints the name and type of the parameters, respectively class name and version. - // Prints also the numbers for an array of type Int_t, Float_t, Double_t. - std::cout<=0) { - std::cout<<"\n Class Type: "<(paramValue),arraySize); - val.ReplaceAll("\n","\n "); - std::cout<(paramValue); - printData(val,nParams); - } else if (strcmp(paramType,"Int_t")==0) { - Int_t* val=reinterpret_cast(paramValue); - printData(val,nParams); - } else if (strcmp(paramType,"Float_t")==0) { - Float_t* val=reinterpret_cast(paramValue); - printData(val,nParams); - } else if (strcmp(paramType,"Double_t")==0) { - Double_t* val=reinterpret_cast(paramValue); - printData(val,nParams); + // Prints the name and type of the parameters, respectively class name and version. + // Prints also the numbers for an array of type Int_t, Float_t, Double_t. + std::cout << GetName() << ": "; + if (classVersion >= 0) { + std::cout << "\n Class Type: " << paramType.Data() << "\n Class Version: " << classVersion << std::endl; + } else if (strcmp(paramType, "Text_t") == 0) { + TString val(reinterpret_cast(paramValue), arraySize); + val.ReplaceAll("\n", "\n "); + std::cout << paramType << "\n " << val.Data() << std::endl; } else { - std::cout<<"Type: "<(paramValue); + printData(val, nParams); + } else if (strcmp(paramType, "Int_t") == 0) { + Int_t* val = reinterpret_cast(paramValue); + printData(val, nParams); + } else if (strcmp(paramType, "Float_t") == 0) { + Float_t* val = reinterpret_cast(paramValue); + printData(val, nParams); + } else if (strcmp(paramType, "Double_t") == 0) { + Double_t* val = reinterpret_cast(paramValue); + printData(val, nParams); + } else { + std::cout << "Type: " << paramType << " Array length: " << arraySize << std::endl; + } } - } } -template void FairParamObj::printData(type* val, Int_t nParams) +template +void FairParamObj::printData(type* val, Int_t nParams) { - Int_t i=0, k=0; - while (k50) { - std::cout<<"..."; - break; + Int_t i = 0, k = 0; + while (k < nParams) { + if (i == 10) { + std::cout << "\n "; + i = 0; + } + std::cout << val[k] << " "; + i++; + k++; + if (k > 50) { + std::cout << "..."; + break; + } } - } - std::cout<setParamType(obj->IsA()->GetName()); + o->setClassVersion(obj->IsA()->GetClassVersion()); + TFile* filesave = gFile; + FairParamTFile* paramFile = new FairParamTFile(); + gFile = paramFile; + const Int_t bufsize = 10000; + + TBufferFile* buffer = new TBufferFile(TBuffer::kWrite, bufsize); + + buffer->SetParent(paramFile); + buffer->MapObject(obj); + obj->Streamer(*buffer); + Int_t len = buffer->Length(); + Char_t* buf = new char[len]; + memcpy(buf, buffer->Buffer(), len); + o->setParamValue(reinterpret_cast(buf), len); + TArrayC* fClassIndex = paramFile->GetClassIndex(); + if (fClassIndex && fClassIndex->fArray[0] != 0) { + TIter next(gROOT->GetListOfStreamerInfo()); + TStreamerInfo* info; + TList list; + while ((info = static_cast(next()))) { + Int_t uid = info->GetNumber(); + if (fClassIndex->fArray[uid]) { + list.Add(info); + } + } + if (list.GetSize() > 0) { + list.Sort(); + fClassIndex->fArray[0] = 2; // to prevent adding classes in TStreamerInfo::TagFile + + TBufferFile* infoBuffer = new TBufferFile(TBuffer::kWrite, bufsize); + + infoBuffer->MapObject(&list); + list.Streamer(*infoBuffer); + Int_t infolen = infoBuffer->Length(); + Char_t* infobuf = new char[infolen]; + memcpy(infobuf, infoBuffer->Buffer(), infolen); + o->setStreamerInfo(reinterpret_cast(infobuf), infolen); + delete infoBuffer; + } else { + o->setStreamerInfo(0, 0); + } + } + fClassIndex->fArray[0] = 0; + delete paramFile; + paramList.Add(o); + delete buffer; + gFile = filesave; } -void FairParamList::addObject(const Text_t* name,TObject* obj) +void FairParamList::print() { - // Adds a TObject to the list, sets the class version and the streamer info for - // ROOT classes - if (!obj) { return; } - FairParamObj* o=new FairParamObj(name); - o->setParamType(obj->IsA()->GetName()); - o->setClassVersion(obj->IsA()->GetClassVersion()); - TFile* filesave=gFile; - FairParamTFile* paramFile=new FairParamTFile(); - gFile=paramFile; - const Int_t bufsize=10000; + // Prints the parameter list including values + TIter next(¶mList); + FairParamObj* o; + while ((o = static_cast(next())) != 0) { + o->print(); + } +} - TBufferFile* buffer=new TBufferFile(TBuffer::kWrite,bufsize); +Bool_t FairParamList::fill(const Text_t* name, Text_t* value, const Int_t length) +{ + // Copies the data from the list object into the parameter value of type string + FairParamObj* o = static_cast(paramList.FindObject(name)); + if (value == 0) { + return kFALSE; + } + if (o != 0 && strcmp(o->getParamType(), "Text_t") == 0) { + Int_t l = o->getLength(); + if (l < length - 1) { + memcpy(value, reinterpret_cast(o->getParamValue()), l); + value[l] = '\0'; + return kTRUE; + } else { + LOG(error) << "char array too small"; + // Error("FairParamList::fill(const Text_t*,Text_t*)","char array too small"); + } + } + LOG(error) << "Could not find parameter " << name; + // Error("FairParamList::fill \nNot found: %s",name); + return kFALSE; +} - buffer->SetParent(paramFile); - buffer->MapObject(obj); - obj->Streamer(*buffer); - Int_t len=buffer->Length(); - Char_t* buf=new char[len]; - memcpy(buf,buffer->Buffer(),len); - o->setParamValue(reinterpret_cast(buf),len); - TArrayC* fClassIndex=paramFile->GetClassIndex(); - if (fClassIndex&&fClassIndex->fArray[0] != 0) { - TIter next(gROOT->GetListOfStreamerInfo()); - TStreamerInfo* info; - TList list; - while ((info=static_cast(next()))) { - Int_t uid=info->GetNumber(); - if (fClassIndex->fArray[uid]) { list.Add(info); } +Bool_t FairParamList::fill(const Text_t* name, UChar_t* values, const Int_t nValues) +{ + // Copies the data from the list object into the parameter array of type UChar_t of size nValues. + // The function returns an error, if the array size of the list object is not equal + // to nValues. + if (values == 0) { + return kFALSE; } - if (list.GetSize()>0) { - list.Sort(); - fClassIndex->fArray[0]=2; //to prevent adding classes in TStreamerInfo::TagFile + FairParamObj* o = static_cast(paramList.FindObject(name)); + if (o != 0 && strcmp(o->getParamType(), "UChar_t") == 0) { + Int_t n = o->getLength(); + if (n == nValues) { + memcpy(values, o->getParamValue(), n); + return kTRUE; + } else { + LOG(error) << "Different array sizes for parameter " << name; + // Error("FairParamList::fill \nDifferent array sizes for parameter %s",name); + return kFALSE; + } + } + LOG(error) << "Could not find parameter " << name; + // Error("FairParamList::fill \nNot found: %s",name); + return kFALSE; +} - TBufferFile* infoBuffer=new TBufferFile(TBuffer::kWrite,bufsize); +Bool_t FairParamList::fill(const Text_t* name, Int_t* values, const Int_t nValues) +{ + // Copies the data from the list object into the parameter array of type Int_t. + // The function returns an error, if the array size of the list object is not equal + // to nValues. + if (values == 0) { + return kFALSE; + } + FairParamObj* o = static_cast(paramList.FindObject(name)); + if (o != 0 && strcmp(o->getParamType(), "Int_t") == 0) { + Int_t l = o->getLength(); + Int_t n = o->getNumParams(); + if (n == nValues) { + memcpy(values, o->getParamValue(), l); + return kTRUE; + } else { + LOG(error) << "Different array sizes for parameter " << name; + // Error("FairParamList::fill \nDifferent array sizes for parameter %s",name); + return kFALSE; + } + } + LOG(error) << "Could not find parameter " << name; + // Error("FairParamList::fill \nNot found: %s",name); + return kFALSE; +} - infoBuffer->MapObject(&list); - list.Streamer(*infoBuffer); - Int_t infolen=infoBuffer->Length(); - Char_t* infobuf=new char[infolen]; - memcpy(infobuf,infoBuffer->Buffer(),infolen); - o->setStreamerInfo(reinterpret_cast(infobuf),infolen); - delete infoBuffer; - } else { - o->setStreamerInfo(0,0); +Bool_t FairParamList::fill(const Text_t* name, Bool_t* values, const Int_t nValues) +{ + // Copies the data from the list object into the parameter array of type Int_t. + // The function returns an error, if the array size of the list object is not equal + // to nValues. + if (values == 0) { + return kFALSE; + } + FairParamObj* o = static_cast(paramList.FindObject(name)); + if (o != 0 && strcmp(o->getParamType(), "Bool_t") == 0) { + Int_t l = o->getLength(); + Int_t n = o->getNumParams(); + if (n == nValues) { + memcpy(values, o->getParamValue(), l); + return kTRUE; + } else { + LOG(error) << "Different array sizes for parameter " << name; + // Error("FairParamList::fill \nDifferent array sizes for parameter %s",name); + return kFALSE; + } } - } - fClassIndex->fArray[0]=0; - delete paramFile; - paramList.Add(o); - delete buffer; - gFile=filesave; + LOG(error) << "Could not find parameter " << name; + // Error("FairParamList::fill \nNot found: %s",name); + return kFALSE; } -void FairParamList::print() +Bool_t FairParamList::fill(const Text_t* name, UInt_t* values, const Int_t nValues) { - // Prints the parameter list including values - TIter next(¶mList); - FairParamObj* o; - while ((o=static_cast(next()))!=0) { o->print(); } + // Copies the data from the list object into the parameter array of type UInt_t. + // The function returns an error, if the array size of the list object is not equal + // to nValues. + if (values == 0) { + return kFALSE; + } + FairParamObj* o = static_cast(paramList.FindObject(name)); + if (o != 0 && strcmp(o->getParamType(), "Int_t") == 0) { + Int_t l = o->getLength(); + Int_t n = o->getNumParams(); + if (n == nValues) { + memcpy(values, o->getParamValue(), l); + return kTRUE; + } else { + LOG(error) << "Different array sizes for parameter " << name; + // Error("FairParamList::fill \nDifferent array sizes for parameter %s",name); + return kFALSE; + } + } + LOG(error) << "Could not find parameter " << name; + // Error("FairParamList::fill \nNot found: %s",name); + return kFALSE; } -Bool_t FairParamList::fill(const Text_t* name,Text_t* value,const Int_t length) +Bool_t FairParamList::fill(const Text_t* name, Float_t* values, const Int_t nValues) { - // Copies the data from the list object into the parameter value of type string - FairParamObj* o=static_cast(paramList.FindObject(name)); - if (value==0) { return kFALSE; } - if (o!=0 && strcmp(o->getParamType(),"Text_t")==0) { - Int_t l=o->getLength(); - if (l(o->getParamValue()),l); - value[l]='\0'; - return kTRUE; - } else { - LOG(error) << "char array too small"; - // Error("FairParamList::fill(const Text_t*,Text_t*)","char array too small"); - } - } - LOG(error) << "Could not find parameter " << name; - // Error("FairParamList::fill \nNot found: %s",name); - return kFALSE; -} - -Bool_t FairParamList::fill(const Text_t* name,UChar_t* values,const Int_t nValues) -{ - // Copies the data from the list object into the parameter array of type UChar_t of size nValues. - // The function returns an error, if the array size of the list object is not equal - // to nValues. - if (values==0) { return kFALSE; } - FairParamObj* o=static_cast(paramList.FindObject(name)); - if (o!=0 && strcmp(o->getParamType(),"UChar_t")==0) { - Int_t n=o->getLength(); - if (n==nValues) { - memcpy(values,o->getParamValue(),n); - return kTRUE; - } else { - LOG(error) << "Different array sizes for parameter " << name; - // Error("FairParamList::fill \nDifferent array sizes for parameter %s",name); - return kFALSE; - } - } - LOG(error) << "Could not find parameter " << name; - // Error("FairParamList::fill \nNot found: %s",name); - return kFALSE; -} - -Bool_t FairParamList::fill(const Text_t* name,Int_t* values,const Int_t nValues) -{ - // Copies the data from the list object into the parameter array of type Int_t. - // The function returns an error, if the array size of the list object is not equal - // to nValues. - if (values==0) { return kFALSE; } - FairParamObj* o=static_cast(paramList.FindObject(name)); - if (o!=0 && strcmp(o->getParamType(),"Int_t")==0) { - Int_t l=o->getLength(); - Int_t n=o->getNumParams(); - if (n==nValues) { - memcpy(values,o->getParamValue(),l); - return kTRUE; - } else { - LOG(error) << "Different array sizes for parameter " << name; - // Error("FairParamList::fill \nDifferent array sizes for parameter %s",name); - return kFALSE; - } - } - LOG(error) << "Could not find parameter " << name; - // Error("FairParamList::fill \nNot found: %s",name); - return kFALSE; -} - -Bool_t FairParamList::fill(const Text_t* name,Bool_t* values,const Int_t nValues) -{ - // Copies the data from the list object into the parameter array of type Int_t. - // The function returns an error, if the array size of the list object is not equal - // to nValues. - if (values==0) { return kFALSE; } - FairParamObj* o=static_cast(paramList.FindObject(name)); - if (o!=0 && strcmp(o->getParamType(),"Bool_t")==0) { - Int_t l=o->getLength(); - Int_t n=o->getNumParams(); - if (n==nValues) { - memcpy(values,o->getParamValue(),l); - return kTRUE; - } else { - LOG(error) << "Different array sizes for parameter " << name; - // Error("FairParamList::fill \nDifferent array sizes for parameter %s",name); - return kFALSE; - } - } - LOG(error) << "Could not find parameter " << name; - // Error("FairParamList::fill \nNot found: %s",name); - return kFALSE; -} - - -Bool_t FairParamList::fill(const Text_t* name,UInt_t* values,const Int_t nValues) -{ - // Copies the data from the list object into the parameter array of type UInt_t. - // The function returns an error, if the array size of the list object is not equal - // to nValues. - if (values==0) { return kFALSE; } - FairParamObj* o=static_cast(paramList.FindObject(name)); - if (o!=0 && strcmp(o->getParamType(),"Int_t")==0) { - Int_t l=o->getLength(); - Int_t n=o->getNumParams(); - if (n==nValues) { - memcpy(values,o->getParamValue(),l); - return kTRUE; - } else { - LOG(error) << "Different array sizes for parameter " << name; - // Error("FairParamList::fill \nDifferent array sizes for parameter %s",name); - return kFALSE; - } - } - LOG(error) << "Could not find parameter " << name; - // Error("FairParamList::fill \nNot found: %s",name); - return kFALSE; -} - - -Bool_t FairParamList::fill(const Text_t* name,Float_t* values,const Int_t nValues) -{ - // Copies the data from the list object into the parameter array of type Float_t. - // The function returns an error, if the array size of the list object is not equal - // to nValues. - if (values==0) { return kFALSE; } - FairParamObj* o=static_cast(paramList.FindObject(name)); - if (o!=0 && strcmp(o->getParamType(),"Float_t")==0) { - Int_t l=o->getLength(); - Int_t n=o->getNumParams(); - if (n==nValues) { - memcpy(values,o->getParamValue(),l); - return kTRUE; - } else { - LOG(error) << "Different array sizes for parameter " << name; - // Error("FairParamList::fill \nDifferent array sizes for parameter %s",name); - return kFALSE; - } - } - LOG(error) << "Could not find parameter " << name; - // Error("FairParamList::fill \nNot found: %s",name); - return kFALSE; -} - -Bool_t FairParamList::fill(const Text_t* name,Double_t* values,const Int_t nValues) -{ - // Copies the data from the list object into the parameter array of type Double_t. - // The function returns an error, if the array size of the list object is not equal - // to nValues. - if (values==0) { return kFALSE; } - FairParamObj* o=static_cast(paramList.FindObject(name)); - if (o!=0 && strcmp(o->getParamType(),"Double_t")==0) { - Int_t l=o->getLength(); - Int_t n=o->getNumParams(); - if (n==nValues) { - memcpy(values,o->getParamValue(),l); - return kTRUE; - } else { - LOG(error) << "Different array sizes for parameter " << name; - // Error("FairParamList::fill \nDifferent array sizes for parameter %s",name); - return kFALSE; - } - } - LOG(error) << "Could not find parameter " << name; - // Error("FairParamList::fill \nNot found: %s",name); - return kFALSE; -} - -Bool_t FairParamList::fill(const Text_t* name,TArrayI* value) -{ - // Copies the data from the list object into the parameter value of type TArrayI - // The array is resized, if the number of data is different. - if (value==0) { return kFALSE; } - FairParamObj* o=static_cast(paramList.FindObject(name)); - if (o!=0 && strcmp(o->getParamType(),"Int_t")==0) { - Int_t l=o->getLength(); - Int_t n=o->getNumParams(); - if (value->GetSize()!=n) { value->Set(n); } - memcpy(value->GetArray(),o->getParamValue(),l); - return kTRUE; - } - LOG(error) << "Could not find parameter " << name; - // Error("FairParamList::fill \nNot found: %s",name); - return kFALSE; -} - -Bool_t FairParamList::fill(const Text_t* name,TArrayC* value) -{ - // Copies the data from the list object into the parameter value of type TArrayC - // The array is resized, if the number of data is different. - if (value==0) { return kFALSE; } - FairParamObj* o=static_cast(paramList.FindObject(name)); - if (o!=0 && strcmp(o->getParamType(),"Char_t")==0) { - Int_t l=o->getLength(); - if (value->GetSize()!=l) { value->Set(l); } - memcpy(value->GetArray(),o->getParamValue(),l); - return kTRUE; - } - LOG(error) << "Could not find parameter " << name; - // Error("FairParamList::fill \nNot found: %s",name); - return kFALSE; -} - -Bool_t FairParamList::fill(const Text_t* name,TArrayF* value) -{ - // Copies the data from the list object into the parameter value of type TArrayF - // The array is resized, if the number of data is different. - if (value==0) { return kFALSE; } - FairParamObj* o=static_cast(paramList.FindObject(name)); - if (o!=0 && strcmp(o->getParamType(),"Float_t")==0) { - Int_t l=o->getLength(); - Int_t n=o->getNumParams(); - if (value->GetSize()!=n) { value->Set(n); } - memcpy(value->GetArray(),o->getParamValue(),l); - return kTRUE; - } - LOG(error) << "Could not find parameter " << name; - // Error("FairParamList::fill \nNot found: %s",name); - return kFALSE; -} - -Bool_t FairParamList::fill(const Text_t* name,TArrayD* value) -{ - // Copies the data from the list object into the parameter value of type TArrayD - // The array is resized, if the number of data is different. - if (value==0) { return kFALSE; } - FairParamObj* o=static_cast(paramList.FindObject(name)); - if (o!=0 && strcmp(o->getParamType(),"Double_t")==0) { - Int_t l=o->getLength(); - Int_t n=o->getNumParams(); - if (value->GetSize()!=n) { value->Set(n); } - memcpy(value->GetArray(),o->getParamValue(),l); - return kTRUE; - } - LOG(error) << "Could not find parameter " << name; - // Error("FairParamList::fill \nNot found: %s",name); - return kFALSE; -} - -Bool_t FairParamList::fillObject(const Text_t* name,TObject* obj) -{ - // Fills the object obj (must exist!) via the Streamer and returns the class version. - // Prints a warning if the class version in the list objects differs from the actual - // class version. - if (!obj) { return 0; } - FairParamObj* o=static_cast(paramList.FindObject(name)); - if (o!=0 && strcmp(o->getParamType(),obj->IsA()->GetName())==0) { - if (o->getClassVersion()!=obj->IsA()->GetClassVersion()) { - LOG(warn) << "Read Class Version = " << o->getClassVersion() << " does not match actual version = " << obj->IsA()->GetClassVersion(); - } - // Warning("FairParamList::fill", - // "\n Read Class Version = %i does not match actual version = %i", - // o->getClassVersion(),obj->IsA()->GetClassVersion()); - TFile* filesave=gFile; - gFile=0; - TBufferFile* buf=0; - - Int_t len=o->getStreamerInfoSize(); - if (len>0&&o->getStreamerInfo()!=0) { - buf=new TBufferFile(TBuffer::kRead,len); - memcpy(buf->Buffer(),reinterpret_cast(o->getStreamerInfo()),len); - buf->SetBufferOffset(0); - TList list; - buf->MapObject(&list); - list.Streamer(*buf); - delete buf; - TStreamerInfo* info; - TIter next(&list); - while ((info = static_cast(next()))) { - if (info->IsA() != TStreamerInfo::Class()) { - LOG(warn) << "Not a TStreamerInfo object"; - // Warning("FairParamList::fill","not a TStreamerInfo object"); - continue; + // Copies the data from the list object into the parameter array of type Float_t. + // The function returns an error, if the array size of the list object is not equal + // to nValues. + if (values == 0) { + return kFALSE; + } + FairParamObj* o = static_cast(paramList.FindObject(name)); + if (o != 0 && strcmp(o->getParamType(), "Float_t") == 0) { + Int_t l = o->getLength(); + Int_t n = o->getNumParams(); + if (n == nValues) { + memcpy(values, o->getParamValue(), l); + return kTRUE; + } else { + LOG(error) << "Different array sizes for parameter " << name; + // Error("FairParamList::fill \nDifferent array sizes for parameter %s",name); + return kFALSE; } - info->BuildCheck(); - } - list.Clear(); //this will delete all TStreamerInfo objects with kCanDelete - } - len=o->getLength(); - buf=new TBufferFile(TBuffer::kRead,len); - memcpy(buf->Buffer(),reinterpret_cast(o->getParamValue()),len); - buf->SetBufferOffset(0); - buf->MapObject(obj); - obj->Streamer(*buf); - delete buf; - gFile=filesave; - return len; - } - LOG(error) << "Could not find parameter " << name; - // Error("FairParamList::fill \nNot found: %s",name); - return 0; + } + LOG(error) << "Could not find parameter " << name; + // Error("FairParamList::fill \nNot found: %s",name); + return kFALSE; +} + +Bool_t FairParamList::fill(const Text_t* name, Double_t* values, const Int_t nValues) +{ + // Copies the data from the list object into the parameter array of type Double_t. + // The function returns an error, if the array size of the list object is not equal + // to nValues. + if (values == 0) { + return kFALSE; + } + FairParamObj* o = static_cast(paramList.FindObject(name)); + if (o != 0 && strcmp(o->getParamType(), "Double_t") == 0) { + Int_t l = o->getLength(); + Int_t n = o->getNumParams(); + if (n == nValues) { + memcpy(values, o->getParamValue(), l); + return kTRUE; + } else { + LOG(error) << "Different array sizes for parameter " << name; + // Error("FairParamList::fill \nDifferent array sizes for parameter %s",name); + return kFALSE; + } + } + LOG(error) << "Could not find parameter " << name; + // Error("FairParamList::fill \nNot found: %s",name); + return kFALSE; +} + +Bool_t FairParamList::fill(const Text_t* name, TArrayI* value) +{ + // Copies the data from the list object into the parameter value of type TArrayI + // The array is resized, if the number of data is different. + if (value == 0) { + return kFALSE; + } + FairParamObj* o = static_cast(paramList.FindObject(name)); + if (o != 0 && strcmp(o->getParamType(), "Int_t") == 0) { + Int_t l = o->getLength(); + Int_t n = o->getNumParams(); + if (value->GetSize() != n) { + value->Set(n); + } + memcpy(value->GetArray(), o->getParamValue(), l); + return kTRUE; + } + LOG(error) << "Could not find parameter " << name; + // Error("FairParamList::fill \nNot found: %s",name); + return kFALSE; +} + +Bool_t FairParamList::fill(const Text_t* name, TArrayC* value) +{ + // Copies the data from the list object into the parameter value of type TArrayC + // The array is resized, if the number of data is different. + if (value == 0) { + return kFALSE; + } + FairParamObj* o = static_cast(paramList.FindObject(name)); + if (o != 0 && strcmp(o->getParamType(), "Char_t") == 0) { + Int_t l = o->getLength(); + if (value->GetSize() != l) { + value->Set(l); + } + memcpy(value->GetArray(), o->getParamValue(), l); + return kTRUE; + } + LOG(error) << "Could not find parameter " << name; + // Error("FairParamList::fill \nNot found: %s",name); + return kFALSE; +} + +Bool_t FairParamList::fill(const Text_t* name, TArrayF* value) +{ + // Copies the data from the list object into the parameter value of type TArrayF + // The array is resized, if the number of data is different. + if (value == 0) { + return kFALSE; + } + FairParamObj* o = static_cast(paramList.FindObject(name)); + if (o != 0 && strcmp(o->getParamType(), "Float_t") == 0) { + Int_t l = o->getLength(); + Int_t n = o->getNumParams(); + if (value->GetSize() != n) { + value->Set(n); + } + memcpy(value->GetArray(), o->getParamValue(), l); + return kTRUE; + } + LOG(error) << "Could not find parameter " << name; + // Error("FairParamList::fill \nNot found: %s",name); + return kFALSE; +} + +Bool_t FairParamList::fill(const Text_t* name, TArrayD* value) +{ + // Copies the data from the list object into the parameter value of type TArrayD + // The array is resized, if the number of data is different. + if (value == 0) { + return kFALSE; + } + FairParamObj* o = static_cast(paramList.FindObject(name)); + if (o != 0 && strcmp(o->getParamType(), "Double_t") == 0) { + Int_t l = o->getLength(); + Int_t n = o->getNumParams(); + if (value->GetSize() != n) { + value->Set(n); + } + memcpy(value->GetArray(), o->getParamValue(), l); + return kTRUE; + } + LOG(error) << "Could not find parameter " << name; + // Error("FairParamList::fill \nNot found: %s",name); + return kFALSE; +} + +Bool_t FairParamList::fillObject(const Text_t* name, TObject* obj) +{ + // Fills the object obj (must exist!) via the Streamer and returns the class version. + // Prints a warning if the class version in the list objects differs from the actual + // class version. + if (!obj) { + return 0; + } + FairParamObj* o = static_cast(paramList.FindObject(name)); + if (o != 0 && strcmp(o->getParamType(), obj->IsA()->GetName()) == 0) { + if (o->getClassVersion() != obj->IsA()->GetClassVersion()) { + LOG(warn) << "Read Class Version = " << o->getClassVersion() + << " does not match actual version = " << obj->IsA()->GetClassVersion(); + } + // Warning("FairParamList::fill", + // "\n Read Class Version = %i does not match actual version = %i", + // o->getClassVersion(),obj->IsA()->GetClassVersion()); + TFile* filesave = gFile; + gFile = 0; + TBufferFile* buf = 0; + + Int_t len = o->getStreamerInfoSize(); + if (len > 0 && o->getStreamerInfo() != 0) { + buf = new TBufferFile(TBuffer::kRead, len); + memcpy(buf->Buffer(), reinterpret_cast(o->getStreamerInfo()), len); + buf->SetBufferOffset(0); + TList list; + buf->MapObject(&list); + list.Streamer(*buf); + delete buf; + TStreamerInfo* info; + TIter next(&list); + while ((info = static_cast(next()))) { + if (info->IsA() != TStreamerInfo::Class()) { + LOG(warn) << "Not a TStreamerInfo object"; + // Warning("FairParamList::fill","not a TStreamerInfo object"); + continue; + } + info->BuildCheck(); + } + list.Clear(); // this will delete all TStreamerInfo objects with kCanDelete + } + len = o->getLength(); + buf = new TBufferFile(TBuffer::kRead, len); + memcpy(buf->Buffer(), reinterpret_cast(o->getParamValue()), len); + buf->SetBufferOffset(0); + buf->MapObject(obj); + obj->Streamer(*buf); + delete buf; + gFile = filesave; + return len; + } + LOG(error) << "Could not find parameter " << name; + // Error("FairParamList::fill \nNot found: %s",name); + return 0; } diff --git a/parbase/FairParamList.h b/parbase/FairParamList.h index 9fe7e6dda2..ea6051be26 100644 --- a/parbase/FairParamList.h +++ b/parbase/FairParamList.h @@ -1,23 +1,22 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRPARAMLIST_H #define FAIRPARAMLIST_H -#include // for TNamed - -#include // for Text_t, Int_t, Bool_t, etc -#include // for TArrayC -#include // for TFile -#include // for THashTable -#include // for TObject -#include // for TROOT, gROOT -#include // for TSeqCollection -#include // for TString +#include // for Text_t, Int_t, Bool_t, etc +#include // for TArrayC +#include // for TFile +#include // for THashTable +#include // for TNamed +#include // for TObject +#include // for TROOT, gROOT +#include // for TSeqCollection +#include // for TString class TArrayD; class TArrayF; @@ -26,37 +25,37 @@ class TArrayI; class FairParamObj : public TNamed { protected: - UChar_t* paramValue; // Pointer to binary array - Int_t arraySize; // Size of binary array - TString paramType; // Type of parameter value or class name - Bool_t basicType; // kTRUE for C-types and C-type parameter arrays, kFALSE for classes - Int_t bytesPerValue; // number of bytes per value - Int_t classVersion; // Code version of classes stored as binary - UChar_t* streamerInfo; // Pointer to binary array container the streamer info - Int_t streamerInfoSize; // Size of streamer info array + UChar_t* paramValue; // Pointer to binary array + Int_t arraySize; // Size of binary array + TString paramType; // Type of parameter value or class name + Bool_t basicType; // kTRUE for C-types and C-type parameter arrays, kFALSE for classes + Int_t bytesPerValue; // number of bytes per value + Int_t classVersion; // Code version of classes stored as binary + UChar_t* streamerInfo; // Pointer to binary array container the streamer info + Int_t streamerInfoSize; // Size of streamer info array public: - FairParamObj(const Text_t* name=""); + FairParamObj(const Text_t* name = ""); FairParamObj(FairParamObj&); - FairParamObj(const Text_t*,Int_t); - FairParamObj(const Text_t*,Bool_t); - FairParamObj(const Text_t*,UInt_t); - FairParamObj(const Text_t*,Float_t); - FairParamObj(const Text_t*,Double_t); - FairParamObj(const Text_t*,const Int_t*,const Int_t); - FairParamObj(const Text_t*,const UInt_t*,const Int_t); - FairParamObj(const Text_t*,const Float_t*,const Int_t); - FairParamObj(const Text_t*,const Double_t*,const Int_t); - FairParamObj(const Text_t*,const Text_t*); - FairParamObj(const Text_t*,const Char_t*,const Int_t); - FairParamObj(const Text_t*,const UChar_t*,const Int_t); + FairParamObj(const Text_t*, Int_t); + FairParamObj(const Text_t*, Bool_t); + FairParamObj(const Text_t*, UInt_t); + FairParamObj(const Text_t*, Float_t); + FairParamObj(const Text_t*, Double_t); + FairParamObj(const Text_t*, const Int_t*, const Int_t); + FairParamObj(const Text_t*, const UInt_t*, const Int_t); + FairParamObj(const Text_t*, const Float_t*, const Int_t); + FairParamObj(const Text_t*, const Double_t*, const Int_t); + FairParamObj(const Text_t*, const Text_t*); + FairParamObj(const Text_t*, const Char_t*, const Int_t); + FairParamObj(const Text_t*, const UChar_t*, const Int_t); ~FairParamObj(); void setParamType(const Text_t* t); UChar_t* setLength(Int_t l); - void setParamValue(UChar_t*,const Int_t); - void setClassVersion(const Int_t v) { classVersion=v; } + void setParamValue(UChar_t*, const Int_t); + void setClassVersion(const Int_t v) { classVersion = v; } UChar_t* setStreamerInfoSize(Int_t); - void setStreamerInfo(UChar_t*,const Int_t); + void setStreamerInfo(UChar_t*, const Int_t); UChar_t* getParamValue() { return paramValue; } Bool_t isBasicType() { return basicType; } const char* getParamType() { return paramType.Data(); } @@ -69,31 +68,35 @@ class FairParamObj : public TNamed void print(); protected: - template void printData(type*,Int_t); + template + void printData(type*, Int_t); private: FairParamObj& operator=(const FairParamObj&); - ClassDef(FairParamObj,0) // Class for binary parameter object (name + binary array) + ClassDef(FairParamObj, 0) // Class for binary parameter object (name + binary array) }; - class FairParamList : public TObject { protected: - THashTable paramList; // List for parameters stored as string + THashTable paramList; // List for parameters stored as string class FairParamTFile : public TFile { public: - FairParamTFile() { - // Create StreamerInfo index - Int_t lenIndex = gROOT->GetListOfStreamerInfo()->GetSize()+1; - if (lenIndex < 5000) { lenIndex = 5000; } - fClassIndex = new TArrayC(lenIndex); + FairParamTFile() + { + // Create StreamerInfo index + Int_t lenIndex = gROOT->GetListOfStreamerInfo()->GetSize() + 1; + if (lenIndex < 5000) { + lenIndex = 5000; + } + fClassIndex = new TArrayC(lenIndex); } - ~FairParamTFile() { - delete fClassIndex; - fClassIndex=0; + ~FairParamTFile() + { + delete fClassIndex; + fClassIndex = 0; } }; @@ -101,44 +104,42 @@ class FairParamList : public TObject FairParamList(); ~FairParamList(); void add(FairParamObj&); - void add(const Text_t*,const Text_t*); - void add(const Text_t*,Int_t); - void add(const Text_t*,Bool_t); - void add(const Text_t*,UInt_t); - void add(const Text_t*,Float_t); - void add(const Text_t*,Double_t); - void add(const Text_t*,TArrayI&); - void add(const Text_t*,TArrayC&); - void add(const Text_t*,TArrayF&); - void add(const Text_t*,TArrayD&); - void add(const Text_t*,const UChar_t*,const Int_t); - void add(const Text_t*,const Int_t*,const Int_t); - void add(const Text_t*,const Float_t*,const Int_t); - void add(const Text_t*,const Double_t*,const Int_t); - void addObject(const Text_t*,TObject*); - Bool_t fill(const Text_t*,Text_t*,const Int_t); - Bool_t fill(const Text_t*,Int_t*,const Int_t nValues=1); - Bool_t fill(const Text_t*,Bool_t*,const Int_t nValues=1); - Bool_t fill(const Text_t*,UInt_t*,const Int_t nValues=1); - Bool_t fill(const Text_t*,Float_t*,const Int_t nValues=1); - Bool_t fill(const Text_t*,Double_t*,const Int_t nValues=1); - Bool_t fill(const Text_t*,UChar_t*,const Int_t nValues=1); - Bool_t fill(const Text_t*,TArrayI*); - Bool_t fill(const Text_t*,TArrayC*); - Bool_t fill(const Text_t*,TArrayF*); - Bool_t fill(const Text_t*,TArrayD*); - Bool_t fillObject(const Text_t*,TObject*); + void add(const Text_t*, const Text_t*); + void add(const Text_t*, Int_t); + void add(const Text_t*, Bool_t); + void add(const Text_t*, UInt_t); + void add(const Text_t*, Float_t); + void add(const Text_t*, Double_t); + void add(const Text_t*, TArrayI&); + void add(const Text_t*, TArrayC&); + void add(const Text_t*, TArrayF&); + void add(const Text_t*, TArrayD&); + void add(const Text_t*, const UChar_t*, const Int_t); + void add(const Text_t*, const Int_t*, const Int_t); + void add(const Text_t*, const Float_t*, const Int_t); + void add(const Text_t*, const Double_t*, const Int_t); + void addObject(const Text_t*, TObject*); + Bool_t fill(const Text_t*, Text_t*, const Int_t); + Bool_t fill(const Text_t*, Int_t*, const Int_t nValues = 1); + Bool_t fill(const Text_t*, Bool_t*, const Int_t nValues = 1); + Bool_t fill(const Text_t*, UInt_t*, const Int_t nValues = 1); + Bool_t fill(const Text_t*, Float_t*, const Int_t nValues = 1); + Bool_t fill(const Text_t*, Double_t*, const Int_t nValues = 1); + Bool_t fill(const Text_t*, UChar_t*, const Int_t nValues = 1); + Bool_t fill(const Text_t*, TArrayI*); + Bool_t fill(const Text_t*, TArrayC*); + Bool_t fill(const Text_t*, TArrayF*); + Bool_t fill(const Text_t*, TArrayD*); + Bool_t fillObject(const Text_t*, TObject*); void print(); - FairParamObj* find(const Text_t* name) { - return static_cast(paramList.FindObject(name)); - } + FairParamObj* find(const Text_t* name) { return static_cast(paramList.FindObject(name)); } THashTable* getList() { return ¶mList; } private: FairParamList(const FairParamList&); FairParamList& operator=(const FairParamList&); - ClassDef(FairParamList,4) // Class for lists of parameters (of type FairParamObj) + ClassDef(FairParamList, 4) // Class for lists of parameters (of type FairParamObj) }; -#endif /* !FAIRPARAMLIST_H */ +#endif /* !FAIRPARAMLIST_H */ diff --git a/parbase/FairRtdbRun.cxx b/parbase/FairRtdbRun.cxx index 7b4b578a9e..7fe2fb9e4d 100644 --- a/parbase/FairRtdbRun.cxx +++ b/parbase/FairRtdbRun.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ //*-- AUTHOR : Ilse Koenig @@ -25,144 +25,143 @@ /////////////////////////////////////////////////////////////////// #include "FairRtdbRun.h" -#include // for TIter -#include // for TList - -#include // for setw, operator<< -#include // for cout -#include // for fstream +#include // for TIter +#include // for TList +#include // for fstream +#include // for setw, operator<< +#include // for cout using std::cout; using std::ios; using std::setw; -ClassImp(FairParVersion) -ClassImp(FairRtdbRun) +ClassImp(FairParVersion); +ClassImp(FairRtdbRun); FairParVersion::FairParVersion(Text_t* name) - :TNamed(name,"version info"), - rootVersion(0) + : TNamed(name, "version info") + , rootVersion(0) { - // constructor with the name of the container - // rootVersion=0; - for(Int_t i=0; i<3; i++) {inputVersions[i]=-1;} + // constructor with the name of the container + // rootVersion=0; + for (Int_t i = 0; i < 3; i++) { + inputVersions[i] = -1; + } } -FairRtdbRun::FairRtdbRun(const Text_t* name,const Text_t* refName) - : TNamed(name,"run parameters"), - parVersions(new TList()), - refRun(refName) +FairRtdbRun::FairRtdbRun(const Text_t* name, const Text_t* refName) + : TNamed(name, "run parameters") + , parVersions(new TList()) + , refRun(refName) { - // constructor with the run id and reference run as strings - // parVersions=new TList(); - // refRun=refName; + // constructor with the run id and reference run as strings + // parVersions=new TList(); + // refRun=refName; } -FairRtdbRun::FairRtdbRun(Int_t r,Int_t rr) -// :TNamed(r,""), - :TNamed(), - parVersions(new TList()), - refRun("") +FairRtdbRun::FairRtdbRun(Int_t r, Int_t rr) + // :TNamed(r,""), + : TNamed() + , parVersions(new TList()) + , refRun("") { - char name[255]; - sprintf(name,"%i",r); - SetName(name); - setRefRun(rr); + char name[255]; + sprintf(name, "%i", r); + SetName(name); + setRefRun(rr); } FairRtdbRun::FairRtdbRun(FairRtdbRun& run) - :TNamed(run), - parVersions(new TList()), - refRun(run.refRun) + : TNamed(run) + , parVersions(new TList()) + , refRun(run.refRun) { - // copy constructor - TList* lv=run.getParVersions(); - TIter next(lv); - FairParVersion* pv; - while ((pv=static_cast(next()))) { - parVersions->Add(pv); - } + // copy constructor + TList* lv = run.getParVersions(); + TIter next(lv); + FairParVersion* pv; + while ((pv = static_cast(next()))) { + parVersions->Add(pv); + } } FairRtdbRun::FairRtdbRun() - :TNamed(), - parVersions(NULL), - refRun("") + : TNamed() + , parVersions(NULL) + , refRun("") { - // default Constructor - // parVersions has to be set to zero otherwise the - // root file is not browsable + // default Constructor + // parVersions has to be set to zero otherwise the + // root file is not browsable } FairRtdbRun::~FairRtdbRun() { - // destructor - if (parVersions) { - parVersions->Delete(); - delete parVersions; - parVersions=0; - } + // destructor + if (parVersions) { + parVersions->Delete(); + delete parVersions; + parVersions = 0; + } } void FairRtdbRun::addParVersion(FairParVersion* pv) { - // adds a container version object to the list - parVersions->Add(pv); + // adds a container version object to the list + parVersions->Add(pv); } FairParVersion* FairRtdbRun::getParVersion(const Text_t* name) { - // return a container version object called by the name of - // the container - return static_cast(parVersions->FindObject(name)); + // return a container version object called by the name of + // the container + return static_cast(parVersions->FindObject(name)); } void FairRtdbRun::resetInputVersions() { - TIter next(parVersions); - FairParVersion* v; - while ((v=static_cast(next()))) { - v->resetInputVersions(); - } + TIter next(parVersions); + FairParVersion* v; + while ((v = static_cast(next()))) { + v->resetInputVersions(); + } } void FairRtdbRun::resetOutputVersions() { - TIter next(parVersions); - FairParVersion* v; - while ((v=static_cast(next()))) { - v->setRootVersion(0); - } + TIter next(parVersions); + FairParVersion* v; + while ((v = static_cast(next()))) { + v->setRootVersion(0); + } } void FairRtdbRun::print() { - // prints the list of container versions for this run - cout<<"run: "<(next()))) { - cout.setf(ios::left,ios::adjustfield); - cout<<" "<GetName(); - cout.setf(ios::right,ios::adjustfield); - cout<getInputVersion(1) - <getInputVersion(2) - <getRootVersion()<<'\n'; - } + // prints the list of container versions for this run + cout << "run: " << GetName() << '\n'; + FairParVersion* v; + TIter next(parVersions); + while ((v = static_cast(next()))) { + cout.setf(ios::left, ios::adjustfield); + cout << " " << setw(45) << v->GetName(); + cout.setf(ios::right, ios::adjustfield); + cout << setw(11) << v->getInputVersion(1) << setw(11) << v->getInputVersion(2) << setw(11) + << v->getRootVersion() << '\n'; + } } void FairRtdbRun::write(std::fstream& fout) { - // writes the list of container versions for this run to fstream - fout<<"run: "<(next()))) { - fout.setf(ios::left,ios::adjustfield); - fout<<" "<GetName(); - fout.setf(ios::right,ios::adjustfield); - fout<getInputVersion(1) - <getInputVersion(2) - <getRootVersion()<<'\n'; - } + // writes the list of container versions for this run to fstream + fout << "run: " << GetName() << '\n'; + FairParVersion* v; + TIter next(parVersions); + while ((v = static_cast(next()))) { + fout.setf(ios::left, ios::adjustfield); + fout << " " << setw(45) << v->GetName(); + fout.setf(ios::right, ios::adjustfield); + fout << setw(11) << v->getInputVersion(1) << setw(11) << v->getInputVersion(2) << setw(11) + << v->getRootVersion() << '\n'; + } } diff --git a/parbase/FairRtdbRun.h b/parbase/FairRtdbRun.h index 68a41d4390..6f7550d571 100644 --- a/parbase/FairRtdbRun.h +++ b/parbase/FairRtdbRun.h @@ -1,20 +1,18 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRRTDBRUN_H #define FAIRRTDBRUN_H -#include // for TNamed - -#include // for fstream -#include // for Int_t, Text_t, UInt_t, etc -#include // for TString - -#include // for sprintf, sscanf +#include // for Int_t, Text_t, UInt_t, etc +#include // for TNamed +#include // for TString +#include // for fstream +#include // for sprintf, sscanf class TList; using std::fstream; @@ -22,26 +20,39 @@ using std::fstream; class FairParVersion : public TNamed { protected: - Int_t inputVersions[3]; //! version of the parameter container in the 2 possible inputs - Int_t rootVersion; // version of the parameter container in the ROOT output file + Int_t inputVersions[3]; //! version of the parameter container in the 2 possible inputs + Int_t rootVersion; // version of the parameter container in the ROOT output file public: - FairParVersion() : TNamed(),rootVersion(0) {} + FairParVersion() + : TNamed() + , rootVersion(0) + {} FairParVersion(Text_t* name); ~FairParVersion() {} - void setInputVersion(Int_t v=-1,Int_t i=0) { - if (i>=0 && i<3) { inputVersions[i]=v; } + void setInputVersion(Int_t v = -1, Int_t i = 0) + { + if (i >= 0 && i < 3) { + inputVersions[i] = v; + } } - Int_t getInputVersion(Int_t i) { - if (i>=0 && i<3) { return inputVersions[i]; } - else { return -1; } + Int_t getInputVersion(Int_t i) + { + if (i >= 0 && i < 3) { + return inputVersions[i]; + } else { + return -1; + } } - void resetInputVersions() { - for(Int_t i=0; i<3; i++) {inputVersions[i]=-1;} + void resetInputVersions() + { + for (Int_t i = 0; i < 3; i++) { + inputVersions[i] = -1; + } } - void setRootVersion(Int_t v) {rootVersion=v;} - Int_t getRootVersion() {return rootVersion;} - ClassDef(FairParVersion,1) // Class for parameter versions + void setRootVersion(Int_t v) { rootVersion = v; } + Int_t getRootVersion() { return rootVersion; } + ClassDef(FairParVersion, 1) // Class for parameter versions }; class FairRtdbRun : public TNamed @@ -52,16 +63,16 @@ class FairRtdbRun : public TNamed public: FairRtdbRun(); - FairRtdbRun(const Text_t* name,const Text_t* refName=""); - FairRtdbRun(Int_t r,Int_t rr=-1); + FairRtdbRun(const Text_t* name, const Text_t* refName = ""); + FairRtdbRun(Int_t r, Int_t rr = -1); FairRtdbRun(FairRtdbRun& run); ~FairRtdbRun(); inline UInt_t getRunId(void); void addParVersion(FairParVersion* pv); FairParVersion* getParVersion(const Text_t* name); - TList* getParVersions() {return parVersions;} - const Text_t* getRefRun() {return refRun.Data();} - void setRefRun(Text_t* s) {refRun=s;} + TList* getParVersions() { return parVersions; } + const Text_t* getRefRun() { return refRun.Data(); } + void setRefRun(Text_t* s) { refRun = s; } inline void setRefRun(Int_t r); void resetInputVersions(); void resetOutputVersions(); @@ -71,27 +82,27 @@ class FairRtdbRun : public TNamed private: FairRtdbRun& operator=(const FairRtdbRun&); - ClassDef(FairRtdbRun,1) // Class for parameter version management of a run + ClassDef(FairRtdbRun, 1) // Class for parameter version management of a run }; // -------------------- inlines --------------------------- inline UInt_t FairRtdbRun::getRunId(void) { - UInt_t r; - sscanf(GetName(),"%i",&r); - return r; + UInt_t r; + sscanf(GetName(), "%i", &r); + return r; } inline void FairRtdbRun::setRefRun(Int_t r) { - if (r==-1) { refRun=""; } - else { - char name[255]; - sprintf(name,"%i",r); - refRun=name; - } + if (r == -1) { + refRun = ""; + } else { + char name[255]; + sprintf(name, "%i", r); + refRun = name; + } } -#endif /* !FAIRRTDBRUN_H */ - +#endif /* !FAIRRTDBRUN_H */ diff --git a/parbase/FairRuntimeDb.cxx b/parbase/FairRuntimeDb.cxx index 280859f925..22b75ccc7c 100644 --- a/parbase/FairRuntimeDb.cxx +++ b/parbase/FairRuntimeDb.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ //*-- AUTHOR : Ilse Koenig @@ -15,28 +15,27 @@ ///////////////////////////////////////////////////////////// #include "FairRuntimeDb.h" -#include "FairContFact.h" // for FairContFact -#include "FairDetParAsciiFileIo.h" // for FairDetParAsciiFileIo -#include "FairDetParRootFileIo.h" // for FairDetParRootFileIo +#include "FairContFact.h" // for FairContFact +#include "FairDetParAsciiFileIo.h" // for FairDetParAsciiFileIo +#include "FairDetParRootFileIo.h" // for FairDetParRootFileIo //#include "FairDetParTSQLIo.h" // for FairDetParTSQLIo -#include "FairGenericParAsciiFileIo.h" // for FairGenericParAsciiFileIo -#include "FairGenericParRootFileIo.h" // for FairGenericParRootFileIo +#include "FairGenericParAsciiFileIo.h" // for FairGenericParAsciiFileIo +#include "FairGenericParRootFileIo.h" // for FairGenericParRootFileIo //#include "FairGenericParTSQLIo.h" // for FairGenericParTSQLIo -#include "FairLogger.h" // for FairLogger, MESSAGE_ORIGIN -#include "FairParAsciiFileIo.h" // for FairParAsciiFileIo -#include "FairParIo.h" // for FairParIo -#include "FairParRootFileIo.h" // for FairParRootFileIo -#include "FairParSet.h" // for FairParSet -#include "FairRtdbRun.h" // for FairRtdbRun, FairParVersion - -#include // for TClass -#include // for TIter -#include // for TFile, gFile - -#include // for sprintf -#include // for strcmp, strlen -#include // for setw, operator<< -#include // for operator<<, basic_ostream, etc +#include "FairLogger.h" // for FairLogger, MESSAGE_ORIGIN +#include "FairParAsciiFileIo.h" // for FairParAsciiFileIo +#include "FairParIo.h" // for FairParIo +#include "FairParRootFileIo.h" // for FairParRootFileIo +#include "FairParSet.h" // for FairParSet +#include "FairRtdbRun.h" // for FairRtdbRun, FairParVersion + +#include // for TClass +#include // for TIter +#include // for TFile, gFile +#include // for sprintf +#include // for strcmp, strlen +#include // for setw, operator<< +#include // for operator<<, basic_ostream, etc class FairDetParIo; @@ -50,354 +49,377 @@ using std::setw; #define USE_DB_METHOD 1 ///////////////////////////////// -ClassImp(FairRuntimeDb) +ClassImp(FairRuntimeDb); -FairRuntimeDb* FairRuntimeDb::gRtdb=0; +FairRuntimeDb* FairRuntimeDb::gRtdb = 0; FairRuntimeDb* FairRuntimeDb::instance(void) { - // Singleton instance - if (gRtdb==0) { gRtdb=new FairRuntimeDb; } - return gRtdb; + // Singleton instance + if (gRtdb == 0) { + gRtdb = new FairRuntimeDb; + } + return gRtdb; } FairRuntimeDb::FairRuntimeDb(void) - :TObject(), - containerList(new TList()), - runs(new TList()), - firstInput(nullptr), - secondInput(nullptr), - output(nullptr), - currentRun(nullptr), - currentFileName(""), - versionsChanged(kFALSE), - isRootFileOutput(kFALSE), - fLogger(FairLogger::GetLogger()), - ioType(UNKNOWN_Type) -{ - gRtdb=this; + : TObject() + , containerList(new TList()) + , runs(new TList()) + , firstInput(nullptr) + , secondInput(nullptr) + , output(nullptr) + , currentRun(nullptr) + , currentFileName("") + , versionsChanged(kFALSE) + , isRootFileOutput(kFALSE) + , fLogger(FairLogger::GetLogger()) + , ioType(UNKNOWN_Type) +{ + gRtdb = this; } FairRuntimeDb::~FairRuntimeDb() { - // destructor - // deletes the list of runs and all containers - closeFirstInput(); - closeSecondInput(); - closeOutput(); - if (containerList) { - TIter next(containerList); - FairParSet* cont; - while ((cont=static_cast(next()))) { - Text_t* name=const_cast(cont->GetName()); - if (!cont->isOwned()) { removeContainer(name); } + // destructor + // deletes the list of runs and all containers + closeFirstInput(); + closeSecondInput(); + closeOutput(); + if (containerList) { + TIter next(containerList); + FairParSet* cont; + while ((cont = static_cast(next()))) { + Text_t* name = const_cast(cont->GetName()); + if (!cont->isOwned()) { + removeContainer(name); + } + } + delete containerList; } - delete containerList; - } - if (runs) { - runs->Delete(); - delete runs; - } - gRtdb=0; + if (runs) { + runs->Delete(); + delete runs; + } + gRtdb = 0; } void FairRuntimeDb::addContFactory(FairContFact* fact) { - // Adds a container factory to the list of factories - if (!(contFactories.FindObject(fact->GetName()))) { - LOG(debug) << "- RTDB container factory " << fact->GetName() << "\n"; - contFactories.Add(fact); - } + // Adds a container factory to the list of factories + if (!(contFactories.FindObject(fact->GetName()))) { + LOG(debug) << "- RTDB container factory " << fact->GetName() << "\n"; + contFactories.Add(fact); + } } void FairRuntimeDb::removeContFactory(FairContFact* fact) { - // removes a container factory to the list of factories - if ((contFactories.Remove(fact))) { - LOG(debug) << "removed RTDB container factory " << fact->GetName(); - } + // removes a container factory to the list of factories + if ((contFactories.Remove(fact))) { + LOG(debug) << "removed RTDB container factory " << fact->GetName(); + } } FairContFact* FairRuntimeDb::getContFactory(const Text_t* FactName) { - return (static_cast(contFactories.FindObject(FactName))); + return (static_cast(contFactories.FindObject(FactName))); } Bool_t FairRuntimeDb::addParamContext(const char* context) { - // Sets via the container factories the context of all parameter containers, - // which accept this context - Bool_t found=kFALSE; - TIter next(&contFactories); - FairContFact* fact; - while((fact=static_cast(next()))) { - if (fact->addContext(context)) { found=kTRUE; } - } - Error("addParamContext(const char*)","Unknown context"); - return found; + // Sets via the container factories the context of all parameter containers, + // which accept this context + Bool_t found = kFALSE; + TIter next(&contFactories); + FairContFact* fact; + while ((fact = static_cast(next()))) { + if (fact->addContext(context)) { + found = kTRUE; + } + } + Error("addParamContext(const char*)", "Unknown context"); + return found; } void FairRuntimeDb::printParamContexts() { - // Prints the context of all parameter containers, which can be created by - // the container factories - TIter next(&contFactories); - FairContFact* fact; - while((fact=static_cast(next()))) { fact->print(); } + // Prints the context of all parameter containers, which can be created by + // the container factories + TIter next(&contFactories); + FairContFact* fact; + while ((fact = static_cast(next()))) { + fact->print(); + } } Bool_t FairRuntimeDb::addContainer(FairParSet* container) { - // adds a container to the list of containers - //cout << "-I- name parset # " << container->GetName()<< endl; - Text_t* name=const_cast(container->GetName()); + // adds a container to the list of containers + // cout << "-I- name parset # " << container->GetName()<< endl; + Text_t* name = const_cast(container->GetName()); + + if (!containerList->FindObject(name)) { + containerList->Add(container); + TIter next(runs); + FairRtdbRun* run; + FairParVersion* vers; + while ((run = static_cast(next()))) { + if (!run->getParVersion(name)) { + vers = new FairParVersion(name); + run->addParVersion(vers); + } + } + // cout << "-I- RTDB entries in list# " << containerList->GetEntries() <<"\n" ; - if (!containerList->FindObject(name)) { - containerList->Add(container); - TIter next(runs); - FairRtdbRun* run; - FairParVersion* vers; - while ((run=static_cast(next()))) { - if (!run->getParVersion(name)) { - vers=new FairParVersion(name); - run->addParVersion(vers); - } + return kTRUE; } - //cout << "-I- RTDB entries in list# " << containerList->GetEntries() <<"\n" ; - - - return kTRUE; - } - - - - Warning("addContainer(FairParSet*)","Container %s already exists!",name); - return kFALSE; + Warning("addContainer(FairParSet*)", "Container %s already exists!", name); + return kFALSE; } FairParSet* FairRuntimeDb::getContainer(const Text_t* name) { - // The function loops over the container factories to find the corresponding container - // with the give name and its context. - // The name is the original name of the parameter container without the concatination - // with the context. - // The factory checks, if the container exists already in the runtime database. Otherwise - // it will be created and added by the factory. - // The function returns a pointer to the container or nullptr, if not created. - TIter next(&contFactories); - FairContFact* fact; - FairParSet* c=0; - while(!c && (fact=static_cast(next()))) { - c=fact->getContainer(name); - } - if (!c) { Error("getContainer(Text_t*)","Container %s not created!",name); } - return c; + // The function loops over the container factories to find the corresponding container + // with the give name and its context. + // The name is the original name of the parameter container without the concatination + // with the context. + // The factory checks, if the container exists already in the runtime database. Otherwise + // it will be created and added by the factory. + // The function returns a pointer to the container or nullptr, if not created. + TIter next(&contFactories); + FairContFact* fact; + FairParSet* c = 0; + while (!c && (fact = static_cast(next()))) { + c = fact->getContainer(name); + } + if (!c) { + Error("getContainer(Text_t*)", "Container %s not created!", name); + } + return c; } FairParSet* FairRuntimeDb::findContainer(const char* name) { - // returns a pointer to the container called by name - // The name is the original name of the parameter container eventually concatinated with - // a non-default context. - return static_cast((containerList->FindObject(name))); + // returns a pointer to the container called by name + // The name is the original name of the parameter container eventually concatinated with + // a non-default context. + return static_cast((containerList->FindObject(name))); } void FairRuntimeDb::removeContainer(Text_t* name) { - // removes the container from the list and deletes it - TObject* c=containerList->FindObject(name); - if (c) { - containerList->Remove(c); - delete c; - } + // removes the container from the list and deletes it + TObject* c = containerList->FindObject(name); + if (c) { + containerList->Remove(c); + delete c; + } } void FairRuntimeDb::removeAllContainers(void) { - // removes all containers from the list and deletes them - containerList->Delete(); + // removes all containers from the list and deletes them + containerList->Delete(); } -FairRtdbRun* FairRuntimeDb::addRun(Int_t runId,Int_t refId) +FairRtdbRun* FairRuntimeDb::addRun(Int_t runId, Int_t refId) { - // adds a run at the end of the list of runs - // returns a pointer to the run newly added - FairRtdbRun* run; - if (refId!=-1) { - run=getRun(refId); - if (!run) { addRun(refId); } - } - run=getRun(runId); - if (!run) { - run=new FairRtdbRun(runId,refId); - TIter next(containerList); - FairParSet* cont; - FairParVersion* vers; - while ((cont=static_cast(next()))) { - vers=new FairParVersion((const_cast(cont->GetName()))); - run->addParVersion(vers); + // adds a run at the end of the list of runs + // returns a pointer to the run newly added + FairRtdbRun* run; + if (refId != -1) { + run = getRun(refId); + if (!run) { + addRun(refId); + } } - runs->Add(run); - currentRun=run; - } else { Warning("addRun(Int_t,Int_t)","Run already exists"); } - return run; + run = getRun(runId); + if (!run) { + run = new FairRtdbRun(runId, refId); + TIter next(containerList); + FairParSet* cont; + FairParVersion* vers; + while ((cont = static_cast(next()))) { + vers = new FairParVersion((const_cast(cont->GetName()))); + run->addParVersion(vers); + } + runs->Add(run); + currentRun = run; + } else { + Warning("addRun(Int_t,Int_t)", "Run already exists"); + } + return run; } FairRtdbRun* FairRuntimeDb::getRun(Int_t id) { - // returns a pointer to the run called by the run id - char name[255]; - sprintf(name,"%i",id); - return static_cast((runs->FindObject(name))); + // returns a pointer to the run called by the run id + char name[255]; + sprintf(name, "%i", id); + return static_cast((runs->FindObject(name))); } FairRtdbRun* FairRuntimeDb::getRun(Text_t* name) { - // returns a pointer to the run called by name - return static_cast((runs->FindObject(name))); + // returns a pointer to the run called by name + return static_cast((runs->FindObject(name))); } void FairRuntimeDb::removeRun(Text_t* name) { - // removes the run from the list and deletes it - TObject* c=runs->FindObject(name); - if (c) { - runs->Remove(c); - delete c; - if(c==currentRun) { currentRun=0; } - } + // removes the run from the list and deletes it + TObject* c = runs->FindObject(name); + if (c) { + runs->Remove(c); + delete c; + if (c == currentRun) { + currentRun = 0; + } + } } -void FairRuntimeDb::clearRunList() -{ - runs->Delete(); -} +void FairRuntimeDb::clearRunList() { runs->Delete(); } void FairRuntimeDb::writeVersions() { - // writes the parameter versions for all runs to the output - if (getOutput() && output->check()) { - if (versionsChanged && isRootFileOutput) { - output->cd(); - if (gFile->IsWritable()) { runs->Write();} - versionsChanged=kFALSE; + // writes the parameter versions for all runs to the output + if (getOutput() && output->check()) { + if (versionsChanged && isRootFileOutput) { + output->cd(); + if (gFile->IsWritable()) { + runs->Write(); + } + versionsChanged = kFALSE; + } } - } } Bool_t FairRuntimeDb::writeContainers() { - // writes all containers to the output - // loops over the list of containers and calls for each the - // function writeContainer(...) - TIter next(containerList); - FairParSet* cont; - Bool_t rc=kTRUE; - FairRtdbRun* refRun=0; - if (currentRun) { - const char* refRunName=currentRun->getRefRun(); - if (strlen(refRunName)>0) { - refRun=static_cast((runs->FindObject(refRunName))); + // writes all containers to the output + // loops over the list of containers and calls for each the + // function writeContainer(...) + TIter next(containerList); + FairParSet* cont; + Bool_t rc = kTRUE; + FairRtdbRun* refRun = 0; + if (currentRun) { + const char* refRunName = currentRun->getRefRun(); + if (strlen(refRunName) > 0) { + refRun = static_cast((runs->FindObject(refRunName))); + } + while ((cont = static_cast(next()))) { + rc = writeContainer(cont, currentRun, refRun) && rc; + } } - while ((cont=static_cast(next()))) { - rc=writeContainer(cont,currentRun,refRun) && rc; + if (!rc) { + Error("writeContainers()", "Error in write of containers to output"); } - } - if (!rc) { Error("writeContainers()","Error in write of containers to output"); } - return rc; + return rc; } Int_t FairRuntimeDb::findOutputVersion(FairParSet* cont) { - Int_t in1=cont->getInputVersion(1); - Int_t in2=cont->getInputVersion(2); - FairRtdbRun* run; - FairParVersion* vers; - const Text_t* name=cont->GetName(); - Int_t v=0; - if (in1==-1 && in2==-1) { - if (cont->hasChanged()) { return 0; } - else { - Int_t i=runs->IndexOf(currentRun); //FIXME: This can be optimized with a backwards iter. - while (i>=0) { - run=static_cast(runs->At(i)); - vers=run->getParVersion(name); - if (vers->getInputVersion(1)==in1 && vers->getInputVersion(2)==in2) { - if ((v=vers->getRootVersion())!=0) { return v; } + Int_t in1 = cont->getInputVersion(1); + Int_t in2 = cont->getInputVersion(2); + FairRtdbRun* run; + FairParVersion* vers; + const Text_t* name = cont->GetName(); + Int_t v = 0; + if (in1 == -1 && in2 == -1) { + if (cont->hasChanged()) { + return 0; + } else { + Int_t i = runs->IndexOf(currentRun); // FIXME: This can be optimized with a backwards iter. + while (i >= 0) { + run = static_cast(runs->At(i)); + vers = run->getParVersion(name); + if (vers->getInputVersion(1) == in1 && vers->getInputVersion(2) == in2) { + if ((v = vers->getRootVersion()) != 0) { + return v; + } + } + --i; + } + return 0; } - --i; - } - return 0; } - } - if ((firstInput==output) && (in1>0 && in2==-1)) { return in1; } - TIter next(runs); - // v=0; - while ((run=static_cast(next()))) { - vers=run->getParVersion(name); - if (vers->getInputVersion(1)==in1 && vers->getInputVersion(2)==in2) { - if ((v=vers->getRootVersion())!=0) { return v; } + if ((firstInput == output) && (in1 > 0 && in2 == -1)) { + return in1; + } + TIter next(runs); + // v=0; + while ((run = static_cast(next()))) { + vers = run->getParVersion(name); + if (vers->getInputVersion(1) == in1 && vers->getInputVersion(2) == in2) { + if ((v = vers->getRootVersion()) != 0) { + return v; + } + } } - } - return 0; + return 0; } //////// Original version //////// #if (USE_DB_METHOD == 0) Bool_t FairRuntimeDb::writeContainer(FairParSet* cont, FairRtdbRun* run, FairRtdbRun* refRun) { - // writes a container to the output if the containers has changed - // The output might be suppressed if the changes is due an initialisation from a - // ROOT file which serves also as output or if it was already written - const Text_t* c=cont->GetName(); - LOG(debug) << "RuntimeDb: write container: " << cont->GetName(); - FairParVersion* vers=run->getParVersion(c); - Bool_t rc=kTRUE; - Int_t cv=0; - if (getOutput() && output->check() && output->isAutoWritable()) { - cout << " CHECK OUTPUT DONE " << endl; - if (isRootFileOutput) { - if (cont->hasChanged()) { - cv=findOutputVersion(cont); - if (cv==0) { - cv=cont->write(output); - if (cv>0) { - LOG(info) << "*** " << c << " written to ROOT file version: " << cv; - } else if (cv==-1) { return kFALSE; } - // -1 indicates and error during write - // 0 is allowed for all containers which have no write function + // writes a container to the output if the containers has changed + // The output might be suppressed if the changes is due an initialisation from a + // ROOT file which serves also as output or if it was already written + const Text_t* c = cont->GetName(); + LOG(debug) << "RuntimeDb: write container: " << cont->GetName(); + FairParVersion* vers = run->getParVersion(c); + Bool_t rc = kTRUE; + Int_t cv = 0; + if (getOutput() && output->check() && output->isAutoWritable()) { + cout << " CHECK OUTPUT DONE " << endl; + if (isRootFileOutput) { + if (cont->hasChanged()) { + cv = findOutputVersion(cont); + if (cv == 0) { + cv = cont->write(output); + if (cv > 0) { + LOG(info) << "*** " << c << " written to ROOT file version: " << cv; + } else if (cv == -1) { + return kFALSE; + } + // -1 indicates and error during write + // 0 is allowed for all containers which have no write function + } + vers->setRootVersion(cv); + } else { + if (vers->getRootVersion() == 0) { + cv = findOutputVersion(cont); + vers->setRootVersion(cv); + } + } + } else { // might be Ascii I/O + if (cont->hasChanged()) { + cv = cont->write(output); + if (cv < 0) { + return kFALSE; + } + cout << "*** " << c << " written to output" << '\n'; + vers->setRootVersion(cv); + } } - vers->setRootVersion(cv); - } else { - if (vers->getRootVersion()==0) { - cv=findOutputVersion(cont); - vers->setRootVersion(cv); + } + vers->setInputVersion(cont->getInputVersion(1), 1); + vers->setInputVersion(cont->getInputVersion(2), 2); + cont->setChanged(kFALSE); + if (refRun) { + FairParVersion* refVers = refRun->getParVersion(c); + if (refVers) { + refVers->setInputVersion(cont->getInputVersion(1), 1); + refVers->setInputVersion(cont->getInputVersion(2), 2); + refVers->setRootVersion(cv); } - } - } else { // might be Ascii I/O - if (cont->hasChanged()) { - cv=cont->write(output); - if (cv<0) { return kFALSE; } - cout<<"*** "<setRootVersion(cv); - } - } - - } - vers->setInputVersion(cont->getInputVersion(1),1); - vers->setInputVersion(cont->getInputVersion(2),2); - cont->setChanged(kFALSE); - if (refRun) { - FairParVersion* refVers=refRun->getParVersion(c); - if (refVers) { - refVers->setInputVersion(cont->getInputVersion(1),1); - refVers->setInputVersion(cont->getInputVersion(2),2); - refVers->setRootVersion(cv); - } - } - return rc; + } + return rc; } #endif @@ -405,424 +427,477 @@ Bool_t FairRuntimeDb::writeContainer(FairParSet* cont, FairRtdbRun* run, FairRtd #if (USE_DB_METHOD > 0) Bool_t FairRuntimeDb::writeContainer(FairParSet* cont, FairRtdbRun* run, FairRtdbRun* refRun) { - // std::cout << "\n -I FairRuntimeDB Using DB mode \n"; - // writes a container to the output if the containers has changed - // The output might be suppressed if the changes is due an initialisation from a - // ROOT file which serves also as output or if it was already written - const Text_t* c = cont->GetName(); - LOG(debug) << "RuntimeDb: write container: " << cont->GetName(); - FairParVersion* vers = run->getParVersion(c); - Bool_t rc = kTRUE; - Int_t cv = 0; - if (getOutput() && output->check() && output->isAutoWritable()) { - switch (ioType) { - case RootFileOutput: // RootFile - if (cont->hasChanged()) { - cv = findOutputVersion(cont); - if (cv == 0) { - cv = cont->write(output); - if (cv>0) { - LOG(info) << "*** " << c << " written to ROOT file version: " << cv; - } else if (cv==-1) { - return kFALSE; - } - // -1 indicates and error during write - // 0 is allowed for all containers which have no write function - } - vers->setRootVersion(cv); - } else { - if (vers->getRootVersion() == 0) { - cv = findOutputVersion(cont); - vers->setRootVersion(cv); - } - } - break;// End of rootfile IO - case RootTSQLOutput://TSQL - if (cont->hasChanged()) { - cv = findOutputVersion(cont); - if(cv == 0) { - //std::cout << "-I- FairRuntimeDB: SQL write() called 1 = "<< cont->GetName() << "\n"; - cont->print(); - /*Int_t test = */ - cont->write(output); - //std::cout << "-I- FairRuntimeDB: SQL write() called 2 = \n"; + // std::cout << "\n -I FairRuntimeDB Using DB mode \n"; + // writes a container to the output if the containers has changed + // The output might be suppressed if the changes is due an initialisation from a + // ROOT file which serves also as output or if it was already written + const Text_t* c = cont->GetName(); + LOG(debug) << "RuntimeDb: write container: " << cont->GetName(); + FairParVersion* vers = run->getParVersion(c); + Bool_t rc = kTRUE; + Int_t cv = 0; + if (getOutput() && output->check() && output->isAutoWritable()) { + switch (ioType) { + case RootFileOutput: // RootFile + if (cont->hasChanged()) { + cv = findOutputVersion(cont); + if (cv == 0) { + cv = cont->write(output); + if (cv > 0) { + LOG(info) << "*** " << c << " written to ROOT file version: " << cv; + } else if (cv == -1) { + return kFALSE; + } + // -1 indicates and error during write + // 0 is allowed for all containers which have no write function + } + vers->setRootVersion(cv); + } else { + if (vers->getRootVersion() == 0) { + cv = findOutputVersion(cont); + vers->setRootVersion(cv); + } + } + break; // End of rootfile IO + case RootTSQLOutput: // TSQL + if (cont->hasChanged()) { + cv = findOutputVersion(cont); + if (cv == 0) { + // std::cout << "-I- FairRuntimeDB: SQL write() called 1 = "<< cont->GetName() << "\n"; + cont->print(); + /*Int_t test = */ + cont->write(output); + // std::cout << "-I- FairRuntimeDB: SQL write() called 2 = \n"; + } + } + break; // End of TSQL IO + case AsciiFileOutput: // might be Ascii I/O + if (cont->hasChanged()) { + cv = cont->write(output); + if (cv < 0) { + return kFALSE; + } + cout << "*** " << c << " written to output" << '\n'; + vers->setRootVersion(cv); + } + break; // End of Ascii IO + default: // Unknown IO + Error("writeContainer()", "Unknown output file type."); + break; } - } - break;//End of TSQL IO - case AsciiFileOutput:// might be Ascii I/O - if(cont->hasChanged()) { - cv = cont->write(output); - if(cv <0) { - return kFALSE; + } + vers->setInputVersion(cont->getInputVersion(1), 1); + vers->setInputVersion(cont->getInputVersion(2), 2); + cont->setChanged(kFALSE); + if (refRun) { + FairParVersion* refVers = refRun->getParVersion(c); + if (refVers) { + refVers->setInputVersion(cont->getInputVersion(1), 1); + refVers->setInputVersion(cont->getInputVersion(2), 2); + refVers->setRootVersion(cv); } - cout << "*** " << c << " written to output" << '\n'; - vers->setRootVersion(cv); - } - break;// End of Ascii IO - default: // Unknown IO - Error("writeContainer()","Unknown output file type."); - break; - } - } - vers->setInputVersion(cont->getInputVersion(1),1); - vers->setInputVersion(cont->getInputVersion(2),2); - cont->setChanged(kFALSE); - if (refRun) { - FairParVersion* refVers=refRun->getParVersion(c); - if (refVers) { - refVers->setInputVersion(cont->getInputVersion(1),1); - refVers->setInputVersion(cont->getInputVersion(2),2); - refVers->setRootVersion(cv); - } - } - return rc; + } + return rc; } #endif //////////////////////////////////////// -Bool_t FairRuntimeDb::initContainers(Int_t runId,Int_t refId, - const Text_t* fileName) +Bool_t FairRuntimeDb::initContainers(Int_t runId, Int_t refId, const Text_t* fileName) { - // loops over the list of containers and calls the init() function of each - // container if it is not static - // (typically called by Hades::eventLoop(...)) - if (currentRun && currentRun->getRunId()!=runId) { writeContainers(); } - FairRtdbRun* run=getRun(runId); - if (!run) { run=addRun(runId,refId); } - else { - run->setRefRun(refId); - if (refId!=-1 && !getRun(refId)) { addRun(refId); } - } - currentRun=run; - currentFileName=fileName; - return initContainers(); + // loops over the list of containers and calls the init() function of each + // container if it is not static + // (typically called by Hades::eventLoop(...)) + if (currentRun && currentRun->getRunId() != runId) { + writeContainers(); + } + FairRtdbRun* run = getRun(runId); + if (!run) { + run = addRun(runId, refId); + } else { + run->setRefRun(refId); + if (refId != -1 && !getRun(refId)) { + addRun(refId); + } + } + currentRun = run; + currentFileName = fileName; + return initContainers(); } Bool_t FairRuntimeDb::readAll() { - // reads all containers with all versions for all runs and writes the - // containers, the setup information and the version table to the output - if (!(getOutput() && output->check())) { - cout<<"***********************************************************"<(next()))!=0) { - rc=initContainers() && rc; - writeContainers(); - } - saveOutput(); - currentRun=0; - return kTRUE; + // reads all containers with all versions for all runs and writes the + // containers, the setup information and the version table to the output + if (!(getOutput() && output->check())) { + cout << "***********************************************************" << endl; + cout << "********************* W A R N I N G *********************" << endl; + cout << "********************* no output ! *********************" << endl; + cout << "***********************************************************" << endl; + } + currentRun = 0; + Bool_t rc = kTRUE; + TIter next(runs); + while ((currentRun = static_cast(next())) != 0) { + rc = initContainers() && rc; + writeContainers(); + } + saveOutput(); + currentRun = 0; + return kTRUE; } Bool_t FairRuntimeDb::initContainers(void) { - // private function - Text_t* refRunName=const_cast(currentRun->getRefRun()); - Int_t len=strlen(refRunName); - if (len<1) { - if (firstInput) { firstInput->readVersions(currentRun); } - if (secondInput) { secondInput->readVersions(currentRun); } - } else { - FairRtdbRun* refRun=getRun(refRunName); - if (firstInput) { firstInput->readVersions(refRun); } - if (secondInput) { secondInput->readVersions(refRun); } - } - TIter next(containerList); - FairParSet* cont; - Bool_t rc=kTRUE; - cout<<'\n'<<"************************************************************* "<<'\n'; - if (currentFileName.IsNull()) { - cout<<" initialisation for run id "<GetName(); - } else { - cout<<" initialisation for event file "<GetName(); - } - if (len>0) { cout << " --> " << refRunName; } - cout<<'\n'<<"************************************************************* "<<'\n'; - while ((cont=static_cast(next()))) { - cout << "-I- FairRunTimeDB::InitContainer() " << cont->GetName() << endl; - if (!cont->isStatic()) { rc=cont->init() && rc; } - } - if (!rc) { Error("initContainers()","Error occured during initialization"); } - return rc; + // private function + Text_t* refRunName = const_cast(currentRun->getRefRun()); + Int_t len = strlen(refRunName); + if (len < 1) { + if (firstInput) { + firstInput->readVersions(currentRun); + } + if (secondInput) { + secondInput->readVersions(currentRun); + } + } else { + FairRtdbRun* refRun = getRun(refRunName); + if (firstInput) { + firstInput->readVersions(refRun); + } + if (secondInput) { + secondInput->readVersions(refRun); + } + } + TIter next(containerList); + FairParSet* cont; + Bool_t rc = kTRUE; + cout << '\n' << "************************************************************* " << '\n'; + if (currentFileName.IsNull()) { + cout << " initialisation for run id " << currentRun->GetName(); + } else { + cout << " initialisation for event file " << currentFileName.Data() << '\n'; + cout << " run id " << currentRun->GetName(); + } + if (len > 0) { + cout << " --> " << refRunName; + } + cout << '\n' << "************************************************************* " << '\n'; + while ((cont = static_cast(next()))) { + cout << "-I- FairRunTimeDB::InitContainer() " << cont->GetName() << endl; + if (!cont->isStatic()) { + rc = cont->init() && rc; + } + } + if (!rc) { + Error("initContainers()", "Error occured during initialization"); + } + return rc; } void FairRuntimeDb::setContainersStatic(Bool_t flag) { - // sets the status flag in all containers - // flag kTRUE sets all 'static' - // flag kFALSE sets all 'not static' - TIter next(containerList); - FairParSet* cont; - while ((cont=static_cast(next()))) { - cont->setStatic(flag); - } -} - -Bool_t FairRuntimeDb::setInputVersion(Int_t run,Text_t* container, - Int_t version,Int_t inp) -{ - // sets the input version of a container defined by its name and a - // run defined by its id taken from input with inputNumber inp - // (1 for first input and 2 for second input) - FairRtdbRun* r=getRun(run); - if (r) { - FairParVersion* v=r->getParVersion(container); - if (v) { - v->setInputVersion(version,inp); - return kTRUE; - } else { Error("setInputVersion","Container not found"); } - } else { Error("setInputVersion","Run not found"); } - return kFALSE; -} - - -Bool_t FairRuntimeDb::setRootOutputVersion(Int_t run,Text_t* container, - Int_t version) -{ - // sets the Root file output version of a container defined by its name - // and a run defined by its id - // should only be used after initialization 'by hand' on the interpreter level - FairRtdbRun* r=getRun(run); - if (r) { - FairParVersion* v=r->getParVersion(container); - if (v) { - v->setRootVersion(version); - return kTRUE; - } else { Error("setRootOutputVersion","Container not found"); } - } else { Error("setRootOutputVersion","Run not found"); } - return kFALSE; + // sets the status flag in all containers + // flag kTRUE sets all 'static' + // flag kFALSE sets all 'not static' + TIter next(containerList); + FairParSet* cont; + while ((cont = static_cast(next()))) { + cont->setStatic(flag); + } +} + +Bool_t FairRuntimeDb::setInputVersion(Int_t run, Text_t* container, Int_t version, Int_t inp) +{ + // sets the input version of a container defined by its name and a + // run defined by its id taken from input with inputNumber inp + // (1 for first input and 2 for second input) + FairRtdbRun* r = getRun(run); + if (r) { + FairParVersion* v = r->getParVersion(container); + if (v) { + v->setInputVersion(version, inp); + return kTRUE; + } else { + Error("setInputVersion", "Container not found"); + } + } else { + Error("setInputVersion", "Run not found"); + } + return kFALSE; +} + +Bool_t FairRuntimeDb::setRootOutputVersion(Int_t run, Text_t* container, Int_t version) +{ + // sets the Root file output version of a container defined by its name + // and a run defined by its id + // should only be used after initialization 'by hand' on the interpreter level + FairRtdbRun* r = getRun(run); + if (r) { + FairParVersion* v = r->getParVersion(container); + if (v) { + v->setRootVersion(version); + return kTRUE; + } else { + Error("setRootOutputVersion", "Container not found"); + } + } else { + Error("setRootOutputVersion", "Run not found"); + } + return kFALSE; } void FairRuntimeDb::print() { - // prints the list of the actual containers, the list of the - // runs/versions and information about input/output - cout<<"--------------------------------------------------------------------------------\n"; - cout<<"-------------- actual containers in runtime database -------------------------\n"; - TIter nextCont(containerList); - FairParSet* cont; - cout.setf(ios::left,ios::adjustfield); - while((cont=static_cast(nextCont()))) { - cout<GetName()<<" "<GetTitle()<<'\n'; - } - TIter next(runs); - FairRtdbRun* run; - cout<<"-------------- runs, versions ------------------------------------------------\n"; - cout<<"run id\n"; - cout<<" "<(next()))) { - run->print(); - } - cout<<"-------------- input/output --------------------------------------------------\n"; - if (firstInput) { - cout<<"first Input:\n"; - firstInput->print(); - } else { cout<<"first input: none"<<'\n'; } - if (secondInput) { - cout<<"second Input:\n"; - secondInput->print(); - } else { cout<<"second input: none"<<'\n'; } - if (output) { - cout<<"output:\n"; - output->print(); - } else { cout<<"output: none"<<'\n'; } + // prints the list of the actual containers, the list of the + // runs/versions and information about input/output + cout << "--------------------------------------------------------------------------------\n"; + cout << "-------------- actual containers in runtime database -------------------------\n"; + TIter nextCont(containerList); + FairParSet* cont; + cout.setf(ios::left, ios::adjustfield); + while ((cont = static_cast(nextCont()))) { + cout << setw(45) << cont->GetName() << " " << cont->GetTitle() << '\n'; + } + TIter next(runs); + FairRtdbRun* run; + cout << "-------------- runs, versions ------------------------------------------------\n"; + cout << "run id\n"; + cout << " " << setw(45) << "container"; + cout.setf(ios::right, ios::adjustfield); + cout << setw(11) << "1st-inp" << setw(11) << " 2nd-inp" << setw(11) << " output\n"; + while ((run = static_cast(next()))) { + run->print(); + } + cout << "-------------- input/output --------------------------------------------------\n"; + if (firstInput) { + cout << "first Input:\n"; + firstInput->print(); + } else { + cout << "first input: none" << '\n'; + } + if (secondInput) { + cout << "second Input:\n"; + secondInput->print(); + } else { + cout << "second input: none" << '\n'; + } + if (output) { + cout << "output:\n"; + output->print(); + } else { + cout << "output: none" << '\n'; + } } void FairRuntimeDb::resetInputVersions() { - // resets all input versions in the list of runs and in all containers which are not static - // is called each time a new input is set - TIter nextRun(runs); - FairRtdbRun* run; - while ((run=static_cast(nextRun()))) { - run->resetInputVersions(); - } - TIter nextCont(containerList); - FairParSet* cont; - while ((cont=static_cast(nextCont()))) { - if (!cont->isStatic()) { cont->resetInputVersions(); } - } + // resets all input versions in the list of runs and in all containers which are not static + // is called each time a new input is set + TIter nextRun(runs); + FairRtdbRun* run; + while ((run = static_cast(nextRun()))) { + run->resetInputVersions(); + } + TIter nextCont(containerList); + FairParSet* cont; + while ((cont = static_cast(nextCont()))) { + if (!cont->isStatic()) { + cont->resetInputVersions(); + } + } } void FairRuntimeDb::resetOutputVersions() { - // resets all output versions in the list of runs - // is called each time a new output is set - // is called also each time a new input is set which is not identical with the output - TIter next(runs); - FairRtdbRun* run; - while ((run=static_cast(next()))) { - run->resetOutputVersions(); - } + // resets all output versions in the list of runs + // is called each time a new output is set + // is called also each time a new input is set which is not identical with the output + TIter next(runs); + FairRtdbRun* run; + while ((run = static_cast(next()))) { + run->resetOutputVersions(); + } } void FairRuntimeDb::resetAllVersions() { - // resets all input and output versions in the list of runs - // and in all containers which are not static - resetInputVersions(); - resetOutputVersions(); + // resets all input and output versions in the list of runs + // and in all containers which are not static + resetInputVersions(); + resetOutputVersions(); } Bool_t FairRuntimeDb::setFirstInput(FairParIo* inp1) { - // sets the first input pointer - firstInput=inp1; - if (inp1->check()==kTRUE) { - inp1->setInputNumber(1); - resetInputVersions(); - if (output && firstInput!=output) { resetOutputVersions(); } - return kTRUE; - } else { Error("setFirstInput(FairParIo*)","no connection to input"); } - return kFALSE; + // sets the first input pointer + firstInput = inp1; + if (inp1->check() == kTRUE) { + inp1->setInputNumber(1); + resetInputVersions(); + if (output && firstInput != output) { + resetOutputVersions(); + } + return kTRUE; + } else { + Error("setFirstInput(FairParIo*)", "no connection to input"); + } + return kFALSE; } Bool_t FairRuntimeDb::setSecondInput(FairParIo* inp2) { - // sets the second input pointer - secondInput=inp2; - if (inp2->check()==kTRUE) { - inp2->setInputNumber(2); - resetInputVersions(); - if (output && firstInput!=output) { resetOutputVersions(); } - return kTRUE; - } else { Error("setSecondInput(FairParIo*)","no connection to input"); } - return kFALSE; + // sets the second input pointer + secondInput = inp2; + if (inp2->check() == kTRUE) { + inp2->setInputNumber(2); + resetInputVersions(); + if (output && firstInput != output) { + resetOutputVersions(); + } + return kTRUE; + } else { + Error("setSecondInput(FairParIo*)", "no connection to input"); + } + return kFALSE; } //////// Original version //////// -#if (USE_DB_METHOD == 0) +#if (USE_DB_METHOD == 0) Bool_t FairRuntimeDb::setOutput(FairParIo* op) { - // sets the output pointer - output=op; - if (output->check()==kTRUE) { - resetOutputVersions(); - if (strcmp(output->IsA()->GetName(),"FairParRootFileIo")==0) { - isRootFileOutput=kTRUE; + // sets the output pointer + output = op; + if (output->check() == kTRUE) { + resetOutputVersions(); + if (strcmp(output->IsA()->GetName(), "FairParRootFileIo") == 0) { + isRootFileOutput = kTRUE; + } + return kTRUE; + } else { + Error("setOutput(FairParIo*)", "no connection to output"); } - return kTRUE; - } else { Error("setOutput(FairParIo*)","no connection to output"); } - return kFALSE; + return kFALSE; } #endif ////// With DB modifications (FIXME FIXME)///// #if (USE_DB_METHOD > 0) Bool_t FairRuntimeDb::setOutput(FairParIo* op) { - // sets the output pointer - output = op; - if (output->check() == kTRUE) { - resetOutputVersions(); - if (strcmp(output->IsA()->GetName(), "FairParRootFileIo") == 0) { - ioType = RootFileOutput; - isRootFileOutput=kTRUE; - } else if (strcmp(output->IsA()->GetName(), "FairParTSQLIo") == 0) { - ioType = RootTSQLOutput; - } else { //ASCII - ioType = AsciiFileOutput; + // sets the output pointer + output = op; + if (output->check() == kTRUE) { + resetOutputVersions(); + if (strcmp(output->IsA()->GetName(), "FairParRootFileIo") == 0) { + ioType = RootFileOutput; + isRootFileOutput = kTRUE; + } else if (strcmp(output->IsA()->GetName(), "FairParTSQLIo") == 0) { + ioType = RootTSQLOutput; + } else { // ASCII + ioType = AsciiFileOutput; + } + return kTRUE; + } else { + Error("setOutput(FairParIo*)", "no connection to output"); } - return kTRUE; - } else { Error("setOutput(FairParIo*)","no connection to output"); } - return kFALSE; + return kFALSE; } #endif ///////////////////////////////// FairParIo* FairRuntimeDb::getFirstInput() { - // return a pointer to the first input - if (firstInput) { firstInput->cd(); } - return firstInput; + // return a pointer to the first input + if (firstInput) { + firstInput->cd(); + } + return firstInput; } FairParIo* FairRuntimeDb::getSecondInput() { - // return a pointer to the second input - if (secondInput) { secondInput->cd(); } - return secondInput; + // return a pointer to the second input + if (secondInput) { + secondInput->cd(); + } + return secondInput; } FairParIo* FairRuntimeDb::getOutput() { - // return a pointer to the output - if (output) { output->cd(); } - return output; + // return a pointer to the output + if (output) { + output->cd(); + } + return output; } void FairRuntimeDb::closeFirstInput() { - if (firstInput) { - firstInput->cd(); - firstInput->close(); - firstInput=0; - } + if (firstInput) { + firstInput->cd(); + firstInput->close(); + firstInput = 0; + } } void FairRuntimeDb::closeSecondInput() { - if (secondInput) { - secondInput->cd(); - secondInput->close(); - secondInput=0; - } + if (secondInput) { + secondInput->cd(); + secondInput->close(); + secondInput = 0; + } } void FairRuntimeDb::saveOutput() { - // writes the versions and the containers (if not yet written out) - // without the version information the containers cannot be read from a ROOT file! - Bool_t rc=kTRUE; - if (currentRun!=0) { rc=writeContainers(); } - writeVersions(); - if (!rc) { Error("saveOutput()","Error occured during write"); } + // writes the versions and the containers (if not yet written out) + // without the version information the containers cannot be read from a ROOT file! + Bool_t rc = kTRUE; + if (currentRun != 0) { + rc = writeContainers(); + } + writeVersions(); + if (!rc) { + Error("saveOutput()", "Error occured during write"); + } } void FairRuntimeDb::closeOutput() { - // calls saveOutput() and deletes then the output - if (output) { - if (output->isAutoWritable()) { saveOutput(); } - output->close(); - resetOutputVersions(); - output=0; - isRootFileOutput=kFALSE; - } + // calls saveOutput() and deletes then the output + if (output) { + if (output->isAutoWritable()) { + saveOutput(); + } + output->close(); + resetOutputVersions(); + output = 0; + isRootFileOutput = kFALSE; + } } void FairRuntimeDb::activateParIo(FairParIo* io) { - // activates the detector I/O - const char* ioName=io->IsA()->GetName(); - FairDetParIo* po=io->getDetParIo("FairGenericParIo"); - if (!po) { - if (strcmp(ioName,"FairParRootFileIo")==0) { - FairDetParRootFileIo* pn= - new FairGenericParRootFileIo((static_cast(io))->getParRootFile()); - io->setDetParIo(pn); - } else if (strcmp(ioName,"FairParAsciiFileIo")==0) { - FairDetParAsciiFileIo* pn= - new FairGenericParAsciiFileIo((static_cast(io))->getFile()); - io->setDetParIo(pn); - } - // else if(strcmp(ioName,"FairParTSQLIo") == 0) { - // std::cout << "\n\n\n\t TSQL versie is called en nu de rest \n\n"; - // FairDetParTSQLIo* pn = new FairGenericParTSQLIo(); - // io->setDetParIo(pn); - //} - } - TIter next(&contFactories); - FairContFact* fact; - while((fact=static_cast(next()))) { - fact->activateParIo(io); - } + // activates the detector I/O + const char* ioName = io->IsA()->GetName(); + FairDetParIo* po = io->getDetParIo("FairGenericParIo"); + if (!po) { + if (strcmp(ioName, "FairParRootFileIo") == 0) { + FairDetParRootFileIo* pn = + new FairGenericParRootFileIo((static_cast(io))->getParRootFile()); + io->setDetParIo(pn); + } else if (strcmp(ioName, "FairParAsciiFileIo") == 0) { + FairDetParAsciiFileIo* pn = + new FairGenericParAsciiFileIo((static_cast(io))->getFile()); + io->setDetParIo(pn); + } + // else if(strcmp(ioName,"FairParTSQLIo") == 0) { + // std::cout << "\n\n\n\t TSQL versie is called en nu de rest \n\n"; + // FairDetParTSQLIo* pn = new FairGenericParTSQLIo(); + // io->setDetParIo(pn); + //} + } + TIter next(&contFactories); + FairContFact* fact; + while ((fact = static_cast(next()))) { + fact->activateParIo(io); + } } diff --git a/parbase/FairRuntimeDb.h b/parbase/FairRuntimeDb.h index 553f19e1e6..b014a29b8f 100644 --- a/parbase/FairRuntimeDb.h +++ b/parbase/FairRuntimeDb.h @@ -1,18 +1,17 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRRUNTIMEDB_H #define FAIRRUNTIMEDB_H -#include // for TObject - -#include // for Bool_t, Int_t, Text_t, etc -#include // for TList -#include // for TString +#include // for Bool_t, Int_t, Text_t, etc +#include // for TList +#include // for TObject +#include // for TString class FairContFact; class FairLogger; @@ -20,37 +19,38 @@ class FairParIo; class FairParSet; class FairRtdbRun; -static TList contFactories; //! list of container factories +static TList contFactories; //! list of container factories class FairRuntimeDb : public TObject { private: - static FairRuntimeDb* gRtdb; //! + static FairRuntimeDb* gRtdb; //! protected: FairRuntimeDb(void); - TList* containerList; // list of parameter containers - TList* runs; // list of runs - FairParIo* firstInput; // first (prefered) input for parameters - FairParIo* secondInput; // second input (used if not found in first input) - FairParIo* output; // output for parameters - FairRtdbRun* currentRun; // Current run - TString currentFileName; // Name of current event file - Bool_t versionsChanged; // flag for write of list of runs (set kTRUE by each write) - Bool_t isRootFileOutput; // flag indicating that the output is a ROOT file + TList* containerList; // list of parameter containers + TList* runs; // list of runs + FairParIo* firstInput; // first (prefered) input for parameters + FairParIo* secondInput; // second input (used if not found in first input) + FairParIo* output; // output for parameters + FairRtdbRun* currentRun; // Current run + TString currentFileName; // Name of current event file + Bool_t versionsChanged; // flag for write of list of runs (set kTRUE by each write) + Bool_t isRootFileOutput; // flag indicating that the output is a ROOT file /** Fair Logger */ - FairLogger* fLogger; //! + FairLogger* fLogger; //! /** * Select which IO type to use. */ - typedef enum { - UNKNOWN_Type = 0, - AsciiFileOutput = 1, // Ascii in-out-put - RootFileOutput = 2, // Root Files - RootTSQLOutput = 3 // Use a TSQL db + typedef enum + { + UNKNOWN_Type = 0, + AsciiFileOutput = 1, // Ascii in-out-put + RootFileOutput = 2, // Root Files + RootTSQLOutput = 3 // Use a TSQL db } ParamIOType; - ParamIOType ioType;//IO Type + ParamIOType ioType; // IO Type public: static FairRuntimeDb* instance(void); @@ -67,24 +67,23 @@ class FairRuntimeDb : public TObject FairParSet* findContainer(const char*); void removeContainer(Text_t*); void removeAllContainers(void); - Bool_t initContainers(Int_t runId,Int_t refId=-1,const Text_t* fileName=""); - void setContainersStatic(Bool_t f=kTRUE); + Bool_t initContainers(Int_t runId, Int_t refId = -1, const Text_t* fileName = ""); + void setContainersStatic(Bool_t f = kTRUE); Bool_t writeContainers(void); - Bool_t writeContainer(FairParSet*,FairRtdbRun*,FairRtdbRun* refRun=0); + Bool_t writeContainer(FairParSet*, FairRtdbRun*, FairRtdbRun* refRun = 0); - FairRtdbRun* addRun(Int_t runId,Int_t refId=-1); + FairRtdbRun* addRun(Int_t runId, Int_t refId = -1); FairRtdbRun* getRun(Int_t); FairRtdbRun* getRun(Text_t*); - FairRtdbRun* getCurrentRun(void) {return currentRun;} - Text_t const* getCurrentFileName() {return currentFileName.Data();} + FairRtdbRun* getCurrentRun(void) { return currentRun; } + Text_t const* getCurrentFileName() { return currentFileName.Data(); } void clearRunList(void); void removeRun(Text_t*); - Bool_t setInputVersion(Int_t run,Text_t* container, - Int_t version,Int_t inputNumber); - Bool_t setRootOutputVersion(Int_t run,Text_t* container,Int_t version); - void setVersionsChanged(Bool_t f=kTRUE) {versionsChanged=f;} + Bool_t setInputVersion(Int_t run, Text_t* container, Int_t version, Int_t inputNumber); + Bool_t setRootOutputVersion(Int_t run, Text_t* container, Int_t version); + void setVersionsChanged(Bool_t f = kTRUE) { versionsChanged = f; } void resetInputVersions(void); void resetOutputVersions(void); void resetAllVersions(void); @@ -103,17 +102,17 @@ class FairRuntimeDb : public TObject void closeSecondInput(void); void closeOutput(void); void activateParIo(FairParIo*); - TList* getListOfContainers() {return containerList;} + TList* getListOfContainers() { return containerList; } void print(void); Int_t findOutputVersion(FairParSet*); private: FairRuntimeDb(const FairRuntimeDb& M); - FairRuntimeDb& operator= (const FairRuntimeDb&) {return *this;} + FairRuntimeDb& operator=(const FairRuntimeDb&) { return *this; } Bool_t initContainers(void); - ClassDef(FairRuntimeDb,0) // Class for runtime database + ClassDef(FairRuntimeDb, 0) // Class for runtime database }; -#endif /* !FAIRRUNTIMEDB_H */ +#endif /* !FAIRRUNTIMEDB_H */ diff --git a/parmq/ParameterMQServer.cxx b/parmq/ParameterMQServer.cxx index 2f2633a2f3..f8fe65d2cd 100644 --- a/parmq/ParameterMQServer.cxx +++ b/parmq/ParameterMQServer.cxx @@ -14,48 +14,43 @@ #include "ParameterMQServer.h" -#include "RootSerializer.h" -#include "FairRuntimeDb.h" #include "FairParAsciiFileIo.h" -#include "FairParRootFileIo.h" #include "FairParGenericSet.h" +#include "FairParRootFileIo.h" #include "FairRunIdGenerator.h" +#include "FairRuntimeDb.h" +#include "RootSerializer.h" #include - -#include #include - -#include // getenv +#include +#include // getenv using namespace std; -ParameterMQServer::ParameterMQServer() : - fRtdb(FairRuntimeDb::instance()), - fRunId(0), - fNofSimDevices(0), - fFirstInputName("first_input.root"), - fFirstInputType("ROOT"), - fSecondInputName(""), - fSecondInputType("ROOT"), - fOutputName(""), - fOutputType("ROOT"), - fRequestChannelName("data"), - fUpdateChannelName("") -{ -} +ParameterMQServer::ParameterMQServer() + : fRtdb(FairRuntimeDb::instance()) + , fRunId(0) + , fNofSimDevices(0) + , fFirstInputName("first_input.root") + , fFirstInputType("ROOT") + , fSecondInputName("") + , fSecondInputType("ROOT") + , fOutputName("") + , fOutputType("ROOT") + , fRequestChannelName("data") + , fUpdateChannelName("") +{} void ParameterMQServer::Init() { fRequestChannelName = fConfig->GetValue("channel-name"); fUpdateChannelName = fConfig->GetValue("update-channel-name"); - if (fRequestChannelName != "") - { + if (fRequestChannelName != "") { OnData(fRequestChannelName, &ParameterMQServer::ProcessRequest); } - if (fUpdateChannelName != "") - { + if (fUpdateChannelName != "") { OnData(fUpdateChannelName, &ParameterMQServer::ProcessUpdate); } } @@ -69,29 +64,22 @@ void ParameterMQServer::InitTask() fOutputName = fConfig->GetValue("output-name"); fOutputType = fConfig->GetValue("output-type"); - if (::getenv("DDS_SESSION_ID")) - { + if (::getenv("DDS_SESSION_ID")) { std::string ddsSessionId = ::getenv("DDS_SESSION_ID"); - if (fOutputName.length() > 5) - { + if (fOutputName.length() > 5) { ddsSessionId = "." + ddsSessionId + ".root"; fOutputName.replace(fOutputName.length() - 5, 5, ddsSessionId.c_str()); } } - if (fRtdb != 0) - { + if (fRtdb != 0) { // Set first input - if (fFirstInputName != "") - { - if (fFirstInputType == "ROOT") - { + if (fFirstInputName != "") { + if (fFirstInputType == "ROOT") { FairParRootFileIo* par1R = new FairParRootFileIo(); par1R->open(fFirstInputName.data(), "UPDATE"); fRtdb->setFirstInput(par1R); - } - else if (fFirstInputType == "ASCII") - { + } else if (fFirstInputType == "ASCII") { FairParAsciiFileIo* par1A = new FairParAsciiFileIo(); par1A->open(fFirstInputName.data(), "in"); fRtdb->setFirstInput(par1A); @@ -99,16 +87,12 @@ void ParameterMQServer::InitTask() } // Set second input - if (fSecondInputName != "") - { - if (fSecondInputType == "ROOT") - { + if (fSecondInputName != "") { + if (fSecondInputType == "ROOT") { FairParRootFileIo* par2R = new FairParRootFileIo(); par2R->open(fSecondInputName.data(), "UPDATE"); fRtdb->setSecondInput(par2R); - } - else if (fSecondInputType == "ASCII") - { + } else if (fSecondInputType == "ASCII") { FairParAsciiFileIo* par2A = new FairParAsciiFileIo(); par2A->open(fSecondInputName.data(), "in"); fRtdb->setSecondInput(par2A); @@ -116,12 +100,9 @@ void ParameterMQServer::InitTask() } // Set output - if (fUpdateChannelName == "") - { - if (fOutputName != "") - { - if (fOutputType == "ROOT") - { + if (fUpdateChannelName == "") { + if (fOutputName != "") { + if (fOutputType == "ROOT") { FairParRootFileIo* parOut = new FairParRootFileIo(kTRUE); parOut->open(fOutputName.data()); fRtdb->setOutput(parOut); @@ -149,34 +130,28 @@ bool ParameterMQServer::ProcessRequest(FairMQMessagePtr& req, int /*index*/) LOG(info) << "Retrieving parameter..."; // Check if the parameter name has changed to avoid getting same container repeatedly - if (newParameterName != parameterName) - { + if (newParameterName != parameterName) { parameterName = newParameterName; par = static_cast(fRtdb->getContainer(parameterName.c_str())); } fRtdb->initContainers(runId); LOG(info) << "Sending following parameter to the client:"; - if (par) - { + if (par) { par->print(); FairMQMessagePtr rep(NewMessage()); Serialize(*rep, par); - if (Send(rep, fRequestChannelName, 0) < 0) - { + if (Send(rep, fRequestChannelName, 0) < 0) { LOG(ERROR) << "failed sending reply"; return false; } - } - else - { + } else { LOG(ERROR) << "Parameter uninitialized! Sending empty message back"; // Send an empty message back to keep the REQ/REP cycle FairMQMessagePtr rep(NewMessage()); - if (Send(rep, fRequestChannelName, 0) < 0) - { + if (Send(rep, fRequestChannelName, 0) < 0) { LOG(ERROR) << "failed sending reply"; return false; } @@ -187,17 +162,16 @@ bool ParameterMQServer::ProcessRequest(FairMQMessagePtr& req, int /*index*/) bool ParameterMQServer::ProcessUpdate(FairMQMessagePtr& update, int /*index*/) { - gGeoManager = nullptr; // FairGeoParSet update deletes previous geometry because of resetting gGeoManager, so let's NULL it + gGeoManager = + nullptr; // FairGeoParSet update deletes previous geometry because of resetting gGeoManager, so let's NULL it std::string* text; LOG(info) << "got process update message with size = " << update->GetSize() << " !"; - if (update->GetSize() < 20) - { + if (update->GetSize() < 20) { std::string repString = string(static_cast(update->GetData()), update->GetSize()); LOG(info) << "Received string " << repString << " !"; - if (fNofSimDevices == 0) - { + if (fNofSimDevices == 0) { FairRunIdGenerator genid; fRunId = genid.generateId(); } @@ -205,35 +179,28 @@ bool ParameterMQServer::ProcessUpdate(FairMQMessagePtr& update, int /*index*/) text = new string(messageToSend); fNofSimDevices += 1; LOG(info) << "Replying with \"" << messageToSend << "\""; - } - else - { + } else { // get the run id coded in the description of FairParSet FairParGenericSet* newPar = nullptr; Deserialize(*update, newPar); std::string parDescr = std::string(newPar->getDescription()); uint runId = 0; - if (parDescr.find("RUNID") != std::string::npos) - { + if (parDescr.find("RUNID") != std::string::npos) { parDescr.erase(0, parDescr.find("RUNID") + 5); runId = atoi(parDescr.data()); - if (parDescr.find("RUNID") != std::string::npos) - { + if (parDescr.find("RUNID") != std::string::npos) { parDescr.erase(0, parDescr.find("RUNID") + 5); } } fRtdb->initContainers(runId); - newPar->setChanged(true); // trigger writing to file - newPar->setStatic(true); // to get rid of error + newPar->setChanged(true); // trigger writing to file + newPar->setStatic(true); // to get rid of error newPar->Print(); - if (fRtdb->addContainer(newPar)) - { + if (fRtdb->addContainer(newPar)) { text = new string("SUCCESS"); - } - else - { + } else { text = new string("FAIL"); } @@ -245,19 +212,16 @@ bool ParameterMQServer::ProcessUpdate(FairMQMessagePtr& update, int /*index*/) fRtdb->closeOutput(); } - FairMQMessagePtr msg(NewMessage(const_cast(text->c_str()), - text->length(), - [](void* /*data*/, void* object) { delete static_cast(object); }, - text)); + FairMQMessagePtr msg(NewMessage( + const_cast(text->c_str()), + text->length(), + [](void* /*data*/, void* object) { delete static_cast(object); }, + text)); - if (Send(msg, fUpdateChannelName) < 0) - { + if (Send(msg, fUpdateChannelName) < 0) { return false; } return true; } -ParameterMQServer::~ParameterMQServer() -{ - delete fRtdb; -} +ParameterMQServer::~ParameterMQServer() { delete fRtdb; } diff --git a/parmq/ParameterMQServer.h b/parmq/ParameterMQServer.h index 99589a14b9..0a2ac6541e 100644 --- a/parmq/ParameterMQServer.h +++ b/parmq/ParameterMQServer.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /** @@ -15,9 +15,8 @@ #ifndef PARAMETERMQSERVER_H_ #define PARAMETERMQSERVER_H_ -#include - #include +#include class FairRuntimeDb; @@ -33,8 +32,8 @@ class ParameterMQServer : public FairMQDevice virtual void InitTask(); virtual void Init(); - bool ProcessRequest(FairMQMessagePtr&, int); - bool ProcessUpdate (FairMQMessagePtr&, int); + bool ProcessRequest(FairMQMessagePtr&, int); + bool ProcessUpdate(FairMQMessagePtr&, int); void SetFirstInputName(const std::string& firstInputName) { fFirstInputName = firstInputName; } std::string GetFirstInputName() { return fFirstInputName; } @@ -57,8 +56,8 @@ class ParameterMQServer : public FairMQDevice private: FairRuntimeDb* fRtdb; - int fRunId; - int fNofSimDevices; + int fRunId; + int fNofSimDevices; std::string fFirstInputName; std::string fFirstInputType; diff --git a/parmq/runParameterMQServer.cxx b/parmq/runParameterMQServer.cxx index 4ff00ebdd4..91acf5fb04 100644 --- a/parmq/runParameterMQServer.cxx +++ b/parmq/runParameterMQServer.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /** @@ -12,8 +12,8 @@ * @author D. Klein, A. Rybalchenko */ -#include "runFairMQDevice.h" #include "ParameterMQServer.h" +#include "runFairMQDevice.h" #include @@ -21,18 +21,17 @@ namespace bpo = boost::program_options; void addCustomOptions(bpo::options_description& options) { + // clang-format off options.add_options() - ("first-input-name", bpo::value()->default_value(""), "First input file name") - ("first-input-type", bpo::value()->default_value("ROOT"), "First input file type (ROOT/ASCII)") - ("second-input-name", bpo::value()->default_value(""), "Second input file name") - ("second-input-type", bpo::value()->default_value("ROOT"), "Second input file type (ROOT/ASCII)") - ("output-name", bpo::value()->default_value(""), "Output file name") - ("output-type", bpo::value()->default_value("ROOT"), "Output file type") - ("channel-name", bpo::value()->default_value(""), "Output channel name") - ("update-channel-name", bpo::value()->default_value(""), "Update channel name"); + ("first-input-name", bpo::value()->default_value(""), "First input file name") + ("first-input-type", bpo::value()->default_value("ROOT"), "First input file type (ROOT/ASCII)") + ("second-input-name", bpo::value()->default_value(""), "Second input file name") + ("second-input-type", bpo::value()->default_value("ROOT"), "Second input file type (ROOT/ASCII)") + ("output-name", bpo::value()->default_value(""), "Output file name") + ("output-type", bpo::value()->default_value("ROOT"), "Output file type") + ("channel-name", bpo::value()->default_value(""), "Output channel name") + ("update-channel-name", bpo::value()->default_value(""), "Update channel name"); + // clang-format on } -FairMQDevicePtr getDevice(const FairMQProgOptions& /*config*/) -{ - return new ParameterMQServer(); -} +FairMQDevicePtr getDevice(const FairMQProgOptions& /*config*/) { return new ParameterMQServer(); } diff --git a/scripts/Read_Memory_File.C b/scripts/Read_Memory_File.C index 49ccce7cb0..2355159a9e 100644 --- a/scripts/Read_Memory_File.C +++ b/scripts/Read_Memory_File.C @@ -1,67 +1,65 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "Riostream.h" -void Read_Memory_File(TString inputFile, Int_t Interval) { -// Read data from the memeory_consumption_.txt file -// and create a root file with an ntuple. -//Author: Florian Uhlig - +void Read_Memory_File(TString inputFile, Int_t Interval) +{ + // Read data from the memeory_consumption_.txt file + // and create a root file with an ntuple. + // Author: Florian Uhlig -// This file has one colum with the time and 10 colums with the data -// The time is the real time which has to be converted into the time -// difference between the actual and the first measurement. -// To make things simple for the begining the time interval is given -// as parameter and all new measurements have time=#measurement*Interval + // This file has one colum with the time and 10 colums with the data + // The time is the real time which has to be converted into the time + // difference between the actual and the first measurement. + // To make things simple for the begining the time interval is given + // as parameter and all new measurements have time=#measurement*Interval - ifstream in; - in.open(inputFile.Data()); + ifstream in; + in.open(inputFile.Data()); - Int_t vmPeak,vmSize,vmLck,vmHWM,vmRSS,vmData,vmStk,vmExe,vmLib,vmPTE; - Int_t time, timeZero, filesize; - Float_t cpu; - TString dummy[14]; - Int_t nlines = 0; - Bool_t firstTime=kTRUE; + Int_t vmPeak, vmSize, vmLck, vmHWM, vmRSS, vmData, vmStk, vmExe, vmLib, vmPTE; + Int_t time, timeZero, filesize; + Float_t cpu; + TString dummy[14]; + Int_t nlines = 0; + Bool_t firstTime = kTRUE; - TString outputFile(inputFile); - outputFile.ReplaceAll(".txt",".root"); - TFile *f = TFile::Open(outputFile,"RECREATE"); - TNtuple *ntuple = new TNtuple("ntuple","data from ascii file", - "time:vmPeak:vmSize:vmLck:vmHWM:vmRSS:vmData:vmStk:vmExe:vmLib:vmPTE:filesize:cpu"); + TString outputFile(inputFile); + outputFile.ReplaceAll(".txt", ".root"); + TFile *f = TFile::Open(outputFile, "RECREATE"); + TNtuple *ntuple = new TNtuple("ntuple", + "data from ascii file", + "time:vmPeak:vmSize:vmLck:vmHWM:vmRSS:vmData:vmStk:vmExe:vmLib:vmPTE:filesize:cpu"); - // Read and skip the first colum which contains only the header - in >> dummy[0] >> dummy[1] >> dummy[2] >> dummy[3] >> dummy[4] - >> dummy[5] >> dummy[6] >> dummy[7] >> dummy[8] >> dummy[9] - >> dummy[10] >> dummy[11] >> dummy[12] - >> dummy[13]; + // Read and skip the first colum which contains only the header + in >> dummy[0] >> dummy[1] >> dummy[2] >> dummy[3] >> dummy[4] >> dummy[5] >> dummy[6] >> dummy[7] >> dummy[8] + >> dummy[9] >> dummy[10] >> dummy[11] >> dummy[12] >> dummy[13]; - while (1) { - in >> dummy[0] >> time >> vmPeak >> dummy[1] >> vmSize >> dummy[2] - >> vmLck >> dummy[3] >> vmHWM >> dummy[4] >> vmRSS >> dummy[5] - >> vmData >> dummy[6] >> vmStk >> dummy[7] >> vmExe >> dummy[8] - >> vmLib >> dummy[9] >> vmPTE >> dummy[10] >> filesize - >> cpu; + while (1) { + in >> dummy[0] >> time >> vmPeak >> dummy[1] >> vmSize >> dummy[2] >> vmLck >> dummy[3] >> vmHWM >> dummy[4] + >> vmRSS >> dummy[5] >> vmData >> dummy[6] >> vmStk >> dummy[7] >> vmExe >> dummy[8] >> vmLib >> dummy[9] + >> vmPTE >> dummy[10] >> filesize >> cpu; - if (firstTime) { - timeZero=time; - firstTime=kFALSE; - } - time-=timeZero; - // filesize in MB - filesize/=1024; -// time=nlines*Interval; - if (!in.good()) break; - ntuple->Fill(time,vmPeak,vmSize,vmLck,vmHWM,vmRSS,vmData,vmStk,vmExe,vmLib,vmPTE,filesize,cpu); - nlines++; - } - printf(" found %d measurements\n",nlines); + if (firstTime) { + timeZero = time; + firstTime = kFALSE; + } + time -= timeZero; + // filesize in MB + filesize /= 1024; + // time=nlines*Interval; + if (!in.good()) + break; + ntuple->Fill(time, vmPeak, vmSize, vmLck, vmHWM, vmRSS, vmData, vmStk, vmExe, vmLib, vmPTE, filesize, cpu); + nlines++; + } + printf(" found %d measurements\n", nlines); - in.close(); + in.close(); - f->Write(); + f->Write(); } diff --git a/templates/NewDetector_root_containers/NewDetector.cxx b/templates/NewDetector_root_containers/NewDetector.cxx index 2cd2630edf..e667e2cef0 100644 --- a/templates/NewDetector_root_containers/NewDetector.cxx +++ b/templates/NewDetector_root_containers/NewDetector.cxx @@ -1,272 +1,260 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "NewDetector.h" -#include "NewDetectorPoint.h" -#include "NewDetectorGeo.h" -#include "NewDetectorGeoPar.h" - -#include "FairVolume.h" -#include "FairGeoVolume.h" +#include "FairGeoInterface.h" +#include "FairGeoLoader.h" #include "FairGeoNode.h" +#include "FairGeoVolume.h" #include "FairRootManager.h" -#include "FairGeoLoader.h" -#include "FairGeoInterface.h" #include "FairRun.h" #include "FairRuntimeDb.h" +#include "FairVolume.h" #include "MyProjDetectorList.h" #include "MyProjStack.h" +#include "NewDetectorGeo.h" +#include "NewDetectorGeoPar.h" +#include "NewDetectorPoint.h" #include -#include -#include #include #include -#include +#include #include #include - +#include +#include #include using std::cout; using std::endl; NewDetector::NewDetector() - : FairDetector("NewDetector", kTRUE, kNewDetector), - fTrackID(-1), - fVolumeID(-1), - fPos(), - fMom(), - fTime(-1.), - fLength(-1.), - fELoss(-1), - fNewDetectorPointCollection(new TClonesArray("NewDetectorPoint")) -{ -} + : FairDetector("NewDetector", kTRUE, kNewDetector) + , fTrackID(-1) + , fVolumeID(-1) + , fPos() + , fMom() + , fTime(-1.) + , fLength(-1.) + , fELoss(-1) + , fNewDetectorPointCollection(new TClonesArray("NewDetectorPoint")) +{} NewDetector::NewDetector(const char* name, Bool_t active) - : FairDetector(name, active, kNewDetector), - fTrackID(-1), - fVolumeID(-1), - fPos(), - fMom(), - fTime(-1.), - fLength(-1.), - fELoss(-1), - fNewDetectorPointCollection(new TClonesArray("NewDetectorPoint")) -{ -} + : FairDetector(name, active, kNewDetector) + , fTrackID(-1) + , fVolumeID(-1) + , fPos() + , fMom() + , fTime(-1.) + , fLength(-1.) + , fELoss(-1) + , fNewDetectorPointCollection(new TClonesArray("NewDetectorPoint")) +{} NewDetector::NewDetector(const NewDetector& right) - : FairDetector(right), - fTrackID(-1), - fVolumeID(-1), - fPos(), - fMom(), - fTime(-1.), - fLength(-1.), - fELoss(-1), - fNewDetectorPointCollection(new TClonesArray("NewDetectorPoint")) -{ -} + : FairDetector(right) + , fTrackID(-1) + , fVolumeID(-1) + , fPos() + , fMom() + , fTime(-1.) + , fLength(-1.) + , fELoss(-1) + , fNewDetectorPointCollection(new TClonesArray("NewDetectorPoint")) +{} NewDetector::~NewDetector() { - if (fNewDetectorPointCollection) { - fNewDetectorPointCollection->Delete(); - delete fNewDetectorPointCollection; - } + if (fNewDetectorPointCollection) { + fNewDetectorPointCollection->Delete(); + delete fNewDetectorPointCollection; + } } void NewDetector::Initialize() { - /** - * WORKAROUND needed for Geant4 in MT mode - * Call AddSensitiveVolume for sensitive volumes in order to fill - * thread-local FairModule::svList. - */ - DefineSensitiveVolumes(); - - FairDetector::Initialize(); - FairRuntimeDb* rtdb= FairRun::Instance()->GetRuntimeDb(); - NewDetectorGeoPar* par=(NewDetectorGeoPar*)(rtdb->getContainer("NewDetectorGeoPar")); + /** + * WORKAROUND needed for Geant4 in MT mode + * Call AddSensitiveVolume for sensitive volumes in order to fill + * thread-local FairModule::svList. + */ + DefineSensitiveVolumes(); + + FairDetector::Initialize(); + FairRuntimeDb* rtdb = FairRun::Instance()->GetRuntimeDb(); + NewDetectorGeoPar* par = (NewDetectorGeoPar*)(rtdb->getContainer("NewDetectorGeoPar")); } -Bool_t NewDetector::ProcessHits(FairVolume* vol) +Bool_t NewDetector::ProcessHits(FairVolume* vol) { - /** This method is called from the MC stepping */ - - //Set parameters at entrance of volume. Reset ELoss. - if ( TVirtualMC::GetMC()->IsTrackEntering() ) { - fELoss = 0.; - fTime = TVirtualMC::GetMC()->TrackTime() * 1.0e09; - fLength = TVirtualMC::GetMC()->TrackLength(); - TVirtualMC::GetMC()->TrackPosition(fPos); - TVirtualMC::GetMC()->TrackMomentum(fMom); - } - - // Sum energy loss for all steps in the active volume - fELoss += TVirtualMC::GetMC()->Edep(); - - // Create NewDetectorPoint at exit of active volume - if ( TVirtualMC::GetMC()->IsTrackExiting() || - TVirtualMC::GetMC()->IsTrackStop() || - TVirtualMC::GetMC()->IsTrackDisappeared() ) { - fTrackID = TVirtualMC::GetMC()->GetStack()->GetCurrentTrackNumber(); - fVolumeID = vol->getMCid(); - if (fELoss == 0. ) { return kFALSE; } - AddHit(fTrackID, fVolumeID, TVector3(fPos.X(), fPos.Y(), fPos.Z()), - TVector3(fMom.Px(), fMom.Py(), fMom.Pz()), fTime, fLength, - fELoss); - - // Increment number of NewDetector det points in TParticle - MyProjStack* stack = (MyProjStack*) TVirtualMC::GetMC()->GetStack(); - stack->AddPoint(kNewDetector); - } - - return kTRUE; + /** This method is called from the MC stepping */ + + // Set parameters at entrance of volume. Reset ELoss. + if (TVirtualMC::GetMC()->IsTrackEntering()) { + fELoss = 0.; + fTime = TVirtualMC::GetMC()->TrackTime() * 1.0e09; + fLength = TVirtualMC::GetMC()->TrackLength(); + TVirtualMC::GetMC()->TrackPosition(fPos); + TVirtualMC::GetMC()->TrackMomentum(fMom); + } + + // Sum energy loss for all steps in the active volume + fELoss += TVirtualMC::GetMC()->Edep(); + + // Create NewDetectorPoint at exit of active volume + if (TVirtualMC::GetMC()->IsTrackExiting() || TVirtualMC::GetMC()->IsTrackStop() + || TVirtualMC::GetMC()->IsTrackDisappeared()) { + fTrackID = TVirtualMC::GetMC()->GetStack()->GetCurrentTrackNumber(); + fVolumeID = vol->getMCid(); + if (fELoss == 0.) { + return kFALSE; + } + AddHit(fTrackID, + fVolumeID, + TVector3(fPos.X(), fPos.Y(), fPos.Z()), + TVector3(fMom.Px(), fMom.Py(), fMom.Pz()), + fTime, + fLength, + fELoss); + + // Increment number of NewDetector det points in TParticle + MyProjStack* stack = (MyProjStack*)TVirtualMC::GetMC()->GetStack(); + stack->AddPoint(kNewDetector); + } + + return kTRUE; } void NewDetector::EndOfEvent() { - LOG(info) << "NewDetector: " << fNewDetectorPointCollection->GetEntriesFast() - << " points registered in this event"; - - fNewDetectorPointCollection->Clear(); + LOG(info) << "NewDetector: " << fNewDetectorPointCollection->GetEntriesFast() << " points registered in this event"; + fNewDetectorPointCollection->Clear(); } - - void NewDetector::Register() { - /** This will create a branch in the output tree called + /** This will create a branch in the output tree called NewDetectorPoint, setting the last parameter to kFALSE means: this collection will not be written to the file, it will exist only during the simulation. */ - if ( ! gMC->IsMT() ) { - FairRootManager::Instance()->Register("NewDetectorPoint", "NewDetector", - fNewDetectorPointCollection, kTRUE); - } else { - FairRootManager::Instance()->RegisterAny("NewDetectorPoint", - fNewDetectorPointCollection, kTRUE); - } - + if (!gMC->IsMT()) { + FairRootManager::Instance()->Register("NewDetectorPoint", "NewDetector", fNewDetectorPointCollection, kTRUE); + } else { + FairRootManager::Instance()->RegisterAny("NewDetectorPoint", fNewDetectorPointCollection, kTRUE); + } } - TClonesArray* NewDetector::GetCollection(Int_t iColl) const { - if (iColl == 0) { return fNewDetectorPointCollection; } - else { return NULL; } + if (iColl == 0) { + return fNewDetectorPointCollection; + } else { + return NULL; + } } -void NewDetector::Reset() -{ - fNewDetectorPointCollection->Clear(); -} +void NewDetector::Reset() { fNewDetectorPointCollection->Clear(); } void NewDetector::ConstructGeometry() { - TGeoVolume *top=gGeoManager->GetTopVolume(); - TGeoMedium *Si =gGeoManager->GetMedium("Si"); - TGeoMedium *Carbon = gGeoManager->GetMedium("C"); + TGeoVolume* top = gGeoManager->GetTopVolume(); + TGeoMedium* Si = gGeoManager->GetMedium("Si"); + TGeoMedium* Carbon = gGeoManager->GetMedium("C"); - if(Si==0){ - TGeoMaterial *matSi = new TGeoMaterial("Si", 28.0855, 14, 2.33); - Si = new TGeoMedium("Si", 2, matSi); + if (Si == 0) { + TGeoMaterial* matSi = new TGeoMaterial("Si", 28.0855, 14, 2.33); + Si = new TGeoMedium("Si", 2, matSi); } - if(Carbon==0){ - TGeoMaterial *matCarbon = new TGeoMaterial("C", 12.011, 6.0, 2.265); - Carbon = new TGeoMedium("C", 3, matCarbon); + if (Carbon == 0) { + TGeoMaterial* matCarbon = new TGeoMaterial("C", 12.011, 6.0, 2.265); + Carbon = new TGeoMedium("C", 3, matCarbon); } - - TGeoVolume *det1= gGeoManager->MakeTubs("Det1",Si,5,80,0.1,0,360); + TGeoVolume* det1 = gGeoManager->MakeTubs("Det1", Si, 5, 80, 0.1, 0, 360); TGeoRotation r1; - r1.SetAngles(0,0,0); + r1.SetAngles(0, 0, 0); TGeoTranslation t1(0, 0, 0); TGeoCombiTrans c1(t1, r1); - TGeoHMatrix *h1 = new TGeoHMatrix(c1); - top->AddNode(det1,1,h1); + TGeoHMatrix* h1 = new TGeoHMatrix(c1); + top->AddNode(det1, 1, h1); det1->SetLineColor(kGreen); AddSensitiveVolume(det1); - TGeoVolume *passive1= gGeoManager->MakeTubs("Pass1",Si,5,120,10,0,360); + TGeoVolume* passive1 = gGeoManager->MakeTubs("Pass1", Si, 5, 120, 10, 0, 360); TGeoRotation rp1; - rp1.SetAngles(0,0,0); + rp1.SetAngles(0, 0, 0); TGeoTranslation tp1(0, 0, 20); TGeoCombiTrans cp1(tp1, rp1); - TGeoHMatrix *hp1 = new TGeoHMatrix(cp1); - top->AddNode(passive1,1,hp1); + TGeoHMatrix* hp1 = new TGeoHMatrix(cp1); + top->AddNode(passive1, 1, hp1); passive1->SetLineColor(kRed); - - - TGeoVolume *det2= gGeoManager->MakeTubs("Det2",Si,5,150,0.1,0,360); + TGeoVolume* det2 = gGeoManager->MakeTubs("Det2", Si, 5, 150, 0.1, 0, 360); TGeoRotation r2; - r2.SetAngles(0,0,0); + r2.SetAngles(0, 0, 0); TGeoTranslation t2(0, 0, 70); TGeoCombiTrans c2(t2, r2); - TGeoHMatrix *h2 = new TGeoHMatrix(c2); - top->AddNode(det2,1,h2); + TGeoHMatrix* h2 = new TGeoHMatrix(c2); + top->AddNode(det2, 1, h2); det2->SetLineColor(kGreen); AddSensitiveVolume(det2); - TGeoVolume *det3= gGeoManager->MakeTubs("Det3",Si,5,150,0.1,0,360); + TGeoVolume* det3 = gGeoManager->MakeTubs("Det3", Si, 5, 150, 0.1, 0, 360); TGeoRotation r3; - r3.SetAngles(0,0,0); + r3.SetAngles(0, 0, 0); TGeoTranslation t3(0, 0, 150); TGeoCombiTrans c3(t3, r3); - TGeoHMatrix *h3 = new TGeoHMatrix(c3); - top->AddNode(det3,1,h3); + TGeoHMatrix* h3 = new TGeoHMatrix(c3); + top->AddNode(det3, 1, h3); det3->SetLineColor(kGreen); AddSensitiveVolume(det3); } -NewDetectorPoint* NewDetector::AddHit(Int_t trackID, Int_t detID, - TVector3 pos, TVector3 mom, - Double_t time, Double_t length, +NewDetectorPoint* NewDetector::AddHit(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t time, + Double_t length, Double_t eLoss) { - TClonesArray& clref = *fNewDetectorPointCollection; - Int_t size = clref.GetEntriesFast(); - return new(clref[size]) NewDetectorPoint(trackID, detID, pos, mom, - time, length, eLoss); + TClonesArray& clref = *fNewDetectorPointCollection; + Int_t size = clref.GetEntriesFast(); + return new (clref[size]) NewDetectorPoint(trackID, detID, pos, mom, time, length, eLoss); } -FairModule* NewDetector::CloneModule() const -{ - return new NewDetector(*this); -} +FairModule* NewDetector::CloneModule() const { return new NewDetector(*this); } void NewDetector::DefineSensitiveVolumes() { - TObjArray* volumes = gGeoManager->GetListOfVolumes(); - TIter next(volumes); - TGeoVolume* volume; - while ( ( volume = static_cast(next()) ) ) { - if ( IsSensitive(volume->GetName()) ) { - LOG(debug2)<<"Sensitive Volume "<< volume->GetName(); - AddSensitiveVolume(volume); + TObjArray* volumes = gGeoManager->GetListOfVolumes(); + TIter next(volumes); + TGeoVolume* volume; + while ((volume = static_cast(next()))) { + if (IsSensitive(volume->GetName())) { + LOG(debug2) << "Sensitive Volume " << volume->GetName(); + AddSensitiveVolume(volume); + } } - } } Bool_t NewDetector::IsSensitive(const std::string& name) { - if ( name.find("Det") != std::string::npos ) { + if (name.find("Det") != std::string::npos) { return kTRUE; } return kFALSE; } -ClassImp(NewDetector) +ClassImp(NewDetector); diff --git a/templates/NewDetector_root_containers/NewDetector.h b/templates/NewDetector_root_containers/NewDetector.h index a1265906ff..b1466af849 100644 --- a/templates/NewDetector_root_containers/NewDetector.h +++ b/templates/NewDetector_root_containers/NewDetector.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef NEWDETECTOR_H @@ -10,22 +10,21 @@ #include "FairDetector.h" -#include #include +#include class NewDetectorPoint; class FairVolume; class TClonesArray; -class NewDetector: public FairDetector +class NewDetector : public FairDetector { public: - /** Name : Detector Name * Active: kTRUE for active detectors (ProcessHits() will be called) * kFALSE for inactive detectors - */ + */ NewDetector(const char* Name, Bool_t Active); /** default constructor */ @@ -35,75 +34,70 @@ class NewDetector: public FairDetector virtual ~NewDetector(); /** 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(); - - /** This method is an example of how to add your own point * of type NewDetectorPoint to the clones array - */ - NewDetectorPoint* AddHit(Int_t trackID, Int_t detID, - TVector3 pos, TVector3 mom, - Double_t time, Double_t length, - Double_t eLoss); + */ + NewDetectorPoint* + AddHit(Int_t trackID, Int_t detID, TVector3 pos, TVector3 mom, Double_t time, Double_t length, Double_t eLoss); /** The following methods can be implemented if you need to make * any optional action in your detector during the transport. - */ + */ - 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 SetSpecialPhysicsCuts() { ; } + virtual void EndOfEvent(); + virtual void FinishPrimary() { ; } + virtual void FinishRun() { ; } + virtual void BeginPrimary() { ; } + virtual void PostTrack() { ; } + virtual void PreTrack() { ; } + virtual void BeginEvent() { ; } virtual FairModule* CloneModule() const; virtual Bool_t IsSensitive(const std::string& name); 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* fNewDetectorPointCollection; //! + TClonesArray* fNewDetectorPointCollection; //! NewDetector(const NewDetector&); NewDetector& operator=(const NewDetector&); void DefineSensitiveVolumes(); - ClassDef(NewDetector,2) + ClassDef(NewDetector, 2) }; -#endif //NEWDETECTOR_H +#endif // NEWDETECTOR_H diff --git a/templates/NewDetector_root_containers/NewDetectorContFact.cxx b/templates/NewDetector_root_containers/NewDetectorContFact.cxx index 428dbcb088..9466b6c6d9 100644 --- a/templates/NewDetector_root_containers/NewDetectorContFact.cxx +++ b/templates/NewDetector_root_containers/NewDetectorContFact.cxx @@ -1,59 +1,55 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "NewDetectorContFact.h" -#include "NewDetectorGeoPar.h" - #include "FairRuntimeDb.h" +#include "NewDetectorGeoPar.h" #include -ClassImp(NewDetectorContFact) +ClassImp(NewDetectorContFact); static NewDetectorContFact gNewDetectorContFact; NewDetectorContFact::NewDetectorContFact() - : FairContFact() + : FairContFact() { - /** Constructor (called when the library is loaded) */ - fName="NewDetectorContFact"; - fTitle="Factory for parameter containers in libNewDetector"; - setAllContainers(); - FairRuntimeDb::instance()->addContFactory(this); + /** Constructor (called when the library is loaded) */ + fName = "NewDetectorContFact"; + fTitle = "Factory for parameter containers in libNewDetector"; + setAllContainers(); + FairRuntimeDb::instance()->addContFactory(this); } void NewDetectorContFact::setAllContainers() { - /** Creates the Container objects with all accepted + /** Creates the Container objects with all accepted contexts and adds them to the list of containers for the NewDetector library. */ - FairContainer* p= new FairContainer("NewDetectorGeoPar", - "NewDetector Geometry Parameters", - "TestDefaultContext"); - p->addContext("TestNonDefaultContext"); + FairContainer* p = new FairContainer("NewDetectorGeoPar", "NewDetector Geometry Parameters", "TestDefaultContext"); + p->addContext("TestNonDefaultContext"); - containers->Add(p); + containers->Add(p); } FairParSet* NewDetectorContFact::createContainer(FairContainer* c) { - /** Calls the constructor of the corresponding parameter container. + /** 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,"NewDetectorGeoPar")==0) { - p=new NewDetectorGeoPar(c->getConcatName().Data(), - c->GetTitle(),c->getContext()); - } - return p; + const char* name = c->GetName(); + FairParSet* p = NULL; + if (strcmp(name, "NewDetectorGeoPar") == 0) { + p = new NewDetectorGeoPar(c->getConcatName().Data(), c->GetTitle(), c->getContext()); + } + return p; } diff --git a/templates/NewDetector_root_containers/NewDetectorContFact.h b/templates/NewDetector_root_containers/NewDetectorContFact.h index f5e4958971..e4c70dca22 100644 --- a/templates/NewDetector_root_containers/NewDetectorContFact.h +++ b/templates/NewDetector_root_containers/NewDetectorContFact.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef NEWDETECTORCONTFACT_H @@ -16,11 +16,12 @@ class NewDetectorContFact : public FairContFact { private: void setAllContainers(); + public: NewDetectorContFact(); ~NewDetectorContFact() {} FairParSet* createContainer(FairContainer*); - ClassDef( NewDetectorContFact,0) // Factory for all NewDetector parameter containers + ClassDef(NewDetectorContFact, 0) // Factory for all NewDetector parameter containers }; #endif diff --git a/templates/NewDetector_root_containers/NewDetectorGeo.cxx b/templates/NewDetector_root_containers/NewDetectorGeo.cxx index 51d77d9fed..8498754bcd 100644 --- a/templates/NewDetector_root_containers/NewDetectorGeo.cxx +++ b/templates/NewDetector_root_containers/NewDetectorGeo.cxx @@ -1,43 +1,44 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "NewDetectorGeo.h" + #include "FairGeoNode.h" -ClassImp(NewDetectorGeo) +ClassImp(NewDetectorGeo); // ----- Default constructor ------------------------------------------- NewDetectorGeo::NewDetectorGeo() - : FairGeoSet() + : FairGeoSet() { - // Constructor - // fName has to be the name used in the geometry for all volumes. - // If there is a mismatch the geometry cannot be build. - fName="newdetector"; - maxSectors=0; - maxModules=10; + // Constructor + // fName has to be the name used in the geometry for all volumes. + // If there is a mismatch the geometry cannot be build. + fName = "newdetector"; + maxSectors = 0; + maxModules = 10; } // ------------------------------------------------------------------------- const char* NewDetectorGeo::getModuleName(Int_t m) { - /** Returns the module name of NewDetector number m + /** Returns the module name of NewDetector number m Setting NewDetector here means that all modules names in the ASCII file should start with NewDetector otherwise they will not be constructed */ - sprintf(modName,"NewDetector%i",m+1); - return modName; + sprintf(modName, "NewDetector%i", m + 1); + return modName; } const char* NewDetectorGeo::getEleName(Int_t m) { - /** Returns the element name of Det number m */ - sprintf(eleName,"NewDetector%i",m+1); - return eleName; + /** Returns the element name of Det number m */ + sprintf(eleName, "NewDetector%i", m + 1); + return eleName; } diff --git a/templates/NewDetector_root_containers/NewDetectorGeo.h b/templates/NewDetector_root_containers/NewDetectorGeo.h index 80b9a67a71..6dd4ab5452 100644 --- a/templates/NewDetector_root_containers/NewDetectorGeo.h +++ b/templates/NewDetector_root_containers/NewDetectorGeo.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef NEWDETECTORGEO_H @@ -10,29 +10,29 @@ #include "FairGeoSet.h" -class NewDetectorGeo : public FairGeoSet +class NewDetectorGeo : public FairGeoSet { protected: - char modName[20]; // name of module - char eleName[20]; // substring for elements in module + char modName[20]; // name of module + char eleName[20]; // substring for elements in module public: NewDetectorGeo(); ~NewDetectorGeo() {} const char* getModuleName(Int_t); const char* getEleName(Int_t); inline Int_t getModNumInMod(const TString&); - ClassDef(NewDetectorGeo,1) + ClassDef(NewDetectorGeo, 1) }; inline Int_t NewDetectorGeo::getModNumInMod(const TString& name) { - /** returns the module index from module name + /** returns the module index from module name ?? in name[??] has to be the length of the detector name in the .geo file. For example if all nodes in this file starts with newdetector ?? has to be 11. */ - return (Int_t)(name[11]-'0')-1; // + return (Int_t)(name[11] - '0') - 1; // } #endif diff --git a/templates/NewDetector_root_containers/NewDetectorGeoPar.cxx b/templates/NewDetector_root_containers/NewDetectorGeoPar.cxx index 96674a51b3..a40fd67e7f 100644 --- a/templates/NewDetector_root_containers/NewDetectorGeoPar.cxx +++ b/templates/NewDetector_root_containers/NewDetectorGeoPar.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "NewDetectorGeoPar.h" @@ -10,41 +10,43 @@ #include "FairParamList.h" #include - #include -ClassImp(NewDetectorGeoPar) +ClassImp(NewDetectorGeoPar); -NewDetectorGeoPar ::NewDetectorGeoPar(const char* name, - const char* title, - const char* context) - : FairParGenericSet(name,title,context), - fGeoSensNodes(new TObjArray()), - fGeoPassNodes(new TObjArray()) -{ -} +NewDetectorGeoPar ::NewDetectorGeoPar(const char* name, const char* title, const char* context) + : FairParGenericSet(name, title, context) + , fGeoSensNodes(new TObjArray()) + , fGeoPassNodes(new TObjArray()) +{} -NewDetectorGeoPar::~NewDetectorGeoPar(void) -{ -} +NewDetectorGeoPar::~NewDetectorGeoPar(void) {} void NewDetectorGeoPar::clear(void) { - delete fGeoSensNodes; - delete fGeoPassNodes; + delete fGeoSensNodes; + delete fGeoPassNodes; } void NewDetectorGeoPar::putParams(FairParamList* l) { - if (!l) { return; } - l->addObject("FairGeoNodes Sensitive List", fGeoSensNodes); - l->addObject("FairGeoNodes Passive List", fGeoPassNodes); + if (!l) { + return; + } + l->addObject("FairGeoNodes Sensitive List", fGeoSensNodes); + l->addObject("FairGeoNodes Passive List", fGeoPassNodes); } Bool_t NewDetectorGeoPar::getParams(FairParamList* l) { - if (!l) { return kFALSE; } - if (!l->fillObject("FairGeoNodes Sensitive List", fGeoSensNodes)) { return kFALSE; } - if (!l->fillObject("FairGeoNodes Passive List", fGeoPassNodes)) { return kFALSE; } - return kTRUE; + if (!l) { + return kFALSE; + } + if (!l->fillObject("FairGeoNodes Sensitive List", fGeoSensNodes)) { + return kFALSE; + } + if (!l->fillObject("FairGeoNodes Passive List", fGeoPassNodes)) { + return kFALSE; + } + return kTRUE; } diff --git a/templates/NewDetector_root_containers/NewDetectorGeoPar.h b/templates/NewDetector_root_containers/NewDetectorGeoPar.h index 96997079c9..b689979309 100644 --- a/templates/NewDetector_root_containers/NewDetectorGeoPar.h +++ b/templates/NewDetector_root_containers/NewDetectorGeoPar.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef NEWDETECTORGEOPAR_H @@ -13,31 +13,30 @@ class TObjArray; class FairParamList; -class NewDetectorGeoPar : public FairParGenericSet +class NewDetectorGeoPar : public FairParGenericSet { public: - /** List of FairGeoNodes for sensitive volumes */ - TObjArray* fGeoSensNodes; + TObjArray* fGeoSensNodes; /** List of FairGeoNodes for sensitive volumes */ - TObjArray* fGeoPassNodes; + TObjArray* fGeoPassNodes; - NewDetectorGeoPar(const char* name="NewDetectorGeoPar", - const char* title="NewDetector Geometry Parameters", - const char* context="TestDefaultContext"); + NewDetectorGeoPar(const char* name = "NewDetectorGeoPar", + const char* title = "NewDetector Geometry Parameters", + const char* context = "TestDefaultContext"); ~NewDetectorGeoPar(void); void clear(void); void putParams(FairParamList*); Bool_t getParams(FairParamList*); - TObjArray* GetGeoSensitiveNodes() {return fGeoSensNodes;} - TObjArray* GetGeoPassiveNodes() {return fGeoPassNodes;} + TObjArray* GetGeoSensitiveNodes() { return fGeoSensNodes; } + TObjArray* GetGeoPassiveNodes() { return fGeoPassNodes; } private: NewDetectorGeoPar(const NewDetectorGeoPar&); NewDetectorGeoPar& operator=(const NewDetectorGeoPar&); - ClassDef(NewDetectorGeoPar,1) + ClassDef(NewDetectorGeoPar, 1) }; #endif diff --git a/templates/NewDetector_root_containers/NewDetectorPoint.cxx b/templates/NewDetector_root_containers/NewDetectorPoint.cxx index a7f06a61ff..7a74f497b7 100644 --- a/templates/NewDetector_root_containers/NewDetectorPoint.cxx +++ b/templates/NewDetector_root_containers/NewDetectorPoint.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "NewDetectorPoint.h" @@ -11,41 +11,37 @@ using std::cout; using std::endl; - // ----- Default constructor ------------------------------------------- NewDetectorPoint::NewDetectorPoint() - : FairMCPoint() -{ -} + : FairMCPoint() +{} // ------------------------------------------------------------------------- // ----- Standard constructor ------------------------------------------ -NewDetectorPoint::NewDetectorPoint(Int_t trackID, Int_t detID, - TVector3 pos, TVector3 mom, - Double_t tof, Double_t length, +NewDetectorPoint::NewDetectorPoint(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t tof, + Double_t length, Double_t eLoss) - : FairMCPoint(trackID, detID, pos, mom, tof, length, eLoss) -{ -} + : FairMCPoint(trackID, detID, pos, mom, tof, length, eLoss) +{} // ------------------------------------------------------------------------- // ----- Destructor ---------------------------------------------------- -NewDetectorPoint::~NewDetectorPoint() { } +NewDetectorPoint::~NewDetectorPoint() {} // ------------------------------------------------------------------------- // ----- Public method Print ------------------------------------------- void NewDetectorPoint::Print(const Option_t* /*opt*/) const { - cout << "-I- NewDetectorPoint: NewDetector 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- NewDetectorPoint: NewDetector 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; } // ------------------------------------------------------------------------- -ClassImp(NewDetectorPoint) - +ClassImp(NewDetectorPoint); diff --git a/templates/NewDetector_root_containers/NewDetectorPoint.h b/templates/NewDetector_root_containers/NewDetectorPoint.h index beeffe54bd..6fd7db2d08 100644 --- a/templates/NewDetector_root_containers/NewDetectorPoint.h +++ b/templates/NewDetector_root_containers/NewDetectorPoint.h @@ -1,14 +1,13 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef NEWDETECTORPOINT_H #define NEWDETECTORPOINT_H 1 - #include "FairMCPoint.h" #include @@ -18,11 +17,9 @@ class NewDetectorPoint : public FairMCPoint { public: - /** Default constructor **/ NewDetectorPoint(); - /** Constructor with arguments *@param trackID Index of MCTrack *@param detID Detector ID @@ -32,11 +29,13 @@ class NewDetectorPoint : public FairMCPoint *@param length Track length since creation [cm] *@param eLoss Energy deposit [GeV] **/ - NewDetectorPoint(Int_t trackID, Int_t detID, TVector3 pos, TVector3 mom, - Double_t tof, Double_t length, Double_t eLoss); - - - + NewDetectorPoint(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t tof, + Double_t length, + Double_t eLoss); /** Destructor **/ virtual ~NewDetectorPoint(); @@ -49,8 +48,7 @@ class NewDetectorPoint : public FairMCPoint NewDetectorPoint(const NewDetectorPoint& point); NewDetectorPoint operator=(const NewDetectorPoint& point); - ClassDef(NewDetectorPoint,1) - + ClassDef(NewDetectorPoint, 1) }; #endif diff --git a/templates/NewDetector_stl_containers/NewDetector.cxx b/templates/NewDetector_stl_containers/NewDetector.cxx index ec2c1d7610..03a14a34f4 100644 --- a/templates/NewDetector_stl_containers/NewDetector.cxx +++ b/templates/NewDetector_stl_containers/NewDetector.cxx @@ -7,28 +7,27 @@ ********************************************************************************/ #include "NewDetector.h" -#include "NewDetectorPoint.h" -#include "NewDetectorGeo.h" -#include "NewDetectorGeoPar.h" - -#include "FairVolume.h" -#include "FairGeoVolume.h" +#include "FairGeoInterface.h" +#include "FairGeoLoader.h" #include "FairGeoNode.h" +#include "FairGeoVolume.h" #include "FairRootManager.h" -#include "FairGeoLoader.h" -#include "FairGeoInterface.h" #include "FairRun.h" #include "FairRuntimeDb.h" +#include "FairVolume.h" #include "MyProjDetectorList.h" #include "MyProjStack.h" +#include "NewDetectorGeo.h" +#include "NewDetectorGeoPar.h" +#include "NewDetectorPoint.h" -#include -#include #include #include -#include +#include #include #include +#include +#include NewDetector::NewDetector() : FairDetector("NewDetector", kTRUE, kNewDetector) @@ -40,8 +39,7 @@ NewDetector::NewDetector() , fLength(-1.) , fELoss(-1) , fVectorPoints(new std::vector) -{ -} +{} NewDetector::NewDetector(const char* name, Bool_t active) : FairDetector(name, active, kNewDetector) @@ -53,8 +51,7 @@ NewDetector::NewDetector(const char* name, Bool_t active) , fLength(-1.) , fELoss(-1) , fVectorPoints(new std::vector) -{ -} +{} NewDetector::NewDetector(const NewDetector& right) : FairDetector(right) @@ -66,15 +63,12 @@ NewDetector::NewDetector(const NewDetector& right) , fLength(-1.) , fELoss(-1) , fVectorPoints(new std::vector) -{ -} +{} NewDetector::~NewDetector() { - if (fVectorPoints->size()) - { - for(auto const& x : (*fVectorPoints)) - { + if (fVectorPoints->size()) { + for (auto const& x : (*fVectorPoints)) { delete x; } fVectorPoints->clear(); @@ -101,8 +95,7 @@ Bool_t NewDetector::ProcessHits(FairVolume* vol) /** This method is called from the MC stepping */ // Set parameters at entrance of volume. Reset ELoss. - if (TVirtualMC::GetMC()->IsTrackEntering()) - { + if (TVirtualMC::GetMC()->IsTrackEntering()) { fELoss = 0.; fTime = TVirtualMC::GetMC()->TrackTime() * 1.0e09; fLength = TVirtualMC::GetMC()->TrackLength(); @@ -114,13 +107,11 @@ Bool_t NewDetector::ProcessHits(FairVolume* vol) fELoss += TVirtualMC::GetMC()->Edep(); // Create NewDetectorPoint at exit of active volume - if (TVirtualMC::GetMC()->IsTrackExiting() || TVirtualMC::GetMC()->IsTrackStop() || - TVirtualMC::GetMC()->IsTrackDisappeared()) - { + if (TVirtualMC::GetMC()->IsTrackExiting() || TVirtualMC::GetMC()->IsTrackStop() + || TVirtualMC::GetMC()->IsTrackDisappeared()) { fTrackID = TVirtualMC::GetMC()->GetStack()->GetCurrentTrackNumber(); fVolumeID = vol->getMCid(); - if (fELoss == 0.) - { + if (fELoss == 0.) { return kFALSE; } AddHit(fTrackID, @@ -141,11 +132,9 @@ Bool_t NewDetector::ProcessHits(FairVolume* vol) void NewDetector::EndOfEvent() { - LOG(info) << "NewDetector: " << fVectorPoints->size() - << " points registered in this event"; + LOG(info) << "NewDetector: " << fVectorPoints->size() << " points registered in this event"; - for(auto const& x : (*fVectorPoints)) - { + for (auto const& x : (*fVectorPoints)) { delete x; } fVectorPoints->clear(); @@ -163,8 +152,7 @@ void NewDetector::Register() void NewDetector::Reset() { - for(auto const& x : (*fVectorPoints)) - { + for (auto const& x : (*fVectorPoints)) { delete x; } fVectorPoints->clear(); @@ -176,13 +164,11 @@ void NewDetector::ConstructGeometry() TGeoMedium* Si = gGeoManager->GetMedium("Si"); TGeoMedium* Carbon = gGeoManager->GetMedium("C"); - if (Si == 0) - { + if (Si == 0) { TGeoMaterial* matSi = new TGeoMaterial("Si", 28.0855, 14, 2.33); Si = new TGeoMedium("Si", 2, matSi); } - if (Carbon == 0) - { + if (Carbon == 0) { TGeoMaterial* matCarbon = new TGeoMaterial("C", 12.011, 6.0, 2.265); Carbon = new TGeoMedium("C", 3, matCarbon); } @@ -228,12 +214,12 @@ void NewDetector::ConstructGeometry() } NewDetectorPoint* NewDetector::AddHit(Int_t trackID, - Int_t detID, - TVector3 pos, - TVector3 mom, - Double_t time, - Double_t length, - Double_t eLoss) + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t time, + Double_t length, + Double_t eLoss) { NewDetectorPoint* point = new NewDetectorPoint(trackID, detID, pos, mom, time, length, eLoss); fVectorPoints->push_back(point); @@ -247,10 +233,8 @@ void NewDetector::DefineSensitiveVolumes() TObjArray* volumes = gGeoManager->GetListOfVolumes(); TIter next(volumes); TGeoVolume* volume; - while ((volume = static_cast(next()))) - { - if (IsSensitive(volume->GetName())) - { + while ((volume = static_cast(next()))) { + if (IsSensitive(volume->GetName())) { LOG(debug2) << "Sensitive Volume " << volume->GetName(); AddSensitiveVolume(volume); } @@ -259,10 +243,10 @@ void NewDetector::DefineSensitiveVolumes() Bool_t NewDetector::IsSensitive(const std::string& name) { - if ( name.find("Det") != std::string::npos ) { + if (name.find("Det") != std::string::npos) { return kTRUE; } return kFALSE; } -ClassImp(NewDetector) +ClassImp(NewDetector); diff --git a/templates/NewDetector_stl_containers/NewDetector.h b/templates/NewDetector_stl_containers/NewDetector.h index b51f862482..38ffe0b77d 100644 --- a/templates/NewDetector_stl_containers/NewDetector.h +++ b/templates/NewDetector_stl_containers/NewDetector.h @@ -10,9 +10,8 @@ #include "FairDetector.h" -#include #include - +#include #include class NewDetectorPoint; @@ -25,7 +24,7 @@ class NewDetector : public FairDetector /** Name : Detector Name * Active: true for active detectors (ProcessHits() will be called) * false for inactive detectors - */ + */ NewDetector(const char* Name, bool Active); /** default constructor */ @@ -39,7 +38,7 @@ class NewDetector : public FairDetector /** this method is called for each step during simulation * (see FairMCApplication::Stepping()) - */ + */ virtual Bool_t ProcessHits(FairVolume* v = 0); /** Registers the produced collections in FAIRRootManager. */ @@ -53,13 +52,13 @@ class NewDetector : public FairDetector /** This method is an example of how to add your own point * of type NewDetectorPoint to the clones array - */ + */ NewDetectorPoint* AddHit(int trackID, int detID, TVector3 pos, TVector3 mom, double time, double length, double eLoss); /** The following methods can be implemented if you need to make * any optional action in your detector during the transport. - */ + */ virtual void SetSpecialPhysicsCuts() { ; } virtual void EndOfEvent(); @@ -73,23 +72,23 @@ class NewDetector : public FairDetector virtual FairModule* CloneModule() const; virtual Bool_t IsSensitive(const std::string& name); - + virtual TClonesArray* GetCollection(Int_t iColl) const { return NULL; } 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 */ - std::vector* fVectorPoints; //! + std::vector* fVectorPoints; //! NewDetector(const NewDetector&); NewDetector& operator=(const NewDetector&); @@ -99,4 +98,4 @@ class NewDetector : public FairDetector ClassDef(NewDetector, 2) }; -#endif // NEWDETECTOR_H +#endif // NEWDETECTOR_H diff --git a/templates/NewDetector_stl_containers/NewDetectorContFact.cxx b/templates/NewDetector_stl_containers/NewDetectorContFact.cxx index 428dbcb088..9466b6c6d9 100644 --- a/templates/NewDetector_stl_containers/NewDetectorContFact.cxx +++ b/templates/NewDetector_stl_containers/NewDetectorContFact.cxx @@ -1,59 +1,55 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "NewDetectorContFact.h" -#include "NewDetectorGeoPar.h" - #include "FairRuntimeDb.h" +#include "NewDetectorGeoPar.h" #include -ClassImp(NewDetectorContFact) +ClassImp(NewDetectorContFact); static NewDetectorContFact gNewDetectorContFact; NewDetectorContFact::NewDetectorContFact() - : FairContFact() + : FairContFact() { - /** Constructor (called when the library is loaded) */ - fName="NewDetectorContFact"; - fTitle="Factory for parameter containers in libNewDetector"; - setAllContainers(); - FairRuntimeDb::instance()->addContFactory(this); + /** Constructor (called when the library is loaded) */ + fName = "NewDetectorContFact"; + fTitle = "Factory for parameter containers in libNewDetector"; + setAllContainers(); + FairRuntimeDb::instance()->addContFactory(this); } void NewDetectorContFact::setAllContainers() { - /** Creates the Container objects with all accepted + /** Creates the Container objects with all accepted contexts and adds them to the list of containers for the NewDetector library. */ - FairContainer* p= new FairContainer("NewDetectorGeoPar", - "NewDetector Geometry Parameters", - "TestDefaultContext"); - p->addContext("TestNonDefaultContext"); + FairContainer* p = new FairContainer("NewDetectorGeoPar", "NewDetector Geometry Parameters", "TestDefaultContext"); + p->addContext("TestNonDefaultContext"); - containers->Add(p); + containers->Add(p); } FairParSet* NewDetectorContFact::createContainer(FairContainer* c) { - /** Calls the constructor of the corresponding parameter container. + /** 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,"NewDetectorGeoPar")==0) { - p=new NewDetectorGeoPar(c->getConcatName().Data(), - c->GetTitle(),c->getContext()); - } - return p; + const char* name = c->GetName(); + FairParSet* p = NULL; + if (strcmp(name, "NewDetectorGeoPar") == 0) { + p = new NewDetectorGeoPar(c->getConcatName().Data(), c->GetTitle(), c->getContext()); + } + return p; } diff --git a/templates/NewDetector_stl_containers/NewDetectorContFact.h b/templates/NewDetector_stl_containers/NewDetectorContFact.h index f5e4958971..e4c70dca22 100644 --- a/templates/NewDetector_stl_containers/NewDetectorContFact.h +++ b/templates/NewDetector_stl_containers/NewDetectorContFact.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef NEWDETECTORCONTFACT_H @@ -16,11 +16,12 @@ class NewDetectorContFact : public FairContFact { private: void setAllContainers(); + public: NewDetectorContFact(); ~NewDetectorContFact() {} FairParSet* createContainer(FairContainer*); - ClassDef( NewDetectorContFact,0) // Factory for all NewDetector parameter containers + ClassDef(NewDetectorContFact, 0) // Factory for all NewDetector parameter containers }; #endif diff --git a/templates/NewDetector_stl_containers/NewDetectorGeo.cxx b/templates/NewDetector_stl_containers/NewDetectorGeo.cxx index 51d77d9fed..8498754bcd 100644 --- a/templates/NewDetector_stl_containers/NewDetectorGeo.cxx +++ b/templates/NewDetector_stl_containers/NewDetectorGeo.cxx @@ -1,43 +1,44 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "NewDetectorGeo.h" + #include "FairGeoNode.h" -ClassImp(NewDetectorGeo) +ClassImp(NewDetectorGeo); // ----- Default constructor ------------------------------------------- NewDetectorGeo::NewDetectorGeo() - : FairGeoSet() + : FairGeoSet() { - // Constructor - // fName has to be the name used in the geometry for all volumes. - // If there is a mismatch the geometry cannot be build. - fName="newdetector"; - maxSectors=0; - maxModules=10; + // Constructor + // fName has to be the name used in the geometry for all volumes. + // If there is a mismatch the geometry cannot be build. + fName = "newdetector"; + maxSectors = 0; + maxModules = 10; } // ------------------------------------------------------------------------- const char* NewDetectorGeo::getModuleName(Int_t m) { - /** Returns the module name of NewDetector number m + /** Returns the module name of NewDetector number m Setting NewDetector here means that all modules names in the ASCII file should start with NewDetector otherwise they will not be constructed */ - sprintf(modName,"NewDetector%i",m+1); - return modName; + sprintf(modName, "NewDetector%i", m + 1); + return modName; } const char* NewDetectorGeo::getEleName(Int_t m) { - /** Returns the element name of Det number m */ - sprintf(eleName,"NewDetector%i",m+1); - return eleName; + /** Returns the element name of Det number m */ + sprintf(eleName, "NewDetector%i", m + 1); + return eleName; } diff --git a/templates/NewDetector_stl_containers/NewDetectorGeo.h b/templates/NewDetector_stl_containers/NewDetectorGeo.h index 80b9a67a71..6dd4ab5452 100644 --- a/templates/NewDetector_stl_containers/NewDetectorGeo.h +++ b/templates/NewDetector_stl_containers/NewDetectorGeo.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef NEWDETECTORGEO_H @@ -10,29 +10,29 @@ #include "FairGeoSet.h" -class NewDetectorGeo : public FairGeoSet +class NewDetectorGeo : public FairGeoSet { protected: - char modName[20]; // name of module - char eleName[20]; // substring for elements in module + char modName[20]; // name of module + char eleName[20]; // substring for elements in module public: NewDetectorGeo(); ~NewDetectorGeo() {} const char* getModuleName(Int_t); const char* getEleName(Int_t); inline Int_t getModNumInMod(const TString&); - ClassDef(NewDetectorGeo,1) + ClassDef(NewDetectorGeo, 1) }; inline Int_t NewDetectorGeo::getModNumInMod(const TString& name) { - /** returns the module index from module name + /** returns the module index from module name ?? in name[??] has to be the length of the detector name in the .geo file. For example if all nodes in this file starts with newdetector ?? has to be 11. */ - return (Int_t)(name[11]-'0')-1; // + return (Int_t)(name[11] - '0') - 1; // } #endif diff --git a/templates/NewDetector_stl_containers/NewDetectorGeoPar.cxx b/templates/NewDetector_stl_containers/NewDetectorGeoPar.cxx index 96674a51b3..a40fd67e7f 100644 --- a/templates/NewDetector_stl_containers/NewDetectorGeoPar.cxx +++ b/templates/NewDetector_stl_containers/NewDetectorGeoPar.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "NewDetectorGeoPar.h" @@ -10,41 +10,43 @@ #include "FairParamList.h" #include - #include -ClassImp(NewDetectorGeoPar) +ClassImp(NewDetectorGeoPar); -NewDetectorGeoPar ::NewDetectorGeoPar(const char* name, - const char* title, - const char* context) - : FairParGenericSet(name,title,context), - fGeoSensNodes(new TObjArray()), - fGeoPassNodes(new TObjArray()) -{ -} +NewDetectorGeoPar ::NewDetectorGeoPar(const char* name, const char* title, const char* context) + : FairParGenericSet(name, title, context) + , fGeoSensNodes(new TObjArray()) + , fGeoPassNodes(new TObjArray()) +{} -NewDetectorGeoPar::~NewDetectorGeoPar(void) -{ -} +NewDetectorGeoPar::~NewDetectorGeoPar(void) {} void NewDetectorGeoPar::clear(void) { - delete fGeoSensNodes; - delete fGeoPassNodes; + delete fGeoSensNodes; + delete fGeoPassNodes; } void NewDetectorGeoPar::putParams(FairParamList* l) { - if (!l) { return; } - l->addObject("FairGeoNodes Sensitive List", fGeoSensNodes); - l->addObject("FairGeoNodes Passive List", fGeoPassNodes); + if (!l) { + return; + } + l->addObject("FairGeoNodes Sensitive List", fGeoSensNodes); + l->addObject("FairGeoNodes Passive List", fGeoPassNodes); } Bool_t NewDetectorGeoPar::getParams(FairParamList* l) { - if (!l) { return kFALSE; } - if (!l->fillObject("FairGeoNodes Sensitive List", fGeoSensNodes)) { return kFALSE; } - if (!l->fillObject("FairGeoNodes Passive List", fGeoPassNodes)) { return kFALSE; } - return kTRUE; + if (!l) { + return kFALSE; + } + if (!l->fillObject("FairGeoNodes Sensitive List", fGeoSensNodes)) { + return kFALSE; + } + if (!l->fillObject("FairGeoNodes Passive List", fGeoPassNodes)) { + return kFALSE; + } + return kTRUE; } diff --git a/templates/NewDetector_stl_containers/NewDetectorGeoPar.h b/templates/NewDetector_stl_containers/NewDetectorGeoPar.h index 96997079c9..b689979309 100644 --- a/templates/NewDetector_stl_containers/NewDetectorGeoPar.h +++ b/templates/NewDetector_stl_containers/NewDetectorGeoPar.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef NEWDETECTORGEOPAR_H @@ -13,31 +13,30 @@ class TObjArray; class FairParamList; -class NewDetectorGeoPar : public FairParGenericSet +class NewDetectorGeoPar : public FairParGenericSet { public: - /** List of FairGeoNodes for sensitive volumes */ - TObjArray* fGeoSensNodes; + TObjArray* fGeoSensNodes; /** List of FairGeoNodes for sensitive volumes */ - TObjArray* fGeoPassNodes; + TObjArray* fGeoPassNodes; - NewDetectorGeoPar(const char* name="NewDetectorGeoPar", - const char* title="NewDetector Geometry Parameters", - const char* context="TestDefaultContext"); + NewDetectorGeoPar(const char* name = "NewDetectorGeoPar", + const char* title = "NewDetector Geometry Parameters", + const char* context = "TestDefaultContext"); ~NewDetectorGeoPar(void); void clear(void); void putParams(FairParamList*); Bool_t getParams(FairParamList*); - TObjArray* GetGeoSensitiveNodes() {return fGeoSensNodes;} - TObjArray* GetGeoPassiveNodes() {return fGeoPassNodes;} + TObjArray* GetGeoSensitiveNodes() { return fGeoSensNodes; } + TObjArray* GetGeoPassiveNodes() { return fGeoPassNodes; } private: NewDetectorGeoPar(const NewDetectorGeoPar&); NewDetectorGeoPar& operator=(const NewDetectorGeoPar&); - ClassDef(NewDetectorGeoPar,1) + ClassDef(NewDetectorGeoPar, 1) }; #endif diff --git a/templates/NewDetector_stl_containers/NewDetectorPoint.cxx b/templates/NewDetector_stl_containers/NewDetectorPoint.cxx index e12456c706..59393dc8a3 100644 --- a/templates/NewDetector_stl_containers/NewDetectorPoint.cxx +++ b/templates/NewDetector_stl_containers/NewDetectorPoint.cxx @@ -24,18 +24,17 @@ NewDetectorPoint::NewDetectorPoint() , fX(0.) , fY(0.) , fZ(0.) -{ -} +{} // ------------------------------------------------------------------------- // ----- Standard constructor ------------------------------------------ NewDetectorPoint::NewDetectorPoint(Int_t trackID, - Int_t detID, - TVector3 pos, - TVector3 mom, - Double_t tof, - Double_t length, - Double_t eLoss) + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t tof, + Double_t length, + Double_t eLoss) : fTrackID(trackID) , fPx(mom.X()) , fPy(mom.Y()) @@ -47,8 +46,7 @@ NewDetectorPoint::NewDetectorPoint(Int_t trackID, , fX(pos.X()) , fY(pos.Y()) , fZ(pos.Z()) -{ -} +{} // ------------------------------------------------------------------------- // ----- Destructor ---------------------------------------------------- @@ -58,8 +56,7 @@ NewDetectorPoint::~NewDetectorPoint() {} // ----- Public method Print ------------------------------------------- void NewDetectorPoint::Print(const Option_t* /*opt*/) const { - cout << "-I- NewDetectorPoint: NewDetector point for track " << fTrackID << " in detector " << fDetectorID - << endl; + cout << "-I- NewDetectorPoint: NewDetector 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" @@ -67,4 +64,4 @@ void NewDetectorPoint::Print(const Option_t* /*opt*/) const } // ------------------------------------------------------------------------- -ClassImp(NewDetectorPoint) +ClassImp(NewDetectorPoint); diff --git a/templates/NewDetector_stl_containers/NewDetectorPoint.h b/templates/NewDetector_stl_containers/NewDetectorPoint.h index be93ec7d40..79f61bdffd 100644 --- a/templates/NewDetector_stl_containers/NewDetectorPoint.h +++ b/templates/NewDetector_stl_containers/NewDetectorPoint.h @@ -27,12 +27,12 @@ class NewDetectorPoint *@param eLoss Energy deposit [GeV] **/ NewDetectorPoint(Int_t trackID, - Int_t detID, - TVector3 pos, - TVector3 mom, - Double_t tof, - Double_t length, - Double_t eLoss); + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t tof, + Double_t length, + Double_t eLoss); /** Destructor **/ virtual ~NewDetectorPoint(); @@ -41,7 +41,7 @@ class NewDetectorPoint virtual void Print(const Option_t* opt) const; /** Accessors */ - uint32_t GetEventID() const { return fEventId; } /// event identifier + uint32_t GetEventID() const { return fEventId; } /// event identifier int GetTrackID() const { return fTrackID; } double GetPx() const { return fPx; } double GetPy() const { return fPy; } @@ -71,14 +71,14 @@ class NewDetectorPoint void SetPosition(const TVector3& pos); protected: - int fTrackID; ///< Track index - uint32_t fEventId; ///< MC Event id - double fPx, fPy, fPz; ///< Momentum components [GeV] - double fTime; ///< Time since event start [ns] - double fLength; ///< Track length since creation [cm] - double fELoss; ///< Energy loss at this point [GeV] - int fDetectorID; ///< Detector unique identifier - double fX, fY, fZ; ///< Position of hit [cm] + int fTrackID; ///< Track index + uint32_t fEventId; ///< MC Event id + double fPx, fPy, fPz; ///< Momentum components [GeV] + double fTime; ///< Time since event start [ns] + double fLength; ///< Track length since creation [cm] + double fELoss; ///< Energy loss at this point [GeV] + int fDetectorID; ///< Detector unique identifier + double fX, fY, fZ; ///< Position of hit [cm] private: /** Copy constructor **/ diff --git a/templates/NewParameterContainer/NewParameterContainer.cxx b/templates/NewParameterContainer/NewParameterContainer.cxx index 7025133e79..13c4cef9a5 100644 --- a/templates/NewParameterContainer/NewParameterContainer.cxx +++ b/templates/NewParameterContainer/NewParameterContainer.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "NewParameterContainer.h" @@ -11,30 +11,27 @@ #include -ClassImp(NewParameterContainer) +ClassImp(NewParameterContainer); -NewParameterContainer ::NewParameterContainer(const char* name, - const char* title, - const char* context) - : FairParGenericSet(name,title,context) -{ -} +NewParameterContainer ::NewParameterContainer(const char* name, const char* title, const char* context) + : FairParGenericSet(name, title, context) +{} -NewParameterContainer::~NewParameterContainer(void) -{ -} +NewParameterContainer::~NewParameterContainer(void) {} -void NewParameterContainer::clear(void) -{ -} +void NewParameterContainer::clear(void) {} void NewParameterContainer::putParams(FairParamList* l) { - if (!l) { return; } + if (!l) { + return; + } } Bool_t NewParameterContainer::getParams(FairParamList* l) { - if (!l) { return kFALSE; } - return kTRUE; + if (!l) { + return kFALSE; + } + return kTRUE; } diff --git a/templates/NewParameterContainer/NewParameterContainer.h b/templates/NewParameterContainer/NewParameterContainer.h index 1e5db4e4f0..6824935149 100644 --- a/templates/NewParameterContainer/NewParameterContainer.h +++ b/templates/NewParameterContainer/NewParameterContainer.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef NEWPARAMETERCONTAINER_H @@ -15,10 +15,9 @@ class FairParamList; class NewParameterContainer : public FairParGenericSet { public: - - NewParameterContainer(const char* name="NewParameterContainer", - const char* title="NewParameterContainer Parameters", - const char* context="TestDefaultContext"); + NewParameterContainer(const char* name = "NewParameterContainer", + const char* title = "NewParameterContainer Parameters", + const char* context = "TestDefaultContext"); ~NewParameterContainer(void); void clear(void); void putParams(FairParamList*); @@ -28,7 +27,7 @@ class NewParameterContainer : public FairParGenericSet NewParameterContainer(const NewParameterContainer&); NewParameterContainer& operator=(const NewParameterContainer&); - ClassDef(NewParameterContainer,1) + ClassDef(NewParameterContainer, 1) }; #endif diff --git a/templates/NewTask/NewTask.cxx b/templates/NewTask/NewTask.cxx index 551326c32f..0eb0420404 100644 --- a/templates/NewTask/NewTask.cxx +++ b/templates/NewTask/NewTask.cxx @@ -1,31 +1,28 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "NewTask.h" // ---- Default constructor ------------------------------------------- NewTask::NewTask() - :FairTask("NewTask") + : FairTask("NewTask") { - LOG(debug) << "Defaul Constructor of NewTask"; + LOG(debug) << "Defaul Constructor of NewTask"; } // ---- Destructor ---------------------------------------------------- -NewTask::~NewTask() -{ - LOG(debug) << "Destructor of NewTask"; -} +NewTask::~NewTask() { LOG(debug) << "Destructor of NewTask"; } // ---- Initialisation ---------------------------------------------- void NewTask::SetParContainers() { - LOG(debug) << "SetParContainers of NewTask"; - // Load all necessary parameter containers from the runtime data base - /* + LOG(debug) << "SetParContainers of NewTask"; + // Load all necessary parameter containers from the runtime data base + /* FairRunAna* ana = FairRunAna::Instance(); FairRuntimeDb* rtdb=ana->GetRuntimeDb(); @@ -37,13 +34,13 @@ void NewTask::SetParContainers() // ---- Init ---------------------------------------------------------- InitStatus NewTask::Init() { - LOG(debug) << "Initilization of NewTask"; + LOG(debug) << "Initilization of NewTask"; - // Get a handle from the IO manager - FairRootManager* ioman = FairRootManager::Instance(); + // Get a handle from the IO manager + FairRootManager* ioman = FairRootManager::Instance(); - // Get a pointer to the previous already existing data level - /* + // Get a pointer to the previous already existing data level + /* = (TClonesArray*) ioman->GetObject("InputDataLevelName"); if ( ! ) { fLogger->Error(MESSAGE_ORIGIN,"No InputDataLevelName array!\n NewTask will be inactive"); @@ -51,38 +48,31 @@ InitStatus NewTask::Init() } */ - // Create the TClonesArray for the output data and register - // it in the IO manager - /* + // Create the TClonesArray for the output data and register + // it in the IO manager + /* = new TClonesArray("OutputDataLevelName", 100); ioman->Register("OutputDataLevelName","OutputDataLevelName",,kTRUE); */ - // Do whatever else is needed at the initilization stage - // Create histograms to be filled - // initialize variables - - return kSUCCESS; + // Do whatever else is needed at the initilization stage + // Create histograms to be filled + // initialize variables + return kSUCCESS; } // ---- ReInit ------------------------------------------------------- InitStatus NewTask::ReInit() { - LOG(debug) << "Initilization of NewTask"; - return kSUCCESS; + LOG(debug) << "Initilization of NewTask"; + return kSUCCESS; } // ---- Exec ---------------------------------------------------------- -void NewTask::Exec(Option_t* /*option*/) -{ - LOG(debug) << "Exec of NewTask"; -} +void NewTask::Exec(Option_t* /*option*/) { LOG(debug) << "Exec of NewTask"; } // ---- Finish -------------------------------------------------------- -void NewTask::Finish() -{ - LOG(debug) << "Finish of NewTask"; -} +void NewTask::Finish() { LOG(debug) << "Finish of NewTask"; } -ClassImp(NewTask) +ClassImp(NewTask); diff --git a/templates/NewTask/NewTask.h b/templates/NewTask/NewTask.h index 95165138b2..3c38c35a06 100644 --- a/templates/NewTask/NewTask.h +++ b/templates/NewTask/NewTask.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef NEWTASK_H @@ -15,25 +15,21 @@ class TClonesArray; class NewTask : public FairTask { public: - /** Default constructor **/ NewTask(); /** Constructor with parameters (Optional) **/ // NewTask(Int_t verbose); - /** Destructor **/ ~NewTask(); - /** Initiliazation of task at the beginning of a run **/ virtual InitStatus Init(); /** ReInitiliazation of task when the runID changes **/ virtual InitStatus ReInit(); - /** Executed for each event. **/ virtual void Exec(Option_t* opt); @@ -44,7 +40,6 @@ class NewTask : public FairTask virtual void Finish(); private: - /** Input array from previous already existing data level **/ // TClonesArray* ; @@ -54,7 +49,7 @@ class NewTask : public FairTask NewTask(const NewTask&); NewTask operator=(const NewTask&); - ClassDef(NewTask,1); + ClassDef(NewTask, 1); }; #endif diff --git a/templates/TimeBased/MyRingSorter.cxx b/templates/TimeBased/MyRingSorter.cxx index 0272a444c6..c4ced3443a 100644 --- a/templates/TimeBased/MyRingSorter.cxx +++ b/templates/TimeBased/MyRingSorter.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* @@ -12,16 +12,12 @@ * Author: uhlig */ -#include #include "MyDataClass.h" -MyRingSorter::~MyRingSorter() -{ -} +#include + +MyRingSorter::~MyRingSorter() {} -FairTimeStamp* MyRingSorter::CreateElement(FairTimeStamp* data) -{ - return new MyDataClass(*(MyDataClass*)data); -} +FairTimeStamp* MyRingSorter::CreateElement(FairTimeStamp* data) { return new MyDataClass(*(MyDataClass*)data); } ClassImp(MyRingSorter); diff --git a/templates/TimeBased/MyRingSorter.h b/templates/TimeBased/MyRingSorter.h index c4a32c68d7..eaff133da8 100644 --- a/templates/TimeBased/MyRingSorter.h +++ b/templates/TimeBased/MyRingSorter.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* @@ -17,17 +17,17 @@ #include -class MyRingSorter: public FairRingSorter +class MyRingSorter : public FairRingSorter { public: MyRingSorter(int size = 100, double width = 10) - : FairRingSorter(size, width) {}; + : FairRingSorter(size, width){}; virtual ~MyRingSorter(); virtual FairTimeStamp* CreateElement(FairTimeStamp* data); - ClassDef (MyRingSorter,1); + ClassDef(MyRingSorter, 1); }; #endif /* MYRINGSORTER_H_ */ diff --git a/templates/TimeBased/MySorterTask.cxx b/templates/TimeBased/MySorterTask.cxx index c79a861b20..1578ab654c 100644 --- a/templates/TimeBased/MySorterTask.cxx +++ b/templates/TimeBased/MySorterTask.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* @@ -18,29 +18,25 @@ #include "MyRingSorter.h" MySorterTask::MySorterTask() - : FairRingSorterTask() -{ -} + : FairRingSorterTask() +{} -MySorterTask::~MySorterTask() -{ -} +MySorterTask::~MySorterTask() {} void MySorterTask::AddNewDataToTClonesArray(FairTimeStamp* data) { - FairRootManager* ioman = FairRootManager::Instance(); - TClonesArray* myArray = ioman->GetTClonesArray(fOutputBranch); - if (fVerbose > 1) { - std::cout << "-I- MySorterTask::AddNewDataToTClonesArray Data: " ; - std::cout << *(MyDataClass*)(data) << std::endl; - } - new ((*myArray)[myArray->GetEntries()]) MyDataClass(*(MyDataClass*)(data)); + FairRootManager* ioman = FairRootManager::Instance(); + TClonesArray* myArray = ioman->GetTClonesArray(fOutputBranch); + if (fVerbose > 1) { + std::cout << "-I- MySorterTask::AddNewDataToTClonesArray Data: "; + std::cout << *(MyDataClass*)(data) << std::endl; + } + new ((*myArray)[myArray->GetEntries()]) MyDataClass(*(MyDataClass*)(data)); } FairRingSorter* MySorterTask::InitSorter(Int_t numberOfCells, Double_t widthOfCells) const { - return new MyRingSorter(numberOfCells, widthOfCells); + return new MyRingSorter(numberOfCells, widthOfCells); } ClassImp(MySorterTask); - diff --git a/templates/TimeBased/MySorterTask.h b/templates/TimeBased/MySorterTask.h index 3b83ababa9..afce551a0d 100644 --- a/templates/TimeBased/MySorterTask.h +++ b/templates/TimeBased/MySorterTask.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* @@ -15,22 +15,23 @@ #ifndef MYSORTERTASK_H_ #define MYSORTERTASK_H_ -#include #include +#include -class MySorterTask: public FairRingSorterTask +class MySorterTask : public FairRingSorterTask { public: MySorterTask(); MySorterTask(const char* name) - : FairRingSorterTask(name) {}; + : FairRingSorterTask(name){}; - MySorterTask(Int_t numberOfCells, Double_t widthOfCells, - TString inputBranch, TString outputBranch, + MySorterTask(Int_t numberOfCells, + Double_t widthOfCells, + TString inputBranch, + TString outputBranch, TString folderName) - : FairRingSorterTask(numberOfCells, widthOfCells, inputBranch, - outputBranch, folderName) { }; + : FairRingSorterTask(numberOfCells, widthOfCells, inputBranch, outputBranch, folderName){}; virtual ~MySorterTask(); diff --git a/templates/TimeBased/MyWriteoutBuffer.cxx b/templates/TimeBased/MyWriteoutBuffer.cxx index 0677bb89de..c62f7e61ba 100644 --- a/templates/TimeBased/MyWriteoutBuffer.cxx +++ b/templates/TimeBased/MyWriteoutBuffer.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* @@ -13,76 +13,76 @@ */ #include "MyWriteoutBuffer.h" + #include "MyDataClass.h" MyWriteoutBuffer::MyWriteoutBuffer() - : FairWriteoutBuffer(), - fData_map() -{ -} - + : FairWriteoutBuffer() + , fData_map() +{} MyWriteoutBuffer::MyWriteoutBuffer(TString branchName, TString folderName, Bool_t persistance) - : FairWriteoutBuffer(branchName, "MyDataClass", folderName, persistance), - fData_map() -{ -} + : FairWriteoutBuffer(branchName, "MyDataClass", folderName, persistance) + , fData_map() +{} -MyWriteoutBuffer::~MyWriteoutBuffer() -{ -} +MyWriteoutBuffer::~MyWriteoutBuffer() {} -std::vector > MyWriteoutBuffer::Modify(std::pair oldData, std::pair newData) +std::vector> MyWriteoutBuffer::Modify(std::pair oldData, + std::pair newData) { - std::vector > result; - std::pair singleResult; - if (newData.first > 0) { - singleResult.first = oldData.first + newData.first; - } - singleResult.second = oldData.second; - singleResult.second->AddCharge(newData.second->GetCharge()); - if (fVerbose > 0) { - std::cout << "Modify hit" << std::endl; - std::cout << "OldData: " << oldData.first << " : " << oldData.second << " NewData: " << newData.first << " : " << newData.second << std::endl; - std::cout << "Resulting Data: " << singleResult.first << " : " << singleResult.second << std::endl; - } + std::vector> result; + std::pair singleResult; + if (newData.first > 0) { + singleResult.first = oldData.first + newData.first; + } + singleResult.second = oldData.second; + singleResult.second->AddCharge(newData.second->GetCharge()); + if (fVerbose > 0) { + std::cout << "Modify hit" << std::endl; + std::cout << "OldData: " << oldData.first << " : " << oldData.second << " NewData: " << newData.first << " : " + << newData.second << std::endl; + std::cout << "Resulting Data: " << singleResult.first << " : " << singleResult.second << std::endl; + } - result.push_back(singleResult); - return result; + result.push_back(singleResult); + return result; } void MyWriteoutBuffer::AddNewDataToTClonesArray(FairTimeStamp* data) { - FairRootManager* ioman = FairRootManager::Instance(); - TClonesArray* myArray = ioman->GetTClonesArray(fBranchName); - if (fVerbose > 1) { std::cout << "Data Inserted: " << *(MyDataClass*)(data) << std::endl; } - new ((*myArray)[myArray->GetEntries()]) MyDataClass(*(MyDataClass*)(data)); + FairRootManager* ioman = FairRootManager::Instance(); + TClonesArray* myArray = ioman->GetTClonesArray(fBranchName); + if (fVerbose > 1) { + std::cout << "Data Inserted: " << *(MyDataClass*)(data) << std::endl; + } + new ((*myArray)[myArray->GetEntries()]) MyDataClass(*(MyDataClass*)(data)); } double MyWriteoutBuffer::FindTimeForData(FairTimeStamp* data) { - std::map::iterator it; - MyDataClass myData = *(MyDataClass*)data; - it = fData_map.find(myData); - if (it == fData_map.end()) { - return -1; - } else { - return it->second; - } + std::map::iterator it; + MyDataClass myData = *(MyDataClass*)data; + it = fData_map.find(myData); + if (it == fData_map.end()) { + return -1; + } else { + return it->second; + } } void MyWriteoutBuffer::FillDataMap(FairTimeStamp* data, double activeTime) { - MyDataClass myData = *(MyDataClass*)data; - fData_map[myData] = activeTime; + MyDataClass myData = *(MyDataClass*)data; + fData_map[myData] = activeTime; } void MyWriteoutBuffer::EraseDataFromDataMap(FairTimeStamp* data) { - MyDataClass myData = *(MyDataClass*)data; - if (fData_map.find(myData) != fData_map.end()) { - fData_map.erase(fData_map.find(myData)); - } + MyDataClass myData = *(MyDataClass*)data; + if (fData_map.find(myData) != fData_map.end()) { + fData_map.erase(fData_map.find(myData)); + } } ClassImp(MyWriteoutBuffer); diff --git a/templates/TimeBased/MyWriteoutBuffer.h b/templates/TimeBased/MyWriteoutBuffer.h index b72c0a211f..a0fbf0cd70 100644 --- a/templates/TimeBased/MyWriteoutBuffer.h +++ b/templates/TimeBased/MyWriteoutBuffer.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ /* MyWriteoutBuffer.h @@ -29,17 +29,17 @@ class MyWriteoutBuffer : public FairWriteoutBuffer virtual ~MyWriteoutBuffer(); - virtual std::vector > Modify(std::pair oldData, std::pair newData); + virtual std::vector> Modify(std::pair oldData, + std::pair newData); - virtual double FindTimeForData(FairTimeStamp* data) ; - virtual void FillDataMap(FairTimeStamp* data, double activeTime) ; + virtual double FindTimeForData(FairTimeStamp* data); + virtual void FillDataMap(FairTimeStamp* data, double activeTime); virtual void EraseDataFromDataMap(FairTimeStamp* data); - protected: + protected: std::map fData_map; ClassDef(MyWriteoutBuffer, 1); }; #endif /* MYWRITEOUTBUFFER_H_ */ - diff --git a/templates/project_root_containers/MyProjData/MyProjDetectorList.h b/templates/project_root_containers/MyProjData/MyProjDetectorList.h index 0d4dc63f7f..c86e445e8b 100644 --- a/templates/project_root_containers/MyProjData/MyProjDetectorList.h +++ b/templates/project_root_containers/MyProjData/MyProjDetectorList.h @@ -11,13 +11,16 @@ // ----- M. Al-Turany June 2014 ----- // ------------------------------------------------------------------------- - /** Defines unique identifier for all MyProj detectors system **/ /** THis is needed for stack filtring **/ #ifndef MyProjDetectorList_H #define MyProjDetectorList_H 1 // kSTOPHERE is needed for iteration over the enum. All detectors have to be put before. -enum DetectorId {kNewDetector, kSTOPHERE}; +enum DetectorId +{ + kNewDetector, + kSTOPHERE +}; #endif diff --git a/templates/project_root_containers/MyProjData/MyProjMCTrack.cxx b/templates/project_root_containers/MyProjData/MyProjMCTrack.cxx index 1acf69aba9..6ecc5b1b6b 100644 --- a/templates/project_root_containers/MyProjData/MyProjMCTrack.cxx +++ b/templates/project_root_containers/MyProjData/MyProjMCTrack.cxx @@ -16,141 +16,129 @@ #include "MyProjMCTrack.h" -#include "FairLogger.h" // for FairLogger, etc -#include // for TDatabasePDG -#include // for TParticle -#include // for TParticlePDG +#include "FairLogger.h" // for FairLogger, etc + +#include // for TDatabasePDG +#include // for TParticle +#include // for TParticlePDG // ----- Default constructor ------------------------------------------- MyProjMCTrack::MyProjMCTrack() - : TObject(), - fPdgCode(0), - fMotherId(-1), - fPx(0.), - fPy(0.), - fPz(0.), - fStartX(0.), - fStartY(0.), - fStartZ(0.), - fStartT(0.), - fNPoints(0) -{ -} + : TObject() + , fPdgCode(0) + , fMotherId(-1) + , fPx(0.) + , fPy(0.) + , fPz(0.) + , fStartX(0.) + , fStartY(0.) + , fStartZ(0.) + , fStartT(0.) + , fNPoints(0) +{} // ------------------------------------------------------------------------- - - // ----- Standard constructor ------------------------------------------ -MyProjMCTrack::MyProjMCTrack(Int_t pdgCode, Int_t motherId, Double_t px, - Double_t py, Double_t pz, Double_t x, Double_t y, - Double_t z, Double_t t, Int_t nPoints = 0) - : TObject(), - fPdgCode(pdgCode), - fMotherId(motherId), - fPx(px), - fPy(py), - fPz(pz), - fStartX(x), - fStartY(y), - fStartZ(z), - fStartT(t), - fNPoints(nPoints) -{ -} +MyProjMCTrack::MyProjMCTrack(Int_t pdgCode, + Int_t motherId, + Double_t px, + Double_t py, + Double_t pz, + Double_t x, + Double_t y, + Double_t z, + Double_t t, + Int_t nPoints = 0) + : TObject() + , fPdgCode(pdgCode) + , fMotherId(motherId) + , fPx(px) + , fPy(py) + , fPz(pz) + , fStartX(x) + , fStartY(y) + , fStartZ(z) + , fStartT(t) + , fNPoints(nPoints) +{} // ------------------------------------------------------------------------- - - // ----- Copy constructor ---------------------------------------------- MyProjMCTrack::MyProjMCTrack(const MyProjMCTrack& track) - : TObject(track), - fPdgCode(track.fPdgCode), - fMotherId(track.fMotherId), - fPx(track.fPx), - fPy(track.fPy), - fPz(track.fPz), - fStartX(track.fStartX), - fStartY(track.fStartY), - fStartZ(track.fStartZ), - fStartT(track.fStartT), - fNPoints(track.fNPoints) -{ -} + : TObject(track) + , fPdgCode(track.fPdgCode) + , fMotherId(track.fMotherId) + , fPx(track.fPx) + , fPy(track.fPy) + , fPz(track.fPz) + , fStartX(track.fStartX) + , fStartY(track.fStartY) + , fStartZ(track.fStartZ) + , fStartT(track.fStartT) + , fNPoints(track.fNPoints) +{} // ------------------------------------------------------------------------- - - // ----- Constructor from TParticle ------------------------------------ MyProjMCTrack::MyProjMCTrack(TParticle* part) - : TObject(), - fPdgCode(part->GetPdgCode()), - fMotherId(part->GetMother(0)), - fPx(part->Px()), - fPy(part->Py()), - fPz(part->Pz()), - fStartX(part->Vx()), - fStartY(part->Vy()), - fStartZ(part->Vz()), - fStartT(part->T()*1e09), - fNPoints(0) -{ -} + : TObject() + , fPdgCode(part->GetPdgCode()) + , fMotherId(part->GetMother(0)) + , fPx(part->Px()) + , fPy(part->Py()) + , fPz(part->Pz()) + , fStartX(part->Vx()) + , fStartY(part->Vy()) + , fStartZ(part->Vz()) + , fStartT(part->T() * 1e09) + , fNPoints(0) +{} // ------------------------------------------------------------------------- - - // ----- Destructor ---------------------------------------------------- -MyProjMCTrack::~MyProjMCTrack() { } +MyProjMCTrack::~MyProjMCTrack() {} // ------------------------------------------------------------------------- - - // ----- Public method Print ------------------------------------------- void MyProjMCTrack::Print(Int_t trackId) const { - LOG(debug) << "Track " << trackId << ", mother : " << fMotherId << ", Type " - << fPdgCode << ", momentum (" << fPx << ", " << fPy << ", " - << fPz << ") GeV"; - /* LOG(debug2) << " Ref " << GetNPoints(kREF) + LOG(debug) << "Track " << trackId << ", mother : " << fMotherId << ", Type " << fPdgCode << ", momentum (" << fPx + << ", " << fPy << ", " << fPz << ") GeV"; + /* LOG(debug2) << " Ref " << GetNPoints(kREF) << ", TutDet " << GetNPoints(kTutDet) << ", Rutherford " << GetNPoints(kFairRutherford); */ } // ------------------------------------------------------------------------- - - // ----- Public method GetMass ----------------------------------------- Double_t MyProjMCTrack::GetMass() const { - if ( TDatabasePDG::Instance() ) { - TParticlePDG* particle = TDatabasePDG::Instance()->GetParticle(fPdgCode); - if ( particle ) { return particle->Mass(); } - else { return 0.; } - } - return 0.; + if (TDatabasePDG::Instance()) { + TParticlePDG* particle = TDatabasePDG::Instance()->GetParticle(fPdgCode); + if (particle) { + return particle->Mass(); + } else { + return 0.; + } + } + return 0.; } // ------------------------------------------------------------------------- - - - // ----- Public method GetRapidity ------------------------------------- Double_t MyProjMCTrack::GetRapidity() const { - Double_t e = GetEnergy(); - Double_t y = 0.5 * TMath::Log( (e+fPz) / (e-fPz) ); - return y; + Double_t e = GetEnergy(); + Double_t y = 0.5 * TMath::Log((e + fPz) / (e - fPz)); + return y; } // ------------------------------------------------------------------------- - - - // ----- Public method GetNPoints -------------------------------------- Int_t MyProjMCTrack::GetNPoints(DetectorId detId) const { -/* // TODO: Where does this come from + /* // TODO: Where does this come from if ( detId == kREF ) { return ( fNPoints & 1); } else if ( detId == kTutDet ) { return ( (fNPoints & ( 7 << 1) ) >> 1); } else if ( detId == kFairRutherford ) { return ( (fNPoints & (31 << 4) ) >> 4); } @@ -162,12 +150,10 @@ Int_t MyProjMCTrack::GetNPoints(DetectorId detId) const } // ------------------------------------------------------------------------- - - // ----- Public method SetNPoints -------------------------------------- void MyProjMCTrack::SetNPoints(Int_t iDet, Int_t nPoints) { -/* + /* if ( iDet == kREF ) { if ( nPoints < 0 ) { nPoints = 0; } else if ( nPoints > 1 ) { nPoints = 1; } @@ -191,7 +177,4 @@ void MyProjMCTrack::SetNPoints(Int_t iDet, Int_t nPoints) } // ------------------------------------------------------------------------- - - - -ClassImp(MyProjMCTrack) +ClassImp(MyProjMCTrack); diff --git a/templates/project_root_containers/MyProjData/MyProjMCTrack.h b/templates/project_root_containers/MyProjData/MyProjMCTrack.h index a65d12701c..2832e19175 100644 --- a/templates/project_root_containers/MyProjData/MyProjMCTrack.h +++ b/templates/project_root_containers/MyProjData/MyProjMCTrack.h @@ -11,24 +11,22 @@ // ----- M. Al-Turany June 2014 ----- // ------------------------------------------------------------------------- - - /** MyProjMCTrack.h ** Data class for storing Monte Carlo tracks processed by the MyProjStack. ** A MyProjMCTrack can be a primary track put into the simulation or a ** secondary one produced by the transport through decay or interaction. **/ - #ifndef MyProjMCTrack_H #define MyProjMCTrack_H 1 -#include // for TObject -#include "MyProjDetectorList.h" // for DetectorId -#include // for Double_t, Int_t, Double32_t, etc -#include // for TLorentzVector -#include // for Sqrt -#include // for TVector3 +#include "MyProjDetectorList.h" // for DetectorId + +#include // for Double_t, Int_t, Double32_t, etc +#include // for TLorentzVector +#include // for Sqrt +#include // for TObject +#include // for TVector3 class TParticle; @@ -36,70 +34,65 @@ class MyProjMCTrack : public TObject { public: - - /** Default constructor **/ MyProjMCTrack(); - /** Standard constructor **/ - MyProjMCTrack(Int_t pdgCode, Int_t motherID, Double_t px, Double_t py, - Double_t pz, Double_t x, Double_t y, Double_t z, - Double_t t, Int_t nPoints); + MyProjMCTrack(Int_t pdgCode, + Int_t motherID, + Double_t px, + Double_t py, + Double_t pz, + Double_t x, + Double_t y, + Double_t z, + Double_t t, + Int_t nPoints); /** Copy constructor **/ MyProjMCTrack(const MyProjMCTrack& track); - /** Constructor from TParticle **/ MyProjMCTrack(TParticle* particle); - /** Destructor **/ virtual ~MyProjMCTrack(); - /** Output to screen **/ - void Print(Int_t iTrack=0) const; - + void Print(Int_t iTrack = 0) const; /** Accessors **/ - Int_t GetPdgCode() const { return fPdgCode; } - Int_t GetMotherId() const { return fMotherId; } - Double_t GetPx() const { return fPx; } - Double_t GetPy() const { return fPy; } - Double_t GetPz() const { return fPz; } - Double_t GetStartX() const { return fStartX; } - Double_t GetStartY() const { return fStartY; } - Double_t GetStartZ() const { return fStartZ; } - Double_t GetStartT() const { return fStartT; } - Double_t GetMass() const; - Double_t GetEnergy() const; - Double_t GetPt() const { return TMath::Sqrt(fPx*fPx+fPy*fPy); } - Double_t GetP() const { return TMath::Sqrt(fPx*fPx+fPy*fPy+fPz*fPz); } + Int_t GetPdgCode() const { return fPdgCode; } + Int_t GetMotherId() const { return fMotherId; } + Double_t GetPx() const { return fPx; } + Double_t GetPy() const { return fPy; } + Double_t GetPz() const { return fPz; } + Double_t GetStartX() const { return fStartX; } + Double_t GetStartY() const { return fStartY; } + Double_t GetStartZ() const { return fStartZ; } + Double_t GetStartT() const { return fStartT; } + Double_t GetMass() const; + Double_t GetEnergy() const; + Double_t GetPt() const { return TMath::Sqrt(fPx * fPx + fPy * fPy); } + Double_t GetP() const { return TMath::Sqrt(fPx * fPx + fPy * fPy + fPz * fPz); } Double_t GetRapidity() const; void GetMomentum(TVector3& momentum); void Get4Momentum(TLorentzVector& momentum); void GetStartVertex(TVector3& vertex); - /** Accessors to the number of MCPoints in the detectors **/ - Int_t GetNPoints(DetectorId detId) const; - + Int_t GetNPoints(DetectorId detId) const; /** Modifiers **/ void SetMotherId(Int_t id) { fMotherId = id; } void SetNPoints(Int_t iDet, Int_t np); - - private: - /** PDG particle code **/ - Int_t fPdgCode; + Int_t fPdgCode; /** Index of mother track. -1 for primary particles. **/ - Int_t fMotherId; + Int_t fMotherId; /** Momentum components at start vertex [GeV] **/ Double32_t fPx, fPy, fPz; @@ -124,41 +117,21 @@ class MyProjMCTrack : public TObject **/ Int_t fNPoints; - - ClassDef(MyProjMCTrack,1); - + ClassDef(MyProjMCTrack, 1); }; - - // ========== Inline functions ======================================== inline Double_t MyProjMCTrack::GetEnergy() const { - Double_t mass = GetMass(); - return TMath::Sqrt(mass*mass + fPx*fPx + fPy*fPy + fPz*fPz ); -} - - -inline void MyProjMCTrack::GetMomentum(TVector3& momentum) -{ - momentum.SetXYZ(fPx,fPy,fPz); -} - - -inline void MyProjMCTrack::Get4Momentum(TLorentzVector& momentum) -{ - momentum.SetXYZT(fPx,fPy,fPz,GetEnergy()); -} - - -inline void MyProjMCTrack::GetStartVertex(TVector3& vertex) -{ - vertex.SetXYZ(fStartX,fStartY,fStartZ); + Double_t mass = GetMass(); + return TMath::Sqrt(mass * mass + fPx * fPx + fPy * fPy + fPz * fPz); } +inline void MyProjMCTrack::GetMomentum(TVector3& momentum) { momentum.SetXYZ(fPx, fPy, fPz); } +inline void MyProjMCTrack::Get4Momentum(TLorentzVector& momentum) { momentum.SetXYZT(fPx, fPy, fPz, GetEnergy()); } - +inline void MyProjMCTrack::GetStartVertex(TVector3& vertex) { vertex.SetXYZ(fStartX, fStartY, fStartZ); } #endif diff --git a/templates/project_root_containers/MyProjData/MyProjStack.cxx b/templates/project_root_containers/MyProjData/MyProjStack.cxx index 14e4a38d31..cabff5698d 100644 --- a/templates/project_root_containers/MyProjData/MyProjStack.cxx +++ b/templates/project_root_containers/MyProjData/MyProjStack.cxx @@ -13,495 +13,486 @@ #include "MyProjStack.h" -#include "FairDetector.h" // for FairDetector -#include "FairLink.h" // for FairLink -#include "FairMCPoint.h" // for FairMCPoint -#include "MyProjMCTrack.h" // for MyProjMCTrack -#include "FairRootManager.h" // for FairRootManager -#include "FairLogger.h" // for FairLogger, MESSAGE_ORIGIN - -#include // for ostream -#include // for TClonesArray -#include // for TIterator -#include // for TLorentzVector -#include // for TParticle -#include // for TRefArray -#include // for gMC - -#include // for NULL -#include // for operator<<, etc +#include "FairDetector.h" // for FairDetector +#include "FairLink.h" // for FairLink +#include "FairLogger.h" // for FairLogger, MESSAGE_ORIGIN +#include "FairMCPoint.h" // for FairMCPoint +#include "FairRootManager.h" // for FairRootManager +#include "MyProjMCTrack.h" // for MyProjMCTrack + +#include // for TClonesArray +#include // for TIterator +#include // for TLorentzVector +#include // for TParticle +#include // for TRefArray +#include // for gMC +#include // for ostream +#include // for operator<<, etc +#include // for NULL using std::cout; using std::endl; using std::pair; - // ----- Default constructor ------------------------------------------- MyProjStack::MyProjStack(Int_t size) - : FairGenericStack(), - fStack(), - fParticles(new TClonesArray("TParticle", size)), - fTracks(new TClonesArray("MyProjMCTrack", size)), - fStoreMap(), - fStoreIter(), - fIndexMap(), - fIndexIter(), - fPointsMap(), - fCurrentTrack(-1), - fNPrimaries(0), - fNParticles(0), - fNTracks(0), - fIndex(0), - fStoreSecondaries(kTRUE), - fMinPoints(1), - fEnergyCut(0.), - fStoreMothers(kTRUE) -{ -} + : FairGenericStack() + , fStack() + , fParticles(new TClonesArray("TParticle", size)) + , fTracks(new TClonesArray("MyProjMCTrack", size)) + , fStoreMap() + , fStoreIter() + , fIndexMap() + , fIndexIter() + , fPointsMap() + , fCurrentTrack(-1) + , fNPrimaries(0) + , fNParticles(0) + , fNTracks(0) + , fIndex(0) + , fStoreSecondaries(kTRUE) + , fMinPoints(1) + , fEnergyCut(0.) + , fStoreMothers(kTRUE) +{} // ------------------------------------------------------------------------- - MyProjStack::MyProjStack(const MyProjStack& right) - : FairGenericStack(right), - fStack(), - fParticles(new TClonesArray("TParticle", 100)), - fTracks(new TClonesArray("MyProjMCTrack", 100)), - fStoreMap(), - fStoreIter(), - fIndexMap(), - fIndexIter(), - fPointsMap(), - fCurrentTrack(), - fNPrimaries(), - fNParticles(), - fNTracks(), - fIndex(), - fStoreSecondaries(right.fStoreSecondaries), - fMinPoints(right.fMinPoints), - fEnergyCut(right.fEnergyCut), - fStoreMothers(right.fStoreMothers) -{ -} - + : FairGenericStack(right) + , fStack() + , fParticles(new TClonesArray("TParticle", 100)) + , fTracks(new TClonesArray("MyProjMCTrack", 100)) + , fStoreMap() + , fStoreIter() + , fIndexMap() + , fIndexIter() + , fPointsMap() + , fCurrentTrack() + , fNPrimaries() + , fNParticles() + , fNTracks() + , fIndex() + , fStoreSecondaries(right.fStoreSecondaries) + , fMinPoints(right.fMinPoints) + , fEnergyCut(right.fEnergyCut) + , fStoreMothers(right.fStoreMothers) +{} // ----- Destructor ---------------------------------------------------- MyProjStack::~MyProjStack() { - if (fParticles) { - fParticles->Delete(); - delete fParticles; - } - if (fTracks) { - fTracks->Delete(); - delete fTracks; - } + if (fParticles) { + fParticles->Delete(); + delete fParticles; + } + if (fTracks) { + fTracks->Delete(); + delete fTracks; + } } // ------------------------------------------------------------------------- -void MyProjStack::PushTrack(Int_t toBeDone, Int_t parentId, Int_t pdgCode, - Double_t px, Double_t py, Double_t pz, - Double_t e, Double_t vx, Double_t vy, Double_t vz, - Double_t time, Double_t polx, Double_t poly, - Double_t polz, TMCProcess proc, Int_t& ntr, - Double_t weight, Int_t is) +void MyProjStack::PushTrack(Int_t toBeDone, + Int_t parentId, + Int_t pdgCode, + Double_t px, + Double_t py, + Double_t pz, + Double_t e, + Double_t vx, + Double_t vy, + Double_t vz, + Double_t time, + Double_t polx, + Double_t poly, + Double_t polz, + TMCProcess proc, + Int_t& ntr, + Double_t weight, + Int_t is) { - PushTrack( toBeDone, parentId, pdgCode, - px, py, pz, - e, vx, vy, vz, - time, polx, poly, - polz, proc, ntr, - weight, is, -1); + PushTrack( + toBeDone, parentId, pdgCode, px, py, pz, e, vx, vy, vz, time, polx, poly, polz, proc, ntr, weight, is, -1); } - - // ----- Virtual public method PushTrack ------------------------------- -void MyProjStack::PushTrack(Int_t toBeDone, Int_t parentId, Int_t pdgCode, - Double_t px, Double_t py, Double_t pz, - Double_t e, Double_t vx, Double_t vy, Double_t vz, - Double_t time, Double_t polx, Double_t poly, - Double_t polz, TMCProcess proc, Int_t& ntr, - Double_t weight, Int_t is, Int_t secondparentID) +void MyProjStack::PushTrack(Int_t toBeDone, + Int_t parentId, + Int_t pdgCode, + Double_t px, + Double_t py, + Double_t pz, + Double_t e, + Double_t vx, + Double_t vy, + Double_t vz, + Double_t time, + Double_t polx, + Double_t poly, + Double_t polz, + TMCProcess proc, + Int_t& ntr, + Double_t weight, + Int_t is, + Int_t secondparentID) { - // --> Get TParticle array - TClonesArray& partArray = *fParticles; - - // --> Create new TParticle and add it to the TParticle array - Int_t trackId = fNParticles; - Int_t nPoints = 0; - Int_t daughter1Id = -1; - Int_t daughter2Id = -1; - TParticle* particle = - new(partArray[fNParticles++]) TParticle(pdgCode, trackId, parentId, - nPoints, daughter1Id, - daughter2Id, px, py, pz, e, - vx, vy, vz, time); - particle->SetPolarisation(polx, poly, polz); - particle->SetWeight(weight); - particle->SetUniqueID(proc); + // --> Get TParticle array + TClonesArray& partArray = *fParticles; - // --> Increment counter - if (parentId < 0) { fNPrimaries++; } - - // --> Set argument variable - ntr = trackId; + // --> Create new TParticle and add it to the TParticle array + Int_t trackId = fNParticles; + Int_t nPoints = 0; + Int_t daughter1Id = -1; + Int_t daughter2Id = -1; + TParticle* particle = new (partArray[fNParticles++]) + TParticle(pdgCode, trackId, parentId, nPoints, daughter1Id, daughter2Id, px, py, pz, e, vx, vy, vz, time); + particle->SetPolarisation(polx, poly, polz); + particle->SetWeight(weight); + particle->SetUniqueID(proc); + + // --> Increment counter + if (parentId < 0) { + fNPrimaries++; + } - // --> Push particle on the stack if toBeDone is set - if (toBeDone == 1) { fStack.push(particle); } + // --> Set argument variable + ntr = trackId; + // --> Push particle on the stack if toBeDone is set + if (toBeDone == 1) { + fStack.push(particle); + } } // ------------------------------------------------------------------------- - - // ----- Virtual method PopNextTrack ----------------------------------- TParticle* MyProjStack::PopNextTrack(Int_t& iTrack) { - // If end of stack: Return empty pointer - if (fStack.empty()) { - iTrack = -1; - return NULL; - } - - // If not, get next particle from stack - TParticle* thisParticle = fStack.top(); - fStack.pop(); + // If end of stack: Return empty pointer + if (fStack.empty()) { + iTrack = -1; + return NULL; + } - if ( !thisParticle) { - iTrack = 0; - return NULL; - } + // If not, get next particle from stack + TParticle* thisParticle = fStack.top(); + fStack.pop(); - fCurrentTrack = thisParticle->GetStatusCode(); - iTrack = fCurrentTrack; + if (!thisParticle) { + iTrack = 0; + return NULL; + } - return thisParticle; + fCurrentTrack = thisParticle->GetStatusCode(); + iTrack = fCurrentTrack; + return thisParticle; } // ------------------------------------------------------------------------- - - // ----- Virtual method PopPrimaryForTracking -------------------------- TParticle* MyProjStack::PopPrimaryForTracking(Int_t iPrim) { - // Get the iPrimth particle from the fStack TClonesArray. This - // should be a primary (if the index is correct). + // Get the iPrimth particle from the fStack TClonesArray. This + // should be a primary (if the index is correct). - // Test for index - if (iPrim < 0 || iPrim >= fNPrimaries) { - LOG(fatal) << "MyProjStack: Primary index out of range! " << iPrim; - } - - // Return the iPrim-th TParticle from the fParticle array. This should be - // a primary. - TParticle* part = (TParticle*)fParticles->At(iPrim); - if ( ! (part->GetMother(0) < 0) ) { - LOG(fatal) << "MyProjStack:: Not a primary track! " << iPrim; - } + // Test for index + if (iPrim < 0 || iPrim >= fNPrimaries) { + LOG(fatal) << "MyProjStack: Primary index out of range! " << iPrim; + } - return part; + // Return the iPrim-th TParticle from the fParticle array. This should be + // a primary. + TParticle* part = (TParticle*)fParticles->At(iPrim); + if (!(part->GetMother(0) < 0)) { + LOG(fatal) << "MyProjStack:: Not a primary track! " << iPrim; + } + return part; } // ------------------------------------------------------------------------- - - // ----- Virtual public method GetCurrentTrack ------------------------- TParticle* MyProjStack::GetCurrentTrack() const { - TParticle* currentPart = GetParticle(fCurrentTrack); - if ( ! currentPart) { - LOG(warning) << "MyProjStack: Current track not found in stack!"; - } - return currentPart; + TParticle* currentPart = GetParticle(fCurrentTrack); + if (!currentPart) { + LOG(warning) << "MyProjStack: Current track not found in stack!"; + } + return currentPart; } // ------------------------------------------------------------------------- - - // ----- Public method AddParticle ------------------------------------- void MyProjStack::AddParticle(TParticle* oldPart) { - TClonesArray& array = *fParticles; - TParticle* newPart = new(array[fIndex]) TParticle(*oldPart); - newPart->SetWeight(oldPart->GetWeight()); - newPart->SetUniqueID(oldPart->GetUniqueID()); - fIndex++; + TClonesArray& array = *fParticles; + TParticle* newPart = new (array[fIndex]) TParticle(*oldPart); + newPart->SetWeight(oldPart->GetWeight()); + newPart->SetUniqueID(oldPart->GetUniqueID()); + fIndex++; } // ------------------------------------------------------------------------- - - // ----- Public method FillTrackArray ---------------------------------- void MyProjStack::FillTrackArray() { - LOG(debug) << "MyProjStack: Filling MCTrack array..."; + LOG(debug) << "MyProjStack: Filling MCTrack array..."; - // --> Reset index map and number of output tracks - fIndexMap.clear(); - fNTracks = 0; + // --> Reset index map and number of output tracks + fIndexMap.clear(); + fNTracks = 0; - // --> Check tracks for selection criteria - SelectTracks(); + // --> Check tracks for selection criteria + SelectTracks(); - // --> Loop over fParticles array and copy selected tracks - for (Int_t iPart=0; iPart Loop over fParticles array and copy selected tracks + for (Int_t iPart = 0; iPart < fNParticles; iPart++) { - fStoreIter = fStoreMap.find(iPart); - if (fStoreIter == fStoreMap.end() ) { - LOG(fatal) << "MyProjStack: Particle " << iPart << " not found in storage map! "; + fStoreIter = fStoreMap.find(iPart); + if (fStoreIter == fStoreMap.end()) { + LOG(fatal) << "MyProjStack: Particle " << iPart << " not found in storage map! "; + } + Bool_t store = (*fStoreIter).second; + + if (store) { + MyProjMCTrack* track = new ((*fTracks)[fNTracks]) MyProjMCTrack(GetParticle(iPart)); + fIndexMap[iPart] = fNTracks; + // --> Set the number of points in the detectors for this track + for (Int_t iDet = kNewDetector; iDet < kSTOPHERE; iDet++) { + pair a(iPart, iDet); + track->SetNPoints(iDet, fPointsMap[a]); + } + fNTracks++; + } else { + fIndexMap[iPart] = -2; + } } - Bool_t store = (*fStoreIter).second; - - if (store) { - MyProjMCTrack* track = - new( (*fTracks)[fNTracks]) MyProjMCTrack(GetParticle(iPart)); - fIndexMap[iPart] = fNTracks; - // --> Set the number of points in the detectors for this track - for (Int_t iDet=kNewDetector; iDet a(iPart, iDet); - track->SetNPoints(iDet, fPointsMap[a]); - } - fNTracks++; - } else { fIndexMap[iPart] = -2; } - - } - // --> Map index for primary mothers - fIndexMap[-1] = -1; - - // --> Screen output - Print(1); + // --> Map index for primary mothers + fIndexMap[-1] = -1; + // --> Screen output + Print(1); } // ------------------------------------------------------------------------- - - // ----- Public method UpdateTrackIndex -------------------------------- void MyProjStack::UpdateTrackIndex(TRefArray* detList) { - LOG(debug) << "MyProjStack: Updating track indizes..."; - Int_t nColl = 0; - - // First update mother ID in MCTracks - for (Int_t i=0; iAt(i); - Int_t iMotherOld = track->GetMotherId(); - fIndexIter = fIndexMap.find(iMotherOld); - if (fIndexIter == fIndexMap.end()) { - LOG(fatal) << "MyProjStack: Particle index " << iMotherOld << " not found in dex map! "; - } - track->SetMotherId( (*fIndexIter).second ); - } - - - if(fDetList==0) { - // Now iterate through all active detectors - fDetIter = detList->MakeIterator(); - fDetIter->Reset(); - } else { - fDetIter->Reset(); - } - - FairDetector* det = NULL; - while( (det = (FairDetector*)fDetIter->Next() ) ) { + LOG(debug) << "MyProjStack: Updating track indizes..."; + Int_t nColl = 0; - - // --> Get hit collections from detector - Int_t iColl = 0; - TClonesArray* hitArray; - while ( (hitArray = det->GetCollection(iColl++)) ) { - nColl++; - Int_t nPoints = hitArray->GetEntriesFast(); - - // --> Update track index for all MCPoints in the collection - for (Int_t iPoint=0; iPointAt(iPoint); - Int_t iTrack = point->GetTrackID(); - - fIndexIter = fIndexMap.find(iTrack); + // First update mother ID in MCTracks + for (Int_t i = 0; i < fNTracks; i++) { + MyProjMCTrack* track = (MyProjMCTrack*)fTracks->At(i); + Int_t iMotherOld = track->GetMotherId(); + fIndexIter = fIndexMap.find(iMotherOld); if (fIndexIter == fIndexMap.end()) { - LOG(fatal) << "MyProjStack: Particle index " << iTrack << " not found in index map! "; + LOG(fatal) << "MyProjStack: Particle index " << iMotherOld << " not found in dex map! "; } - point->SetTrackID((*fIndexIter).second); - point->SetLink(FairLink("MCTrack", (*fIndexIter).second)); - } + track->SetMotherId((*fIndexIter).second); + } + + if (fDetList == 0) { + // Now iterate through all active detectors + fDetIter = detList->MakeIterator(); + fDetIter->Reset(); + } else { + fDetIter->Reset(); + } - } // Collections of this detector - } // List of active detectors - LOG(debug) << "...stack and " << nColl << " collections updated."; + FairDetector* det = NULL; + while ((det = (FairDetector*)fDetIter->Next())) { + + // --> Get hit collections from detector + Int_t iColl = 0; + TClonesArray* hitArray; + while ((hitArray = det->GetCollection(iColl++))) { + nColl++; + Int_t nPoints = hitArray->GetEntriesFast(); + + // --> Update track index for all MCPoints in the collection + for (Int_t iPoint = 0; iPoint < nPoints; iPoint++) { + FairMCPoint* point = (FairMCPoint*)hitArray->At(iPoint); + Int_t iTrack = point->GetTrackID(); + + fIndexIter = fIndexMap.find(iTrack); + if (fIndexIter == fIndexMap.end()) { + LOG(fatal) << "MyProjStack: Particle index " << iTrack << " not found in index map! "; + } + point->SetTrackID((*fIndexIter).second); + point->SetLink(FairLink("MCTrack", (*fIndexIter).second)); + } + + } // Collections of this detector + } // List of active detectors + LOG(debug) << "...stack and " << nColl << " collections updated."; } // ------------------------------------------------------------------------- - - // ----- Public method Reset ------------------------------------------- void MyProjStack::Reset() { - fIndex = 0; - fCurrentTrack = -1; - fNPrimaries = fNParticles = fNTracks = 0; - while (! fStack.empty() ) { fStack.pop(); } - fParticles->Clear(); - fTracks->Clear(); - fPointsMap.clear(); + fIndex = 0; + fCurrentTrack = -1; + fNPrimaries = fNParticles = fNTracks = 0; + while (!fStack.empty()) { + fStack.pop(); + } + fParticles->Clear(); + fTracks->Clear(); + fPointsMap.clear(); } // ------------------------------------------------------------------------- - - // ----- Public method Register ---------------------------------------- void MyProjStack::Register() { - if ( gMC && ( ! gMC->IsMT() ) ) { - FairRootManager::Instance()->Register("MCTrack", "Stack", fTracks,kTRUE); - } else { - FairRootManager::Instance()->RegisterAny("MCTrack",fTracks,kTRUE); - } + if (gMC && (!gMC->IsMT())) { + FairRootManager::Instance()->Register("MCTrack", "Stack", fTracks, kTRUE); + } else { + FairRootManager::Instance()->RegisterAny("MCTrack", fTracks, kTRUE); + } } // ------------------------------------------------------------------------- - - // ----- Public method Print -------------------------------------------- void MyProjStack::Print(Int_t iVerbose) const { - cout << "-I- MyProjStack: Number of primaries = " - << fNPrimaries << endl; - cout << " Total number of particles = " - << fNParticles << endl; - cout << " Number of tracks in output = " - << fNTracks << endl; - if (iVerbose) { - for (Int_t iTrack=0; iTrackAt(iTrack))->Print(iTrack); + cout << "-I- MyProjStack: Number of primaries = " << fNPrimaries << endl; + cout << " Total number of particles = " << fNParticles << endl; + cout << " Number of tracks in output = " << fNTracks << endl; + if (iVerbose) { + for (Int_t iTrack = 0; iTrack < fNTracks; iTrack++) { + ((MyProjMCTrack*)fTracks->At(iTrack))->Print(iTrack); + } } - } } // ------------------------------------------------------------------------- - - // ----- Public method AddPoint (for current track) -------------------- void MyProjStack::AddPoint(DetectorId detId) { - Int_t iDet = detId; -// cout << "Add point for Detektor" << iDet << endl; - pair a(fCurrentTrack, iDet); - if ( fPointsMap.find(a) == fPointsMap.end() ) { fPointsMap[a] = 1; } - else { fPointsMap[a]++; } + Int_t iDet = detId; + // cout << "Add point for Detektor" << iDet << endl; + pair a(fCurrentTrack, iDet); + if (fPointsMap.find(a) == fPointsMap.end()) { + fPointsMap[a] = 1; + } else { + fPointsMap[a]++; + } } // ------------------------------------------------------------------------- - - // ----- Public method AddPoint (for arbitrary track) ------------------- void MyProjStack::AddPoint(DetectorId detId, Int_t iTrack) { - if ( iTrack < 0 ) { return; } - Int_t iDet = detId; - pair a(iTrack, iDet); - if ( fPointsMap.find(a) == fPointsMap.end() ) { fPointsMap[a] = 1; } - else { fPointsMap[a]++; } + if (iTrack < 0) { + return; + } + Int_t iDet = detId; + pair a(iTrack, iDet); + if (fPointsMap.find(a) == fPointsMap.end()) { + fPointsMap[a] = 1; + } else { + fPointsMap[a]++; + } } // ------------------------------------------------------------------------- - - - // ----- Virtual method GetCurrentParentTrackNumber -------------------- Int_t MyProjStack::GetCurrentParentTrackNumber() const { - TParticle* currentPart = GetCurrentTrack(); - if ( currentPart ) { return currentPart->GetFirstMother(); } - else { return -1; } + TParticle* currentPart = GetCurrentTrack(); + if (currentPart) { + return currentPart->GetFirstMother(); + } else { + return -1; + } } // ------------------------------------------------------------------------- - - // ----- Public method GetParticle ------------------------------------- TParticle* MyProjStack::GetParticle(Int_t trackID) const { - if (trackID < 0 || trackID >= fNParticles) { - LOG(fatal) << "MyProjStack: Particle index " << trackID << " out of range."; - } - return (TParticle*)fParticles->At(trackID); + if (trackID < 0 || trackID >= fNParticles) { + LOG(fatal) << "MyProjStack: Particle index " << trackID << " out of range."; + } + return (TParticle*)fParticles->At(trackID); } // ------------------------------------------------------------------------- - - // ----- Private method SelectTracks ----------------------------------- void MyProjStack::SelectTracks() { - // --> Clear storage map - fStoreMap.clear(); - - // --> Check particles in the fParticle array - for (Int_t i=0; i Get track parameters - Int_t iMother = thisPart->GetMother(0); - TLorentzVector p; - thisPart->Momentum(p); - Double_t energy = p.E(); - Double_t mass = p.M(); -// Double_t mass = thisPart->GetMass(); - Double_t eKin = energy - mass; + // --> Clear storage map + fStoreMap.clear(); + + // --> Check particles in the fParticle array + for (Int_t i = 0; i < fNParticles; i++) { + + TParticle* thisPart = GetParticle(i); + Bool_t store = kTRUE; + + // --> Get track parameters + Int_t iMother = thisPart->GetMother(0); + TLorentzVector p; + thisPart->Momentum(p); + Double_t energy = p.E(); + Double_t mass = p.M(); + // Double_t mass = thisPart->GetMass(); + Double_t eKin = energy - mass; + + // --> Calculate number of points + Int_t nPoints = 0; + for (Int_t iDet = kNewDetector; iDet < kSTOPHERE; iDet++) { + pair a(i, iDet); + if (fPointsMap.find(a) != fPointsMap.end()) { + nPoints += fPointsMap[a]; + } + } - // --> Calculate number of points - Int_t nPoints = 0; - for (Int_t iDet=kNewDetector; iDet a(i, iDet); - if ( fPointsMap.find(a) != fPointsMap.end() ) { - nPoints += fPointsMap[a]; - } - } + // --> Check for cuts (store primaries in any case) + if (iMother < 0) { + store = kTRUE; + } else { + if (!fStoreSecondaries) { + store = kFALSE; + } + if (nPoints < fMinPoints) { + store = kFALSE; + } + if (eKin < fEnergyCut) { + store = kFALSE; + } + } - // --> Check for cuts (store primaries in any case) - if (iMother < 0) { store = kTRUE; } - else { - if (!fStoreSecondaries) { store = kFALSE; } - if (nPoints < fMinPoints) { store = kFALSE; } - if (eKin < fEnergyCut) { store = kFALSE; } + // --> Set storage flag + fStoreMap[i] = store; } - // --> Set storage flag - fStoreMap[i] = store; - - - } - - // --> If flag is set, flag recursively mothers of selected tracks - if (fStoreMothers) { - for (Int_t i=0; iGetMother(0); - while(iMother >= 0) { - fStoreMap[iMother] = kTRUE; - iMother = GetParticle(iMother)->GetMother(0); + // --> If flag is set, flag recursively mothers of selected tracks + if (fStoreMothers) { + for (Int_t i = 0; i < fNParticles; i++) { + if (fStoreMap[i]) { + Int_t iMother = GetParticle(i)->GetMother(0); + while (iMother >= 0) { + fStoreMap[iMother] = kTRUE; + iMother = GetParticle(iMother)->GetMother(0); + } + } } - } } - } - } // ------------------------------------------------------------------------- - - -ClassImp(MyProjStack) +ClassImp(MyProjStack); diff --git a/templates/project_root_containers/MyProjData/MyProjStack.h b/templates/project_root_containers/MyProjData/MyProjStack.h index 3e9d49815b..833290e872 100644 --- a/templates/project_root_containers/MyProjData/MyProjStack.h +++ b/templates/project_root_containers/MyProjData/MyProjStack.h @@ -11,7 +11,6 @@ // ----- M. Al-Turany June 2014 ----- // ------------------------------------------------------------------------- - /** MyProjStack.h ** ** This class handles the particle stack for the transport simulation. @@ -30,20 +29,17 @@ ** By default, the minimal number of points is 1 and the energy cut is 0. **/ - #ifndef MyProjStack_H #define MyProjStack_H -#include "FairGenericStack.h" // for FairGenericStack - -#include "MyProjDetectorList.h" // for DetectorId +#include "FairGenericStack.h" // for FairGenericStack +#include "MyProjDetectorList.h" // for DetectorId -#include // for Int_t, Double_t, Bool_t, etc -#include // for TMCProcess - -#include // for map, map<>::iterator -#include // for stack -#include // for pair +#include // for Int_t, Double_t, Bool_t, etc +#include // for TMCProcess +#include // for map, map<>::iterator +#include // for stack +#include // for pair class TClonesArray; class TParticle; @@ -53,17 +49,14 @@ class MyProjStack : public FairGenericStack { public: - /** Default constructor *param size Estimated track number **/ MyProjStack(Int_t size = 100); - /** Destructor **/ virtual ~MyProjStack(); - /** Add a TParticle to the stack. ** Declared in TVirtualMCStack *@param toBeDone Flag for tracking @@ -79,22 +72,44 @@ class MyProjStack : public FairGenericStack *@param weight Particle weight *@param is Generation status code (whatever that means) **/ - virtual void PushTrack(Int_t toBeDone, Int_t parentID, Int_t pdgCode, - Double_t px, Double_t py, Double_t pz, - Double_t e, Double_t vx, Double_t vy, - Double_t vz, Double_t time, Double_t polx, - Double_t poly, Double_t polz, TMCProcess proc, - Int_t& ntr, Double_t weight, Int_t is); - - virtual void PushTrack(Int_t toBeDone, Int_t parentID, Int_t pdgCode, - Double_t px, Double_t py, Double_t pz, - Double_t e, Double_t vx, Double_t vy, - Double_t vz, Double_t time, Double_t polx, - Double_t poly, Double_t polz, TMCProcess proc, - Int_t& ntr, Double_t weight, Int_t is,Int_t secondParentId); - - - + virtual void PushTrack(Int_t toBeDone, + Int_t parentID, + Int_t pdgCode, + Double_t px, + Double_t py, + Double_t pz, + Double_t e, + Double_t vx, + Double_t vy, + Double_t vz, + Double_t time, + Double_t polx, + Double_t poly, + Double_t polz, + TMCProcess proc, + Int_t& ntr, + Double_t weight, + Int_t is); + + virtual void PushTrack(Int_t toBeDone, + Int_t parentID, + Int_t pdgCode, + Double_t px, + Double_t py, + Double_t pz, + Double_t e, + Double_t vx, + Double_t vy, + Double_t vz, + Double_t time, + Double_t polx, + Double_t poly, + Double_t polz, + TMCProcess proc, + Int_t& ntr, + Double_t weight, + Int_t is, + Int_t secondParentId); /** Get next particle for tracking from the stack. ** Declared in TVirtualMCStack @@ -103,7 +118,6 @@ class MyProjStack : public FairGenericStack **/ virtual TParticle* PopNextTrack(Int_t& iTrack); - /** Get primary particle by index for tracking from stack ** Declared in TVirtualMCStack *@param iPrim index of primary particle @@ -111,90 +125,74 @@ class MyProjStack : public FairGenericStack **/ virtual TParticle* PopPrimaryForTracking(Int_t iPrim); - /** Set the current track number ** Declared in TVirtualMCStack *@param iTrack track number **/ - virtual void SetCurrentTrack(Int_t iTrack) { fCurrentTrack = iTrack; } - + virtual void SetCurrentTrack(Int_t iTrack) { fCurrentTrack = iTrack; } /** Get total number of tracks ** Declared in TVirtualMCStack **/ virtual Int_t GetNtrack() const { return fNParticles; } - /** Get number of primary tracks ** Declared in TVirtualMCStack **/ virtual Int_t GetNprimary() const { return fNPrimaries; } - /** Get the current track's particle ** Declared in TVirtualMCStack **/ virtual TParticle* GetCurrentTrack() const; - /** Get the number of the current track ** Declared in TVirtualMCStack **/ virtual Int_t GetCurrentTrackNumber() const { return fCurrentTrack; } - /** Get the track number of the parent of the current track ** Declared in TVirtualMCStack **/ virtual Int_t GetCurrentParentTrackNumber() const; - /** Add a TParticle to the fParticles array **/ virtual void AddParticle(TParticle* part); - /** Fill the MCTrack output array, applying filter criteria **/ virtual void FillTrackArray(); - /** Update the track index in the MCTracks and MCPoints **/ - virtual void UpdateTrackIndex(TRefArray* detArray=0); - + virtual void UpdateTrackIndex(TRefArray* detArray = 0); /** Resets arrays and stack and deletes particles and tracks **/ virtual void Reset(); - /** Register the MCTrack array to the Root Manager **/ virtual void Register(); - /** Output to screen **@param iVerbose: 0=events summary, 1=track info **/ - virtual void Print(Int_t iVerbose=0) const; - + virtual void Print(Int_t iVerbose = 0) const; /** Modifiers **/ void StoreSecondaries(Bool_t choice = kTRUE) { fStoreSecondaries = choice; } - void SetMinPoints(Int_t min) { fMinPoints = min; } - void SetEnergyCut(Double_t eMin) { fEnergyCut = eMin; } - void StoreMothers(Bool_t choice = kTRUE) { fStoreMothers = choice; } - + void SetMinPoints(Int_t min) { fMinPoints = min; } + void SetEnergyCut(Double_t eMin) { fEnergyCut = eMin; } + void StoreMothers(Bool_t choice = kTRUE) { fStoreMothers = choice; } /** Increment number of points for the current track in a given detector *@param iDet Detector unique identifier **/ void AddPoint(DetectorId iDet); - /** Increment number of points for an arbitrary track in a given detector *@param iDet Detector unique identifier *@param iTrack Track number **/ void AddPoint(DetectorId iDet, Int_t iTrack); - /** Accessors **/ TParticle* GetParticle(Int_t trackId) const; TClonesArray* GetListOfParticles() { return fParticles; } @@ -204,47 +202,39 @@ class MyProjStack : public FairGenericStack private: /** STL stack (FILO) used to handle the TParticles for tracking **/ - std::stack fStack; //! - + std::stack fStack; //! /** Array of TParticles (contains all TParticles put into or created ** by the transport **/ - TClonesArray* fParticles; //! - + TClonesArray* fParticles; //! /** Array of FairMCTracks containg the tracks written to the output **/ TClonesArray* fTracks; - /** STL map from particle index to storage flag **/ - std::map fStoreMap; //! - std::map::iterator fStoreIter; //! - + std::map fStoreMap; //! + std::map::iterator fStoreIter; //! /** STL map from particle index to track index **/ - std::map fIndexMap; //! - std::map::iterator fIndexIter; //! - + std::map fIndexMap; //! + std::map::iterator fIndexIter; //! /** STL map from track index and detector ID to number of MCPoints **/ - std::map, Int_t> fPointsMap; //! - + std::map, Int_t> fPointsMap; //! /** Some indizes and counters **/ - Int_t fCurrentTrack; //! Index of current track - Int_t fNPrimaries; //! Number of primary particles - Int_t fNParticles; //! Number of entries in fParticles - Int_t fNTracks; //! Number of entries in fTracks - Int_t fIndex; //! Used for merging - + Int_t fCurrentTrack; //! Index of current track + Int_t fNPrimaries; //! Number of primary particles + Int_t fNParticles; //! Number of entries in fParticles + Int_t fNTracks; //! Number of entries in fTracks + Int_t fIndex; //! Used for merging /** Variables defining the criteria for output selection **/ - Bool_t fStoreSecondaries; - Int_t fMinPoints; + Bool_t fStoreSecondaries; + Int_t fMinPoints; Double32_t fEnergyCut; - Bool_t fStoreMothers; - + Bool_t fStoreMothers; /** Mark tracks for output using selection criteria **/ void SelectTracks(); @@ -252,14 +242,7 @@ class MyProjStack : public FairGenericStack MyProjStack(const MyProjStack&); MyProjStack& operator=(const MyProjStack&); - ClassDef(MyProjStack,1) - - + ClassDef(MyProjStack, 1) }; - - - - - #endif diff --git a/templates/project_root_containers/MyProjGenerators/Pythia6Generator.cxx b/templates/project_root_containers/MyProjGenerators/Pythia6Generator.cxx index 56376cfb0a..112a56cf70 100644 --- a/templates/project_root_containers/MyProjGenerators/Pythia6Generator.cxx +++ b/templates/project_root_containers/MyProjGenerators/Pythia6Generator.cxx @@ -14,11 +14,11 @@ // ------------------------------------------------------------------------- #include "Pythia6Generator.h" -#include "FairPrimaryGenerator.h" #include "FairLogger.h" +#include "FairPrimaryGenerator.h" -#include #include +#include using std::cout; using std::endl; @@ -28,113 +28,119 @@ using std::max; Pythia6Generator::Pythia6Generator() {} // ------------------------------------------------------------------------ - - // ----- Standard constructor ----------------------------------------- -Pythia6Generator::Pythia6Generator(const char* fileName) { - fFileName = fileName; - fVerbose = 0; - cout << "-I Pythia6Generator: Opening input file " << fileName << endl; - if ((fInputFile = fopen(fFileName,"r"))==NULL) - // fInputFile = new ifstream(fFileName); - // if ( ! fInputFile->is_open() ) - LOG(fatal) << "Pythia6Generator: Cannot open input file."; - - // fPDG=TDatabasePDG::Instance(); +Pythia6Generator::Pythia6Generator(const char* fileName) +{ + fFileName = fileName; + fVerbose = 0; + cout << "-I Pythia6Generator: Opening input file " << fileName << endl; + if ((fInputFile = fopen(fFileName, "r")) == NULL) + // fInputFile = new ifstream(fFileName); + // if ( ! fInputFile->is_open() ) + LOG(fatal) << "Pythia6Generator: Cannot open input file."; + + // fPDG=TDatabasePDG::Instance(); } // ------------------------------------------------------------------------ - - // ----- Destructor --------------------------------------------------- -Pythia6Generator::~Pythia6Generator() { - CloseInput(); -} +Pythia6Generator::~Pythia6Generator() { CloseInput(); } // ------------------------------------------------------------------------ +// ----- Public method ReadEvent -------------------------------------- +Bool_t Pythia6Generator::ReadEvent(FairPrimaryGenerator* primGen) +{ + + // Check for input file + if (!fInputFile) { + // if ( ! fInputFile->is_open() ) { + cout << "-E Pythia6Generator: Input file not open!" << endl; + return kFALSE; + } + + // Define event variable to be read from file + Int_t ntracks = 0, eventID = 0, ncols = 0; + + // Define track variables to be read from file + Int_t nLev = 0, pdgID = 0, nM1 = -1, nM2 = -1, nDF = -1, nDL = -1; + Float_t fPx = 0., fPy = 0., fPz = 0., fM = 0., fE = 0.; + Float_t fVx = 0., fVy = 0., fVz = 0., fT = 0.; + + // Read event header line from input file + + Int_t max_nr = 0; + + Text_t buffer[200]; + ncols = fscanf(fInputFile, "%d\t%d", &eventID, &ntracks); + + if (ncols && ntracks > 0) { + + if (fVerbose > 0) + cout << "Event number: " << eventID << "\tNtracks: " << ntracks << endl; + + for (Int_t ll = 0; ll < ntracks; ll++) { + ncols = fscanf(fInputFile, + "%d %d %d %d %d %d %f %f %f %f %f %f %f %f %f", + &nLev, + &pdgID, + &nM1, + &nM2, + &nDF, + &nDL, + &fPx, + &fPy, + &fPz, + &fE, + &fM, + &fVx, + &fVy, + &fVz, + &fT); + if (fVerbose > 0) + cout << nLev << "\t" << pdgID << "\t" << nM1 << "\t" << nM2 << "\t" << nDF << "\t" << nDL << "\t" << fPx + << "\t" << fPy << "\t" << fPz << "\t" << fE << "\t" << fM << "\t" << fVx << "\t" << fVy << "\t" + << fVz << "\t" << fT << endl; + if (nLev == 1) + primGen->AddTrack(pdgID, fPx, fPy, fPz, fVx, fVy, fVz); + } + } else { + cout << "-I Pythia6Generator: End of input file reached " << endl; + CloseInput(); + return kFALSE; + } + // If end of input file is reached : close it and abort run + if (feof(fInputFile)) { + cout << "-I Pythia6Generator: End of input file reached " << endl; + CloseInput(); + return kFALSE; + } -// ----- Public method ReadEvent -------------------------------------- -Bool_t Pythia6Generator::ReadEvent(FairPrimaryGenerator* primGen) { - - // Check for input file - if (!fInputFile) { - // if ( ! fInputFile->is_open() ) { - cout << "-E Pythia6Generator: Input file not open!" << endl; - return kFALSE; - } - - // Define event variable to be read from file - Int_t ntracks = 0, eventID = 0, ncols = 0; - - // Define track variables to be read from file - Int_t nLev = 0, pdgID = 0, nM1 = -1, nM2 = -1, nDF = -1, nDL = -1; - Float_t fPx = 0., fPy = 0., fPz = 0., fM = 0., fE = 0.; - Float_t fVx = 0., fVy = 0., fVz = 0., fT = 0.; - - // Read event header line from input file - - Int_t max_nr = 0; - - Text_t buffer[200]; - ncols = fscanf(fInputFile,"%d\t%d", &eventID, &ntracks); - - if (ncols && ntracks>0) { - - if (fVerbose>0) cout << "Event number: " << eventID << "\tNtracks: " << ntracks << endl; - - for (Int_t ll=0; ll0) cout << nLev << "\t" << pdgID << "\t" << nM1 << "\t" << nM2 << "\t" << nDF << "\t" << nDL << - "\t" << fPx << "\t" << fPy << "\t" << fPz << "\t" << fE << "\t" << fM << "\t" << fVx << "\t" << fVy << "\t" << fVz << "\t" << fT << endl; - if (nLev==1) - primGen->AddTrack(pdgID, fPx, fPy, fPz, fVx, fVy, fVz); - } - } - else { - cout << "-I Pythia6Generator: End of input file reached " << endl; - CloseInput(); - return kFALSE; - } - - - // If end of input file is reached : close it and abort run - if ( feof(fInputFile) ) { - cout << "-I Pythia6Generator: End of input file reached " << endl; - CloseInput(); - return kFALSE; - } - - /* + /* cout << "-I Pythia6Generator: Event " << eventID << ", vertex = (" << vx << "," << vy << "," << vz << ") cm, multiplicity " << ntracks << endl; */ - - return kTRUE; + + return kTRUE; } // ------------------------------------------------------------------------ - - // ----- Private method CloseInput ------------------------------------ -void Pythia6Generator::CloseInput() { - if ( fInputFile ) { - //if ( fInputFile->is_open() ) { - { - cout << "-I Pythia6Generator: Closing input file " - << fFileName << endl; - // fInputFile->close(); - - fclose(fInputFile); +void Pythia6Generator::CloseInput() +{ + if (fInputFile) { + // if ( fInputFile->is_open() ) { + { + cout << "-I Pythia6Generator: Closing input file " << fFileName << endl; + // fInputFile->close(); + + fclose(fInputFile); + } + delete fInputFile; + fInputFile = NULL; } - delete fInputFile; - fInputFile = NULL; - } } // ------------------------------------------------------------------------ - -ClassImp(Pythia6Generator) - +ClassImp(Pythia6Generator); diff --git a/templates/project_root_containers/MyProjGenerators/Pythia6Generator.h b/templates/project_root_containers/MyProjGenerators/Pythia6Generator.h index 197f01e028..ab660e2cb6 100644 --- a/templates/project_root_containers/MyProjGenerators/Pythia6Generator.h +++ b/templates/project_root_containers/MyProjGenerators/Pythia6Generator.h @@ -9,13 +9,12 @@ // ----- M. Al-Turany June 2014 ----- // ------------------------------------------------------------------------- - // ------------------------------------------------------------------------- // ----- Pythia6Generator header file ----- // ----- Created 08/08/08 by S. Spataro ----- // ------------------------------------------------------------------------- -/** Pythia6Generator.h +/** Pythia6Generator.h *@author S.Spataro * The Pythia6Generator reads a Pythia6 input file. The file must contain @@ -23,95 +22,101 @@ [start] 1 20 - 3 -2212 0 0 0 0 0.00000000E+00 0.00000000E+00 0.14000000E+02 0.14031406E+02 0.93827000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 - 3 2212 0 0 0 0 0.00000000E+00 0.00000000E+00 -0.13444107E-16 0.93827000E+00 0.93827000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 - 3 -2 1 0 0 0 -0.70661074E+00 -0.81156104E+00 0.49379331E+01 0.50538217E+01 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 - 3 2 2 0 0 0 -0.79043780E+00 0.32642680E+00 0.10299757E+01 0.13387293E+01 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 - 3 -2 3 0 0 0 -0.70661074E+00 -0.81156104E+00 0.49379331E+01 0.50538217E+01 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 - 3 2 4 0 0 0 -0.79043780E+00 0.32642680E+00 0.10299757E+01 0.13387293E+01 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 - 3 23 5 6 0 0 -0.14970485E+01 -0.48513424E+00 0.59679088E+01 0.63925510E+01 0.16650116E+01 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 - 3 11 7 0 0 0 -0.16024130E+01 0.20883507E-01 0.32233123E+01 0.35997091E+01 0.51000000E-03 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 - 3 -11 7 0 0 0 0.10536443E+00 -0.50601774E+00 0.27445965E+01 0.27928419E+01 0.51000000E-03 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 - 2 23 7 0 11 13 -0.14970485E+01 -0.48513424E+00 0.59679088E+01 0.63925510E+01 0.16650116E+01 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 - 1 -11 9 0 0 0 0.10536442E+00 -0.50601769E+00 0.27445962E+01 0.27928416E+01 0.51000000E-03 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 - 1 11 8 0 0 0 -0.16017105E+01 0.20863360E-01 0.32218964E+01 0.35981284E+01 0.51000000E-03 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 - 1 22 8 0 0 0 -0.70246172E-03 0.20096726E-04 0.14161816E-02 0.15809575E-02 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 - 2 -2103 1 0 16 16 0.70661074E+00 0.81156104E+00 0.69735272E+01 0.70980957E+01 0.77133000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 - 2 2101 2 0 16 16 0.79043780E+00 -0.32642680E+00 0.10585640E+01 0.14790292E+01 0.57933000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 - 2 92 14 15 17 18 0.14970485E+01 0.48513424E+00 0.80320912E+01 0.85771248E+01 0.25643853E+01 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 - 2 -2214 16 0 19 20 0.81382620E+00 0.70515618E+00 0.61830559E+01 0.63829315E+01 0.11627878E+01 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 - 1 2212 16 0 0 0 0.68322234E+00 -0.22002195E+00 0.18490353E+01 0.21941934E+01 0.93827000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 - 1 -2112 17 0 0 0 0.78494059E+00 0.52384336E+00 0.55944336E+01 0.57507411E+01 0.93957000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 - 1 -211 17 0 0 0 0.28885610E-01 0.18131282E+00 0.58862227E+00 0.63219038E+00 0.13957000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 - 2 25 - 3 -2212 0 0 0 0 0.00000000E+00 0.00000000E+00 0.14000000E+02 0.14031406E+02 0.93827000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 - 3 2212 0 0 0 0 0.00000000E+00 0.00000000E+00 -0.13444107E-16 0.93827000E+00 0.93827000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 - - + 3 -2212 0 0 0 0 0.00000000E+00 0.00000000E+00 0.14000000E+02 +0.14031406E+02 0.93827000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 3 2212 0 0 +0 0 0.00000000E+00 0.00000000E+00 -0.13444107E-16 0.93827000E+00 0.93827000E+00 0.00000000E+00 +0.00000000E+00 0.00000000E+00 0.00000000E+00 3 -2 1 0 0 0 -0.70661074E+00 +-0.81156104E+00 0.49379331E+01 0.50538217E+01 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 +0.00000000E+00 3 2 2 0 0 0 -0.79043780E+00 0.32642680E+00 0.10299757E+01 +0.13387293E+01 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 3 -2 3 0 +0 0 -0.70661074E+00 -0.81156104E+00 0.49379331E+01 0.50538217E+01 0.00000000E+00 0.00000000E+00 +0.00000000E+00 0.00000000E+00 0.00000000E+00 3 2 4 0 0 0 -0.79043780E+00 +0.32642680E+00 0.10299757E+01 0.13387293E+01 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 +0.00000000E+00 3 23 5 6 0 0 -0.14970485E+01 -0.48513424E+00 0.59679088E+01 +0.63925510E+01 0.16650116E+01 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 3 11 7 0 +0 0 -0.16024130E+01 0.20883507E-01 0.32233123E+01 0.35997091E+01 0.51000000E-03 0.00000000E+00 +0.00000000E+00 0.00000000E+00 0.00000000E+00 3 -11 7 0 0 0 0.10536443E+00 +-0.50601774E+00 0.27445965E+01 0.27928419E+01 0.51000000E-03 0.00000000E+00 0.00000000E+00 0.00000000E+00 +0.00000000E+00 2 23 7 0 11 13 -0.14970485E+01 -0.48513424E+00 0.59679088E+01 +0.63925510E+01 0.16650116E+01 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 1 -11 9 0 +0 0 0.10536442E+00 -0.50601769E+00 0.27445962E+01 0.27928416E+01 0.51000000E-03 0.00000000E+00 +0.00000000E+00 0.00000000E+00 0.00000000E+00 1 11 8 0 0 0 -0.16017105E+01 +0.20863360E-01 0.32218964E+01 0.35981284E+01 0.51000000E-03 0.00000000E+00 0.00000000E+00 0.00000000E+00 +0.00000000E+00 1 22 8 0 0 0 -0.70246172E-03 0.20096726E-04 0.14161816E-02 +0.15809575E-02 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 2 -2103 1 0 +16 16 0.70661074E+00 0.81156104E+00 0.69735272E+01 0.70980957E+01 0.77133000E+00 0.00000000E+00 +0.00000000E+00 0.00000000E+00 0.00000000E+00 2 2101 2 0 16 16 0.79043780E+00 +-0.32642680E+00 0.10585640E+01 0.14790292E+01 0.57933000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 +0.00000000E+00 2 92 14 15 17 18 0.14970485E+01 0.48513424E+00 0.80320912E+01 +0.85771248E+01 0.25643853E+01 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 2 -2214 16 0 +19 20 0.81382620E+00 0.70515618E+00 0.61830559E+01 0.63829315E+01 0.11627878E+01 0.00000000E+00 +0.00000000E+00 0.00000000E+00 0.00000000E+00 1 2212 16 0 0 0 0.68322234E+00 +-0.22002195E+00 0.18490353E+01 0.21941934E+01 0.93827000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 +0.00000000E+00 1 -2112 17 0 0 0 0.78494059E+00 0.52384336E+00 0.55944336E+01 +0.57507411E+01 0.93957000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 1 -211 17 0 +0 0 0.28885610E-01 0.18131282E+00 0.58862227E+00 0.63219038E+00 0.13957000E+00 0.00000000E+00 +0.00000000E+00 0.00000000E+00 0.00000000E+00 2 25 3 -2212 0 0 0 0 0.00000000E+00 +0.00000000E+00 0.14000000E+02 0.14031406E+02 0.93827000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 +0.00000000E+00 3 2212 0 0 0 0 0.00000000E+00 0.00000000E+00 -0.13444107E-16 +0.93827000E+00 0.93827000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 + + ... [stop] - + where the first row has the number of event and the number of particles, and below "N" is the line - number of the event, + number of the event, Derived from FairGenerator. **/ - #ifndef PND_PYTHIAGENERATOR_H #define PND_PYTHIAGENERATOR_H -#include // for FILE -#include "FairGenerator.h" // for FairGenerator -#include // for Int_t, Pythia6Generator::Class, Bool_t, etc -class FairPrimaryGenerator; // lines 68-68 +#include "FairGenerator.h" // for FairGenerator +#include // for Int_t, Pythia6Generator::Class, Bool_t, etc +#include // for FILE +class FairPrimaryGenerator; // lines 68-68 -class Pythia6Generator : public FairGenerator +class Pythia6Generator : public FairGenerator { - public: - - /** Default constructor without arguments should not be used. **/ - Pythia6Generator(); - - - /** Standard constructor. - ** @param fileName The input file name - **/ - Pythia6Generator(const char* fileName); + public: + /** Default constructor without arguments should not be used. **/ + Pythia6Generator(); + /** Standard constructor. + ** @param fileName The input file name + **/ + Pythia6Generator(const char* fileName); - /** Destructor. **/ - virtual ~Pythia6Generator(); + /** Destructor. **/ + virtual ~Pythia6Generator(); - - /** Reads on event from the input file and pushes the tracks onto - ** the stack. Abstract method in base class. - ** @param primGen pointer to the CbmrimaryGenerator - **/ - virtual Bool_t ReadEvent(FairPrimaryGenerator* primGen); + /** Reads on event from the input file and pushes the tracks onto + ** the stack. Abstract method in base class. + ** @param primGen pointer to the CbmrimaryGenerator + **/ + virtual Bool_t ReadEvent(FairPrimaryGenerator* primGen); - void SetVerbose (Int_t verb) { fVerbose = verb; }; + void SetVerbose(Int_t verb) { fVerbose = verb; }; - private: + private: + // ifstream* fInputFile; //! Input file stream + const Char_t* fFileName; //! Input file Name + FILE* fInputFile; //! File + Int_t fVerbose; //! Verbose Level - //ifstream* fInputFile; //! Input file stream - const Char_t * fFileName; //! Input file Name - FILE *fInputFile; //! File - Int_t fVerbose; //! Verbose Level + /** Private method CloseInput. Just for convenience. Closes the + ** input file properly. Called from destructor and from ReadEvent. **/ + void CloseInput(); - /** Private method CloseInput. Just for convenience. Closes the - ** input file properly. Called from destructor and from ReadEvent. **/ - void CloseInput(); - - - /** PDG data base */ - -// TDatabasePDG *fPDG; //! + /** PDG data base */ - ClassDef(Pythia6Generator,1); + // TDatabasePDG *fPDG; //! + ClassDef(Pythia6Generator, 1); }; #endif diff --git a/templates/project_root_containers/MyProjGenerators/Pythia8Generator.cxx b/templates/project_root_containers/MyProjGenerators/Pythia8Generator.cxx index 53ea9d1262..798bfbfcbf 100644 --- a/templates/project_root_containers/MyProjGenerators/Pythia8Generator.cxx +++ b/templates/project_root_containers/MyProjGenerators/Pythia8Generator.cxx @@ -9,11 +9,11 @@ // ----- M. Al-Turany June 2014 ----- // ------------------------------------------------------------------------- +#include "FairPrimaryGenerator.h" +#include "Pythia8/Pythia.h" -#include #include -#include "Pythia8/Pythia.h" -#include "FairPrimaryGenerator.h" +#include //#include "FairGenerator.h" #include "Pythia8Generator.h" @@ -21,138 +21,144 @@ using namespace Pythia8; // ----- Default constructor ------------------------------------------- -Pythia8Generator::Pythia8Generator() +Pythia8Generator::Pythia8Generator() { - fUseRandom1 = kFALSE; - fUseRandom3 = kTRUE; - fId = 2212; // proton - fMom = 400; // proton - fHNL = 0; // HNL if set to !=0, for example 9900014, only track + fUseRandom1 = kFALSE; + fUseRandom3 = kTRUE; + fId = 2212; // proton + fMom = 400; // proton + fHNL = 0; // HNL if set to !=0, for example 9900014, only track } // ------------------------------------------------------------------------- // ----- Default constructor ------------------------------------------- -Bool_t Pythia8Generator::Init() +Bool_t Pythia8Generator::Init() { - if (fUseRandom1) fRandomEngine = new PyTr1Rng(); - if (fUseRandom3) fRandomEngine = new PyTr3Rng(); - - fPythia.setRndmEnginePtr(fRandomEngine); - - cout<<"Beam Momentum "< 7000. && x<250. && y<250.) { - npart++; - } - } - } - else {npart++;} - }; - }; -// happens if a charm particle being produced which does decay without producing a HNL. Try another event. -// if (npart == 0){ fPythia.event.list();} - }; -// cout<<"debug p8 event 0 " << fPythia.event[0].id()<< " "<< fPythia.event[1].id()<< " "<< fPythia.event[2].id()<< " "<< npart <AddTrack((Int_t)fPythia.event[ii].id(),px,py,pz,x,y,z, - (Int_t)fPythia.event[ii].mother1(),wanttracking); - // cout<<"debug p8->geant4 "<< wanttracking << " "<< ii << " " << fPythia.event[ii].id()<< " "<< fPythia.event[ii].mother1()<<" "< 7000. && x < 250. && y < 250.) { + npart++; + } + } + } else { + npart++; + } + }; + }; + // happens if a charm particle being produced which does decay without producing a HNL. Try another event. + // if (npart == 0){ fPythia.event.list();} }; - if (fHNL != 0 && fPythia.event[ii].id() == fHNL){ - Int_t im = (Int_t)fPythia.event[ii].mother1(); - Double_t z = fPythia.event[ii].zProd(); - Double_t x = fPythia.event[ii].xProd(); - Double_t y = fPythia.event[ii].yProd(); - Double_t pz = fPythia.event[ii].pz(); - Double_t px = fPythia.event[ii].px(); - Double_t py = fPythia.event[ii].py(); - cpg->AddTrack((Int_t)fPythia.event[im].id(),px,py,pz,x,y,z,0,false); - cpg->AddTrack((Int_t)fPythia.event[ii].id(),px,py,pz,x,y,z, im,false); - //cout<<"debug p8->geant4 "<< 0 << " "<< ii << " " << fake<< " "<< fPythia.event[ii].mother1()<AddTrack((Int_t)fPythia.event[ii].id(), + px, + py, + pz, + x, + y, + z, + (Int_t)fPythia.event[ii].mother1(), + wanttracking); + // cout<<"debug p8->geant4 "<< wanttracking << " "<< ii << " " << fPythia.event[ii].id()<< " "<< + // fPythia.event[ii].mother1()<<" "<AddTrack((Int_t)fPythia.event[im].id(), px, py, pz, x, y, z, 0, false); + cpg->AddTrack((Int_t)fPythia.event[ii].id(), px, py, pz, x, y, z, im, false); + // cout<<"debug p8->geant4 "<< 0 << " "<< ii << " " << fake<< " "<< fPythia.event[ii].mother1()< // for Double_t, Bool_t, Int_t, etc -#include // for TRandom -#include // for TRandom1 -#include // for TRandom3, gRandom -class FairPrimaryGenerator; // lines 22-22 +#include "FairGenerator.h" // for FairGenerator +#include "Pythia8/Basics.h" // for RndmEngine +#include "Pythia8/Pythia.h" // for Pythia + +#include // for Double_t, Bool_t, Int_t, etc +#include // for TRandom +#include // for TRandom1 +#include // for TRandom3, gRandom +class FairPrimaryGenerator; // lines 22-22 class FairPrimaryGenerator; using namespace Pythia8; class PyTr1Rng : public RndmEngine { - public: - PyTr1Rng() { rng = new TRandom1(gRandom->GetSeed()); }; - virtual ~PyTr1Rng() {}; + public: + PyTr1Rng() { rng = new TRandom1(gRandom->GetSeed()); }; + virtual ~PyTr1Rng(){}; - Double_t flat() { return rng->Rndm(); }; + Double_t flat() { return rng->Rndm(); }; - private: - TRandom1 *rng; //! + private: + TRandom1 *rng; //! }; class PyTr3Rng : public RndmEngine { - public: - PyTr3Rng() { rng = new TRandom3(gRandom->GetSeed()); }; - virtual ~PyTr3Rng() {}; + public: + PyTr3Rng() { rng = new TRandom3(gRandom->GetSeed()); }; + virtual ~PyTr3Rng(){}; - Double_t flat() { return rng->Rndm(); }; + Double_t flat() { return rng->Rndm(); }; - private: - TRandom3 *rng; //! + private: + TRandom3 *rng; //! }; - - - class Pythia8Generator : public FairGenerator { - public: - - /** default constructor **/ - Pythia8Generator(); - - /** destructor **/ - virtual ~Pythia8Generator(); - - /** public method ReadEvent **/ - Bool_t ReadEvent(FairPrimaryGenerator*); - void SetParameters(char*); - void Print(); //! - - virtual Bool_t Init(); //! - - void SetMom(Double_t mom) { fMom = mom; }; - void SetId(Double_t id) { fId = id; }; - void SetHNLId(Int_t id) { fHNL = id; }; - void UseRandom1() { fUseRandom1 = kTRUE; fUseRandom3 = kFALSE; }; - void UseRandom3() { fUseRandom1 = kFALSE; fUseRandom3 = kTRUE; }; - void GetPythiaInstance(int); - - private: - - Pythia fPythia; //! - RndmEngine* fRandomEngine; //! - - protected: - - Double_t fMom; // proton momentum - Int_t fHNL; // HNL ID - Int_t fId; // target type - Bool_t fUseRandom1; // flag to use TRandom1 - Bool_t fUseRandom3; // flag to use TRandom3 (default) - - ClassDef(Pythia8Generator,1); + public: + /** default constructor **/ + Pythia8Generator(); + + /** destructor **/ + virtual ~Pythia8Generator(); + + /** public method ReadEvent **/ + Bool_t ReadEvent(FairPrimaryGenerator *); + void SetParameters(char *); + void Print(); //! + + virtual Bool_t Init(); //! + + void SetMom(Double_t mom) { fMom = mom; }; + void SetId(Double_t id) { fId = id; }; + void SetHNLId(Int_t id) { fHNL = id; }; + void UseRandom1() + { + fUseRandom1 = kTRUE; + fUseRandom3 = kFALSE; + }; + void UseRandom3() + { + fUseRandom1 = kFALSE; + fUseRandom3 = kTRUE; + }; + void GetPythiaInstance(int); + + private: + Pythia fPythia; //! + RndmEngine *fRandomEngine; //! + + protected: + Double_t fMom; // proton momentum + Int_t fHNL; // HNL ID + Int_t fId; // target type + Bool_t fUseRandom1; // flag to use TRandom1 + Bool_t fUseRandom3; // flag to use TRandom3 (default) + + ClassDef(Pythia8Generator, 1); }; #endif /* !PNDP8GENERATOR_H */ diff --git a/templates/project_root_containers/NewDetector/NewDetector.cxx b/templates/project_root_containers/NewDetector/NewDetector.cxx index 2cd2630edf..e667e2cef0 100644 --- a/templates/project_root_containers/NewDetector/NewDetector.cxx +++ b/templates/project_root_containers/NewDetector/NewDetector.cxx @@ -1,272 +1,260 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "NewDetector.h" -#include "NewDetectorPoint.h" -#include "NewDetectorGeo.h" -#include "NewDetectorGeoPar.h" - -#include "FairVolume.h" -#include "FairGeoVolume.h" +#include "FairGeoInterface.h" +#include "FairGeoLoader.h" #include "FairGeoNode.h" +#include "FairGeoVolume.h" #include "FairRootManager.h" -#include "FairGeoLoader.h" -#include "FairGeoInterface.h" #include "FairRun.h" #include "FairRuntimeDb.h" +#include "FairVolume.h" #include "MyProjDetectorList.h" #include "MyProjStack.h" +#include "NewDetectorGeo.h" +#include "NewDetectorGeoPar.h" +#include "NewDetectorPoint.h" #include -#include -#include #include #include -#include +#include #include #include - +#include +#include #include using std::cout; using std::endl; NewDetector::NewDetector() - : FairDetector("NewDetector", kTRUE, kNewDetector), - fTrackID(-1), - fVolumeID(-1), - fPos(), - fMom(), - fTime(-1.), - fLength(-1.), - fELoss(-1), - fNewDetectorPointCollection(new TClonesArray("NewDetectorPoint")) -{ -} + : FairDetector("NewDetector", kTRUE, kNewDetector) + , fTrackID(-1) + , fVolumeID(-1) + , fPos() + , fMom() + , fTime(-1.) + , fLength(-1.) + , fELoss(-1) + , fNewDetectorPointCollection(new TClonesArray("NewDetectorPoint")) +{} NewDetector::NewDetector(const char* name, Bool_t active) - : FairDetector(name, active, kNewDetector), - fTrackID(-1), - fVolumeID(-1), - fPos(), - fMom(), - fTime(-1.), - fLength(-1.), - fELoss(-1), - fNewDetectorPointCollection(new TClonesArray("NewDetectorPoint")) -{ -} + : FairDetector(name, active, kNewDetector) + , fTrackID(-1) + , fVolumeID(-1) + , fPos() + , fMom() + , fTime(-1.) + , fLength(-1.) + , fELoss(-1) + , fNewDetectorPointCollection(new TClonesArray("NewDetectorPoint")) +{} NewDetector::NewDetector(const NewDetector& right) - : FairDetector(right), - fTrackID(-1), - fVolumeID(-1), - fPos(), - fMom(), - fTime(-1.), - fLength(-1.), - fELoss(-1), - fNewDetectorPointCollection(new TClonesArray("NewDetectorPoint")) -{ -} + : FairDetector(right) + , fTrackID(-1) + , fVolumeID(-1) + , fPos() + , fMom() + , fTime(-1.) + , fLength(-1.) + , fELoss(-1) + , fNewDetectorPointCollection(new TClonesArray("NewDetectorPoint")) +{} NewDetector::~NewDetector() { - if (fNewDetectorPointCollection) { - fNewDetectorPointCollection->Delete(); - delete fNewDetectorPointCollection; - } + if (fNewDetectorPointCollection) { + fNewDetectorPointCollection->Delete(); + delete fNewDetectorPointCollection; + } } void NewDetector::Initialize() { - /** - * WORKAROUND needed for Geant4 in MT mode - * Call AddSensitiveVolume for sensitive volumes in order to fill - * thread-local FairModule::svList. - */ - DefineSensitiveVolumes(); - - FairDetector::Initialize(); - FairRuntimeDb* rtdb= FairRun::Instance()->GetRuntimeDb(); - NewDetectorGeoPar* par=(NewDetectorGeoPar*)(rtdb->getContainer("NewDetectorGeoPar")); + /** + * WORKAROUND needed for Geant4 in MT mode + * Call AddSensitiveVolume for sensitive volumes in order to fill + * thread-local FairModule::svList. + */ + DefineSensitiveVolumes(); + + FairDetector::Initialize(); + FairRuntimeDb* rtdb = FairRun::Instance()->GetRuntimeDb(); + NewDetectorGeoPar* par = (NewDetectorGeoPar*)(rtdb->getContainer("NewDetectorGeoPar")); } -Bool_t NewDetector::ProcessHits(FairVolume* vol) +Bool_t NewDetector::ProcessHits(FairVolume* vol) { - /** This method is called from the MC stepping */ - - //Set parameters at entrance of volume. Reset ELoss. - if ( TVirtualMC::GetMC()->IsTrackEntering() ) { - fELoss = 0.; - fTime = TVirtualMC::GetMC()->TrackTime() * 1.0e09; - fLength = TVirtualMC::GetMC()->TrackLength(); - TVirtualMC::GetMC()->TrackPosition(fPos); - TVirtualMC::GetMC()->TrackMomentum(fMom); - } - - // Sum energy loss for all steps in the active volume - fELoss += TVirtualMC::GetMC()->Edep(); - - // Create NewDetectorPoint at exit of active volume - if ( TVirtualMC::GetMC()->IsTrackExiting() || - TVirtualMC::GetMC()->IsTrackStop() || - TVirtualMC::GetMC()->IsTrackDisappeared() ) { - fTrackID = TVirtualMC::GetMC()->GetStack()->GetCurrentTrackNumber(); - fVolumeID = vol->getMCid(); - if (fELoss == 0. ) { return kFALSE; } - AddHit(fTrackID, fVolumeID, TVector3(fPos.X(), fPos.Y(), fPos.Z()), - TVector3(fMom.Px(), fMom.Py(), fMom.Pz()), fTime, fLength, - fELoss); - - // Increment number of NewDetector det points in TParticle - MyProjStack* stack = (MyProjStack*) TVirtualMC::GetMC()->GetStack(); - stack->AddPoint(kNewDetector); - } - - return kTRUE; + /** This method is called from the MC stepping */ + + // Set parameters at entrance of volume. Reset ELoss. + if (TVirtualMC::GetMC()->IsTrackEntering()) { + fELoss = 0.; + fTime = TVirtualMC::GetMC()->TrackTime() * 1.0e09; + fLength = TVirtualMC::GetMC()->TrackLength(); + TVirtualMC::GetMC()->TrackPosition(fPos); + TVirtualMC::GetMC()->TrackMomentum(fMom); + } + + // Sum energy loss for all steps in the active volume + fELoss += TVirtualMC::GetMC()->Edep(); + + // Create NewDetectorPoint at exit of active volume + if (TVirtualMC::GetMC()->IsTrackExiting() || TVirtualMC::GetMC()->IsTrackStop() + || TVirtualMC::GetMC()->IsTrackDisappeared()) { + fTrackID = TVirtualMC::GetMC()->GetStack()->GetCurrentTrackNumber(); + fVolumeID = vol->getMCid(); + if (fELoss == 0.) { + return kFALSE; + } + AddHit(fTrackID, + fVolumeID, + TVector3(fPos.X(), fPos.Y(), fPos.Z()), + TVector3(fMom.Px(), fMom.Py(), fMom.Pz()), + fTime, + fLength, + fELoss); + + // Increment number of NewDetector det points in TParticle + MyProjStack* stack = (MyProjStack*)TVirtualMC::GetMC()->GetStack(); + stack->AddPoint(kNewDetector); + } + + return kTRUE; } void NewDetector::EndOfEvent() { - LOG(info) << "NewDetector: " << fNewDetectorPointCollection->GetEntriesFast() - << " points registered in this event"; - - fNewDetectorPointCollection->Clear(); + LOG(info) << "NewDetector: " << fNewDetectorPointCollection->GetEntriesFast() << " points registered in this event"; + fNewDetectorPointCollection->Clear(); } - - void NewDetector::Register() { - /** This will create a branch in the output tree called + /** This will create a branch in the output tree called NewDetectorPoint, setting the last parameter to kFALSE means: this collection will not be written to the file, it will exist only during the simulation. */ - if ( ! gMC->IsMT() ) { - FairRootManager::Instance()->Register("NewDetectorPoint", "NewDetector", - fNewDetectorPointCollection, kTRUE); - } else { - FairRootManager::Instance()->RegisterAny("NewDetectorPoint", - fNewDetectorPointCollection, kTRUE); - } - + if (!gMC->IsMT()) { + FairRootManager::Instance()->Register("NewDetectorPoint", "NewDetector", fNewDetectorPointCollection, kTRUE); + } else { + FairRootManager::Instance()->RegisterAny("NewDetectorPoint", fNewDetectorPointCollection, kTRUE); + } } - TClonesArray* NewDetector::GetCollection(Int_t iColl) const { - if (iColl == 0) { return fNewDetectorPointCollection; } - else { return NULL; } + if (iColl == 0) { + return fNewDetectorPointCollection; + } else { + return NULL; + } } -void NewDetector::Reset() -{ - fNewDetectorPointCollection->Clear(); -} +void NewDetector::Reset() { fNewDetectorPointCollection->Clear(); } void NewDetector::ConstructGeometry() { - TGeoVolume *top=gGeoManager->GetTopVolume(); - TGeoMedium *Si =gGeoManager->GetMedium("Si"); - TGeoMedium *Carbon = gGeoManager->GetMedium("C"); + TGeoVolume* top = gGeoManager->GetTopVolume(); + TGeoMedium* Si = gGeoManager->GetMedium("Si"); + TGeoMedium* Carbon = gGeoManager->GetMedium("C"); - if(Si==0){ - TGeoMaterial *matSi = new TGeoMaterial("Si", 28.0855, 14, 2.33); - Si = new TGeoMedium("Si", 2, matSi); + if (Si == 0) { + TGeoMaterial* matSi = new TGeoMaterial("Si", 28.0855, 14, 2.33); + Si = new TGeoMedium("Si", 2, matSi); } - if(Carbon==0){ - TGeoMaterial *matCarbon = new TGeoMaterial("C", 12.011, 6.0, 2.265); - Carbon = new TGeoMedium("C", 3, matCarbon); + if (Carbon == 0) { + TGeoMaterial* matCarbon = new TGeoMaterial("C", 12.011, 6.0, 2.265); + Carbon = new TGeoMedium("C", 3, matCarbon); } - - TGeoVolume *det1= gGeoManager->MakeTubs("Det1",Si,5,80,0.1,0,360); + TGeoVolume* det1 = gGeoManager->MakeTubs("Det1", Si, 5, 80, 0.1, 0, 360); TGeoRotation r1; - r1.SetAngles(0,0,0); + r1.SetAngles(0, 0, 0); TGeoTranslation t1(0, 0, 0); TGeoCombiTrans c1(t1, r1); - TGeoHMatrix *h1 = new TGeoHMatrix(c1); - top->AddNode(det1,1,h1); + TGeoHMatrix* h1 = new TGeoHMatrix(c1); + top->AddNode(det1, 1, h1); det1->SetLineColor(kGreen); AddSensitiveVolume(det1); - TGeoVolume *passive1= gGeoManager->MakeTubs("Pass1",Si,5,120,10,0,360); + TGeoVolume* passive1 = gGeoManager->MakeTubs("Pass1", Si, 5, 120, 10, 0, 360); TGeoRotation rp1; - rp1.SetAngles(0,0,0); + rp1.SetAngles(0, 0, 0); TGeoTranslation tp1(0, 0, 20); TGeoCombiTrans cp1(tp1, rp1); - TGeoHMatrix *hp1 = new TGeoHMatrix(cp1); - top->AddNode(passive1,1,hp1); + TGeoHMatrix* hp1 = new TGeoHMatrix(cp1); + top->AddNode(passive1, 1, hp1); passive1->SetLineColor(kRed); - - - TGeoVolume *det2= gGeoManager->MakeTubs("Det2",Si,5,150,0.1,0,360); + TGeoVolume* det2 = gGeoManager->MakeTubs("Det2", Si, 5, 150, 0.1, 0, 360); TGeoRotation r2; - r2.SetAngles(0,0,0); + r2.SetAngles(0, 0, 0); TGeoTranslation t2(0, 0, 70); TGeoCombiTrans c2(t2, r2); - TGeoHMatrix *h2 = new TGeoHMatrix(c2); - top->AddNode(det2,1,h2); + TGeoHMatrix* h2 = new TGeoHMatrix(c2); + top->AddNode(det2, 1, h2); det2->SetLineColor(kGreen); AddSensitiveVolume(det2); - TGeoVolume *det3= gGeoManager->MakeTubs("Det3",Si,5,150,0.1,0,360); + TGeoVolume* det3 = gGeoManager->MakeTubs("Det3", Si, 5, 150, 0.1, 0, 360); TGeoRotation r3; - r3.SetAngles(0,0,0); + r3.SetAngles(0, 0, 0); TGeoTranslation t3(0, 0, 150); TGeoCombiTrans c3(t3, r3); - TGeoHMatrix *h3 = new TGeoHMatrix(c3); - top->AddNode(det3,1,h3); + TGeoHMatrix* h3 = new TGeoHMatrix(c3); + top->AddNode(det3, 1, h3); det3->SetLineColor(kGreen); AddSensitiveVolume(det3); } -NewDetectorPoint* NewDetector::AddHit(Int_t trackID, Int_t detID, - TVector3 pos, TVector3 mom, - Double_t time, Double_t length, +NewDetectorPoint* NewDetector::AddHit(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t time, + Double_t length, Double_t eLoss) { - TClonesArray& clref = *fNewDetectorPointCollection; - Int_t size = clref.GetEntriesFast(); - return new(clref[size]) NewDetectorPoint(trackID, detID, pos, mom, - time, length, eLoss); + TClonesArray& clref = *fNewDetectorPointCollection; + Int_t size = clref.GetEntriesFast(); + return new (clref[size]) NewDetectorPoint(trackID, detID, pos, mom, time, length, eLoss); } -FairModule* NewDetector::CloneModule() const -{ - return new NewDetector(*this); -} +FairModule* NewDetector::CloneModule() const { return new NewDetector(*this); } void NewDetector::DefineSensitiveVolumes() { - TObjArray* volumes = gGeoManager->GetListOfVolumes(); - TIter next(volumes); - TGeoVolume* volume; - while ( ( volume = static_cast(next()) ) ) { - if ( IsSensitive(volume->GetName()) ) { - LOG(debug2)<<"Sensitive Volume "<< volume->GetName(); - AddSensitiveVolume(volume); + TObjArray* volumes = gGeoManager->GetListOfVolumes(); + TIter next(volumes); + TGeoVolume* volume; + while ((volume = static_cast(next()))) { + if (IsSensitive(volume->GetName())) { + LOG(debug2) << "Sensitive Volume " << volume->GetName(); + AddSensitiveVolume(volume); + } } - } } Bool_t NewDetector::IsSensitive(const std::string& name) { - if ( name.find("Det") != std::string::npos ) { + if (name.find("Det") != std::string::npos) { return kTRUE; } return kFALSE; } -ClassImp(NewDetector) +ClassImp(NewDetector); diff --git a/templates/project_root_containers/NewDetector/NewDetector.h b/templates/project_root_containers/NewDetector/NewDetector.h index a1265906ff..b1466af849 100644 --- a/templates/project_root_containers/NewDetector/NewDetector.h +++ b/templates/project_root_containers/NewDetector/NewDetector.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef NEWDETECTOR_H @@ -10,22 +10,21 @@ #include "FairDetector.h" -#include #include +#include class NewDetectorPoint; class FairVolume; class TClonesArray; -class NewDetector: public FairDetector +class NewDetector : public FairDetector { public: - /** Name : Detector Name * Active: kTRUE for active detectors (ProcessHits() will be called) * kFALSE for inactive detectors - */ + */ NewDetector(const char* Name, Bool_t Active); /** default constructor */ @@ -35,75 +34,70 @@ class NewDetector: public FairDetector virtual ~NewDetector(); /** 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(); - - /** This method is an example of how to add your own point * of type NewDetectorPoint to the clones array - */ - NewDetectorPoint* AddHit(Int_t trackID, Int_t detID, - TVector3 pos, TVector3 mom, - Double_t time, Double_t length, - Double_t eLoss); + */ + NewDetectorPoint* + AddHit(Int_t trackID, Int_t detID, TVector3 pos, TVector3 mom, Double_t time, Double_t length, Double_t eLoss); /** The following methods can be implemented if you need to make * any optional action in your detector during the transport. - */ + */ - 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 SetSpecialPhysicsCuts() { ; } + virtual void EndOfEvent(); + virtual void FinishPrimary() { ; } + virtual void FinishRun() { ; } + virtual void BeginPrimary() { ; } + virtual void PostTrack() { ; } + virtual void PreTrack() { ; } + virtual void BeginEvent() { ; } virtual FairModule* CloneModule() const; virtual Bool_t IsSensitive(const std::string& name); 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* fNewDetectorPointCollection; //! + TClonesArray* fNewDetectorPointCollection; //! NewDetector(const NewDetector&); NewDetector& operator=(const NewDetector&); void DefineSensitiveVolumes(); - ClassDef(NewDetector,2) + ClassDef(NewDetector, 2) }; -#endif //NEWDETECTOR_H +#endif // NEWDETECTOR_H diff --git a/templates/project_root_containers/NewDetector/NewDetectorContFact.cxx b/templates/project_root_containers/NewDetector/NewDetectorContFact.cxx index 428dbcb088..9466b6c6d9 100644 --- a/templates/project_root_containers/NewDetector/NewDetectorContFact.cxx +++ b/templates/project_root_containers/NewDetector/NewDetectorContFact.cxx @@ -1,59 +1,55 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "NewDetectorContFact.h" -#include "NewDetectorGeoPar.h" - #include "FairRuntimeDb.h" +#include "NewDetectorGeoPar.h" #include -ClassImp(NewDetectorContFact) +ClassImp(NewDetectorContFact); static NewDetectorContFact gNewDetectorContFact; NewDetectorContFact::NewDetectorContFact() - : FairContFact() + : FairContFact() { - /** Constructor (called when the library is loaded) */ - fName="NewDetectorContFact"; - fTitle="Factory for parameter containers in libNewDetector"; - setAllContainers(); - FairRuntimeDb::instance()->addContFactory(this); + /** Constructor (called when the library is loaded) */ + fName = "NewDetectorContFact"; + fTitle = "Factory for parameter containers in libNewDetector"; + setAllContainers(); + FairRuntimeDb::instance()->addContFactory(this); } void NewDetectorContFact::setAllContainers() { - /** Creates the Container objects with all accepted + /** Creates the Container objects with all accepted contexts and adds them to the list of containers for the NewDetector library. */ - FairContainer* p= new FairContainer("NewDetectorGeoPar", - "NewDetector Geometry Parameters", - "TestDefaultContext"); - p->addContext("TestNonDefaultContext"); + FairContainer* p = new FairContainer("NewDetectorGeoPar", "NewDetector Geometry Parameters", "TestDefaultContext"); + p->addContext("TestNonDefaultContext"); - containers->Add(p); + containers->Add(p); } FairParSet* NewDetectorContFact::createContainer(FairContainer* c) { - /** Calls the constructor of the corresponding parameter container. + /** 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,"NewDetectorGeoPar")==0) { - p=new NewDetectorGeoPar(c->getConcatName().Data(), - c->GetTitle(),c->getContext()); - } - return p; + const char* name = c->GetName(); + FairParSet* p = NULL; + if (strcmp(name, "NewDetectorGeoPar") == 0) { + p = new NewDetectorGeoPar(c->getConcatName().Data(), c->GetTitle(), c->getContext()); + } + return p; } diff --git a/templates/project_root_containers/NewDetector/NewDetectorContFact.h b/templates/project_root_containers/NewDetector/NewDetectorContFact.h index f5e4958971..e4c70dca22 100644 --- a/templates/project_root_containers/NewDetector/NewDetectorContFact.h +++ b/templates/project_root_containers/NewDetector/NewDetectorContFact.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef NEWDETECTORCONTFACT_H @@ -16,11 +16,12 @@ class NewDetectorContFact : public FairContFact { private: void setAllContainers(); + public: NewDetectorContFact(); ~NewDetectorContFact() {} FairParSet* createContainer(FairContainer*); - ClassDef( NewDetectorContFact,0) // Factory for all NewDetector parameter containers + ClassDef(NewDetectorContFact, 0) // Factory for all NewDetector parameter containers }; #endif diff --git a/templates/project_root_containers/NewDetector/NewDetectorGeo.cxx b/templates/project_root_containers/NewDetector/NewDetectorGeo.cxx index 51d77d9fed..8498754bcd 100644 --- a/templates/project_root_containers/NewDetector/NewDetectorGeo.cxx +++ b/templates/project_root_containers/NewDetector/NewDetectorGeo.cxx @@ -1,43 +1,44 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "NewDetectorGeo.h" + #include "FairGeoNode.h" -ClassImp(NewDetectorGeo) +ClassImp(NewDetectorGeo); // ----- Default constructor ------------------------------------------- NewDetectorGeo::NewDetectorGeo() - : FairGeoSet() + : FairGeoSet() { - // Constructor - // fName has to be the name used in the geometry for all volumes. - // If there is a mismatch the geometry cannot be build. - fName="newdetector"; - maxSectors=0; - maxModules=10; + // Constructor + // fName has to be the name used in the geometry for all volumes. + // If there is a mismatch the geometry cannot be build. + fName = "newdetector"; + maxSectors = 0; + maxModules = 10; } // ------------------------------------------------------------------------- const char* NewDetectorGeo::getModuleName(Int_t m) { - /** Returns the module name of NewDetector number m + /** Returns the module name of NewDetector number m Setting NewDetector here means that all modules names in the ASCII file should start with NewDetector otherwise they will not be constructed */ - sprintf(modName,"NewDetector%i",m+1); - return modName; + sprintf(modName, "NewDetector%i", m + 1); + return modName; } const char* NewDetectorGeo::getEleName(Int_t m) { - /** Returns the element name of Det number m */ - sprintf(eleName,"NewDetector%i",m+1); - return eleName; + /** Returns the element name of Det number m */ + sprintf(eleName, "NewDetector%i", m + 1); + return eleName; } diff --git a/templates/project_root_containers/NewDetector/NewDetectorGeo.h b/templates/project_root_containers/NewDetector/NewDetectorGeo.h index 80b9a67a71..6dd4ab5452 100644 --- a/templates/project_root_containers/NewDetector/NewDetectorGeo.h +++ b/templates/project_root_containers/NewDetector/NewDetectorGeo.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef NEWDETECTORGEO_H @@ -10,29 +10,29 @@ #include "FairGeoSet.h" -class NewDetectorGeo : public FairGeoSet +class NewDetectorGeo : public FairGeoSet { protected: - char modName[20]; // name of module - char eleName[20]; // substring for elements in module + char modName[20]; // name of module + char eleName[20]; // substring for elements in module public: NewDetectorGeo(); ~NewDetectorGeo() {} const char* getModuleName(Int_t); const char* getEleName(Int_t); inline Int_t getModNumInMod(const TString&); - ClassDef(NewDetectorGeo,1) + ClassDef(NewDetectorGeo, 1) }; inline Int_t NewDetectorGeo::getModNumInMod(const TString& name) { - /** returns the module index from module name + /** returns the module index from module name ?? in name[??] has to be the length of the detector name in the .geo file. For example if all nodes in this file starts with newdetector ?? has to be 11. */ - return (Int_t)(name[11]-'0')-1; // + return (Int_t)(name[11] - '0') - 1; // } #endif diff --git a/templates/project_root_containers/NewDetector/NewDetectorGeoPar.cxx b/templates/project_root_containers/NewDetector/NewDetectorGeoPar.cxx index 96674a51b3..a40fd67e7f 100644 --- a/templates/project_root_containers/NewDetector/NewDetectorGeoPar.cxx +++ b/templates/project_root_containers/NewDetector/NewDetectorGeoPar.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "NewDetectorGeoPar.h" @@ -10,41 +10,43 @@ #include "FairParamList.h" #include - #include -ClassImp(NewDetectorGeoPar) +ClassImp(NewDetectorGeoPar); -NewDetectorGeoPar ::NewDetectorGeoPar(const char* name, - const char* title, - const char* context) - : FairParGenericSet(name,title,context), - fGeoSensNodes(new TObjArray()), - fGeoPassNodes(new TObjArray()) -{ -} +NewDetectorGeoPar ::NewDetectorGeoPar(const char* name, const char* title, const char* context) + : FairParGenericSet(name, title, context) + , fGeoSensNodes(new TObjArray()) + , fGeoPassNodes(new TObjArray()) +{} -NewDetectorGeoPar::~NewDetectorGeoPar(void) -{ -} +NewDetectorGeoPar::~NewDetectorGeoPar(void) {} void NewDetectorGeoPar::clear(void) { - delete fGeoSensNodes; - delete fGeoPassNodes; + delete fGeoSensNodes; + delete fGeoPassNodes; } void NewDetectorGeoPar::putParams(FairParamList* l) { - if (!l) { return; } - l->addObject("FairGeoNodes Sensitive List", fGeoSensNodes); - l->addObject("FairGeoNodes Passive List", fGeoPassNodes); + if (!l) { + return; + } + l->addObject("FairGeoNodes Sensitive List", fGeoSensNodes); + l->addObject("FairGeoNodes Passive List", fGeoPassNodes); } Bool_t NewDetectorGeoPar::getParams(FairParamList* l) { - if (!l) { return kFALSE; } - if (!l->fillObject("FairGeoNodes Sensitive List", fGeoSensNodes)) { return kFALSE; } - if (!l->fillObject("FairGeoNodes Passive List", fGeoPassNodes)) { return kFALSE; } - return kTRUE; + if (!l) { + return kFALSE; + } + if (!l->fillObject("FairGeoNodes Sensitive List", fGeoSensNodes)) { + return kFALSE; + } + if (!l->fillObject("FairGeoNodes Passive List", fGeoPassNodes)) { + return kFALSE; + } + return kTRUE; } diff --git a/templates/project_root_containers/NewDetector/NewDetectorGeoPar.h b/templates/project_root_containers/NewDetector/NewDetectorGeoPar.h index 96997079c9..b689979309 100644 --- a/templates/project_root_containers/NewDetector/NewDetectorGeoPar.h +++ b/templates/project_root_containers/NewDetector/NewDetectorGeoPar.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef NEWDETECTORGEOPAR_H @@ -13,31 +13,30 @@ class TObjArray; class FairParamList; -class NewDetectorGeoPar : public FairParGenericSet +class NewDetectorGeoPar : public FairParGenericSet { public: - /** List of FairGeoNodes for sensitive volumes */ - TObjArray* fGeoSensNodes; + TObjArray* fGeoSensNodes; /** List of FairGeoNodes for sensitive volumes */ - TObjArray* fGeoPassNodes; + TObjArray* fGeoPassNodes; - NewDetectorGeoPar(const char* name="NewDetectorGeoPar", - const char* title="NewDetector Geometry Parameters", - const char* context="TestDefaultContext"); + NewDetectorGeoPar(const char* name = "NewDetectorGeoPar", + const char* title = "NewDetector Geometry Parameters", + const char* context = "TestDefaultContext"); ~NewDetectorGeoPar(void); void clear(void); void putParams(FairParamList*); Bool_t getParams(FairParamList*); - TObjArray* GetGeoSensitiveNodes() {return fGeoSensNodes;} - TObjArray* GetGeoPassiveNodes() {return fGeoPassNodes;} + TObjArray* GetGeoSensitiveNodes() { return fGeoSensNodes; } + TObjArray* GetGeoPassiveNodes() { return fGeoPassNodes; } private: NewDetectorGeoPar(const NewDetectorGeoPar&); NewDetectorGeoPar& operator=(const NewDetectorGeoPar&); - ClassDef(NewDetectorGeoPar,1) + ClassDef(NewDetectorGeoPar, 1) }; #endif diff --git a/templates/project_root_containers/NewDetector/NewDetectorPoint.cxx b/templates/project_root_containers/NewDetector/NewDetectorPoint.cxx index a7f06a61ff..7a74f497b7 100644 --- a/templates/project_root_containers/NewDetector/NewDetectorPoint.cxx +++ b/templates/project_root_containers/NewDetector/NewDetectorPoint.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "NewDetectorPoint.h" @@ -11,41 +11,37 @@ using std::cout; using std::endl; - // ----- Default constructor ------------------------------------------- NewDetectorPoint::NewDetectorPoint() - : FairMCPoint() -{ -} + : FairMCPoint() +{} // ------------------------------------------------------------------------- // ----- Standard constructor ------------------------------------------ -NewDetectorPoint::NewDetectorPoint(Int_t trackID, Int_t detID, - TVector3 pos, TVector3 mom, - Double_t tof, Double_t length, +NewDetectorPoint::NewDetectorPoint(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t tof, + Double_t length, Double_t eLoss) - : FairMCPoint(trackID, detID, pos, mom, tof, length, eLoss) -{ -} + : FairMCPoint(trackID, detID, pos, mom, tof, length, eLoss) +{} // ------------------------------------------------------------------------- // ----- Destructor ---------------------------------------------------- -NewDetectorPoint::~NewDetectorPoint() { } +NewDetectorPoint::~NewDetectorPoint() {} // ------------------------------------------------------------------------- // ----- Public method Print ------------------------------------------- void NewDetectorPoint::Print(const Option_t* /*opt*/) const { - cout << "-I- NewDetectorPoint: NewDetector 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- NewDetectorPoint: NewDetector 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; } // ------------------------------------------------------------------------- -ClassImp(NewDetectorPoint) - +ClassImp(NewDetectorPoint); diff --git a/templates/project_root_containers/NewDetector/NewDetectorPoint.h b/templates/project_root_containers/NewDetector/NewDetectorPoint.h index beeffe54bd..6fd7db2d08 100644 --- a/templates/project_root_containers/NewDetector/NewDetectorPoint.h +++ b/templates/project_root_containers/NewDetector/NewDetectorPoint.h @@ -1,14 +1,13 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef NEWDETECTORPOINT_H #define NEWDETECTORPOINT_H 1 - #include "FairMCPoint.h" #include @@ -18,11 +17,9 @@ class NewDetectorPoint : public FairMCPoint { public: - /** Default constructor **/ NewDetectorPoint(); - /** Constructor with arguments *@param trackID Index of MCTrack *@param detID Detector ID @@ -32,11 +29,13 @@ class NewDetectorPoint : public FairMCPoint *@param length Track length since creation [cm] *@param eLoss Energy deposit [GeV] **/ - NewDetectorPoint(Int_t trackID, Int_t detID, TVector3 pos, TVector3 mom, - Double_t tof, Double_t length, Double_t eLoss); - - - + NewDetectorPoint(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t tof, + Double_t length, + Double_t eLoss); /** Destructor **/ virtual ~NewDetectorPoint(); @@ -49,8 +48,7 @@ class NewDetectorPoint : public FairMCPoint NewDetectorPoint(const NewDetectorPoint& point); NewDetectorPoint operator=(const NewDetectorPoint& point); - ClassDef(NewDetectorPoint,1) - + ClassDef(NewDetectorPoint, 1) }; #endif diff --git a/templates/project_root_containers/field/MyConstField.cxx b/templates/project_root_containers/field/MyConstField.cxx index 8538ec5a08..258e751354 100644 --- a/templates/project_root_containers/field/MyConstField.cxx +++ b/templates/project_root_containers/field/MyConstField.cxx @@ -18,174 +18,158 @@ #include #include -using std::cout; using std::cerr; +using std::cout; using std::endl; using std::setw; - // ----- Default constructor ------------------------------------------- -MyConstField::MyConstField() - : FairField(), - fXmin(0.), - fXmax(0.), - fYmin(0.), - fYmax(0.), - fZmin(0.), - fZmax(0.), - fBx(0.), - fBy(0.), - fBz(0.) +MyConstField::MyConstField() + : 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 ------------------------------------------ -MyConstField::MyConstField(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) +MyConstField::MyConstField(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 ------------------------------- MyConstField::MyConstField(MyFieldPar* 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- MyConstField::MyConstField: 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- MyConstField::MyConstField: 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 ---------------------------------------------------- -MyConstField::~MyConstField() { } +MyConstField::~MyConstField() {} // ------------------------------------------------------------------------- - - // ----- Set field region ---------------------------------------------- -void MyConstField::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 MyConstField::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 MyConstField::SetField(Double_t bX, Double_t bY, Double_t bZ) { - fBx = bX; - fBy = bY; - fBz = bZ; +void MyConstField::SetField(Double_t bX, Double_t bY, Double_t bZ) +{ + fBx = bX; + fBy = bY; + fBz = bZ; } // ------------------------------------------------------------------------- - - // ----- Get x component of field -------------------------------------- -Double_t MyConstField::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 MyConstField::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 MyConstField::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 MyConstField::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 MyConstField::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 MyConstField::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 MyConstField::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 MyConstField::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; } // ------------------------------------------------------------------------- - - -ClassImp(MyConstField) +ClassImp(MyConstField); diff --git a/templates/project_root_containers/field/MyConstField.h b/templates/project_root_containers/field/MyConstField.h index 91274ef949..079b3d4ade 100644 --- a/templates/project_root_containers/field/MyConstField.h +++ b/templates/project_root_containers/field/MyConstField.h @@ -11,7 +11,6 @@ // ----- Created 25/03/14 by M. Al-Turany ----- // ------------------------------------------------------------------------- - /** MyConstField.h ** @author M.Al-Turany ** @since 25.03.2014 @@ -20,106 +19,94 @@ ** A constant (homogeneous) magnetic field **/ - #ifndef MyConstField_H #define MyConstField_H 1 - #include "FairField.h" - class MyFieldPar; - class MyConstField : public FairField { - public: - - /** Default constructor **/ - MyConstField(); - - - /** 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] - **/ - MyConstField(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 MyFieldPar **/ - MyConstField(MyFieldPar* fieldPar); - - - /** Destructor **/ - virtual ~MyConstField(); - - - /** 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(MyConstField, 1); - + public: + /** Default constructor **/ + MyConstField(); + + /** 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] + **/ + MyConstField(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 MyFieldPar **/ + MyConstField(MyFieldPar* fieldPar); + + /** Destructor **/ + virtual ~MyConstField(); + + /** 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(MyConstField, 1); }; - #endif diff --git a/templates/project_root_containers/field/MyFieldCreator.cxx b/templates/project_root_containers/field/MyFieldCreator.cxx index 5f4fc54275..dd0a545b05 100644 --- a/templates/project_root_containers/field/MyFieldCreator.cxx +++ b/templates/project_root_containers/field/MyFieldCreator.cxx @@ -12,61 +12,56 @@ #include "MyFieldCreator.h" -#include "MyFieldPar.h" -#include "MyConstField.h" - +#include "FairField.h" #include "FairRunAna.h" #include "FairRuntimeDb.h" -#include "FairField.h" +#include "MyConstField.h" +#include "MyFieldPar.h" #include -using std::cout; using std::cerr; +using std::cout; using std::endl; static MyFieldCreator gMyFieldCreator; MyFieldCreator::MyFieldCreator() - :FairFieldFactory(), - fFieldPar(NULL) + : FairFieldFactory() + , fFieldPar(NULL) { - fCreator=this; + fCreator = this; } -MyFieldCreator::~MyFieldCreator() -{ -} +MyFieldCreator::~MyFieldCreator() {} void MyFieldCreator::SetParm() { - FairRunAna *Run = FairRunAna::Instance(); - FairRuntimeDb *RunDB = Run->GetRuntimeDb(); - fFieldPar = (MyFieldPar*) RunDB->getContainer("MyFieldPar"); - + FairRunAna *Run = FairRunAna::Instance(); + FairRuntimeDb *RunDB = Run->GetRuntimeDb(); + fFieldPar = (MyFieldPar *)RunDB->getContainer("MyFieldPar"); } -FairField* MyFieldCreator::createFairField() -{ - FairField *fMagneticField=0; +FairField *MyFieldCreator::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 MyConstField(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; + if (!fFieldPar) { + cerr << "-E- No field parameters available!" << endl; + } else { + // Instantiate correct field type + Int_t fType = fFieldPar->GetType(); + if (fType == 0) + fMagneticField = new MyConstField(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; } - -ClassImp(MyFieldCreator) +ClassImp(MyFieldCreator); diff --git a/templates/project_root_containers/field/MyFieldCreator.h b/templates/project_root_containers/field/MyFieldCreator.h index aaa73cef7e..2e0b5203e2 100644 --- a/templates/project_root_containers/field/MyFieldCreator.h +++ b/templates/project_root_containers/field/MyFieldCreator.h @@ -11,7 +11,6 @@ // ----- Created 26/03/14 by M. Al-Turany ----- // ------------------------------------------------------------------------- - #ifndef MyFieldCreator_H #define MyFieldCreator_H @@ -21,22 +20,21 @@ class MyFieldPar; class FairField; -class MyFieldCreator : public FairFieldFactory +class MyFieldCreator : public FairFieldFactory { - public: - MyFieldCreator(); - virtual ~MyFieldCreator(); - virtual FairField* createFairField(); - virtual void SetParm(); - ClassDef(MyFieldCreator,1); - - protected: - MyFieldPar* fFieldPar; - - private: - MyFieldCreator(const MyFieldCreator&); - MyFieldCreator& operator=(const MyFieldCreator&); + public: + MyFieldCreator(); + virtual ~MyFieldCreator(); + virtual FairField* createFairField(); + virtual void SetParm(); + ClassDef(MyFieldCreator, 1); + + protected: + MyFieldPar* fFieldPar; + private: + MyFieldCreator(const MyFieldCreator&); + MyFieldCreator& operator=(const MyFieldCreator&); }; -#endif //MyFieldCreator_H +#endif // MyFieldCreator_H diff --git a/templates/project_root_containers/field/MyFieldPar.cxx b/templates/project_root_containers/field/MyFieldPar.cxx index 3022e6524f..a19e65f995 100644 --- a/templates/project_root_containers/field/MyFieldPar.cxx +++ b/templates/project_root_containers/field/MyFieldPar.cxx @@ -11,190 +11,190 @@ // ----- Created 26/03/14 by M. Al-Turany ----- // ------------------------------------------------------------------------- - #include "MyFieldPar.h" -#include "MyConstField.h" #include "FairParamList.h" +#include "MyConstField.h" #include -using std::cout; using std::cerr; +using std::cout; using std::endl; -const int kMaxLen = 2048; +const int kMaxLen = 2048; // ------ Constructor -------------------------------------------------- -MyFieldPar::MyFieldPar(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.) - -{ -} +MyFieldPar::MyFieldPar(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.) + +{} // ------------------------------------------------------------------------- -MyFieldPar::MyFieldPar() - : 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.) - -{ -} +MyFieldPar::MyFieldPar() + : 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 --------------------------------------------------- -MyFieldPar::~MyFieldPar() { } +MyFieldPar::~MyFieldPar() {} // ------------------------------------------------------------------------- - - // ------ Put parameters ----------------------------------------------- -void MyFieldPar::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 MyFieldPar::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 MyFieldPar::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 MyFieldPar::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 MyFieldPar::SetParameters(FairField* field) +{ + if (!field) { + cerr << "-W- MyFieldPar::SetParameters: Empty field pointer!" << endl; + return; + } + + fType = field->GetType(); + + if (fType == 0) { // constant field + MyConstField* fieldConst = (MyConstField*)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- MyFieldPar::SetParameters: Unknown field type " << fType << "!" << endl; + fBx = fBy = fBz = 0.; + fXmin = fXmax = fYmin = fYmax = fZmin = fZmax = 0.; + fMapName = ""; + fPosX = fPosY = fPosZ = fScale = 0.; + } -void MyFieldPar::SetParameters(FairField* field) { - - if ( ! field ) { - cerr << "-W- MyFieldPar::SetParameters: Empty field pointer!" << endl; return; - } - - fType = field->GetType(); - - if ( fType == 0 ) { // constant field - MyConstField* fieldConst = (MyConstField*) 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- MyFieldPar::SetParameters: Unknown field type " - << fType << "!" << endl; - fBx = fBy = fBz = 0.; - fXmin = fXmax = fYmin = fYmax = fZmin = fZmax = 0.; - fMapName = ""; - fPosX = fPosY = fPosZ = fScale = 0.; - } - - return; - } // ------------------------------------------------------------------------- - - - - - -ClassImp(MyFieldPar) - +ClassImp(MyFieldPar); diff --git a/templates/project_root_containers/field/MyFieldPar.h b/templates/project_root_containers/field/MyFieldPar.h index daa7070e2f..bd9846d3cb 100644 --- a/templates/project_root_containers/field/MyFieldPar.h +++ b/templates/project_root_containers/field/MyFieldPar.h @@ -11,8 +11,6 @@ // ----- Created 26/03/14 by M. Al-Turany ----- // ------------------------------------------------------------------------- - - #ifndef MyFieldPar_H #define MyFieldPar_H 1 @@ -21,101 +19,84 @@ class FairField; class FairParamList; -const int kMaxFieldMapType = 5; +const int kMaxFieldMapType = 5; class MyFieldPar : public FairParGenericSet { - public: - - - /** Standard constructor **/ - MyFieldPar(const char* name, const char* title, const char* context); - -/** default constructor **/ - MyFieldPar(); - - /** Destructor **/ - ~MyFieldPar(); - - - /** 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; } - - - - 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; - - - MyFieldPar(const MyFieldPar&); - MyFieldPar& operator=(const MyFieldPar&); - - ClassDef(MyFieldPar,1); - + public: + /** Standard constructor **/ + MyFieldPar(const char* name, const char* title, const char* context); + + /** default constructor **/ + MyFieldPar(); + + /** Destructor **/ + ~MyFieldPar(); + + /** 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; } + + 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; + + MyFieldPar(const MyFieldPar&); + MyFieldPar& operator=(const MyFieldPar&); + + ClassDef(MyFieldPar, 1); }; - #endif diff --git a/templates/project_root_containers/gconfig/DecayConfig.C b/templates/project_root_containers/gconfig/DecayConfig.C index 4f83d837fd..fa8dafcdd3 100644 --- a/templates/project_root_containers/gconfig/DecayConfig.C +++ b/templates/project_root_containers/gconfig/DecayConfig.C @@ -6,94 +6,94 @@ * copied verbatim in the file "LICENSE" * ********************************************************************************/ -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. - - // 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; +void DecayConfig() +{ - //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); + // 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. - 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); - - 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]; - - 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 - } - - - // 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); - //} -} + // 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; + + // 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(); + + // 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()); + // 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 + + pythia6.SetMDCY(pythia6.Pycomp(ipdg), 1, 1); // Activate decay in pythia + } + + // 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); + //} +} diff --git a/templates/project_root_containers/gconfig/Geane.C b/templates/project_root_containers/gconfig/Geane.C index 263e4be3b9..4f74c4f143 100644 --- a/templates/project_root_containers/gconfig/Geane.C +++ b/templates/project_root_containers/gconfig/Geane.C @@ -10,38 +10,41 @@ void Config() { - TGeoMedium *m=gGeoManager->GetMedium("air"); - if(m != NULL) m->SetParam(6, 0.005); // epsil - TGeoMedium *m2=gGeoManager->GetMedium("FscScint"); - if(m2 != NULL) m2->SetParam(6, 0.005); // epsil - TGeoMedium *m3=gGeoManager->GetMedium("lead"); - if(m3 != NULL) m3->SetParam(6, 0.005); // epsil - - gMC3= new TGeant3TGeo("C++ Interface to Geant3"); - cout << "-I- G3Config: Geant3 with TGeo has been created for Geane." - << endl; + TGeoMedium *m = gGeoManager->GetMedium("air"); + if (m != NULL) + m->SetParam(6, 0.005); // epsil + TGeoMedium *m2 = gGeoManager->GetMedium("FscScint"); + if (m2 != NULL) + m2->SetParam(6, 0.005); // epsil + TGeoMedium *m3 = gGeoManager->GetMedium("lead"); + if (m3 != NULL) + m3->SetParam(6, 0.005); // epsil + + gMC3 = new TGeant3TGeo("C++ Interface to Geant3"); + cout << "-I- G3Config: Geant3 with TGeo has been created for Geane." << endl; // create Cbm Specific Stack PndStack *st = new PndStack(10); - gMC3->SetStack( st ) ; - + gMC3->SetStack(st); + // only from geant3 rev. 252 on -------- // NOPRNT = 1 means no IERR printout // NOPRNT = 0 means IERR are printed - if(gROOT->GetVersionCode() >= 334848) - { + if (gROOT->GetVersionCode() >= 334848) { Ertrio1_t *fErtrio1 = gMC3->fErtrio1; fErtrio1->noprnt = 1; - cout << "-I- Geane.C: NOPRNT flag set to " << fErtrio1->noprnt << endl; - if(fErtrio1->noprnt == 1) { - cout << "-I- Geane.C: IERR flags are not printed. If you want to switch them on, please set fErtrio1->noprnt = 0 in Geane.C" << endl; + cout << "-I- Geane.C: NOPRNT flag set to " << fErtrio1->noprnt << endl; + if (fErtrio1->noprnt == 1) { + cout << "-I- Geane.C: IERR flags are not printed. If you want to switch them on, please set " + "fErtrio1->noprnt = 0 in Geane.C" + << endl; } } // ------------------------------------- - + // ******* GEANEconfiguration for simulated Runs ******* gMC3->SetDEBU(0, 0, 1); gMC3->SetSWIT(4, 10); - + gMC3->SetDCAY(0); gMC3->SetPAIR(0); gMC3->SetCOMP(0); @@ -52,55 +55,50 @@ void Config() 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->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->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->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 - - 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); - + 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); - } - diff --git a/templates/project_root_containers/gconfig/SetCuts.C b/templates/project_root_containers/gconfig/SetCuts.C index 0df92c6bd5..8f678b1a2f 100644 --- a/templates/project_root_containers/gconfig/SetCuts.C +++ b/templates/project_root_containers/gconfig/SetCuts.C @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ @@ -13,49 +13,47 @@ 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. - TVirtualMC *MC =TVirtualMC::GetMC(); + // cout << "SetCuts Macro: Setting Processes.." <SetProcess("PAIR",1); /** pair production*/ - MC->SetProcess("COMP",1); /**Compton scattering*/ - MC->SetProcess("PHOT",1); /** photo electric effect */ - MC->SetProcess("PFIS",0); /**photofission*/ - MC->SetProcess("DRAY",1); /**delta-ray*/ - MC->SetProcess("ANNI",1); /**annihilation*/ - MC->SetProcess("BREM",1); /**bremsstrahlung*/ - MC->SetProcess("HADR",1); /**hadronic process*/ - MC->SetProcess("MUNU",1); /**muon nuclear interaction*/ - MC->SetProcess("DCAY",1); /**decay*/ - MC->SetProcess("LOSS",1); /**energy loss*/ - MC->SetProcess("MULS",1); /**multiple scattering*/ + // ------>>>> 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. + TVirtualMC *MC = TVirtualMC::GetMC(); - 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)*/ - MC->SetCut("CUTELE",cut1); /** electrons (GeV)*/ - MC->SetCut("CUTNEU",cut1); /** neutral hadrons (GeV)*/ - MC->SetCut("CUTHAD",cut1); /** charged hadrons (GeV)*/ - MC->SetCut("CUTMUO",cut1); /** muons (GeV)*/ - MC->SetCut("BCUTE",cut1); /** electron bremsstrahlung (GeV)*/ - MC->SetCut("BCUTM",cut1); /** muon and hadron bremsstrahlung(GeV)*/ - MC->SetCut("DCUTE",cut1); /** delta-rays by electrons (GeV)*/ - MC->SetCut("DCUTM",cut1); /** delta-rays by muons (GeV)*/ - MC->SetCut("PPCUTM",cut1); /** direct pair production by muons (GeV)*/ - MC->SetCut("TOFMAX",tofmax); /**time of flight cut in seconds*/ - - + MC->SetProcess("PAIR", 1); /** pair production*/ + MC->SetProcess("COMP", 1); /**Compton scattering*/ + MC->SetProcess("PHOT", 1); /** photo electric effect */ + MC->SetProcess("PFIS", 0); /**photofission*/ + MC->SetProcess("DRAY", 1); /**delta-ray*/ + MC->SetProcess("ANNI", 1); /**annihilation*/ + MC->SetProcess("BREM", 1); /**bremsstrahlung*/ + MC->SetProcess("HADR", 1); /**hadronic process*/ + MC->SetProcess("MUNU", 1); /**muon nuclear interaction*/ + MC->SetProcess("DCAY", 1); /**decay*/ + MC->SetProcess("LOSS", 1); /**energy loss*/ + MC->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)*/ + MC->SetCut("CUTELE", cut1); /** electrons (GeV)*/ + MC->SetCut("CUTNEU", cut1); /** neutral hadrons (GeV)*/ + MC->SetCut("CUTHAD", cut1); /** charged hadrons (GeV)*/ + MC->SetCut("CUTMUO", cut1); /** muons (GeV)*/ + MC->SetCut("BCUTE", cut1); /** electron bremsstrahlung (GeV)*/ + MC->SetCut("BCUTM", cut1); /** muon and hadron bremsstrahlung(GeV)*/ + MC->SetCut("DCUTE", cut1); /** delta-rays by electrons (GeV)*/ + MC->SetCut("DCUTM", cut1); /** delta-rays by muons (GeV)*/ + MC->SetCut("PPCUTM", cut1); /** direct pair production by muons (GeV)*/ + MC->SetCut("TOFMAX", tofmax); /**time of flight cut in seconds*/ } diff --git a/templates/project_root_containers/gconfig/UserDecay.C b/templates/project_root_containers/gconfig/UserDecay.C index 279a2b9f9c..338ae381ba 100644 --- a/templates/project_root_containers/gconfig/UserDecay.C +++ b/templates/project_root_containers/gconfig/UserDecay.C @@ -6,37 +6,37 @@ * copied verbatim in the file "LICENSE" * ********************************************************************************/ -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"); + 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.; + 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); - - + */ + gMC->SetDecayMode(He5PDG, bratio, mode); } \ No newline at end of file diff --git a/templates/project_root_containers/gconfig/g3Config.C b/templates/project_root_containers/gconfig/g3Config.C old mode 100755 new mode 100644 index 0305931d61..65728c9922 --- a/templates/project_root_containers/gconfig/g3Config.C +++ b/templates/project_root_containers/gconfig/g3Config.C @@ -8,43 +8,36 @@ // $Id: g3Config.C,v 1.1.1.1 2005/06/23 07:14:09 dbertini Exp $ // -// Configuration macro for Geant3 VirtualMC +// Configuration macro for Geant3 VirtualMC 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 - MyProjStack *st = new MyProjStack(); - 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 + MyProjStack* st = new MyProjStack(); + 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(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->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(1); // cerenkov photons - + geant3->SetCKOV(1); // cerenkov photons } - - diff --git a/templates/project_root_containers/gconfig/g3libs.C b/templates/project_root_containers/gconfig/g3libs.C index 8fbbda3901..f1c5f2f3db 100644 --- a/templates/project_root_containers/gconfig/g3libs.C +++ b/templates/project_root_containers/gconfig/g3libs.C @@ -10,9 +10,9 @@ void g3libs() { - cout << "Loading Geant3 libraries ..." << endl; + cout << "Loading Geant3 libraries ..." << endl; - gSystem->Load("libgeant321"); + gSystem->Load("libgeant321"); - cout << "Loading Geant3 libraries ... finished" << endl; + cout << "Loading Geant3 libraries ... finished" << endl; } diff --git a/templates/project_root_containers/gconfig/g4Config.C b/templates/project_root_containers/gconfig/g4Config.C old mode 100755 new mode 100644 index db38c941cb..fb26396fc8 --- a/templates/project_root_containers/gconfig/g4Config.C +++ b/templates/project_root_containers/gconfig/g4Config.C @@ -9,63 +9,62 @@ // 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: -/// Available options: -/// EMonly, EMonly+Extra, Hadron_EM, Hadron_EM+Extra -/// where EMonly = emStandard -/// Hadron = FTFP_BERT FTFP_BERT_TRV FTFP_BERT_HP FTFP_INCLXX FTFP_INCLXX_HP FTF_BIC LBE QBBC QGSP_BERT QGSP_BERT_HP QGSP_BIC QGSP_BIC_HP QGSP_FTFP_BERT QGSP_INCLXX QGSP_INCLXX_HP QGS_BIC Shielding ShieldingLEND -/// EM = _EMV _EMX _EMY _EMZ _LIV _PEN -/// Extra = extra optical radDecay -/// The Extra selections are cumulative, while Hadron selections are exlusive. - -/// 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. + /// 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: + /// Available options: + /// EMonly, EMonly+Extra, Hadron_EM, Hadron_EM+Extra + /// where EMonly = emStandard + /// Hadron = FTFP_BERT FTFP_BERT_TRV FTFP_BERT_HP FTFP_INCLXX FTFP_INCLXX_HP FTF_BIC LBE QBBC QGSP_BERT + /// QGSP_BERT_HP QGSP_BIC QGSP_BIC_HP QGSP_FTFP_BERT QGSP_INCLXX QGSP_INCLXX_HP QGS_BIC Shielding ShieldingLEND + /// EM = _EMV _EMX _EMY _EMZ _LIV _PEN + /// Extra = extra optical radDecay + /// The Extra selections are cumulative, while Hadron selections are exlusive. - Bool_t mtMode = FairRunSim::Instance()->IsMT(); - Bool_t specialStacking = false; - TG4RunConfiguration* runConfiguration - = new TG4RunConfiguration("geomRoot", "QGSP_FTFP_BERT", "stepLimiter+specialCuts+specialControls+stackPopper", - specialStacking, mtMode); + /// 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. -/// Create the G4 VMC - TGeant4* geant4 = new TGeant4("TGeant4", "The Geant4 Monte Carlo", runConfiguration); - cout << "Geant4 has been created." << endl; + Bool_t mtMode = FairRunSim::Instance()->IsMT(); + Bool_t specialStacking = false; + TG4RunConfiguration* runConfiguration = new TG4RunConfiguration( + "geomRoot", "QGSP_FTFP_BERT", "stepLimiter+specialCuts+specialControls+stackPopper", specialStacking, mtMode); -/// create the Specific stack - MyProjStack *stack = new MyProjStack(1000); - stack->StoreSecondaries(kTRUE); - stack->SetMinPoints(0); - geant4->SetStack(stack); + /// Create the G4 VMC + TGeant4* geant4 = new TGeant4("TGeant4", "The Geant4 Monte Carlo", runConfiguration); + cout << "Geant4 has been created." << endl; - if(FairRunSim::Instance()->IsExtDecayer()){ - TVirtualMCDecayer* decayer = TPythia6Decayer::Instance(); - geant4->SetExternalDecayer(decayer); - } - -/// Customise Geant4 setting -/// (verbose level, global range cut, ..) + /// create the Specific stack + MyProjStack* stack = new MyProjStack(1000); + stack->StoreSecondaries(kTRUE); + stack->SetMinPoints(0); + geant4->SetStack(stack); - TString configm(gSystem->Getenv("VMCWORKDIR")); - TString configm1 = configm + "/gconfig/g4config.in"; - cout << " -I g4Config() using g4conf macro: " << configm1 << endl; + if (FairRunSim::Instance()->IsExtDecayer()) { + TVirtualMCDecayer* decayer = TPythia6Decayer::Instance(); + geant4->SetExternalDecayer(decayer); + } - //set geant4 specific stuff - geant4->SetMaxNStep(10000); // default is 30000 - geant4->ProcessGeantMacro(configm1.Data()); + /// 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 + geant4->SetMaxNStep(10000); // default is 30000 + geant4->ProcessGeantMacro(configm1.Data()); } diff --git a/templates/project_root_containers/macro/eventDisplay.C b/templates/project_root_containers/macro/eventDisplay.C index 648d564da2..68893c4d52 100644 --- a/templates/project_root_containers/macro/eventDisplay.C +++ b/templates/project_root_containers/macro/eventDisplay.C @@ -1,32 +1,29 @@ void eventDisplay() { - //-----User Settings:----------------------------------------------- - TString InputFile ="test.root"; - TString ParFile ="params.root"; - TString OutFile ="tst.root"; + //-----User Settings:----------------------------------------------- + TString InputFile = "test.root"; + TString ParFile = "params.root"; + TString OutFile = "tst.root"; + // ----- Reconstruction run ------------------------------------------- + FairRunAna *fRun = new FairRunAna(); + FairFileSource *fFileSource = new FairFileSource(InputFile); + fRun->SetSource(fFileSource); + fRun->SetSink(new FairRootFileSink(OutFile.Data())); - // ----- Reconstruction run ------------------------------------------- - FairRunAna *fRun= new FairRunAna(); - FairFileSource *fFileSource = new FairFileSource(InputFile); - fRun->SetSource(fFileSource); - fRun->SetSink(new FairRootFileSink(OutFile.Data())); + FairRuntimeDb *rtdb = fRun->GetRuntimeDb(); + FairParRootFileIo *parInput1 = new FairParRootFileIo(); + parInput1->open(ParFile.Data()); + rtdb->setFirstInput(parInput1); - FairRuntimeDb* rtdb = fRun->GetRuntimeDb(); - FairParRootFileIo* parInput1 = new FairParRootFileIo(); - parInput1->open(ParFile.Data()); - rtdb->setFirstInput(parInput1); + FairEventManager *fMan = new FairEventManager(); - FairEventManager *fMan= new FairEventManager(); + //----------------------Traks and points ------------------------------------- + FairMCTracks *Track = new FairMCTracks("Monte-Carlo Tracks"); + // FairMCPointDraw *TorinoDetectorPoints = new FairMCPointDraw("FairTestDetectorPoint", kRed, kFullSquare); - //----------------------Traks and points ------------------------------------- - FairMCTracks *Track = new FairMCTracks("Monte-Carlo Tracks"); -// FairMCPointDraw *TorinoDetectorPoints = new FairMCPointDraw("FairTestDetectorPoint", kRed, kFullSquare); - - fMan->AddTask(Track); -// fMan->AddTask(TorinoDetectorPoints); - - - fMan->Init(); + fMan->AddTask(Track); + // fMan->AddTask(TorinoDetectorPoints); + fMan->Init(); } diff --git a/templates/project_root_containers/macro/run_sim.C b/templates/project_root_containers/macro/run_sim.C index 5c413aac35..669205d0b4 100644 --- a/templates/project_root_containers/macro/run_sim.C +++ b/templates/project_root_containers/macro/run_sim.C @@ -1,111 +1,102 @@ void run_sim(Int_t nEvents = 100, TString mcEngine = "TGeant4", Bool_t isMT = false) { - - // Output file name - TString outFile ="test.root"; - - // Parameter file name - TString parFile="params.root"; - - // ----- Timer -------------------------------------------------------- - TStopwatch timer; - timer.Start(); - // ------------------------------------------------------------------------ - - // ----- Create simulation run ---------------------------------------- - FairRunSim* run = new FairRunSim(); - run->SetName(mcEngine); // Transport engine - run->SetSink(new FairRootFileSink(outFile)); // Output file - run->SetIsMT(isMT); - FairRuntimeDb* rtdb = run->GetRuntimeDb(); - // ------------------------------------------------------------------------ - - // ----- Create media ------------------------------------------------- - run->SetMaterials("media.geo"); // Materials - // ------------------------------------------------------------------------ - - // ----- Create geometry ---------------------------------------------- - - FairModule* cave= new MyCave("CAVE"); - cave->SetGeometryFileName("cave.geo"); - run->AddModule(cave); - - FairModule* magnet = new MyMagnet("Magnet"); - run->AddModule(magnet); - - FairModule* pipe = new MyPipe("Pipe"); - run->AddModule(pipe); - - FairDetector* NewDet = new NewDetector("TestDetector", kTRUE); - run->AddModule(NewDet); - - // ------------------------------------------------------------------------ + // Output file name + TString outFile = "test.root"; + + // Parameter file name + TString parFile = "params.root"; + + // ----- Timer -------------------------------------------------------- + TStopwatch timer; + timer.Start(); + // ------------------------------------------------------------------------ + + // ----- Create simulation run ---------------------------------------- + FairRunSim* run = new FairRunSim(); + run->SetName(mcEngine); // Transport engine + run->SetSink(new FairRootFileSink(outFile)); // Output file + run->SetIsMT(isMT); + FairRuntimeDb* rtdb = run->GetRuntimeDb(); + // ------------------------------------------------------------------------ + + // ----- Create media ------------------------------------------------- + run->SetMaterials("media.geo"); // Materials + // ------------------------------------------------------------------------ + + // ----- Create geometry ---------------------------------------------- + + FairModule* cave = new MyCave("CAVE"); + cave->SetGeometryFileName("cave.geo"); + run->AddModule(cave); + + FairModule* magnet = new MyMagnet("Magnet"); + run->AddModule(magnet); + + FairModule* pipe = new MyPipe("Pipe"); + run->AddModule(pipe); + + FairDetector* NewDet = new NewDetector("TestDetector", kTRUE); + run->AddModule(NewDet); + + // ------------------------------------------------------------------------ // ----- Magnetic field ------------------------------------------- // Constant Field - MyConstField *fMagField = new MyConstField(); - fMagField->SetField(0., 20. ,0. ); // values are in kG - fMagField->SetFieldRegion(-200, 200,-200, 200, -200, 200); // values are in cm - // (xmin,xmax,ymin,ymax,zmin,zmax) + MyConstField* fMagField = new MyConstField(); + fMagField->SetField(0., 20., 0.); // values are in kG + fMagField->SetFieldRegion(-200, 200, -200, 200, -200, 200); // values are in cm + // (xmin,xmax,ymin,ymax,zmin,zmax) run->SetField(fMagField); // -------------------------------------------------------------------- - - - // ----- Create PrimaryGenerator -------------------------------------- - FairPrimaryGenerator* primGen = new FairPrimaryGenerator(); - + // ----- Create PrimaryGenerator -------------------------------------- + FairPrimaryGenerator* primGen = new FairPrimaryGenerator(); + // Add a box generator also to the run - FairBoxGenerator* boxGen = new FairBoxGenerator(13, 5); // 13 = muon; 1 = multipl. - boxGen->SetPRange(20,25); // GeV/c - boxGen->SetPhiRange(0., 360.); // Azimuth angle range [degree] - boxGen->SetThetaRange(0., 90.); // Polar angle in lab system range [degree] - boxGen->SetXYZ(0., 0., 0.); // cm + FairBoxGenerator* boxGen = new FairBoxGenerator(13, 5); // 13 = muon; 1 = multipl. + boxGen->SetPRange(20, 25); // GeV/c + boxGen->SetPhiRange(0., 360.); // Azimuth angle range [degree] + boxGen->SetThetaRange(0., 90.); // Polar angle in lab system range [degree] + boxGen->SetXYZ(0., 0., 0.); // cm 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! - run->SetStoreTraj(kTRUE); - - - - // ----- Initialize simulation run ------------------------------------ - run->Init(); - // ------------------------------------------------------------------------ - - // ----- Runtime database --------------------------------------------- - - Bool_t kParameterMerged = kTRUE; - FairParRootFileIo* parOut = new FairParRootFileIo(kParameterMerged); - parOut->open(parFile.Data()); - rtdb->setOutput(parOut); - rtdb->saveOutput(); - rtdb->print(); - // ------------------------------------------------------------------------ - - // ----- Start run ---------------------------------------------------- - run->Run(nEvents); - - //You can export your ROOT geometry ot a separate file - run->CreateGeometryFile("geofile_full.root"); - // ------------------------------------------------------------------------ - - // ----- Finish ------------------------------------------------------- - timer.Stop(); - Double_t rtime = timer.RealTime(); - Double_t ctime = timer.CpuTime(); - cout << endl << endl; - cout << "Macro finished succesfully." << endl; - cout << "Output file is " << outFile << endl; - cout << "Parameter file is " << parFile << endl; - cout << "Real time " << rtime << " s, CPU time " << ctime - << "s" << endl << endl; - // ------------------------------------------------------------------------ -} + // ------------------------------------------------------------------------ + + //---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(kTRUE); + + // ----- Initialize simulation run ------------------------------------ + run->Init(); + // ------------------------------------------------------------------------ + // ----- Runtime database --------------------------------------------- + Bool_t kParameterMerged = kTRUE; + FairParRootFileIo* parOut = new FairParRootFileIo(kParameterMerged); + parOut->open(parFile.Data()); + rtdb->setOutput(parOut); + rtdb->saveOutput(); + rtdb->print(); + // ------------------------------------------------------------------------ + + // ----- Start run ---------------------------------------------------- + run->Run(nEvents); + + // You can export your ROOT geometry ot a separate file + run->CreateGeometryFile("geofile_full.root"); + // ------------------------------------------------------------------------ + + // ----- Finish ------------------------------------------------------- + timer.Stop(); + Double_t rtime = timer.RealTime(); + Double_t ctime = timer.CpuTime(); + cout << endl << endl; + cout << "Macro finished succesfully." << endl; + cout << "Output file is " << outFile << endl; + cout << "Parameter file is " << parFile << endl; + cout << "Real time " << rtime << " s, CPU time " << ctime << "s" << endl << endl; + // ------------------------------------------------------------------------ +} diff --git a/templates/project_root_containers/passive/MyCave.cxx b/templates/project_root_containers/passive/MyCave.cxx index 16ad4582b0..06fbc0df86 100644 --- a/templates/project_root_containers/passive/MyCave.cxx +++ b/templates/project_root_containers/passive/MyCave.cxx @@ -12,60 +12,53 @@ // ----- Created 26/03/14 by M. Al-Turany ----- // ------------------------------------------------------------------------- #include "MyCave.h" -#include "MyGeoCave.h" // for MyGeoCave -#include "FairGeoInterface.h" // for FairGeoInterface -#include "FairGeoLoader.h" // for FairGeoLoader -#include "FairGeoNode.h" // for FairGeoNode -#include "FairGeoVolume.h" // for FairGeoVolume -#include "FairRun.h" // for FairRun -#include "FairRuntimeDb.h" // for FairRuntimeDb -#include // for TListIter, TList (ptr only) -#include // for TObjArray -#include // for TString +#include "FairGeoInterface.h" // for FairGeoInterface +#include "FairGeoLoader.h" // for FairGeoLoader +#include "FairGeoNode.h" // for FairGeoNode +#include "FairGeoVolume.h" // for FairGeoVolume +#include "FairRun.h" // for FairRun +#include "FairRuntimeDb.h" // for FairRuntimeDb +#include "MyGeoCave.h" // for MyGeoCave -#include // for NULL +#include // for TListIter, TList (ptr only) +#include // for TObjArray +#include // for TString +#include // for NULL -ClassImp(MyCave) +ClassImp(MyCave); void MyCave::ConstructGeometry() { - FairGeoLoader* loader=FairGeoLoader::Instance(); - FairGeoInterface* GeoInterface =loader->getGeoInterface(); - MyGeoCave* MGeo=new MyGeoCave(); - MGeo->setGeomFile(GetGeometryFileName()); - GeoInterface->addGeoModule(MGeo); - Bool_t rc = GeoInterface->readSet(MGeo); - if ( rc ) { MGeo->create(loader->getGeoBuilder()); } - + FairGeoLoader* loader = FairGeoLoader::Instance(); + FairGeoInterface* GeoInterface = loader->getGeoInterface(); + MyGeoCave* MGeo = new MyGeoCave(); + MGeo->setGeomFile(GetGeometryFileName()); + GeoInterface->addGeoModule(MGeo); + Bool_t rc = GeoInterface->readSet(MGeo); + if (rc) { + MGeo->create(loader->getGeoBuilder()); + } } MyCave::MyCave() -:FairModule() -{ -} + : FairModule() +{} -MyCave::~MyCave() +MyCave::~MyCave() {} +MyCave::MyCave(const char* name, const char* Title) + : FairModule(name, Title) { - -} -MyCave::MyCave(const char* name, const char* Title) - : FairModule(name ,Title) -{ - world[0] = 0; - world[1] = 0; - world[2] = 0; + world[0] = 0; + world[1] = 0; + world[2] = 0; } MyCave::MyCave(const MyCave& right) - : FairModule(right) -{ - world[0] = right.world[0]; - world[1] = right.world[1]; - world[2] = right.world[2]; -} - -FairModule* MyCave::CloneModule() const + : FairModule(right) { - return new MyCave(*this); + world[0] = right.world[0]; + world[1] = right.world[1]; + world[2] = right.world[2]; } +FairModule* MyCave::CloneModule() const { return new MyCave(*this); } diff --git a/templates/project_root_containers/passive/MyCave.h b/templates/project_root_containers/passive/MyCave.h index fd496b0e7b..1c4c330608 100644 --- a/templates/project_root_containers/passive/MyCave.h +++ b/templates/project_root_containers/passive/MyCave.h @@ -11,18 +11,17 @@ // ----- Created 26/03/14 by M. Al-Turany ----- // ------------------------------------------------------------------------- - #ifndef Cave_H #define Cave_H -#include "FairModule.h" // for FairModule +#include "FairModule.h" // for FairModule -#include // for MyCave::Class, ClassDef, etc +#include // for MyCave::Class, ClassDef, etc class MyCave : public FairModule { public: - MyCave(const char* name, const char* Title="Exp Cave"); + MyCave(const char* name, const char* Title = "Exp Cave"); MyCave(); virtual ~MyCave(); virtual void ConstructGeometry(); @@ -35,8 +34,7 @@ class MyCave : public FairModule MyCave(const MyCave&); MyCave& operator=(const MyCave&); - ClassDef(MyCave,1) //PNDCaveSD + ClassDef(MyCave, 1) // PNDCaveSD }; -#endif //Cave_H - +#endif // Cave_H diff --git a/templates/project_root_containers/passive/MyGeoCave.cxx b/templates/project_root_containers/passive/MyGeoCave.cxx index be73eb5ef1..92ad4bddbe 100644 --- a/templates/project_root_containers/passive/MyGeoCave.cxx +++ b/templates/project_root_containers/passive/MyGeoCave.cxx @@ -20,108 +20,119 @@ #include "MyGeoCave.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 // for TList - -#include // for strcmp -#include // for cout +#include // for TList +#include // for cout +#include // for strcmp using namespace std; -ClassImp(MyGeoCave) +ClassImp(MyGeoCave); MyGeoCave::MyGeoCave() - : FairGeoSet(), - name("cave") + : FairGeoSet() + , name("cave") { - // Constructor - fName="cave"; - name="cave"; - maxModules=1; + // Constructor + fName = "cave"; + maxModules = 1; } -Bool_t MyGeoCave::read(fstream& fin,FairGeoMedia* media) +Bool_t MyGeoCave::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 MyGeoCave::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 MyGeoCave::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 MyGeoCave::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/templates/project_root_containers/passive/MyGeoCave.h b/templates/project_root_containers/passive/MyGeoCave.h index 0573e9640b..6a32ba9161 100644 --- a/templates/project_root_containers/passive/MyGeoCave.h +++ b/templates/project_root_containers/passive/MyGeoCave.h @@ -12,32 +12,32 @@ // ----- Created 26/03/14 by M. Al-Turany ----- // ------------------------------------------------------------------------- - #ifndef MYGEOCAVE_H #define MYGEOCAVE_H -#include "FairGeoSet.h" // for FairGeoSet -#include // for fstream -#include // for MyGeoCave::Class, Bool_t, etc -#include // for TString +#include "FairGeoSet.h" // for FairGeoSet -#include // for fstream +#include // for MyGeoCave::Class, Bool_t, etc +#include // for TString +#include // for fstream +#include // for fstream class FairGeoMedia; -class MyGeoCave : public FairGeoSet +class MyGeoCave : public FairGeoSet { protected: TString name; + public: MyGeoCave(); ~MyGeoCave() {} - 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(MyGeoCave,0) // Class for the geometry of CAVE + ClassDef(MyGeoCave, 0) // Class for the geometry of CAVE }; -#endif /* !PNDGEOCAVE_H */ +#endif /* !PNDGEOCAVE_H */ diff --git a/templates/project_root_containers/passive/MyMagnet.cxx b/templates/project_root_containers/passive/MyMagnet.cxx index 02eaf2cf99..22e3fdfc08 100644 --- a/templates/project_root_containers/passive/MyMagnet.cxx +++ b/templates/project_root_containers/passive/MyMagnet.cxx @@ -13,70 +13,63 @@ #include "MyMagnet.h" -#include -#include "FairRun.h" // for FairRun -#include "FairRuntimeDb.h" // for FairRuntimeDb -#include // for ostream -#include // for TListIter, TList (ptr only) -#include // for TObjArray -#include // for TString +#include "FairRun.h" // for FairRun +#include "FairRuntimeDb.h" // for FairRuntimeDb + #include #include -#include -#include #include +#include +#include #include -#include // for NULL -#include // for operator<<, basic_ostream, etc - - - -MyMagnet::~MyMagnet() -{ -} +#include +#include // for TListIter, TList (ptr only) +#include // for TObjArray +#include // for TString +#include // for ostream +#include // for operator<<, basic_ostream, etc +#include // for NULL + +MyMagnet::~MyMagnet() {} MyMagnet::MyMagnet() - : FairModule("MyMagnet", "") -{ -} + : FairModule("MyMagnet", "") +{} -MyMagnet::MyMagnet(const char* name, const char* Title) - : FairModule(name ,Title) -{ -} +MyMagnet::MyMagnet(const char *name, const char *Title) + : FairModule(name, Title) +{} -MyMagnet::MyMagnet(const MyMagnet& right) - : FairModule(right) -{ -} +MyMagnet::MyMagnet(const MyMagnet &right) + : FairModule(right) +{} void MyMagnet::ConstructGeometry() { - - TGeoVolume *top=gGeoManager->GetTopVolume(); - + + TGeoVolume *top = gGeoManager->GetTopVolume(); + // define some materials - TGeoMaterial *matFe = new TGeoMaterial("Fe", 55.84, 26, 7.9); + TGeoMaterial *matFe = new TGeoMaterial("Fe", 55.84, 26, 7.9); // define some media - TGeoMedium *Fe = new TGeoMedium("Fe", 5, matFe); - + TGeoMedium *Fe = new TGeoMedium("Fe", 5, matFe); // 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); + // magyoke->SetTransparency(50); top->AddNode(magyoke, 1, new TGeoTranslation(0, 0, 0)); - + // 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"); @@ -84,39 +77,20 @@ void MyMagnet::ConstructGeometry() 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); top->AddNode(magnet1, 1, new TGeoTranslation(0, 0, 0)); - + TGeoRotation m3; m3.SetAngles(180, 0, 0); TGeoTranslation m4(0, 0, 0); TGeoCombiTrans m5(m4, m3); TGeoHMatrix *m6 = new TGeoHMatrix(m5); top->AddNode(magnet1, 2, m6); - - -} - -FairModule* MyMagnet::CloneModule() const -{ - return new MyMagnet(*this); } -ClassImp(MyMagnet) - - - - - - - - - - - - - +FairModule *MyMagnet::CloneModule() const { return new MyMagnet(*this); } +ClassImp(MyMagnet); diff --git a/templates/project_root_containers/passive/MyMagnet.h b/templates/project_root_containers/passive/MyMagnet.h index 1d7799fae4..ed991c832b 100644 --- a/templates/project_root_containers/passive/MyMagnet.h +++ b/templates/project_root_containers/passive/MyMagnet.h @@ -11,18 +11,18 @@ // ----- Created 26/03/14 by M. Al-Turany ----- // ------------------------------------------------------------------------- - #ifndef MAGNET_H #define MAGNET_H -#include "FairModule.h" // for FairModule -#include // for MyMagnet::Class, Bool_t, etc -#include // for string +#include "FairModule.h" // for FairModule + +#include // for MyMagnet::Class, Bool_t, etc +#include // for string class MyMagnet : public FairModule { public: - MyMagnet(const char* name, const char* Title="MY Magnet"); + MyMagnet(const char* name, const char* Title = "MY Magnet"); MyMagnet(); virtual ~MyMagnet(); void ConstructGeometry(); @@ -33,8 +33,7 @@ class MyMagnet : public FairModule MyMagnet(const MyMagnet&); MyMagnet& operator=(const MyMagnet&); - ClassDef(MyMagnet,1) + ClassDef(MyMagnet, 1) }; -#endif //MAGNET_H - +#endif // MAGNET_H diff --git a/templates/project_root_containers/passive/MyPassiveContFact.cxx b/templates/project_root_containers/passive/MyPassiveContFact.cxx index 257031437d..72dcbe2ae3 100644 --- a/templates/project_root_containers/passive/MyPassiveContFact.cxx +++ b/templates/project_root_containers/passive/MyPassiveContFact.cxx @@ -11,7 +11,6 @@ // ----- Created 26/03/14 by M. Al-Turany ----- // ------------------------------------------------------------------------- - //*-- AUTHOR : Denis Bertini //*-- Created : 21/06/2005 @@ -24,50 +23,47 @@ ///////////////////////////////////////////////////////////// #include "MyPassiveContFact.h" -#include "FairRuntimeDb.h" // for FairRuntimeDb - -#include // for TList -#include // for TString +#include "FairRuntimeDb.h" // for FairRuntimeDb -#include // for strcmp, NULL +#include // for TList +#include // for TString +#include // for strcmp, NULL class FairParSet; using namespace std; -ClassImp(MyPassiveContFact) +ClassImp(MyPassiveContFact); static MyPassiveContFact gMyPassiveContFact; MyPassiveContFact::MyPassiveContFact() - : FairContFact() + : FairContFact() { - // Constructor (called when the library is loaded) - fName="MyPassiveContFact"; - fTitle="Factory for parameter containers in libPassive"; - setAllContainers(); - FairRuntimeDb::instance()->addContFactory(this); + // Constructor (called when the library is loaded) + fName = "MyPassiveContFact"; + fTitle = "Factory for parameter containers in libPassive"; + setAllContainers(); + FairRuntimeDb::instance()->addContFactory(this); } void MyPassiveContFact::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* MyPassiveContFact::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(); + /** 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()); @@ -75,4 +71,3 @@ FairParSet* MyPassiveContFact::createContainer(FairContainer* c) return p; */ } - diff --git a/templates/project_root_containers/passive/MyPassiveContFact.h b/templates/project_root_containers/passive/MyPassiveContFact.h index 51c245f9bc..fe2a0bbf80 100644 --- a/templates/project_root_containers/passive/MyPassiveContFact.h +++ b/templates/project_root_containers/passive/MyPassiveContFact.h @@ -11,12 +11,12 @@ // ----- Created 26/03/14 by M. Al-Turany ----- // ------------------------------------------------------------------------- - #ifndef PNDPASSIVECONTFACT_H #define PNDPASSIVECONTFACT_H -#include "FairContFact.h" // for FairContFact, etc -#include // for MyPassiveContFact::Class, etc +#include "FairContFact.h" // for FairContFact, etc + +#include // for MyPassiveContFact::Class, etc class FairParSet; @@ -24,11 +24,12 @@ class MyPassiveContFact : public FairContFact { private: void setAllContainers(); + public: MyPassiveContFact(); ~MyPassiveContFact() {} FairParSet* createContainer(FairContainer*); - ClassDef( MyPassiveContFact,0) // Factory for all Passive parameter containers + ClassDef(MyPassiveContFact, 0) // Factory for all Passive parameter containers }; -#endif /* !PNDPASSIVECONTFACT_H */ +#endif /* !PNDPASSIVECONTFACT_H */ diff --git a/templates/project_root_containers/passive/MyPipe.cxx b/templates/project_root_containers/passive/MyPipe.cxx index 3a6221c133..6a4632e22d 100644 --- a/templates/project_root_containers/passive/MyPipe.cxx +++ b/templates/project_root_containers/passive/MyPipe.cxx @@ -12,82 +12,68 @@ // ------------------------------------------------------------------------- #include "MyPipe.h" -#include -#include -#include -#include +#include #include #include -#include - +#include +#include +#include +#include -MyPipe::~MyPipe() -{ -} +MyPipe::~MyPipe() {} MyPipe::MyPipe() - : FairModule() -{ -} + : FairModule() +{} -MyPipe::MyPipe(const char * name, const char * title) - : FairModule(name ,title) -{ -} +MyPipe::MyPipe(const char* name, const char* title) + : FairModule(name, title) +{} MyPipe::MyPipe(const MyPipe& right) - : FairModule(right) -{ -} - + : FairModule(right) +{} // ----- ConstructGeometry -------------------------------------------------- void MyPipe::ConstructGeometry() { - TGeoVolume *top=gGeoManager->GetTopVolume(); - - TGeoMedium *Carbon = gGeoManager->GetMedium("C"); - if(Carbon==0){ - TGeoMaterial *matCarbon = new TGeoMaterial("C", 12.011, 6.0, 2.265); - Carbon = new TGeoMedium("C", 3, matCarbon); - } - - TGeoMaterial *matVacuum = new TGeoMaterial("Vacuum", 0, 0, 0); - TGeoMedium *Vacuum = new TGeoMedium("Vacuum", 4, matVacuum); - - - Int_t nSects=2; - Double_t z[] = { -100, 300}; // in cm - Double_t r[] = { 2.5, 2.5}; // in cm - Double_t Thickness = 0.05; // thickness of beam pipe [cm] + TGeoVolume* top = gGeoManager->GetTopVolume(); + + TGeoMedium* Carbon = gGeoManager->GetMedium("C"); + if (Carbon == 0) { + TGeoMaterial* matCarbon = new TGeoMaterial("C", 12.011, 6.0, 2.265); + Carbon = new TGeoMedium("C", 3, matCarbon); + } + + TGeoMaterial* matVacuum = new TGeoMaterial("Vacuum", 0, 0, 0); + TGeoMedium* Vacuum = new TGeoMedium("Vacuum", 4, matVacuum); + + Int_t nSects = 2; + Double_t z[] = {-100, 300}; // in cm + Double_t r[] = {2.5, 2.5}; // in cm + Double_t Thickness = 0.05; // thickness of beam pipe [cm] TGeoPcon* shape = new TGeoPcon(0., 360., nSects); for (Int_t iSect = 0; iSect < nSects; iSect++) { - shape->DefineSection(iSect, z[iSect], r[iSect], r[iSect]+Thickness); + shape->DefineSection(iSect, z[iSect], r[iSect], r[iSect] + Thickness); } - + // ---> Volume TGeoVolume* pipe = new TGeoVolume("MyPipe", shape, Carbon); - + // --Now create the same but diameter less by Thikness and vacuum instead of Carbon TGeoPcon* Vshape = new TGeoPcon(0., 360., nSects); for (Int_t iSect = 0; iSect < nSects; iSect++) { Vshape->DefineSection(iSect, z[iSect], r[iSect], r[iSect]); } - + // ---> Volume TGeoVolume* Vpipe = new TGeoVolume("MyPipe", shape, Vacuum); - + top->AddNode(pipe, 1); top->AddNode(Vpipe, 1); - - } // ---------------------------------------------------------------------------- -FairModule* MyPipe::CloneModule() const -{ - return new MyPipe(*this); -} - -ClassImp(MyPipe) +FairModule* MyPipe::CloneModule() const { return new MyPipe(*this); } +ClassImp(MyPipe); diff --git a/templates/project_root_containers/passive/MyPipe.h b/templates/project_root_containers/passive/MyPipe.h index 7695f9a3ff..f25552ee96 100644 --- a/templates/project_root_containers/passive/MyPipe.h +++ b/templates/project_root_containers/passive/MyPipe.h @@ -16,9 +16,10 @@ #include "FairModule.h" -class MyPipe : public FairModule { +class MyPipe : public FairModule +{ public: - MyPipe(const char * name, const char *Title="My Pipe"); + MyPipe(const char* name, const char* Title = "My Pipe"); MyPipe(); virtual ~MyPipe(); @@ -29,10 +30,8 @@ class MyPipe : public FairModule { private: MyPipe(const MyPipe&); MyPipe& operator=(const MyPipe&); - - ClassDef(MyPipe,1) //MyPIPE + ClassDef(MyPipe, 1) // MyPIPE }; -#endif //PIPE_H - +#endif // PIPE_H diff --git a/templates/project_stl_containers/MyProjData/MyProjDetectorList.h b/templates/project_stl_containers/MyProjData/MyProjDetectorList.h index 0d4dc63f7f..c86e445e8b 100644 --- a/templates/project_stl_containers/MyProjData/MyProjDetectorList.h +++ b/templates/project_stl_containers/MyProjData/MyProjDetectorList.h @@ -11,13 +11,16 @@ // ----- M. Al-Turany June 2014 ----- // ------------------------------------------------------------------------- - /** Defines unique identifier for all MyProj detectors system **/ /** THis is needed for stack filtring **/ #ifndef MyProjDetectorList_H #define MyProjDetectorList_H 1 // kSTOPHERE is needed for iteration over the enum. All detectors have to be put before. -enum DetectorId {kNewDetector, kSTOPHERE}; +enum DetectorId +{ + kNewDetector, + kSTOPHERE +}; #endif diff --git a/templates/project_stl_containers/MyProjData/MyProjMCTrack.cxx b/templates/project_stl_containers/MyProjData/MyProjMCTrack.cxx index 1acf69aba9..6ecc5b1b6b 100644 --- a/templates/project_stl_containers/MyProjData/MyProjMCTrack.cxx +++ b/templates/project_stl_containers/MyProjData/MyProjMCTrack.cxx @@ -16,141 +16,129 @@ #include "MyProjMCTrack.h" -#include "FairLogger.h" // for FairLogger, etc -#include // for TDatabasePDG -#include // for TParticle -#include // for TParticlePDG +#include "FairLogger.h" // for FairLogger, etc + +#include // for TDatabasePDG +#include // for TParticle +#include // for TParticlePDG // ----- Default constructor ------------------------------------------- MyProjMCTrack::MyProjMCTrack() - : TObject(), - fPdgCode(0), - fMotherId(-1), - fPx(0.), - fPy(0.), - fPz(0.), - fStartX(0.), - fStartY(0.), - fStartZ(0.), - fStartT(0.), - fNPoints(0) -{ -} + : TObject() + , fPdgCode(0) + , fMotherId(-1) + , fPx(0.) + , fPy(0.) + , fPz(0.) + , fStartX(0.) + , fStartY(0.) + , fStartZ(0.) + , fStartT(0.) + , fNPoints(0) +{} // ------------------------------------------------------------------------- - - // ----- Standard constructor ------------------------------------------ -MyProjMCTrack::MyProjMCTrack(Int_t pdgCode, Int_t motherId, Double_t px, - Double_t py, Double_t pz, Double_t x, Double_t y, - Double_t z, Double_t t, Int_t nPoints = 0) - : TObject(), - fPdgCode(pdgCode), - fMotherId(motherId), - fPx(px), - fPy(py), - fPz(pz), - fStartX(x), - fStartY(y), - fStartZ(z), - fStartT(t), - fNPoints(nPoints) -{ -} +MyProjMCTrack::MyProjMCTrack(Int_t pdgCode, + Int_t motherId, + Double_t px, + Double_t py, + Double_t pz, + Double_t x, + Double_t y, + Double_t z, + Double_t t, + Int_t nPoints = 0) + : TObject() + , fPdgCode(pdgCode) + , fMotherId(motherId) + , fPx(px) + , fPy(py) + , fPz(pz) + , fStartX(x) + , fStartY(y) + , fStartZ(z) + , fStartT(t) + , fNPoints(nPoints) +{} // ------------------------------------------------------------------------- - - // ----- Copy constructor ---------------------------------------------- MyProjMCTrack::MyProjMCTrack(const MyProjMCTrack& track) - : TObject(track), - fPdgCode(track.fPdgCode), - fMotherId(track.fMotherId), - fPx(track.fPx), - fPy(track.fPy), - fPz(track.fPz), - fStartX(track.fStartX), - fStartY(track.fStartY), - fStartZ(track.fStartZ), - fStartT(track.fStartT), - fNPoints(track.fNPoints) -{ -} + : TObject(track) + , fPdgCode(track.fPdgCode) + , fMotherId(track.fMotherId) + , fPx(track.fPx) + , fPy(track.fPy) + , fPz(track.fPz) + , fStartX(track.fStartX) + , fStartY(track.fStartY) + , fStartZ(track.fStartZ) + , fStartT(track.fStartT) + , fNPoints(track.fNPoints) +{} // ------------------------------------------------------------------------- - - // ----- Constructor from TParticle ------------------------------------ MyProjMCTrack::MyProjMCTrack(TParticle* part) - : TObject(), - fPdgCode(part->GetPdgCode()), - fMotherId(part->GetMother(0)), - fPx(part->Px()), - fPy(part->Py()), - fPz(part->Pz()), - fStartX(part->Vx()), - fStartY(part->Vy()), - fStartZ(part->Vz()), - fStartT(part->T()*1e09), - fNPoints(0) -{ -} + : TObject() + , fPdgCode(part->GetPdgCode()) + , fMotherId(part->GetMother(0)) + , fPx(part->Px()) + , fPy(part->Py()) + , fPz(part->Pz()) + , fStartX(part->Vx()) + , fStartY(part->Vy()) + , fStartZ(part->Vz()) + , fStartT(part->T() * 1e09) + , fNPoints(0) +{} // ------------------------------------------------------------------------- - - // ----- Destructor ---------------------------------------------------- -MyProjMCTrack::~MyProjMCTrack() { } +MyProjMCTrack::~MyProjMCTrack() {} // ------------------------------------------------------------------------- - - // ----- Public method Print ------------------------------------------- void MyProjMCTrack::Print(Int_t trackId) const { - LOG(debug) << "Track " << trackId << ", mother : " << fMotherId << ", Type " - << fPdgCode << ", momentum (" << fPx << ", " << fPy << ", " - << fPz << ") GeV"; - /* LOG(debug2) << " Ref " << GetNPoints(kREF) + LOG(debug) << "Track " << trackId << ", mother : " << fMotherId << ", Type " << fPdgCode << ", momentum (" << fPx + << ", " << fPy << ", " << fPz << ") GeV"; + /* LOG(debug2) << " Ref " << GetNPoints(kREF) << ", TutDet " << GetNPoints(kTutDet) << ", Rutherford " << GetNPoints(kFairRutherford); */ } // ------------------------------------------------------------------------- - - // ----- Public method GetMass ----------------------------------------- Double_t MyProjMCTrack::GetMass() const { - if ( TDatabasePDG::Instance() ) { - TParticlePDG* particle = TDatabasePDG::Instance()->GetParticle(fPdgCode); - if ( particle ) { return particle->Mass(); } - else { return 0.; } - } - return 0.; + if (TDatabasePDG::Instance()) { + TParticlePDG* particle = TDatabasePDG::Instance()->GetParticle(fPdgCode); + if (particle) { + return particle->Mass(); + } else { + return 0.; + } + } + return 0.; } // ------------------------------------------------------------------------- - - - // ----- Public method GetRapidity ------------------------------------- Double_t MyProjMCTrack::GetRapidity() const { - Double_t e = GetEnergy(); - Double_t y = 0.5 * TMath::Log( (e+fPz) / (e-fPz) ); - return y; + Double_t e = GetEnergy(); + Double_t y = 0.5 * TMath::Log((e + fPz) / (e - fPz)); + return y; } // ------------------------------------------------------------------------- - - - // ----- Public method GetNPoints -------------------------------------- Int_t MyProjMCTrack::GetNPoints(DetectorId detId) const { -/* // TODO: Where does this come from + /* // TODO: Where does this come from if ( detId == kREF ) { return ( fNPoints & 1); } else if ( detId == kTutDet ) { return ( (fNPoints & ( 7 << 1) ) >> 1); } else if ( detId == kFairRutherford ) { return ( (fNPoints & (31 << 4) ) >> 4); } @@ -162,12 +150,10 @@ Int_t MyProjMCTrack::GetNPoints(DetectorId detId) const } // ------------------------------------------------------------------------- - - // ----- Public method SetNPoints -------------------------------------- void MyProjMCTrack::SetNPoints(Int_t iDet, Int_t nPoints) { -/* + /* if ( iDet == kREF ) { if ( nPoints < 0 ) { nPoints = 0; } else if ( nPoints > 1 ) { nPoints = 1; } @@ -191,7 +177,4 @@ void MyProjMCTrack::SetNPoints(Int_t iDet, Int_t nPoints) } // ------------------------------------------------------------------------- - - - -ClassImp(MyProjMCTrack) +ClassImp(MyProjMCTrack); diff --git a/templates/project_stl_containers/MyProjData/MyProjMCTrack.h b/templates/project_stl_containers/MyProjData/MyProjMCTrack.h index a65d12701c..2832e19175 100644 --- a/templates/project_stl_containers/MyProjData/MyProjMCTrack.h +++ b/templates/project_stl_containers/MyProjData/MyProjMCTrack.h @@ -11,24 +11,22 @@ // ----- M. Al-Turany June 2014 ----- // ------------------------------------------------------------------------- - - /** MyProjMCTrack.h ** Data class for storing Monte Carlo tracks processed by the MyProjStack. ** A MyProjMCTrack can be a primary track put into the simulation or a ** secondary one produced by the transport through decay or interaction. **/ - #ifndef MyProjMCTrack_H #define MyProjMCTrack_H 1 -#include // for TObject -#include "MyProjDetectorList.h" // for DetectorId -#include // for Double_t, Int_t, Double32_t, etc -#include // for TLorentzVector -#include // for Sqrt -#include // for TVector3 +#include "MyProjDetectorList.h" // for DetectorId + +#include // for Double_t, Int_t, Double32_t, etc +#include // for TLorentzVector +#include // for Sqrt +#include // for TObject +#include // for TVector3 class TParticle; @@ -36,70 +34,65 @@ class MyProjMCTrack : public TObject { public: - - /** Default constructor **/ MyProjMCTrack(); - /** Standard constructor **/ - MyProjMCTrack(Int_t pdgCode, Int_t motherID, Double_t px, Double_t py, - Double_t pz, Double_t x, Double_t y, Double_t z, - Double_t t, Int_t nPoints); + MyProjMCTrack(Int_t pdgCode, + Int_t motherID, + Double_t px, + Double_t py, + Double_t pz, + Double_t x, + Double_t y, + Double_t z, + Double_t t, + Int_t nPoints); /** Copy constructor **/ MyProjMCTrack(const MyProjMCTrack& track); - /** Constructor from TParticle **/ MyProjMCTrack(TParticle* particle); - /** Destructor **/ virtual ~MyProjMCTrack(); - /** Output to screen **/ - void Print(Int_t iTrack=0) const; - + void Print(Int_t iTrack = 0) const; /** Accessors **/ - Int_t GetPdgCode() const { return fPdgCode; } - Int_t GetMotherId() const { return fMotherId; } - Double_t GetPx() const { return fPx; } - Double_t GetPy() const { return fPy; } - Double_t GetPz() const { return fPz; } - Double_t GetStartX() const { return fStartX; } - Double_t GetStartY() const { return fStartY; } - Double_t GetStartZ() const { return fStartZ; } - Double_t GetStartT() const { return fStartT; } - Double_t GetMass() const; - Double_t GetEnergy() const; - Double_t GetPt() const { return TMath::Sqrt(fPx*fPx+fPy*fPy); } - Double_t GetP() const { return TMath::Sqrt(fPx*fPx+fPy*fPy+fPz*fPz); } + Int_t GetPdgCode() const { return fPdgCode; } + Int_t GetMotherId() const { return fMotherId; } + Double_t GetPx() const { return fPx; } + Double_t GetPy() const { return fPy; } + Double_t GetPz() const { return fPz; } + Double_t GetStartX() const { return fStartX; } + Double_t GetStartY() const { return fStartY; } + Double_t GetStartZ() const { return fStartZ; } + Double_t GetStartT() const { return fStartT; } + Double_t GetMass() const; + Double_t GetEnergy() const; + Double_t GetPt() const { return TMath::Sqrt(fPx * fPx + fPy * fPy); } + Double_t GetP() const { return TMath::Sqrt(fPx * fPx + fPy * fPy + fPz * fPz); } Double_t GetRapidity() const; void GetMomentum(TVector3& momentum); void Get4Momentum(TLorentzVector& momentum); void GetStartVertex(TVector3& vertex); - /** Accessors to the number of MCPoints in the detectors **/ - Int_t GetNPoints(DetectorId detId) const; - + Int_t GetNPoints(DetectorId detId) const; /** Modifiers **/ void SetMotherId(Int_t id) { fMotherId = id; } void SetNPoints(Int_t iDet, Int_t np); - - private: - /** PDG particle code **/ - Int_t fPdgCode; + Int_t fPdgCode; /** Index of mother track. -1 for primary particles. **/ - Int_t fMotherId; + Int_t fMotherId; /** Momentum components at start vertex [GeV] **/ Double32_t fPx, fPy, fPz; @@ -124,41 +117,21 @@ class MyProjMCTrack : public TObject **/ Int_t fNPoints; - - ClassDef(MyProjMCTrack,1); - + ClassDef(MyProjMCTrack, 1); }; - - // ========== Inline functions ======================================== inline Double_t MyProjMCTrack::GetEnergy() const { - Double_t mass = GetMass(); - return TMath::Sqrt(mass*mass + fPx*fPx + fPy*fPy + fPz*fPz ); -} - - -inline void MyProjMCTrack::GetMomentum(TVector3& momentum) -{ - momentum.SetXYZ(fPx,fPy,fPz); -} - - -inline void MyProjMCTrack::Get4Momentum(TLorentzVector& momentum) -{ - momentum.SetXYZT(fPx,fPy,fPz,GetEnergy()); -} - - -inline void MyProjMCTrack::GetStartVertex(TVector3& vertex) -{ - vertex.SetXYZ(fStartX,fStartY,fStartZ); + Double_t mass = GetMass(); + return TMath::Sqrt(mass * mass + fPx * fPx + fPy * fPy + fPz * fPz); } +inline void MyProjMCTrack::GetMomentum(TVector3& momentum) { momentum.SetXYZ(fPx, fPy, fPz); } +inline void MyProjMCTrack::Get4Momentum(TLorentzVector& momentum) { momentum.SetXYZT(fPx, fPy, fPz, GetEnergy()); } - +inline void MyProjMCTrack::GetStartVertex(TVector3& vertex) { vertex.SetXYZ(fStartX, fStartY, fStartZ); } #endif diff --git a/templates/project_stl_containers/MyProjData/MyProjStack.cxx b/templates/project_stl_containers/MyProjData/MyProjStack.cxx index d776b338cc..ca13a5ce80 100644 --- a/templates/project_stl_containers/MyProjData/MyProjStack.cxx +++ b/templates/project_stl_containers/MyProjData/MyProjStack.cxx @@ -13,288 +13,282 @@ #include "MyProjStack.h" -#include "FairDetector.h" // for FairDetector -#include "FairLink.h" // for FairLink -#include "FairMCPoint.h" // for FairMCPoint -#include "MyProjMCTrack.h" // for MyProjMCTrack -#include "FairRootManager.h" // for FairRootManager -#include "FairLogger.h" // for FairLogger, MESSAGE_ORIGIN - -#include // for ostream -#include // for TClonesArray -#include // for TIterator -#include // for TLorentzVector -#include // for TParticle -#include // for TRefArray -#include // for gMC - -#include // for NULL -#include // for operator<<, etc +#include "FairDetector.h" // for FairDetector +#include "FairLink.h" // for FairLink +#include "FairLogger.h" // for FairLogger, MESSAGE_ORIGIN +#include "FairMCPoint.h" // for FairMCPoint +#include "FairRootManager.h" // for FairRootManager +#include "MyProjMCTrack.h" // for MyProjMCTrack + +#include // for TClonesArray +#include // for TIterator +#include // for TLorentzVector +#include // for TParticle +#include // for TRefArray +#include // for gMC +#include // for ostream +#include // for operator<<, etc +#include // for NULL using std::cout; using std::endl; using std::pair; - // ----- Default constructor ------------------------------------------- MyProjStack::MyProjStack(Int_t size) - : FairGenericStack(), - fStack(), - fParticles(new TClonesArray("TParticle", size)), - fTracks(new TClonesArray("MyProjMCTrack", size)), - fStoreMap(), - fStoreIter(), - fIndexMap(), - fIndexIter(), - fPointsMap(), - fCurrentTrack(-1), - fNPrimaries(0), - fNParticles(0), - fNTracks(0), - fIndex(0), - fStoreSecondaries(kTRUE), - fMinPoints(0), - fEnergyCut(0.), - fStoreMothers(kTRUE) -{ -} + : FairGenericStack() + , fStack() + , fParticles(new TClonesArray("TParticle", size)) + , fTracks(new TClonesArray("MyProjMCTrack", size)) + , fStoreMap() + , fStoreIter() + , fIndexMap() + , fIndexIter() + , fPointsMap() + , fCurrentTrack(-1) + , fNPrimaries(0) + , fNParticles(0) + , fNTracks(0) + , fIndex(0) + , fStoreSecondaries(kTRUE) + , fMinPoints(0) + , fEnergyCut(0.) + , fStoreMothers(kTRUE) +{} // ------------------------------------------------------------------------- - MyProjStack::MyProjStack(const MyProjStack& right) - : FairGenericStack(right), - fStack(), - fParticles(new TClonesArray("TParticle", 100)), - fTracks(new TClonesArray("MyProjMCTrack", 100)), - fStoreMap(), - fStoreIter(), - fIndexMap(), - fIndexIter(), - fPointsMap(), - fCurrentTrack(), - fNPrimaries(), - fNParticles(), - fNTracks(), - fIndex(), - fStoreSecondaries(right.fStoreSecondaries), - fMinPoints(right.fMinPoints), - fEnergyCut(right.fEnergyCut), - fStoreMothers(right.fStoreMothers) -{ -} - + : FairGenericStack(right) + , fStack() + , fParticles(new TClonesArray("TParticle", 100)) + , fTracks(new TClonesArray("MyProjMCTrack", 100)) + , fStoreMap() + , fStoreIter() + , fIndexMap() + , fIndexIter() + , fPointsMap() + , fCurrentTrack() + , fNPrimaries() + , fNParticles() + , fNTracks() + , fIndex() + , fStoreSecondaries(right.fStoreSecondaries) + , fMinPoints(right.fMinPoints) + , fEnergyCut(right.fEnergyCut) + , fStoreMothers(right.fStoreMothers) +{} // ----- Destructor ---------------------------------------------------- MyProjStack::~MyProjStack() { - if (fParticles) { - fParticles->Delete(); - delete fParticles; - } - if (fTracks) { - fTracks->Delete(); - delete fTracks; - } + if (fParticles) { + fParticles->Delete(); + delete fParticles; + } + if (fTracks) { + fTracks->Delete(); + delete fTracks; + } } // ------------------------------------------------------------------------- -void MyProjStack::PushTrack(Int_t toBeDone, Int_t parentId, Int_t pdgCode, - Double_t px, Double_t py, Double_t pz, - Double_t e, Double_t vx, Double_t vy, Double_t vz, - Double_t time, Double_t polx, Double_t poly, - Double_t polz, TMCProcess proc, Int_t& ntr, - Double_t weight, Int_t is) +void MyProjStack::PushTrack(Int_t toBeDone, + Int_t parentId, + Int_t pdgCode, + Double_t px, + Double_t py, + Double_t pz, + Double_t e, + Double_t vx, + Double_t vy, + Double_t vz, + Double_t time, + Double_t polx, + Double_t poly, + Double_t polz, + TMCProcess proc, + Int_t& ntr, + Double_t weight, + Int_t is) { - PushTrack( toBeDone, parentId, pdgCode, - px, py, pz, - e, vx, vy, vz, - time, polx, poly, - polz, proc, ntr, - weight, is, -1); + PushTrack( + toBeDone, parentId, pdgCode, px, py, pz, e, vx, vy, vz, time, polx, poly, polz, proc, ntr, weight, is, -1); } - - // ----- Virtual public method PushTrack ------------------------------- -void MyProjStack::PushTrack(Int_t toBeDone, Int_t parentId, Int_t pdgCode, - Double_t px, Double_t py, Double_t pz, - Double_t e, Double_t vx, Double_t vy, Double_t vz, - Double_t time, Double_t polx, Double_t poly, - Double_t polz, TMCProcess proc, Int_t& ntr, - Double_t weight, Int_t is, Int_t secondparentID) +void MyProjStack::PushTrack(Int_t toBeDone, + Int_t parentId, + Int_t pdgCode, + Double_t px, + Double_t py, + Double_t pz, + Double_t e, + Double_t vx, + Double_t vy, + Double_t vz, + Double_t time, + Double_t polx, + Double_t poly, + Double_t polz, + TMCProcess proc, + Int_t& ntr, + Double_t weight, + Int_t is, + Int_t secondparentID) { - // --> Get TParticle array - TClonesArray& partArray = *fParticles; - - // --> Create new TParticle and add it to the TParticle array - Int_t trackId = fNParticles; - Int_t nPoints = 0; - Int_t daughter1Id = -1; - Int_t daughter2Id = -1; - TParticle* particle = - new(partArray[fNParticles++]) TParticle(pdgCode, trackId, parentId, - nPoints, daughter1Id, - daughter2Id, px, py, pz, e, - vx, vy, vz, time); - particle->SetPolarisation(polx, poly, polz); - particle->SetWeight(weight); - particle->SetUniqueID(proc); - - // --> Increment counter - if (parentId < 0) { fNPrimaries++; } + // --> Get TParticle array + TClonesArray& partArray = *fParticles; - // --> Set argument variable - ntr = trackId; + // --> Create new TParticle and add it to the TParticle array + Int_t trackId = fNParticles; + Int_t nPoints = 0; + Int_t daughter1Id = -1; + Int_t daughter2Id = -1; + TParticle* particle = new (partArray[fNParticles++]) + TParticle(pdgCode, trackId, parentId, nPoints, daughter1Id, daughter2Id, px, py, pz, e, vx, vy, vz, time); + particle->SetPolarisation(polx, poly, polz); + particle->SetWeight(weight); + particle->SetUniqueID(proc); + + // --> Increment counter + if (parentId < 0) { + fNPrimaries++; + } - // --> Push particle on the stack if toBeDone is set - if (toBeDone == 1) { fStack.push(particle); } + // --> Set argument variable + ntr = trackId; + // --> Push particle on the stack if toBeDone is set + if (toBeDone == 1) { + fStack.push(particle); + } } // ------------------------------------------------------------------------- - - // ----- Virtual method PopNextTrack ----------------------------------- TParticle* MyProjStack::PopNextTrack(Int_t& iTrack) { - // If end of stack: Return empty pointer - if (fStack.empty()) { - iTrack = -1; - return NULL; - } - - // If not, get next particle from stack - TParticle* thisParticle = fStack.top(); - fStack.pop(); + // If end of stack: Return empty pointer + if (fStack.empty()) { + iTrack = -1; + return NULL; + } - if ( !thisParticle) { - iTrack = 0; - return NULL; - } + // If not, get next particle from stack + TParticle* thisParticle = fStack.top(); + fStack.pop(); - fCurrentTrack = thisParticle->GetStatusCode(); - iTrack = fCurrentTrack; + if (!thisParticle) { + iTrack = 0; + return NULL; + } - return thisParticle; + fCurrentTrack = thisParticle->GetStatusCode(); + iTrack = fCurrentTrack; + return thisParticle; } // ------------------------------------------------------------------------- - - // ----- Virtual method PopPrimaryForTracking -------------------------- TParticle* MyProjStack::PopPrimaryForTracking(Int_t iPrim) { - // Get the iPrimth particle from the fStack TClonesArray. This - // should be a primary (if the index is correct). + // Get the iPrimth particle from the fStack TClonesArray. This + // should be a primary (if the index is correct). - // Test for index - if (iPrim < 0 || iPrim >= fNPrimaries) { - LOG(fatal) << "MyProjStack: Primary index out of range! " << iPrim; - } - - // Return the iPrim-th TParticle from the fParticle array. This should be - // a primary. - TParticle* part = (TParticle*)fParticles->At(iPrim); - if ( ! (part->GetMother(0) < 0) ) { - LOG(fatal) << "MyProjStack:: Not a primary track! " << iPrim; - } + // Test for index + if (iPrim < 0 || iPrim >= fNPrimaries) { + LOG(fatal) << "MyProjStack: Primary index out of range! " << iPrim; + } - return part; + // Return the iPrim-th TParticle from the fParticle array. This should be + // a primary. + TParticle* part = (TParticle*)fParticles->At(iPrim); + if (!(part->GetMother(0) < 0)) { + LOG(fatal) << "MyProjStack:: Not a primary track! " << iPrim; + } + return part; } // ------------------------------------------------------------------------- - - // ----- Virtual public method GetCurrentTrack ------------------------- TParticle* MyProjStack::GetCurrentTrack() const { - TParticle* currentPart = GetParticle(fCurrentTrack); - if ( ! currentPart) { - LOG(warning) << "MyProjStack: Current track not found in stack!"; - } - return currentPart; + TParticle* currentPart = GetParticle(fCurrentTrack); + if (!currentPart) { + LOG(warning) << "MyProjStack: Current track not found in stack!"; + } + return currentPart; } // ------------------------------------------------------------------------- - - // ----- Public method AddParticle ------------------------------------- void MyProjStack::AddParticle(TParticle* oldPart) { - TClonesArray& array = *fParticles; - TParticle* newPart = new(array[fIndex]) TParticle(*oldPart); - newPart->SetWeight(oldPart->GetWeight()); - newPart->SetUniqueID(oldPart->GetUniqueID()); - fIndex++; + TClonesArray& array = *fParticles; + TParticle* newPart = new (array[fIndex]) TParticle(*oldPart); + newPart->SetWeight(oldPart->GetWeight()); + newPart->SetUniqueID(oldPart->GetUniqueID()); + fIndex++; } // ------------------------------------------------------------------------- - - // ----- Public method FillTrackArray ---------------------------------- void MyProjStack::FillTrackArray() { - LOG(debug) << "MyProjStack: Filling MCTrack array..."; + LOG(debug) << "MyProjStack: Filling MCTrack array..."; - // --> Reset index map and number of output tracks - fIndexMap.clear(); - fNTracks = 0; + // --> Reset index map and number of output tracks + fIndexMap.clear(); + fNTracks = 0; - // --> Check tracks for selection criteria - //SelectTracks(); + // --> Check tracks for selection criteria + // SelectTracks(); - // --> Loop over fParticles array and copy selected tracks - for (Int_t iPart=0; iPart Loop over fParticles array and copy selected tracks + for (Int_t iPart = 0; iPart < fNParticles; iPart++) { - /*fStoreIter = fStoreMap.find(iPart); + /*fStoreIter = fStoreMap.find(iPart); if (fStoreIter == fStoreMap.end() ) { LOG(fatal) << "MyProjStack: Particle " << iPart << " not found in storage map! "; } Bool_t store = (*fStoreIter).second;*/ - - Bool_t store = kTRUE; - - if (store) { - MyProjMCTrack* track = - new( (*fTracks)[fNTracks]) MyProjMCTrack(GetParticle(iPart)); - fIndexMap[iPart] = fNTracks; - // --> Set the number of points in the detectors for this track - for (Int_t iDet=kNewDetector; iDet a(iPart, iDet); - track->SetNPoints(iDet, fPointsMap[a]); - } - fNTracks++; - } - else - { - fIndexMap[iPart] = -2; - } - } - // --> Map index for primary mothers - fIndexMap[-1] = -1; + Bool_t store = kTRUE; + + if (store) { + MyProjMCTrack* track = new ((*fTracks)[fNTracks]) MyProjMCTrack(GetParticle(iPart)); + fIndexMap[iPart] = fNTracks; + // --> Set the number of points in the detectors for this track + for (Int_t iDet = kNewDetector; iDet < kSTOPHERE; iDet++) { + pair a(iPart, iDet); + track->SetNPoints(iDet, fPointsMap[a]); + } + fNTracks++; + } else { + fIndexMap[iPart] = -2; + } + } - // --> Screen output - Print(1); + // --> Map index for primary mothers + fIndexMap[-1] = -1; + // --> Screen output + Print(1); } // ------------------------------------------------------------------------- - - // ----- Public method UpdateTrackIndex -------------------------------- void MyProjStack::UpdateTrackIndex(TRefArray* detList) { -/* + /* LOG(debug) << "MyProjStack: Updating track indizes..."; Int_t nColl = 0; @@ -349,166 +343,161 @@ void MyProjStack::UpdateTrackIndex(TRefArray* detList) } // ------------------------------------------------------------------------- - - // ----- Public method Reset ------------------------------------------- void MyProjStack::Reset() { - fIndex = 0; - fCurrentTrack = -1; - fNPrimaries = fNParticles = fNTracks = 0; - while (! fStack.empty() ) { fStack.pop(); } - fParticles->Clear(); - fTracks->Clear(); - fPointsMap.clear(); + fIndex = 0; + fCurrentTrack = -1; + fNPrimaries = fNParticles = fNTracks = 0; + while (!fStack.empty()) { + fStack.pop(); + } + fParticles->Clear(); + fTracks->Clear(); + fPointsMap.clear(); } // ------------------------------------------------------------------------- - - // ----- Public method Register ---------------------------------------- void MyProjStack::Register() { - if ( gMC && ( ! gMC->IsMT() ) ) { - FairRootManager::Instance()->Register("MCTrack", "Stack", fTracks,kTRUE); - } else { - FairRootManager::Instance()->RegisterAny("MCTrack",fTracks,kTRUE); - } + if (gMC && (!gMC->IsMT())) { + FairRootManager::Instance()->Register("MCTrack", "Stack", fTracks, kTRUE); + } else { + FairRootManager::Instance()->RegisterAny("MCTrack", fTracks, kTRUE); + } } // ------------------------------------------------------------------------- - - // ----- Public method Print -------------------------------------------- void MyProjStack::Print(Int_t iVerbose) const { - cout << "-I- MyProjStack: Number of primaries = " - << fNPrimaries << endl; - cout << " Total number of particles = " - << fNParticles << endl; - cout << " Number of tracks in output = " - << fNTracks << endl; - if (iVerbose) { - for (Int_t iTrack=0; iTrackAt(iTrack))->Print(iTrack); + cout << "-I- MyProjStack: Number of primaries = " << fNPrimaries << endl; + cout << " Total number of particles = " << fNParticles << endl; + cout << " Number of tracks in output = " << fNTracks << endl; + if (iVerbose) { + for (Int_t iTrack = 0; iTrack < fNTracks; iTrack++) { + ((MyProjMCTrack*)fTracks->At(iTrack))->Print(iTrack); + } } - } } // ------------------------------------------------------------------------- - - // ----- Public method AddPoint (for current track) -------------------- void MyProjStack::AddPoint(DetectorId detId) { - Int_t iDet = detId; -// cout << "Add point for Detektor" << iDet << endl; - pair a(fCurrentTrack, iDet); - if ( fPointsMap.find(a) == fPointsMap.end() ) { fPointsMap[a] = 1; } - else { fPointsMap[a]++; } + Int_t iDet = detId; + // cout << "Add point for Detektor" << iDet << endl; + pair a(fCurrentTrack, iDet); + if (fPointsMap.find(a) == fPointsMap.end()) { + fPointsMap[a] = 1; + } else { + fPointsMap[a]++; + } } // ------------------------------------------------------------------------- - - // ----- Public method AddPoint (for arbitrary track) ------------------- void MyProjStack::AddPoint(DetectorId detId, Int_t iTrack) { - if ( iTrack < 0 ) { return; } - Int_t iDet = detId; - pair a(iTrack, iDet); - if ( fPointsMap.find(a) == fPointsMap.end() ) { fPointsMap[a] = 1; } - else { fPointsMap[a]++; } + if (iTrack < 0) { + return; + } + Int_t iDet = detId; + pair a(iTrack, iDet); + if (fPointsMap.find(a) == fPointsMap.end()) { + fPointsMap[a] = 1; + } else { + fPointsMap[a]++; + } } // ------------------------------------------------------------------------- - - - // ----- Virtual method GetCurrentParentTrackNumber -------------------- Int_t MyProjStack::GetCurrentParentTrackNumber() const { - TParticle* currentPart = GetCurrentTrack(); - if ( currentPart ) { return currentPart->GetFirstMother(); } - else { return -1; } + TParticle* currentPart = GetCurrentTrack(); + if (currentPart) { + return currentPart->GetFirstMother(); + } else { + return -1; + } } // ------------------------------------------------------------------------- - - // ----- Public method GetParticle ------------------------------------- TParticle* MyProjStack::GetParticle(Int_t trackID) const { - if (trackID < 0 || trackID >= fNParticles) { - LOG(fatal) << "MyProjStack: Particle index " << trackID << " out of range."; - } - return (TParticle*)fParticles->At(trackID); + if (trackID < 0 || trackID >= fNParticles) { + LOG(fatal) << "MyProjStack: Particle index " << trackID << " out of range."; + } + return (TParticle*)fParticles->At(trackID); } // ------------------------------------------------------------------------- - - // ----- Private method SelectTracks ----------------------------------- void MyProjStack::SelectTracks() { - // --> Clear storage map - fStoreMap.clear(); - - // --> Check particles in the fParticle array - for (Int_t i=0; i Get track parameters - Int_t iMother = thisPart->GetMother(0); - TLorentzVector p; - thisPart->Momentum(p); - Double_t energy = p.E(); - Double_t mass = p.M(); -// Double_t mass = thisPart->GetMass(); - Double_t eKin = energy - mass; + // --> Clear storage map + fStoreMap.clear(); + + // --> Check particles in the fParticle array + for (Int_t i = 0; i < fNParticles; i++) { + + TParticle* thisPart = GetParticle(i); + Bool_t store = kTRUE; + + // --> Get track parameters + Int_t iMother = thisPart->GetMother(0); + TLorentzVector p; + thisPart->Momentum(p); + Double_t energy = p.E(); + Double_t mass = p.M(); + // Double_t mass = thisPart->GetMass(); + Double_t eKin = energy - mass; + + // --> Calculate number of points + Int_t nPoints = 0; + for (Int_t iDet = kNewDetector; iDet < kSTOPHERE; iDet++) { + pair a(i, iDet); + if (fPointsMap.find(a) != fPointsMap.end()) { + nPoints += fPointsMap[a]; + } + } - // --> Calculate number of points - Int_t nPoints = 0; - for (Int_t iDet=kNewDetector; iDet a(i, iDet); - if ( fPointsMap.find(a) != fPointsMap.end() ) { - nPoints += fPointsMap[a]; - } - } + // --> Check for cuts (store primaries in any case) + if (iMother < 0) { + store = kTRUE; + } else { + if (!fStoreSecondaries) { + store = kFALSE; + } + if (nPoints < fMinPoints) { + store = kFALSE; + } + if (eKin < fEnergyCut) { + store = kFALSE; + } + } - // --> Check for cuts (store primaries in any case) - if (iMother < 0) { store = kTRUE; } - else { - if (!fStoreSecondaries) { store = kFALSE; } - if (nPoints < fMinPoints) { store = kFALSE; } - if (eKin < fEnergyCut) { store = kFALSE; } + // --> Set storage flag + fStoreMap[i] = store; } - // --> Set storage flag - fStoreMap[i] = store; - - - } - - // --> If flag is set, flag recursively mothers of selected tracks - if (fStoreMothers) { - for (Int_t i=0; iGetMother(0); - while(iMother >= 0) { - fStoreMap[iMother] = kTRUE; - iMother = GetParticle(iMother)->GetMother(0); + // --> If flag is set, flag recursively mothers of selected tracks + if (fStoreMothers) { + for (Int_t i = 0; i < fNParticles; i++) { + if (fStoreMap[i]) { + Int_t iMother = GetParticle(i)->GetMother(0); + while (iMother >= 0) { + fStoreMap[iMother] = kTRUE; + iMother = GetParticle(iMother)->GetMother(0); + } + } } - } } - } - } // ------------------------------------------------------------------------- - - -ClassImp(MyProjStack) +ClassImp(MyProjStack); diff --git a/templates/project_stl_containers/MyProjData/MyProjStack.h b/templates/project_stl_containers/MyProjData/MyProjStack.h index 3e9d49815b..833290e872 100644 --- a/templates/project_stl_containers/MyProjData/MyProjStack.h +++ b/templates/project_stl_containers/MyProjData/MyProjStack.h @@ -11,7 +11,6 @@ // ----- M. Al-Turany June 2014 ----- // ------------------------------------------------------------------------- - /** MyProjStack.h ** ** This class handles the particle stack for the transport simulation. @@ -30,20 +29,17 @@ ** By default, the minimal number of points is 1 and the energy cut is 0. **/ - #ifndef MyProjStack_H #define MyProjStack_H -#include "FairGenericStack.h" // for FairGenericStack - -#include "MyProjDetectorList.h" // for DetectorId +#include "FairGenericStack.h" // for FairGenericStack +#include "MyProjDetectorList.h" // for DetectorId -#include // for Int_t, Double_t, Bool_t, etc -#include // for TMCProcess - -#include // for map, map<>::iterator -#include // for stack -#include // for pair +#include // for Int_t, Double_t, Bool_t, etc +#include // for TMCProcess +#include // for map, map<>::iterator +#include // for stack +#include // for pair class TClonesArray; class TParticle; @@ -53,17 +49,14 @@ class MyProjStack : public FairGenericStack { public: - /** Default constructor *param size Estimated track number **/ MyProjStack(Int_t size = 100); - /** Destructor **/ virtual ~MyProjStack(); - /** Add a TParticle to the stack. ** Declared in TVirtualMCStack *@param toBeDone Flag for tracking @@ -79,22 +72,44 @@ class MyProjStack : public FairGenericStack *@param weight Particle weight *@param is Generation status code (whatever that means) **/ - virtual void PushTrack(Int_t toBeDone, Int_t parentID, Int_t pdgCode, - Double_t px, Double_t py, Double_t pz, - Double_t e, Double_t vx, Double_t vy, - Double_t vz, Double_t time, Double_t polx, - Double_t poly, Double_t polz, TMCProcess proc, - Int_t& ntr, Double_t weight, Int_t is); - - virtual void PushTrack(Int_t toBeDone, Int_t parentID, Int_t pdgCode, - Double_t px, Double_t py, Double_t pz, - Double_t e, Double_t vx, Double_t vy, - Double_t vz, Double_t time, Double_t polx, - Double_t poly, Double_t polz, TMCProcess proc, - Int_t& ntr, Double_t weight, Int_t is,Int_t secondParentId); - - - + virtual void PushTrack(Int_t toBeDone, + Int_t parentID, + Int_t pdgCode, + Double_t px, + Double_t py, + Double_t pz, + Double_t e, + Double_t vx, + Double_t vy, + Double_t vz, + Double_t time, + Double_t polx, + Double_t poly, + Double_t polz, + TMCProcess proc, + Int_t& ntr, + Double_t weight, + Int_t is); + + virtual void PushTrack(Int_t toBeDone, + Int_t parentID, + Int_t pdgCode, + Double_t px, + Double_t py, + Double_t pz, + Double_t e, + Double_t vx, + Double_t vy, + Double_t vz, + Double_t time, + Double_t polx, + Double_t poly, + Double_t polz, + TMCProcess proc, + Int_t& ntr, + Double_t weight, + Int_t is, + Int_t secondParentId); /** Get next particle for tracking from the stack. ** Declared in TVirtualMCStack @@ -103,7 +118,6 @@ class MyProjStack : public FairGenericStack **/ virtual TParticle* PopNextTrack(Int_t& iTrack); - /** Get primary particle by index for tracking from stack ** Declared in TVirtualMCStack *@param iPrim index of primary particle @@ -111,90 +125,74 @@ class MyProjStack : public FairGenericStack **/ virtual TParticle* PopPrimaryForTracking(Int_t iPrim); - /** Set the current track number ** Declared in TVirtualMCStack *@param iTrack track number **/ - virtual void SetCurrentTrack(Int_t iTrack) { fCurrentTrack = iTrack; } - + virtual void SetCurrentTrack(Int_t iTrack) { fCurrentTrack = iTrack; } /** Get total number of tracks ** Declared in TVirtualMCStack **/ virtual Int_t GetNtrack() const { return fNParticles; } - /** Get number of primary tracks ** Declared in TVirtualMCStack **/ virtual Int_t GetNprimary() const { return fNPrimaries; } - /** Get the current track's particle ** Declared in TVirtualMCStack **/ virtual TParticle* GetCurrentTrack() const; - /** Get the number of the current track ** Declared in TVirtualMCStack **/ virtual Int_t GetCurrentTrackNumber() const { return fCurrentTrack; } - /** Get the track number of the parent of the current track ** Declared in TVirtualMCStack **/ virtual Int_t GetCurrentParentTrackNumber() const; - /** Add a TParticle to the fParticles array **/ virtual void AddParticle(TParticle* part); - /** Fill the MCTrack output array, applying filter criteria **/ virtual void FillTrackArray(); - /** Update the track index in the MCTracks and MCPoints **/ - virtual void UpdateTrackIndex(TRefArray* detArray=0); - + virtual void UpdateTrackIndex(TRefArray* detArray = 0); /** Resets arrays and stack and deletes particles and tracks **/ virtual void Reset(); - /** Register the MCTrack array to the Root Manager **/ virtual void Register(); - /** Output to screen **@param iVerbose: 0=events summary, 1=track info **/ - virtual void Print(Int_t iVerbose=0) const; - + virtual void Print(Int_t iVerbose = 0) const; /** Modifiers **/ void StoreSecondaries(Bool_t choice = kTRUE) { fStoreSecondaries = choice; } - void SetMinPoints(Int_t min) { fMinPoints = min; } - void SetEnergyCut(Double_t eMin) { fEnergyCut = eMin; } - void StoreMothers(Bool_t choice = kTRUE) { fStoreMothers = choice; } - + void SetMinPoints(Int_t min) { fMinPoints = min; } + void SetEnergyCut(Double_t eMin) { fEnergyCut = eMin; } + void StoreMothers(Bool_t choice = kTRUE) { fStoreMothers = choice; } /** Increment number of points for the current track in a given detector *@param iDet Detector unique identifier **/ void AddPoint(DetectorId iDet); - /** Increment number of points for an arbitrary track in a given detector *@param iDet Detector unique identifier *@param iTrack Track number **/ void AddPoint(DetectorId iDet, Int_t iTrack); - /** Accessors **/ TParticle* GetParticle(Int_t trackId) const; TClonesArray* GetListOfParticles() { return fParticles; } @@ -204,47 +202,39 @@ class MyProjStack : public FairGenericStack private: /** STL stack (FILO) used to handle the TParticles for tracking **/ - std::stack fStack; //! - + std::stack fStack; //! /** Array of TParticles (contains all TParticles put into or created ** by the transport **/ - TClonesArray* fParticles; //! - + TClonesArray* fParticles; //! /** Array of FairMCTracks containg the tracks written to the output **/ TClonesArray* fTracks; - /** STL map from particle index to storage flag **/ - std::map fStoreMap; //! - std::map::iterator fStoreIter; //! - + std::map fStoreMap; //! + std::map::iterator fStoreIter; //! /** STL map from particle index to track index **/ - std::map fIndexMap; //! - std::map::iterator fIndexIter; //! - + std::map fIndexMap; //! + std::map::iterator fIndexIter; //! /** STL map from track index and detector ID to number of MCPoints **/ - std::map, Int_t> fPointsMap; //! - + std::map, Int_t> fPointsMap; //! /** Some indizes and counters **/ - Int_t fCurrentTrack; //! Index of current track - Int_t fNPrimaries; //! Number of primary particles - Int_t fNParticles; //! Number of entries in fParticles - Int_t fNTracks; //! Number of entries in fTracks - Int_t fIndex; //! Used for merging - + Int_t fCurrentTrack; //! Index of current track + Int_t fNPrimaries; //! Number of primary particles + Int_t fNParticles; //! Number of entries in fParticles + Int_t fNTracks; //! Number of entries in fTracks + Int_t fIndex; //! Used for merging /** Variables defining the criteria for output selection **/ - Bool_t fStoreSecondaries; - Int_t fMinPoints; + Bool_t fStoreSecondaries; + Int_t fMinPoints; Double32_t fEnergyCut; - Bool_t fStoreMothers; - + Bool_t fStoreMothers; /** Mark tracks for output using selection criteria **/ void SelectTracks(); @@ -252,14 +242,7 @@ class MyProjStack : public FairGenericStack MyProjStack(const MyProjStack&); MyProjStack& operator=(const MyProjStack&); - ClassDef(MyProjStack,1) - - + ClassDef(MyProjStack, 1) }; - - - - - #endif diff --git a/templates/project_stl_containers/MyProjGenerators/Pythia6Generator.cxx b/templates/project_stl_containers/MyProjGenerators/Pythia6Generator.cxx index 56376cfb0a..112a56cf70 100644 --- a/templates/project_stl_containers/MyProjGenerators/Pythia6Generator.cxx +++ b/templates/project_stl_containers/MyProjGenerators/Pythia6Generator.cxx @@ -14,11 +14,11 @@ // ------------------------------------------------------------------------- #include "Pythia6Generator.h" -#include "FairPrimaryGenerator.h" #include "FairLogger.h" +#include "FairPrimaryGenerator.h" -#include #include +#include using std::cout; using std::endl; @@ -28,113 +28,119 @@ using std::max; Pythia6Generator::Pythia6Generator() {} // ------------------------------------------------------------------------ - - // ----- Standard constructor ----------------------------------------- -Pythia6Generator::Pythia6Generator(const char* fileName) { - fFileName = fileName; - fVerbose = 0; - cout << "-I Pythia6Generator: Opening input file " << fileName << endl; - if ((fInputFile = fopen(fFileName,"r"))==NULL) - // fInputFile = new ifstream(fFileName); - // if ( ! fInputFile->is_open() ) - LOG(fatal) << "Pythia6Generator: Cannot open input file."; - - // fPDG=TDatabasePDG::Instance(); +Pythia6Generator::Pythia6Generator(const char* fileName) +{ + fFileName = fileName; + fVerbose = 0; + cout << "-I Pythia6Generator: Opening input file " << fileName << endl; + if ((fInputFile = fopen(fFileName, "r")) == NULL) + // fInputFile = new ifstream(fFileName); + // if ( ! fInputFile->is_open() ) + LOG(fatal) << "Pythia6Generator: Cannot open input file."; + + // fPDG=TDatabasePDG::Instance(); } // ------------------------------------------------------------------------ - - // ----- Destructor --------------------------------------------------- -Pythia6Generator::~Pythia6Generator() { - CloseInput(); -} +Pythia6Generator::~Pythia6Generator() { CloseInput(); } // ------------------------------------------------------------------------ +// ----- Public method ReadEvent -------------------------------------- +Bool_t Pythia6Generator::ReadEvent(FairPrimaryGenerator* primGen) +{ + + // Check for input file + if (!fInputFile) { + // if ( ! fInputFile->is_open() ) { + cout << "-E Pythia6Generator: Input file not open!" << endl; + return kFALSE; + } + + // Define event variable to be read from file + Int_t ntracks = 0, eventID = 0, ncols = 0; + + // Define track variables to be read from file + Int_t nLev = 0, pdgID = 0, nM1 = -1, nM2 = -1, nDF = -1, nDL = -1; + Float_t fPx = 0., fPy = 0., fPz = 0., fM = 0., fE = 0.; + Float_t fVx = 0., fVy = 0., fVz = 0., fT = 0.; + + // Read event header line from input file + + Int_t max_nr = 0; + + Text_t buffer[200]; + ncols = fscanf(fInputFile, "%d\t%d", &eventID, &ntracks); + + if (ncols && ntracks > 0) { + + if (fVerbose > 0) + cout << "Event number: " << eventID << "\tNtracks: " << ntracks << endl; + + for (Int_t ll = 0; ll < ntracks; ll++) { + ncols = fscanf(fInputFile, + "%d %d %d %d %d %d %f %f %f %f %f %f %f %f %f", + &nLev, + &pdgID, + &nM1, + &nM2, + &nDF, + &nDL, + &fPx, + &fPy, + &fPz, + &fE, + &fM, + &fVx, + &fVy, + &fVz, + &fT); + if (fVerbose > 0) + cout << nLev << "\t" << pdgID << "\t" << nM1 << "\t" << nM2 << "\t" << nDF << "\t" << nDL << "\t" << fPx + << "\t" << fPy << "\t" << fPz << "\t" << fE << "\t" << fM << "\t" << fVx << "\t" << fVy << "\t" + << fVz << "\t" << fT << endl; + if (nLev == 1) + primGen->AddTrack(pdgID, fPx, fPy, fPz, fVx, fVy, fVz); + } + } else { + cout << "-I Pythia6Generator: End of input file reached " << endl; + CloseInput(); + return kFALSE; + } + // If end of input file is reached : close it and abort run + if (feof(fInputFile)) { + cout << "-I Pythia6Generator: End of input file reached " << endl; + CloseInput(); + return kFALSE; + } -// ----- Public method ReadEvent -------------------------------------- -Bool_t Pythia6Generator::ReadEvent(FairPrimaryGenerator* primGen) { - - // Check for input file - if (!fInputFile) { - // if ( ! fInputFile->is_open() ) { - cout << "-E Pythia6Generator: Input file not open!" << endl; - return kFALSE; - } - - // Define event variable to be read from file - Int_t ntracks = 0, eventID = 0, ncols = 0; - - // Define track variables to be read from file - Int_t nLev = 0, pdgID = 0, nM1 = -1, nM2 = -1, nDF = -1, nDL = -1; - Float_t fPx = 0., fPy = 0., fPz = 0., fM = 0., fE = 0.; - Float_t fVx = 0., fVy = 0., fVz = 0., fT = 0.; - - // Read event header line from input file - - Int_t max_nr = 0; - - Text_t buffer[200]; - ncols = fscanf(fInputFile,"%d\t%d", &eventID, &ntracks); - - if (ncols && ntracks>0) { - - if (fVerbose>0) cout << "Event number: " << eventID << "\tNtracks: " << ntracks << endl; - - for (Int_t ll=0; ll0) cout << nLev << "\t" << pdgID << "\t" << nM1 << "\t" << nM2 << "\t" << nDF << "\t" << nDL << - "\t" << fPx << "\t" << fPy << "\t" << fPz << "\t" << fE << "\t" << fM << "\t" << fVx << "\t" << fVy << "\t" << fVz << "\t" << fT << endl; - if (nLev==1) - primGen->AddTrack(pdgID, fPx, fPy, fPz, fVx, fVy, fVz); - } - } - else { - cout << "-I Pythia6Generator: End of input file reached " << endl; - CloseInput(); - return kFALSE; - } - - - // If end of input file is reached : close it and abort run - if ( feof(fInputFile) ) { - cout << "-I Pythia6Generator: End of input file reached " << endl; - CloseInput(); - return kFALSE; - } - - /* + /* cout << "-I Pythia6Generator: Event " << eventID << ", vertex = (" << vx << "," << vy << "," << vz << ") cm, multiplicity " << ntracks << endl; */ - - return kTRUE; + + return kTRUE; } // ------------------------------------------------------------------------ - - // ----- Private method CloseInput ------------------------------------ -void Pythia6Generator::CloseInput() { - if ( fInputFile ) { - //if ( fInputFile->is_open() ) { - { - cout << "-I Pythia6Generator: Closing input file " - << fFileName << endl; - // fInputFile->close(); - - fclose(fInputFile); +void Pythia6Generator::CloseInput() +{ + if (fInputFile) { + // if ( fInputFile->is_open() ) { + { + cout << "-I Pythia6Generator: Closing input file " << fFileName << endl; + // fInputFile->close(); + + fclose(fInputFile); + } + delete fInputFile; + fInputFile = NULL; } - delete fInputFile; - fInputFile = NULL; - } } // ------------------------------------------------------------------------ - -ClassImp(Pythia6Generator) - +ClassImp(Pythia6Generator); diff --git a/templates/project_stl_containers/MyProjGenerators/Pythia6Generator.h b/templates/project_stl_containers/MyProjGenerators/Pythia6Generator.h index 197f01e028..ab660e2cb6 100644 --- a/templates/project_stl_containers/MyProjGenerators/Pythia6Generator.h +++ b/templates/project_stl_containers/MyProjGenerators/Pythia6Generator.h @@ -9,13 +9,12 @@ // ----- M. Al-Turany June 2014 ----- // ------------------------------------------------------------------------- - // ------------------------------------------------------------------------- // ----- Pythia6Generator header file ----- // ----- Created 08/08/08 by S. Spataro ----- // ------------------------------------------------------------------------- -/** Pythia6Generator.h +/** Pythia6Generator.h *@author S.Spataro * The Pythia6Generator reads a Pythia6 input file. The file must contain @@ -23,95 +22,101 @@ [start] 1 20 - 3 -2212 0 0 0 0 0.00000000E+00 0.00000000E+00 0.14000000E+02 0.14031406E+02 0.93827000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 - 3 2212 0 0 0 0 0.00000000E+00 0.00000000E+00 -0.13444107E-16 0.93827000E+00 0.93827000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 - 3 -2 1 0 0 0 -0.70661074E+00 -0.81156104E+00 0.49379331E+01 0.50538217E+01 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 - 3 2 2 0 0 0 -0.79043780E+00 0.32642680E+00 0.10299757E+01 0.13387293E+01 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 - 3 -2 3 0 0 0 -0.70661074E+00 -0.81156104E+00 0.49379331E+01 0.50538217E+01 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 - 3 2 4 0 0 0 -0.79043780E+00 0.32642680E+00 0.10299757E+01 0.13387293E+01 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 - 3 23 5 6 0 0 -0.14970485E+01 -0.48513424E+00 0.59679088E+01 0.63925510E+01 0.16650116E+01 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 - 3 11 7 0 0 0 -0.16024130E+01 0.20883507E-01 0.32233123E+01 0.35997091E+01 0.51000000E-03 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 - 3 -11 7 0 0 0 0.10536443E+00 -0.50601774E+00 0.27445965E+01 0.27928419E+01 0.51000000E-03 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 - 2 23 7 0 11 13 -0.14970485E+01 -0.48513424E+00 0.59679088E+01 0.63925510E+01 0.16650116E+01 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 - 1 -11 9 0 0 0 0.10536442E+00 -0.50601769E+00 0.27445962E+01 0.27928416E+01 0.51000000E-03 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 - 1 11 8 0 0 0 -0.16017105E+01 0.20863360E-01 0.32218964E+01 0.35981284E+01 0.51000000E-03 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 - 1 22 8 0 0 0 -0.70246172E-03 0.20096726E-04 0.14161816E-02 0.15809575E-02 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 - 2 -2103 1 0 16 16 0.70661074E+00 0.81156104E+00 0.69735272E+01 0.70980957E+01 0.77133000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 - 2 2101 2 0 16 16 0.79043780E+00 -0.32642680E+00 0.10585640E+01 0.14790292E+01 0.57933000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 - 2 92 14 15 17 18 0.14970485E+01 0.48513424E+00 0.80320912E+01 0.85771248E+01 0.25643853E+01 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 - 2 -2214 16 0 19 20 0.81382620E+00 0.70515618E+00 0.61830559E+01 0.63829315E+01 0.11627878E+01 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 - 1 2212 16 0 0 0 0.68322234E+00 -0.22002195E+00 0.18490353E+01 0.21941934E+01 0.93827000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 - 1 -2112 17 0 0 0 0.78494059E+00 0.52384336E+00 0.55944336E+01 0.57507411E+01 0.93957000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 - 1 -211 17 0 0 0 0.28885610E-01 0.18131282E+00 0.58862227E+00 0.63219038E+00 0.13957000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 - 2 25 - 3 -2212 0 0 0 0 0.00000000E+00 0.00000000E+00 0.14000000E+02 0.14031406E+02 0.93827000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 - 3 2212 0 0 0 0 0.00000000E+00 0.00000000E+00 -0.13444107E-16 0.93827000E+00 0.93827000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 - - + 3 -2212 0 0 0 0 0.00000000E+00 0.00000000E+00 0.14000000E+02 +0.14031406E+02 0.93827000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 3 2212 0 0 +0 0 0.00000000E+00 0.00000000E+00 -0.13444107E-16 0.93827000E+00 0.93827000E+00 0.00000000E+00 +0.00000000E+00 0.00000000E+00 0.00000000E+00 3 -2 1 0 0 0 -0.70661074E+00 +-0.81156104E+00 0.49379331E+01 0.50538217E+01 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 +0.00000000E+00 3 2 2 0 0 0 -0.79043780E+00 0.32642680E+00 0.10299757E+01 +0.13387293E+01 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 3 -2 3 0 +0 0 -0.70661074E+00 -0.81156104E+00 0.49379331E+01 0.50538217E+01 0.00000000E+00 0.00000000E+00 +0.00000000E+00 0.00000000E+00 0.00000000E+00 3 2 4 0 0 0 -0.79043780E+00 +0.32642680E+00 0.10299757E+01 0.13387293E+01 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 +0.00000000E+00 3 23 5 6 0 0 -0.14970485E+01 -0.48513424E+00 0.59679088E+01 +0.63925510E+01 0.16650116E+01 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 3 11 7 0 +0 0 -0.16024130E+01 0.20883507E-01 0.32233123E+01 0.35997091E+01 0.51000000E-03 0.00000000E+00 +0.00000000E+00 0.00000000E+00 0.00000000E+00 3 -11 7 0 0 0 0.10536443E+00 +-0.50601774E+00 0.27445965E+01 0.27928419E+01 0.51000000E-03 0.00000000E+00 0.00000000E+00 0.00000000E+00 +0.00000000E+00 2 23 7 0 11 13 -0.14970485E+01 -0.48513424E+00 0.59679088E+01 +0.63925510E+01 0.16650116E+01 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 1 -11 9 0 +0 0 0.10536442E+00 -0.50601769E+00 0.27445962E+01 0.27928416E+01 0.51000000E-03 0.00000000E+00 +0.00000000E+00 0.00000000E+00 0.00000000E+00 1 11 8 0 0 0 -0.16017105E+01 +0.20863360E-01 0.32218964E+01 0.35981284E+01 0.51000000E-03 0.00000000E+00 0.00000000E+00 0.00000000E+00 +0.00000000E+00 1 22 8 0 0 0 -0.70246172E-03 0.20096726E-04 0.14161816E-02 +0.15809575E-02 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 2 -2103 1 0 +16 16 0.70661074E+00 0.81156104E+00 0.69735272E+01 0.70980957E+01 0.77133000E+00 0.00000000E+00 +0.00000000E+00 0.00000000E+00 0.00000000E+00 2 2101 2 0 16 16 0.79043780E+00 +-0.32642680E+00 0.10585640E+01 0.14790292E+01 0.57933000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 +0.00000000E+00 2 92 14 15 17 18 0.14970485E+01 0.48513424E+00 0.80320912E+01 +0.85771248E+01 0.25643853E+01 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 2 -2214 16 0 +19 20 0.81382620E+00 0.70515618E+00 0.61830559E+01 0.63829315E+01 0.11627878E+01 0.00000000E+00 +0.00000000E+00 0.00000000E+00 0.00000000E+00 1 2212 16 0 0 0 0.68322234E+00 +-0.22002195E+00 0.18490353E+01 0.21941934E+01 0.93827000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 +0.00000000E+00 1 -2112 17 0 0 0 0.78494059E+00 0.52384336E+00 0.55944336E+01 +0.57507411E+01 0.93957000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 1 -211 17 0 +0 0 0.28885610E-01 0.18131282E+00 0.58862227E+00 0.63219038E+00 0.13957000E+00 0.00000000E+00 +0.00000000E+00 0.00000000E+00 0.00000000E+00 2 25 3 -2212 0 0 0 0 0.00000000E+00 +0.00000000E+00 0.14000000E+02 0.14031406E+02 0.93827000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 +0.00000000E+00 3 2212 0 0 0 0 0.00000000E+00 0.00000000E+00 -0.13444107E-16 +0.93827000E+00 0.93827000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 + + ... [stop] - + where the first row has the number of event and the number of particles, and below "N" is the line - number of the event, + number of the event, Derived from FairGenerator. **/ - #ifndef PND_PYTHIAGENERATOR_H #define PND_PYTHIAGENERATOR_H -#include // for FILE -#include "FairGenerator.h" // for FairGenerator -#include // for Int_t, Pythia6Generator::Class, Bool_t, etc -class FairPrimaryGenerator; // lines 68-68 +#include "FairGenerator.h" // for FairGenerator +#include // for Int_t, Pythia6Generator::Class, Bool_t, etc +#include // for FILE +class FairPrimaryGenerator; // lines 68-68 -class Pythia6Generator : public FairGenerator +class Pythia6Generator : public FairGenerator { - public: - - /** Default constructor without arguments should not be used. **/ - Pythia6Generator(); - - - /** Standard constructor. - ** @param fileName The input file name - **/ - Pythia6Generator(const char* fileName); + public: + /** Default constructor without arguments should not be used. **/ + Pythia6Generator(); + /** Standard constructor. + ** @param fileName The input file name + **/ + Pythia6Generator(const char* fileName); - /** Destructor. **/ - virtual ~Pythia6Generator(); + /** Destructor. **/ + virtual ~Pythia6Generator(); - - /** Reads on event from the input file and pushes the tracks onto - ** the stack. Abstract method in base class. - ** @param primGen pointer to the CbmrimaryGenerator - **/ - virtual Bool_t ReadEvent(FairPrimaryGenerator* primGen); + /** Reads on event from the input file and pushes the tracks onto + ** the stack. Abstract method in base class. + ** @param primGen pointer to the CbmrimaryGenerator + **/ + virtual Bool_t ReadEvent(FairPrimaryGenerator* primGen); - void SetVerbose (Int_t verb) { fVerbose = verb; }; + void SetVerbose(Int_t verb) { fVerbose = verb; }; - private: + private: + // ifstream* fInputFile; //! Input file stream + const Char_t* fFileName; //! Input file Name + FILE* fInputFile; //! File + Int_t fVerbose; //! Verbose Level - //ifstream* fInputFile; //! Input file stream - const Char_t * fFileName; //! Input file Name - FILE *fInputFile; //! File - Int_t fVerbose; //! Verbose Level + /** Private method CloseInput. Just for convenience. Closes the + ** input file properly. Called from destructor and from ReadEvent. **/ + void CloseInput(); - /** Private method CloseInput. Just for convenience. Closes the - ** input file properly. Called from destructor and from ReadEvent. **/ - void CloseInput(); - - - /** PDG data base */ - -// TDatabasePDG *fPDG; //! + /** PDG data base */ - ClassDef(Pythia6Generator,1); + // TDatabasePDG *fPDG; //! + ClassDef(Pythia6Generator, 1); }; #endif diff --git a/templates/project_stl_containers/MyProjGenerators/Pythia8Generator.cxx b/templates/project_stl_containers/MyProjGenerators/Pythia8Generator.cxx index 53ea9d1262..798bfbfcbf 100644 --- a/templates/project_stl_containers/MyProjGenerators/Pythia8Generator.cxx +++ b/templates/project_stl_containers/MyProjGenerators/Pythia8Generator.cxx @@ -9,11 +9,11 @@ // ----- M. Al-Turany June 2014 ----- // ------------------------------------------------------------------------- +#include "FairPrimaryGenerator.h" +#include "Pythia8/Pythia.h" -#include #include -#include "Pythia8/Pythia.h" -#include "FairPrimaryGenerator.h" +#include //#include "FairGenerator.h" #include "Pythia8Generator.h" @@ -21,138 +21,144 @@ using namespace Pythia8; // ----- Default constructor ------------------------------------------- -Pythia8Generator::Pythia8Generator() +Pythia8Generator::Pythia8Generator() { - fUseRandom1 = kFALSE; - fUseRandom3 = kTRUE; - fId = 2212; // proton - fMom = 400; // proton - fHNL = 0; // HNL if set to !=0, for example 9900014, only track + fUseRandom1 = kFALSE; + fUseRandom3 = kTRUE; + fId = 2212; // proton + fMom = 400; // proton + fHNL = 0; // HNL if set to !=0, for example 9900014, only track } // ------------------------------------------------------------------------- // ----- Default constructor ------------------------------------------- -Bool_t Pythia8Generator::Init() +Bool_t Pythia8Generator::Init() { - if (fUseRandom1) fRandomEngine = new PyTr1Rng(); - if (fUseRandom3) fRandomEngine = new PyTr3Rng(); - - fPythia.setRndmEnginePtr(fRandomEngine); - - cout<<"Beam Momentum "< 7000. && x<250. && y<250.) { - npart++; - } - } - } - else {npart++;} - }; - }; -// happens if a charm particle being produced which does decay without producing a HNL. Try another event. -// if (npart == 0){ fPythia.event.list();} - }; -// cout<<"debug p8 event 0 " << fPythia.event[0].id()<< " "<< fPythia.event[1].id()<< " "<< fPythia.event[2].id()<< " "<< npart <AddTrack((Int_t)fPythia.event[ii].id(),px,py,pz,x,y,z, - (Int_t)fPythia.event[ii].mother1(),wanttracking); - // cout<<"debug p8->geant4 "<< wanttracking << " "<< ii << " " << fPythia.event[ii].id()<< " "<< fPythia.event[ii].mother1()<<" "< 7000. && x < 250. && y < 250.) { + npart++; + } + } + } else { + npart++; + } + }; + }; + // happens if a charm particle being produced which does decay without producing a HNL. Try another event. + // if (npart == 0){ fPythia.event.list();} }; - if (fHNL != 0 && fPythia.event[ii].id() == fHNL){ - Int_t im = (Int_t)fPythia.event[ii].mother1(); - Double_t z = fPythia.event[ii].zProd(); - Double_t x = fPythia.event[ii].xProd(); - Double_t y = fPythia.event[ii].yProd(); - Double_t pz = fPythia.event[ii].pz(); - Double_t px = fPythia.event[ii].px(); - Double_t py = fPythia.event[ii].py(); - cpg->AddTrack((Int_t)fPythia.event[im].id(),px,py,pz,x,y,z,0,false); - cpg->AddTrack((Int_t)fPythia.event[ii].id(),px,py,pz,x,y,z, im,false); - //cout<<"debug p8->geant4 "<< 0 << " "<< ii << " " << fake<< " "<< fPythia.event[ii].mother1()<AddTrack((Int_t)fPythia.event[ii].id(), + px, + py, + pz, + x, + y, + z, + (Int_t)fPythia.event[ii].mother1(), + wanttracking); + // cout<<"debug p8->geant4 "<< wanttracking << " "<< ii << " " << fPythia.event[ii].id()<< " "<< + // fPythia.event[ii].mother1()<<" "<AddTrack((Int_t)fPythia.event[im].id(), px, py, pz, x, y, z, 0, false); + cpg->AddTrack((Int_t)fPythia.event[ii].id(), px, py, pz, x, y, z, im, false); + // cout<<"debug p8->geant4 "<< 0 << " "<< ii << " " << fake<< " "<< fPythia.event[ii].mother1()< // for Double_t, Bool_t, Int_t, etc -#include // for TRandom -#include // for TRandom1 -#include // for TRandom3, gRandom -class FairPrimaryGenerator; // lines 22-22 +#include "FairGenerator.h" // for FairGenerator +#include "Pythia8/Basics.h" // for RndmEngine +#include "Pythia8/Pythia.h" // for Pythia + +#include // for Double_t, Bool_t, Int_t, etc +#include // for TRandom +#include // for TRandom1 +#include // for TRandom3, gRandom +class FairPrimaryGenerator; // lines 22-22 class FairPrimaryGenerator; using namespace Pythia8; class PyTr1Rng : public RndmEngine { - public: - PyTr1Rng() { rng = new TRandom1(gRandom->GetSeed()); }; - virtual ~PyTr1Rng() {}; + public: + PyTr1Rng() { rng = new TRandom1(gRandom->GetSeed()); }; + virtual ~PyTr1Rng(){}; - Double_t flat() { return rng->Rndm(); }; + Double_t flat() { return rng->Rndm(); }; - private: - TRandom1 *rng; //! + private: + TRandom1 *rng; //! }; class PyTr3Rng : public RndmEngine { - public: - PyTr3Rng() { rng = new TRandom3(gRandom->GetSeed()); }; - virtual ~PyTr3Rng() {}; + public: + PyTr3Rng() { rng = new TRandom3(gRandom->GetSeed()); }; + virtual ~PyTr3Rng(){}; - Double_t flat() { return rng->Rndm(); }; + Double_t flat() { return rng->Rndm(); }; - private: - TRandom3 *rng; //! + private: + TRandom3 *rng; //! }; - - - class Pythia8Generator : public FairGenerator { - public: - - /** default constructor **/ - Pythia8Generator(); - - /** destructor **/ - virtual ~Pythia8Generator(); - - /** public method ReadEvent **/ - Bool_t ReadEvent(FairPrimaryGenerator*); - void SetParameters(char*); - void Print(); //! - - virtual Bool_t Init(); //! - - void SetMom(Double_t mom) { fMom = mom; }; - void SetId(Double_t id) { fId = id; }; - void SetHNLId(Int_t id) { fHNL = id; }; - void UseRandom1() { fUseRandom1 = kTRUE; fUseRandom3 = kFALSE; }; - void UseRandom3() { fUseRandom1 = kFALSE; fUseRandom3 = kTRUE; }; - void GetPythiaInstance(int); - - private: - - Pythia fPythia; //! - RndmEngine* fRandomEngine; //! - - protected: - - Double_t fMom; // proton momentum - Int_t fHNL; // HNL ID - Int_t fId; // target type - Bool_t fUseRandom1; // flag to use TRandom1 - Bool_t fUseRandom3; // flag to use TRandom3 (default) - - ClassDef(Pythia8Generator,1); + public: + /** default constructor **/ + Pythia8Generator(); + + /** destructor **/ + virtual ~Pythia8Generator(); + + /** public method ReadEvent **/ + Bool_t ReadEvent(FairPrimaryGenerator *); + void SetParameters(char *); + void Print(); //! + + virtual Bool_t Init(); //! + + void SetMom(Double_t mom) { fMom = mom; }; + void SetId(Double_t id) { fId = id; }; + void SetHNLId(Int_t id) { fHNL = id; }; + void UseRandom1() + { + fUseRandom1 = kTRUE; + fUseRandom3 = kFALSE; + }; + void UseRandom3() + { + fUseRandom1 = kFALSE; + fUseRandom3 = kTRUE; + }; + void GetPythiaInstance(int); + + private: + Pythia fPythia; //! + RndmEngine *fRandomEngine; //! + + protected: + Double_t fMom; // proton momentum + Int_t fHNL; // HNL ID + Int_t fId; // target type + Bool_t fUseRandom1; // flag to use TRandom1 + Bool_t fUseRandom3; // flag to use TRandom3 (default) + + ClassDef(Pythia8Generator, 1); }; #endif /* !PNDP8GENERATOR_H */ diff --git a/templates/project_stl_containers/NewDetector/NewDetector.cxx b/templates/project_stl_containers/NewDetector/NewDetector.cxx index ec2c1d7610..03a14a34f4 100644 --- a/templates/project_stl_containers/NewDetector/NewDetector.cxx +++ b/templates/project_stl_containers/NewDetector/NewDetector.cxx @@ -7,28 +7,27 @@ ********************************************************************************/ #include "NewDetector.h" -#include "NewDetectorPoint.h" -#include "NewDetectorGeo.h" -#include "NewDetectorGeoPar.h" - -#include "FairVolume.h" -#include "FairGeoVolume.h" +#include "FairGeoInterface.h" +#include "FairGeoLoader.h" #include "FairGeoNode.h" +#include "FairGeoVolume.h" #include "FairRootManager.h" -#include "FairGeoLoader.h" -#include "FairGeoInterface.h" #include "FairRun.h" #include "FairRuntimeDb.h" +#include "FairVolume.h" #include "MyProjDetectorList.h" #include "MyProjStack.h" +#include "NewDetectorGeo.h" +#include "NewDetectorGeoPar.h" +#include "NewDetectorPoint.h" -#include -#include #include #include -#include +#include #include #include +#include +#include NewDetector::NewDetector() : FairDetector("NewDetector", kTRUE, kNewDetector) @@ -40,8 +39,7 @@ NewDetector::NewDetector() , fLength(-1.) , fELoss(-1) , fVectorPoints(new std::vector) -{ -} +{} NewDetector::NewDetector(const char* name, Bool_t active) : FairDetector(name, active, kNewDetector) @@ -53,8 +51,7 @@ NewDetector::NewDetector(const char* name, Bool_t active) , fLength(-1.) , fELoss(-1) , fVectorPoints(new std::vector) -{ -} +{} NewDetector::NewDetector(const NewDetector& right) : FairDetector(right) @@ -66,15 +63,12 @@ NewDetector::NewDetector(const NewDetector& right) , fLength(-1.) , fELoss(-1) , fVectorPoints(new std::vector) -{ -} +{} NewDetector::~NewDetector() { - if (fVectorPoints->size()) - { - for(auto const& x : (*fVectorPoints)) - { + if (fVectorPoints->size()) { + for (auto const& x : (*fVectorPoints)) { delete x; } fVectorPoints->clear(); @@ -101,8 +95,7 @@ Bool_t NewDetector::ProcessHits(FairVolume* vol) /** This method is called from the MC stepping */ // Set parameters at entrance of volume. Reset ELoss. - if (TVirtualMC::GetMC()->IsTrackEntering()) - { + if (TVirtualMC::GetMC()->IsTrackEntering()) { fELoss = 0.; fTime = TVirtualMC::GetMC()->TrackTime() * 1.0e09; fLength = TVirtualMC::GetMC()->TrackLength(); @@ -114,13 +107,11 @@ Bool_t NewDetector::ProcessHits(FairVolume* vol) fELoss += TVirtualMC::GetMC()->Edep(); // Create NewDetectorPoint at exit of active volume - if (TVirtualMC::GetMC()->IsTrackExiting() || TVirtualMC::GetMC()->IsTrackStop() || - TVirtualMC::GetMC()->IsTrackDisappeared()) - { + if (TVirtualMC::GetMC()->IsTrackExiting() || TVirtualMC::GetMC()->IsTrackStop() + || TVirtualMC::GetMC()->IsTrackDisappeared()) { fTrackID = TVirtualMC::GetMC()->GetStack()->GetCurrentTrackNumber(); fVolumeID = vol->getMCid(); - if (fELoss == 0.) - { + if (fELoss == 0.) { return kFALSE; } AddHit(fTrackID, @@ -141,11 +132,9 @@ Bool_t NewDetector::ProcessHits(FairVolume* vol) void NewDetector::EndOfEvent() { - LOG(info) << "NewDetector: " << fVectorPoints->size() - << " points registered in this event"; + LOG(info) << "NewDetector: " << fVectorPoints->size() << " points registered in this event"; - for(auto const& x : (*fVectorPoints)) - { + for (auto const& x : (*fVectorPoints)) { delete x; } fVectorPoints->clear(); @@ -163,8 +152,7 @@ void NewDetector::Register() void NewDetector::Reset() { - for(auto const& x : (*fVectorPoints)) - { + for (auto const& x : (*fVectorPoints)) { delete x; } fVectorPoints->clear(); @@ -176,13 +164,11 @@ void NewDetector::ConstructGeometry() TGeoMedium* Si = gGeoManager->GetMedium("Si"); TGeoMedium* Carbon = gGeoManager->GetMedium("C"); - if (Si == 0) - { + if (Si == 0) { TGeoMaterial* matSi = new TGeoMaterial("Si", 28.0855, 14, 2.33); Si = new TGeoMedium("Si", 2, matSi); } - if (Carbon == 0) - { + if (Carbon == 0) { TGeoMaterial* matCarbon = new TGeoMaterial("C", 12.011, 6.0, 2.265); Carbon = new TGeoMedium("C", 3, matCarbon); } @@ -228,12 +214,12 @@ void NewDetector::ConstructGeometry() } NewDetectorPoint* NewDetector::AddHit(Int_t trackID, - Int_t detID, - TVector3 pos, - TVector3 mom, - Double_t time, - Double_t length, - Double_t eLoss) + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t time, + Double_t length, + Double_t eLoss) { NewDetectorPoint* point = new NewDetectorPoint(trackID, detID, pos, mom, time, length, eLoss); fVectorPoints->push_back(point); @@ -247,10 +233,8 @@ void NewDetector::DefineSensitiveVolumes() TObjArray* volumes = gGeoManager->GetListOfVolumes(); TIter next(volumes); TGeoVolume* volume; - while ((volume = static_cast(next()))) - { - if (IsSensitive(volume->GetName())) - { + while ((volume = static_cast(next()))) { + if (IsSensitive(volume->GetName())) { LOG(debug2) << "Sensitive Volume " << volume->GetName(); AddSensitiveVolume(volume); } @@ -259,10 +243,10 @@ void NewDetector::DefineSensitiveVolumes() Bool_t NewDetector::IsSensitive(const std::string& name) { - if ( name.find("Det") != std::string::npos ) { + if (name.find("Det") != std::string::npos) { return kTRUE; } return kFALSE; } -ClassImp(NewDetector) +ClassImp(NewDetector); diff --git a/templates/project_stl_containers/NewDetector/NewDetector.h b/templates/project_stl_containers/NewDetector/NewDetector.h index b51f862482..38ffe0b77d 100644 --- a/templates/project_stl_containers/NewDetector/NewDetector.h +++ b/templates/project_stl_containers/NewDetector/NewDetector.h @@ -10,9 +10,8 @@ #include "FairDetector.h" -#include #include - +#include #include class NewDetectorPoint; @@ -25,7 +24,7 @@ class NewDetector : public FairDetector /** Name : Detector Name * Active: true for active detectors (ProcessHits() will be called) * false for inactive detectors - */ + */ NewDetector(const char* Name, bool Active); /** default constructor */ @@ -39,7 +38,7 @@ class NewDetector : public FairDetector /** this method is called for each step during simulation * (see FairMCApplication::Stepping()) - */ + */ virtual Bool_t ProcessHits(FairVolume* v = 0); /** Registers the produced collections in FAIRRootManager. */ @@ -53,13 +52,13 @@ class NewDetector : public FairDetector /** This method is an example of how to add your own point * of type NewDetectorPoint to the clones array - */ + */ NewDetectorPoint* AddHit(int trackID, int detID, TVector3 pos, TVector3 mom, double time, double length, double eLoss); /** The following methods can be implemented if you need to make * any optional action in your detector during the transport. - */ + */ virtual void SetSpecialPhysicsCuts() { ; } virtual void EndOfEvent(); @@ -73,23 +72,23 @@ class NewDetector : public FairDetector virtual FairModule* CloneModule() const; virtual Bool_t IsSensitive(const std::string& name); - + virtual TClonesArray* GetCollection(Int_t iColl) const { return NULL; } 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 */ - std::vector* fVectorPoints; //! + std::vector* fVectorPoints; //! NewDetector(const NewDetector&); NewDetector& operator=(const NewDetector&); @@ -99,4 +98,4 @@ class NewDetector : public FairDetector ClassDef(NewDetector, 2) }; -#endif // NEWDETECTOR_H +#endif // NEWDETECTOR_H diff --git a/templates/project_stl_containers/NewDetector/NewDetectorContFact.cxx b/templates/project_stl_containers/NewDetector/NewDetectorContFact.cxx index 428dbcb088..9466b6c6d9 100644 --- a/templates/project_stl_containers/NewDetector/NewDetectorContFact.cxx +++ b/templates/project_stl_containers/NewDetector/NewDetectorContFact.cxx @@ -1,59 +1,55 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "NewDetectorContFact.h" -#include "NewDetectorGeoPar.h" - #include "FairRuntimeDb.h" +#include "NewDetectorGeoPar.h" #include -ClassImp(NewDetectorContFact) +ClassImp(NewDetectorContFact); static NewDetectorContFact gNewDetectorContFact; NewDetectorContFact::NewDetectorContFact() - : FairContFact() + : FairContFact() { - /** Constructor (called when the library is loaded) */ - fName="NewDetectorContFact"; - fTitle="Factory for parameter containers in libNewDetector"; - setAllContainers(); - FairRuntimeDb::instance()->addContFactory(this); + /** Constructor (called when the library is loaded) */ + fName = "NewDetectorContFact"; + fTitle = "Factory for parameter containers in libNewDetector"; + setAllContainers(); + FairRuntimeDb::instance()->addContFactory(this); } void NewDetectorContFact::setAllContainers() { - /** Creates the Container objects with all accepted + /** Creates the Container objects with all accepted contexts and adds them to the list of containers for the NewDetector library. */ - FairContainer* p= new FairContainer("NewDetectorGeoPar", - "NewDetector Geometry Parameters", - "TestDefaultContext"); - p->addContext("TestNonDefaultContext"); + FairContainer* p = new FairContainer("NewDetectorGeoPar", "NewDetector Geometry Parameters", "TestDefaultContext"); + p->addContext("TestNonDefaultContext"); - containers->Add(p); + containers->Add(p); } FairParSet* NewDetectorContFact::createContainer(FairContainer* c) { - /** Calls the constructor of the corresponding parameter container. + /** 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,"NewDetectorGeoPar")==0) { - p=new NewDetectorGeoPar(c->getConcatName().Data(), - c->GetTitle(),c->getContext()); - } - return p; + const char* name = c->GetName(); + FairParSet* p = NULL; + if (strcmp(name, "NewDetectorGeoPar") == 0) { + p = new NewDetectorGeoPar(c->getConcatName().Data(), c->GetTitle(), c->getContext()); + } + return p; } diff --git a/templates/project_stl_containers/NewDetector/NewDetectorContFact.h b/templates/project_stl_containers/NewDetector/NewDetectorContFact.h index f5e4958971..e4c70dca22 100644 --- a/templates/project_stl_containers/NewDetector/NewDetectorContFact.h +++ b/templates/project_stl_containers/NewDetector/NewDetectorContFact.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef NEWDETECTORCONTFACT_H @@ -16,11 +16,12 @@ class NewDetectorContFact : public FairContFact { private: void setAllContainers(); + public: NewDetectorContFact(); ~NewDetectorContFact() {} FairParSet* createContainer(FairContainer*); - ClassDef( NewDetectorContFact,0) // Factory for all NewDetector parameter containers + ClassDef(NewDetectorContFact, 0) // Factory for all NewDetector parameter containers }; #endif diff --git a/templates/project_stl_containers/NewDetector/NewDetectorGeo.cxx b/templates/project_stl_containers/NewDetector/NewDetectorGeo.cxx index 51d77d9fed..8498754bcd 100644 --- a/templates/project_stl_containers/NewDetector/NewDetectorGeo.cxx +++ b/templates/project_stl_containers/NewDetector/NewDetectorGeo.cxx @@ -1,43 +1,44 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "NewDetectorGeo.h" + #include "FairGeoNode.h" -ClassImp(NewDetectorGeo) +ClassImp(NewDetectorGeo); // ----- Default constructor ------------------------------------------- NewDetectorGeo::NewDetectorGeo() - : FairGeoSet() + : FairGeoSet() { - // Constructor - // fName has to be the name used in the geometry for all volumes. - // If there is a mismatch the geometry cannot be build. - fName="newdetector"; - maxSectors=0; - maxModules=10; + // Constructor + // fName has to be the name used in the geometry for all volumes. + // If there is a mismatch the geometry cannot be build. + fName = "newdetector"; + maxSectors = 0; + maxModules = 10; } // ------------------------------------------------------------------------- const char* NewDetectorGeo::getModuleName(Int_t m) { - /** Returns the module name of NewDetector number m + /** Returns the module name of NewDetector number m Setting NewDetector here means that all modules names in the ASCII file should start with NewDetector otherwise they will not be constructed */ - sprintf(modName,"NewDetector%i",m+1); - return modName; + sprintf(modName, "NewDetector%i", m + 1); + return modName; } const char* NewDetectorGeo::getEleName(Int_t m) { - /** Returns the element name of Det number m */ - sprintf(eleName,"NewDetector%i",m+1); - return eleName; + /** Returns the element name of Det number m */ + sprintf(eleName, "NewDetector%i", m + 1); + return eleName; } diff --git a/templates/project_stl_containers/NewDetector/NewDetectorGeo.h b/templates/project_stl_containers/NewDetector/NewDetectorGeo.h index 80b9a67a71..6dd4ab5452 100644 --- a/templates/project_stl_containers/NewDetector/NewDetectorGeo.h +++ b/templates/project_stl_containers/NewDetector/NewDetectorGeo.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef NEWDETECTORGEO_H @@ -10,29 +10,29 @@ #include "FairGeoSet.h" -class NewDetectorGeo : public FairGeoSet +class NewDetectorGeo : public FairGeoSet { protected: - char modName[20]; // name of module - char eleName[20]; // substring for elements in module + char modName[20]; // name of module + char eleName[20]; // substring for elements in module public: NewDetectorGeo(); ~NewDetectorGeo() {} const char* getModuleName(Int_t); const char* getEleName(Int_t); inline Int_t getModNumInMod(const TString&); - ClassDef(NewDetectorGeo,1) + ClassDef(NewDetectorGeo, 1) }; inline Int_t NewDetectorGeo::getModNumInMod(const TString& name) { - /** returns the module index from module name + /** returns the module index from module name ?? in name[??] has to be the length of the detector name in the .geo file. For example if all nodes in this file starts with newdetector ?? has to be 11. */ - return (Int_t)(name[11]-'0')-1; // + return (Int_t)(name[11] - '0') - 1; // } #endif diff --git a/templates/project_stl_containers/NewDetector/NewDetectorGeoPar.cxx b/templates/project_stl_containers/NewDetector/NewDetectorGeoPar.cxx index 96674a51b3..a40fd67e7f 100644 --- a/templates/project_stl_containers/NewDetector/NewDetectorGeoPar.cxx +++ b/templates/project_stl_containers/NewDetector/NewDetectorGeoPar.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "NewDetectorGeoPar.h" @@ -10,41 +10,43 @@ #include "FairParamList.h" #include - #include -ClassImp(NewDetectorGeoPar) +ClassImp(NewDetectorGeoPar); -NewDetectorGeoPar ::NewDetectorGeoPar(const char* name, - const char* title, - const char* context) - : FairParGenericSet(name,title,context), - fGeoSensNodes(new TObjArray()), - fGeoPassNodes(new TObjArray()) -{ -} +NewDetectorGeoPar ::NewDetectorGeoPar(const char* name, const char* title, const char* context) + : FairParGenericSet(name, title, context) + , fGeoSensNodes(new TObjArray()) + , fGeoPassNodes(new TObjArray()) +{} -NewDetectorGeoPar::~NewDetectorGeoPar(void) -{ -} +NewDetectorGeoPar::~NewDetectorGeoPar(void) {} void NewDetectorGeoPar::clear(void) { - delete fGeoSensNodes; - delete fGeoPassNodes; + delete fGeoSensNodes; + delete fGeoPassNodes; } void NewDetectorGeoPar::putParams(FairParamList* l) { - if (!l) { return; } - l->addObject("FairGeoNodes Sensitive List", fGeoSensNodes); - l->addObject("FairGeoNodes Passive List", fGeoPassNodes); + if (!l) { + return; + } + l->addObject("FairGeoNodes Sensitive List", fGeoSensNodes); + l->addObject("FairGeoNodes Passive List", fGeoPassNodes); } Bool_t NewDetectorGeoPar::getParams(FairParamList* l) { - if (!l) { return kFALSE; } - if (!l->fillObject("FairGeoNodes Sensitive List", fGeoSensNodes)) { return kFALSE; } - if (!l->fillObject("FairGeoNodes Passive List", fGeoPassNodes)) { return kFALSE; } - return kTRUE; + if (!l) { + return kFALSE; + } + if (!l->fillObject("FairGeoNodes Sensitive List", fGeoSensNodes)) { + return kFALSE; + } + if (!l->fillObject("FairGeoNodes Passive List", fGeoPassNodes)) { + return kFALSE; + } + return kTRUE; } diff --git a/templates/project_stl_containers/NewDetector/NewDetectorGeoPar.h b/templates/project_stl_containers/NewDetector/NewDetectorGeoPar.h index 96997079c9..b689979309 100644 --- a/templates/project_stl_containers/NewDetector/NewDetectorGeoPar.h +++ b/templates/project_stl_containers/NewDetector/NewDetectorGeoPar.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef NEWDETECTORGEOPAR_H @@ -13,31 +13,30 @@ class TObjArray; class FairParamList; -class NewDetectorGeoPar : public FairParGenericSet +class NewDetectorGeoPar : public FairParGenericSet { public: - /** List of FairGeoNodes for sensitive volumes */ - TObjArray* fGeoSensNodes; + TObjArray* fGeoSensNodes; /** List of FairGeoNodes for sensitive volumes */ - TObjArray* fGeoPassNodes; + TObjArray* fGeoPassNodes; - NewDetectorGeoPar(const char* name="NewDetectorGeoPar", - const char* title="NewDetector Geometry Parameters", - const char* context="TestDefaultContext"); + NewDetectorGeoPar(const char* name = "NewDetectorGeoPar", + const char* title = "NewDetector Geometry Parameters", + const char* context = "TestDefaultContext"); ~NewDetectorGeoPar(void); void clear(void); void putParams(FairParamList*); Bool_t getParams(FairParamList*); - TObjArray* GetGeoSensitiveNodes() {return fGeoSensNodes;} - TObjArray* GetGeoPassiveNodes() {return fGeoPassNodes;} + TObjArray* GetGeoSensitiveNodes() { return fGeoSensNodes; } + TObjArray* GetGeoPassiveNodes() { return fGeoPassNodes; } private: NewDetectorGeoPar(const NewDetectorGeoPar&); NewDetectorGeoPar& operator=(const NewDetectorGeoPar&); - ClassDef(NewDetectorGeoPar,1) + ClassDef(NewDetectorGeoPar, 1) }; #endif diff --git a/templates/project_stl_containers/NewDetector/NewDetectorPoint.cxx b/templates/project_stl_containers/NewDetector/NewDetectorPoint.cxx index e12456c706..59393dc8a3 100644 --- a/templates/project_stl_containers/NewDetector/NewDetectorPoint.cxx +++ b/templates/project_stl_containers/NewDetector/NewDetectorPoint.cxx @@ -24,18 +24,17 @@ NewDetectorPoint::NewDetectorPoint() , fX(0.) , fY(0.) , fZ(0.) -{ -} +{} // ------------------------------------------------------------------------- // ----- Standard constructor ------------------------------------------ NewDetectorPoint::NewDetectorPoint(Int_t trackID, - Int_t detID, - TVector3 pos, - TVector3 mom, - Double_t tof, - Double_t length, - Double_t eLoss) + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t tof, + Double_t length, + Double_t eLoss) : fTrackID(trackID) , fPx(mom.X()) , fPy(mom.Y()) @@ -47,8 +46,7 @@ NewDetectorPoint::NewDetectorPoint(Int_t trackID, , fX(pos.X()) , fY(pos.Y()) , fZ(pos.Z()) -{ -} +{} // ------------------------------------------------------------------------- // ----- Destructor ---------------------------------------------------- @@ -58,8 +56,7 @@ NewDetectorPoint::~NewDetectorPoint() {} // ----- Public method Print ------------------------------------------- void NewDetectorPoint::Print(const Option_t* /*opt*/) const { - cout << "-I- NewDetectorPoint: NewDetector point for track " << fTrackID << " in detector " << fDetectorID - << endl; + cout << "-I- NewDetectorPoint: NewDetector 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" @@ -67,4 +64,4 @@ void NewDetectorPoint::Print(const Option_t* /*opt*/) const } // ------------------------------------------------------------------------- -ClassImp(NewDetectorPoint) +ClassImp(NewDetectorPoint); diff --git a/templates/project_stl_containers/NewDetector/NewDetectorPoint.h b/templates/project_stl_containers/NewDetector/NewDetectorPoint.h index be93ec7d40..79f61bdffd 100644 --- a/templates/project_stl_containers/NewDetector/NewDetectorPoint.h +++ b/templates/project_stl_containers/NewDetector/NewDetectorPoint.h @@ -27,12 +27,12 @@ class NewDetectorPoint *@param eLoss Energy deposit [GeV] **/ NewDetectorPoint(Int_t trackID, - Int_t detID, - TVector3 pos, - TVector3 mom, - Double_t tof, - Double_t length, - Double_t eLoss); + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t tof, + Double_t length, + Double_t eLoss); /** Destructor **/ virtual ~NewDetectorPoint(); @@ -41,7 +41,7 @@ class NewDetectorPoint virtual void Print(const Option_t* opt) const; /** Accessors */ - uint32_t GetEventID() const { return fEventId; } /// event identifier + uint32_t GetEventID() const { return fEventId; } /// event identifier int GetTrackID() const { return fTrackID; } double GetPx() const { return fPx; } double GetPy() const { return fPy; } @@ -71,14 +71,14 @@ class NewDetectorPoint void SetPosition(const TVector3& pos); protected: - int fTrackID; ///< Track index - uint32_t fEventId; ///< MC Event id - double fPx, fPy, fPz; ///< Momentum components [GeV] - double fTime; ///< Time since event start [ns] - double fLength; ///< Track length since creation [cm] - double fELoss; ///< Energy loss at this point [GeV] - int fDetectorID; ///< Detector unique identifier - double fX, fY, fZ; ///< Position of hit [cm] + int fTrackID; ///< Track index + uint32_t fEventId; ///< MC Event id + double fPx, fPy, fPz; ///< Momentum components [GeV] + double fTime; ///< Time since event start [ns] + double fLength; ///< Track length since creation [cm] + double fELoss; ///< Energy loss at this point [GeV] + int fDetectorID; ///< Detector unique identifier + double fX, fY, fZ; ///< Position of hit [cm] private: /** Copy constructor **/ diff --git a/templates/project_stl_containers/field/MyConstField.cxx b/templates/project_stl_containers/field/MyConstField.cxx index 8538ec5a08..258e751354 100644 --- a/templates/project_stl_containers/field/MyConstField.cxx +++ b/templates/project_stl_containers/field/MyConstField.cxx @@ -18,174 +18,158 @@ #include #include -using std::cout; using std::cerr; +using std::cout; using std::endl; using std::setw; - // ----- Default constructor ------------------------------------------- -MyConstField::MyConstField() - : FairField(), - fXmin(0.), - fXmax(0.), - fYmin(0.), - fYmax(0.), - fZmin(0.), - fZmax(0.), - fBx(0.), - fBy(0.), - fBz(0.) +MyConstField::MyConstField() + : 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 ------------------------------------------ -MyConstField::MyConstField(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) +MyConstField::MyConstField(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 ------------------------------- MyConstField::MyConstField(MyFieldPar* 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- MyConstField::MyConstField: 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- MyConstField::MyConstField: 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 ---------------------------------------------------- -MyConstField::~MyConstField() { } +MyConstField::~MyConstField() {} // ------------------------------------------------------------------------- - - // ----- Set field region ---------------------------------------------- -void MyConstField::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 MyConstField::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 MyConstField::SetField(Double_t bX, Double_t bY, Double_t bZ) { - fBx = bX; - fBy = bY; - fBz = bZ; +void MyConstField::SetField(Double_t bX, Double_t bY, Double_t bZ) +{ + fBx = bX; + fBy = bY; + fBz = bZ; } // ------------------------------------------------------------------------- - - // ----- Get x component of field -------------------------------------- -Double_t MyConstField::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 MyConstField::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 MyConstField::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 MyConstField::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 MyConstField::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 MyConstField::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 MyConstField::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 MyConstField::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; } // ------------------------------------------------------------------------- - - -ClassImp(MyConstField) +ClassImp(MyConstField); diff --git a/templates/project_stl_containers/field/MyConstField.h b/templates/project_stl_containers/field/MyConstField.h index 91274ef949..079b3d4ade 100644 --- a/templates/project_stl_containers/field/MyConstField.h +++ b/templates/project_stl_containers/field/MyConstField.h @@ -11,7 +11,6 @@ // ----- Created 25/03/14 by M. Al-Turany ----- // ------------------------------------------------------------------------- - /** MyConstField.h ** @author M.Al-Turany ** @since 25.03.2014 @@ -20,106 +19,94 @@ ** A constant (homogeneous) magnetic field **/ - #ifndef MyConstField_H #define MyConstField_H 1 - #include "FairField.h" - class MyFieldPar; - class MyConstField : public FairField { - public: - - /** Default constructor **/ - MyConstField(); - - - /** 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] - **/ - MyConstField(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 MyFieldPar **/ - MyConstField(MyFieldPar* fieldPar); - - - /** Destructor **/ - virtual ~MyConstField(); - - - /** 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(MyConstField, 1); - + public: + /** Default constructor **/ + MyConstField(); + + /** 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] + **/ + MyConstField(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 MyFieldPar **/ + MyConstField(MyFieldPar* fieldPar); + + /** Destructor **/ + virtual ~MyConstField(); + + /** 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(MyConstField, 1); }; - #endif diff --git a/templates/project_stl_containers/field/MyFieldCreator.cxx b/templates/project_stl_containers/field/MyFieldCreator.cxx index 5f4fc54275..dd0a545b05 100644 --- a/templates/project_stl_containers/field/MyFieldCreator.cxx +++ b/templates/project_stl_containers/field/MyFieldCreator.cxx @@ -12,61 +12,56 @@ #include "MyFieldCreator.h" -#include "MyFieldPar.h" -#include "MyConstField.h" - +#include "FairField.h" #include "FairRunAna.h" #include "FairRuntimeDb.h" -#include "FairField.h" +#include "MyConstField.h" +#include "MyFieldPar.h" #include -using std::cout; using std::cerr; +using std::cout; using std::endl; static MyFieldCreator gMyFieldCreator; MyFieldCreator::MyFieldCreator() - :FairFieldFactory(), - fFieldPar(NULL) + : FairFieldFactory() + , fFieldPar(NULL) { - fCreator=this; + fCreator = this; } -MyFieldCreator::~MyFieldCreator() -{ -} +MyFieldCreator::~MyFieldCreator() {} void MyFieldCreator::SetParm() { - FairRunAna *Run = FairRunAna::Instance(); - FairRuntimeDb *RunDB = Run->GetRuntimeDb(); - fFieldPar = (MyFieldPar*) RunDB->getContainer("MyFieldPar"); - + FairRunAna *Run = FairRunAna::Instance(); + FairRuntimeDb *RunDB = Run->GetRuntimeDb(); + fFieldPar = (MyFieldPar *)RunDB->getContainer("MyFieldPar"); } -FairField* MyFieldCreator::createFairField() -{ - FairField *fMagneticField=0; +FairField *MyFieldCreator::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 MyConstField(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; + if (!fFieldPar) { + cerr << "-E- No field parameters available!" << endl; + } else { + // Instantiate correct field type + Int_t fType = fFieldPar->GetType(); + if (fType == 0) + fMagneticField = new MyConstField(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; } - -ClassImp(MyFieldCreator) +ClassImp(MyFieldCreator); diff --git a/templates/project_stl_containers/field/MyFieldCreator.h b/templates/project_stl_containers/field/MyFieldCreator.h index aaa73cef7e..2e0b5203e2 100644 --- a/templates/project_stl_containers/field/MyFieldCreator.h +++ b/templates/project_stl_containers/field/MyFieldCreator.h @@ -11,7 +11,6 @@ // ----- Created 26/03/14 by M. Al-Turany ----- // ------------------------------------------------------------------------- - #ifndef MyFieldCreator_H #define MyFieldCreator_H @@ -21,22 +20,21 @@ class MyFieldPar; class FairField; -class MyFieldCreator : public FairFieldFactory +class MyFieldCreator : public FairFieldFactory { - public: - MyFieldCreator(); - virtual ~MyFieldCreator(); - virtual FairField* createFairField(); - virtual void SetParm(); - ClassDef(MyFieldCreator,1); - - protected: - MyFieldPar* fFieldPar; - - private: - MyFieldCreator(const MyFieldCreator&); - MyFieldCreator& operator=(const MyFieldCreator&); + public: + MyFieldCreator(); + virtual ~MyFieldCreator(); + virtual FairField* createFairField(); + virtual void SetParm(); + ClassDef(MyFieldCreator, 1); + + protected: + MyFieldPar* fFieldPar; + private: + MyFieldCreator(const MyFieldCreator&); + MyFieldCreator& operator=(const MyFieldCreator&); }; -#endif //MyFieldCreator_H +#endif // MyFieldCreator_H diff --git a/templates/project_stl_containers/field/MyFieldPar.cxx b/templates/project_stl_containers/field/MyFieldPar.cxx index 3022e6524f..a19e65f995 100644 --- a/templates/project_stl_containers/field/MyFieldPar.cxx +++ b/templates/project_stl_containers/field/MyFieldPar.cxx @@ -11,190 +11,190 @@ // ----- Created 26/03/14 by M. Al-Turany ----- // ------------------------------------------------------------------------- - #include "MyFieldPar.h" -#include "MyConstField.h" #include "FairParamList.h" +#include "MyConstField.h" #include -using std::cout; using std::cerr; +using std::cout; using std::endl; -const int kMaxLen = 2048; +const int kMaxLen = 2048; // ------ Constructor -------------------------------------------------- -MyFieldPar::MyFieldPar(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.) - -{ -} +MyFieldPar::MyFieldPar(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.) + +{} // ------------------------------------------------------------------------- -MyFieldPar::MyFieldPar() - : 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.) - -{ -} +MyFieldPar::MyFieldPar() + : 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 --------------------------------------------------- -MyFieldPar::~MyFieldPar() { } +MyFieldPar::~MyFieldPar() {} // ------------------------------------------------------------------------- - - // ------ Put parameters ----------------------------------------------- -void MyFieldPar::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 MyFieldPar::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 MyFieldPar::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 MyFieldPar::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 MyFieldPar::SetParameters(FairField* field) +{ + if (!field) { + cerr << "-W- MyFieldPar::SetParameters: Empty field pointer!" << endl; + return; + } + + fType = field->GetType(); + + if (fType == 0) { // constant field + MyConstField* fieldConst = (MyConstField*)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- MyFieldPar::SetParameters: Unknown field type " << fType << "!" << endl; + fBx = fBy = fBz = 0.; + fXmin = fXmax = fYmin = fYmax = fZmin = fZmax = 0.; + fMapName = ""; + fPosX = fPosY = fPosZ = fScale = 0.; + } -void MyFieldPar::SetParameters(FairField* field) { - - if ( ! field ) { - cerr << "-W- MyFieldPar::SetParameters: Empty field pointer!" << endl; return; - } - - fType = field->GetType(); - - if ( fType == 0 ) { // constant field - MyConstField* fieldConst = (MyConstField*) 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- MyFieldPar::SetParameters: Unknown field type " - << fType << "!" << endl; - fBx = fBy = fBz = 0.; - fXmin = fXmax = fYmin = fYmax = fZmin = fZmax = 0.; - fMapName = ""; - fPosX = fPosY = fPosZ = fScale = 0.; - } - - return; - } // ------------------------------------------------------------------------- - - - - - -ClassImp(MyFieldPar) - +ClassImp(MyFieldPar); diff --git a/templates/project_stl_containers/field/MyFieldPar.h b/templates/project_stl_containers/field/MyFieldPar.h index daa7070e2f..bd9846d3cb 100644 --- a/templates/project_stl_containers/field/MyFieldPar.h +++ b/templates/project_stl_containers/field/MyFieldPar.h @@ -11,8 +11,6 @@ // ----- Created 26/03/14 by M. Al-Turany ----- // ------------------------------------------------------------------------- - - #ifndef MyFieldPar_H #define MyFieldPar_H 1 @@ -21,101 +19,84 @@ class FairField; class FairParamList; -const int kMaxFieldMapType = 5; +const int kMaxFieldMapType = 5; class MyFieldPar : public FairParGenericSet { - public: - - - /** Standard constructor **/ - MyFieldPar(const char* name, const char* title, const char* context); - -/** default constructor **/ - MyFieldPar(); - - /** Destructor **/ - ~MyFieldPar(); - - - /** 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; } - - - - 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; - - - MyFieldPar(const MyFieldPar&); - MyFieldPar& operator=(const MyFieldPar&); - - ClassDef(MyFieldPar,1); - + public: + /** Standard constructor **/ + MyFieldPar(const char* name, const char* title, const char* context); + + /** default constructor **/ + MyFieldPar(); + + /** Destructor **/ + ~MyFieldPar(); + + /** 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; } + + 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; + + MyFieldPar(const MyFieldPar&); + MyFieldPar& operator=(const MyFieldPar&); + + ClassDef(MyFieldPar, 1); }; - #endif diff --git a/templates/project_stl_containers/gconfig/DecayConfig.C b/templates/project_stl_containers/gconfig/DecayConfig.C index 4f83d837fd..fa8dafcdd3 100644 --- a/templates/project_stl_containers/gconfig/DecayConfig.C +++ b/templates/project_stl_containers/gconfig/DecayConfig.C @@ -6,94 +6,94 @@ * copied verbatim in the file "LICENSE" * ********************************************************************************/ -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. - - // 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; +void DecayConfig() +{ - //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); + // 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. - 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); - - 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]; - - 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 - } - - - // 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); - //} -} + // 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; + + // 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(); + + // 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()); + // 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 + + pythia6.SetMDCY(pythia6.Pycomp(ipdg), 1, 1); // Activate decay in pythia + } + + // 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); + //} +} diff --git a/templates/project_stl_containers/gconfig/Geane.C b/templates/project_stl_containers/gconfig/Geane.C index 263e4be3b9..4f74c4f143 100644 --- a/templates/project_stl_containers/gconfig/Geane.C +++ b/templates/project_stl_containers/gconfig/Geane.C @@ -10,38 +10,41 @@ void Config() { - TGeoMedium *m=gGeoManager->GetMedium("air"); - if(m != NULL) m->SetParam(6, 0.005); // epsil - TGeoMedium *m2=gGeoManager->GetMedium("FscScint"); - if(m2 != NULL) m2->SetParam(6, 0.005); // epsil - TGeoMedium *m3=gGeoManager->GetMedium("lead"); - if(m3 != NULL) m3->SetParam(6, 0.005); // epsil - - gMC3= new TGeant3TGeo("C++ Interface to Geant3"); - cout << "-I- G3Config: Geant3 with TGeo has been created for Geane." - << endl; + TGeoMedium *m = gGeoManager->GetMedium("air"); + if (m != NULL) + m->SetParam(6, 0.005); // epsil + TGeoMedium *m2 = gGeoManager->GetMedium("FscScint"); + if (m2 != NULL) + m2->SetParam(6, 0.005); // epsil + TGeoMedium *m3 = gGeoManager->GetMedium("lead"); + if (m3 != NULL) + m3->SetParam(6, 0.005); // epsil + + gMC3 = new TGeant3TGeo("C++ Interface to Geant3"); + cout << "-I- G3Config: Geant3 with TGeo has been created for Geane." << endl; // create Cbm Specific Stack PndStack *st = new PndStack(10); - gMC3->SetStack( st ) ; - + gMC3->SetStack(st); + // only from geant3 rev. 252 on -------- // NOPRNT = 1 means no IERR printout // NOPRNT = 0 means IERR are printed - if(gROOT->GetVersionCode() >= 334848) - { + if (gROOT->GetVersionCode() >= 334848) { Ertrio1_t *fErtrio1 = gMC3->fErtrio1; fErtrio1->noprnt = 1; - cout << "-I- Geane.C: NOPRNT flag set to " << fErtrio1->noprnt << endl; - if(fErtrio1->noprnt == 1) { - cout << "-I- Geane.C: IERR flags are not printed. If you want to switch them on, please set fErtrio1->noprnt = 0 in Geane.C" << endl; + cout << "-I- Geane.C: NOPRNT flag set to " << fErtrio1->noprnt << endl; + if (fErtrio1->noprnt == 1) { + cout << "-I- Geane.C: IERR flags are not printed. If you want to switch them on, please set " + "fErtrio1->noprnt = 0 in Geane.C" + << endl; } } // ------------------------------------- - + // ******* GEANEconfiguration for simulated Runs ******* gMC3->SetDEBU(0, 0, 1); gMC3->SetSWIT(4, 10); - + gMC3->SetDCAY(0); gMC3->SetPAIR(0); gMC3->SetCOMP(0); @@ -52,55 +55,50 @@ void Config() 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->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->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->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 - - 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); - + 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); - } - diff --git a/templates/project_stl_containers/gconfig/SetCuts.C b/templates/project_stl_containers/gconfig/SetCuts.C index 0df92c6bd5..8f678b1a2f 100644 --- a/templates/project_stl_containers/gconfig/SetCuts.C +++ b/templates/project_stl_containers/gconfig/SetCuts.C @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ @@ -13,49 +13,47 @@ 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. - TVirtualMC *MC =TVirtualMC::GetMC(); + // cout << "SetCuts Macro: Setting Processes.." <SetProcess("PAIR",1); /** pair production*/ - MC->SetProcess("COMP",1); /**Compton scattering*/ - MC->SetProcess("PHOT",1); /** photo electric effect */ - MC->SetProcess("PFIS",0); /**photofission*/ - MC->SetProcess("DRAY",1); /**delta-ray*/ - MC->SetProcess("ANNI",1); /**annihilation*/ - MC->SetProcess("BREM",1); /**bremsstrahlung*/ - MC->SetProcess("HADR",1); /**hadronic process*/ - MC->SetProcess("MUNU",1); /**muon nuclear interaction*/ - MC->SetProcess("DCAY",1); /**decay*/ - MC->SetProcess("LOSS",1); /**energy loss*/ - MC->SetProcess("MULS",1); /**multiple scattering*/ + // ------>>>> 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. + TVirtualMC *MC = TVirtualMC::GetMC(); - 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)*/ - MC->SetCut("CUTELE",cut1); /** electrons (GeV)*/ - MC->SetCut("CUTNEU",cut1); /** neutral hadrons (GeV)*/ - MC->SetCut("CUTHAD",cut1); /** charged hadrons (GeV)*/ - MC->SetCut("CUTMUO",cut1); /** muons (GeV)*/ - MC->SetCut("BCUTE",cut1); /** electron bremsstrahlung (GeV)*/ - MC->SetCut("BCUTM",cut1); /** muon and hadron bremsstrahlung(GeV)*/ - MC->SetCut("DCUTE",cut1); /** delta-rays by electrons (GeV)*/ - MC->SetCut("DCUTM",cut1); /** delta-rays by muons (GeV)*/ - MC->SetCut("PPCUTM",cut1); /** direct pair production by muons (GeV)*/ - MC->SetCut("TOFMAX",tofmax); /**time of flight cut in seconds*/ - - + MC->SetProcess("PAIR", 1); /** pair production*/ + MC->SetProcess("COMP", 1); /**Compton scattering*/ + MC->SetProcess("PHOT", 1); /** photo electric effect */ + MC->SetProcess("PFIS", 0); /**photofission*/ + MC->SetProcess("DRAY", 1); /**delta-ray*/ + MC->SetProcess("ANNI", 1); /**annihilation*/ + MC->SetProcess("BREM", 1); /**bremsstrahlung*/ + MC->SetProcess("HADR", 1); /**hadronic process*/ + MC->SetProcess("MUNU", 1); /**muon nuclear interaction*/ + MC->SetProcess("DCAY", 1); /**decay*/ + MC->SetProcess("LOSS", 1); /**energy loss*/ + MC->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)*/ + MC->SetCut("CUTELE", cut1); /** electrons (GeV)*/ + MC->SetCut("CUTNEU", cut1); /** neutral hadrons (GeV)*/ + MC->SetCut("CUTHAD", cut1); /** charged hadrons (GeV)*/ + MC->SetCut("CUTMUO", cut1); /** muons (GeV)*/ + MC->SetCut("BCUTE", cut1); /** electron bremsstrahlung (GeV)*/ + MC->SetCut("BCUTM", cut1); /** muon and hadron bremsstrahlung(GeV)*/ + MC->SetCut("DCUTE", cut1); /** delta-rays by electrons (GeV)*/ + MC->SetCut("DCUTM", cut1); /** delta-rays by muons (GeV)*/ + MC->SetCut("PPCUTM", cut1); /** direct pair production by muons (GeV)*/ + MC->SetCut("TOFMAX", tofmax); /**time of flight cut in seconds*/ } diff --git a/templates/project_stl_containers/gconfig/UserDecay.C b/templates/project_stl_containers/gconfig/UserDecay.C index 279a2b9f9c..338ae381ba 100644 --- a/templates/project_stl_containers/gconfig/UserDecay.C +++ b/templates/project_stl_containers/gconfig/UserDecay.C @@ -6,37 +6,37 @@ * copied verbatim in the file "LICENSE" * ********************************************************************************/ -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"); + 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.; + 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); - - + */ + gMC->SetDecayMode(He5PDG, bratio, mode); } \ No newline at end of file diff --git a/templates/project_stl_containers/gconfig/g3Config.C b/templates/project_stl_containers/gconfig/g3Config.C old mode 100755 new mode 100644 index 0305931d61..65728c9922 --- a/templates/project_stl_containers/gconfig/g3Config.C +++ b/templates/project_stl_containers/gconfig/g3Config.C @@ -8,43 +8,36 @@ // $Id: g3Config.C,v 1.1.1.1 2005/06/23 07:14:09 dbertini Exp $ // -// Configuration macro for Geant3 VirtualMC +// Configuration macro for Geant3 VirtualMC 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 - MyProjStack *st = new MyProjStack(); - 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 + MyProjStack* st = new MyProjStack(); + 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(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->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(1); // cerenkov photons - + geant3->SetCKOV(1); // cerenkov photons } - - diff --git a/templates/project_stl_containers/gconfig/g3libs.C b/templates/project_stl_containers/gconfig/g3libs.C index 8fbbda3901..f1c5f2f3db 100644 --- a/templates/project_stl_containers/gconfig/g3libs.C +++ b/templates/project_stl_containers/gconfig/g3libs.C @@ -10,9 +10,9 @@ void g3libs() { - cout << "Loading Geant3 libraries ..." << endl; + cout << "Loading Geant3 libraries ..." << endl; - gSystem->Load("libgeant321"); + gSystem->Load("libgeant321"); - cout << "Loading Geant3 libraries ... finished" << endl; + cout << "Loading Geant3 libraries ... finished" << endl; } diff --git a/templates/project_stl_containers/gconfig/g4Config.C b/templates/project_stl_containers/gconfig/g4Config.C old mode 100755 new mode 100644 index db38c941cb..fb26396fc8 --- a/templates/project_stl_containers/gconfig/g4Config.C +++ b/templates/project_stl_containers/gconfig/g4Config.C @@ -9,63 +9,62 @@ // 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: -/// Available options: -/// EMonly, EMonly+Extra, Hadron_EM, Hadron_EM+Extra -/// where EMonly = emStandard -/// Hadron = FTFP_BERT FTFP_BERT_TRV FTFP_BERT_HP FTFP_INCLXX FTFP_INCLXX_HP FTF_BIC LBE QBBC QGSP_BERT QGSP_BERT_HP QGSP_BIC QGSP_BIC_HP QGSP_FTFP_BERT QGSP_INCLXX QGSP_INCLXX_HP QGS_BIC Shielding ShieldingLEND -/// EM = _EMV _EMX _EMY _EMZ _LIV _PEN -/// Extra = extra optical radDecay -/// The Extra selections are cumulative, while Hadron selections are exlusive. - -/// 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. + /// 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: + /// Available options: + /// EMonly, EMonly+Extra, Hadron_EM, Hadron_EM+Extra + /// where EMonly = emStandard + /// Hadron = FTFP_BERT FTFP_BERT_TRV FTFP_BERT_HP FTFP_INCLXX FTFP_INCLXX_HP FTF_BIC LBE QBBC QGSP_BERT + /// QGSP_BERT_HP QGSP_BIC QGSP_BIC_HP QGSP_FTFP_BERT QGSP_INCLXX QGSP_INCLXX_HP QGS_BIC Shielding ShieldingLEND + /// EM = _EMV _EMX _EMY _EMZ _LIV _PEN + /// Extra = extra optical radDecay + /// The Extra selections are cumulative, while Hadron selections are exlusive. - Bool_t mtMode = FairRunSim::Instance()->IsMT(); - Bool_t specialStacking = false; - TG4RunConfiguration* runConfiguration - = new TG4RunConfiguration("geomRoot", "QGSP_FTFP_BERT", "stepLimiter+specialCuts+specialControls+stackPopper", - specialStacking, mtMode); + /// 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. -/// Create the G4 VMC - TGeant4* geant4 = new TGeant4("TGeant4", "The Geant4 Monte Carlo", runConfiguration); - cout << "Geant4 has been created." << endl; + Bool_t mtMode = FairRunSim::Instance()->IsMT(); + Bool_t specialStacking = false; + TG4RunConfiguration* runConfiguration = new TG4RunConfiguration( + "geomRoot", "QGSP_FTFP_BERT", "stepLimiter+specialCuts+specialControls+stackPopper", specialStacking, mtMode); -/// create the Specific stack - MyProjStack *stack = new MyProjStack(1000); - stack->StoreSecondaries(kTRUE); - stack->SetMinPoints(0); - geant4->SetStack(stack); + /// Create the G4 VMC + TGeant4* geant4 = new TGeant4("TGeant4", "The Geant4 Monte Carlo", runConfiguration); + cout << "Geant4 has been created." << endl; - if(FairRunSim::Instance()->IsExtDecayer()){ - TVirtualMCDecayer* decayer = TPythia6Decayer::Instance(); - geant4->SetExternalDecayer(decayer); - } - -/// Customise Geant4 setting -/// (verbose level, global range cut, ..) + /// create the Specific stack + MyProjStack* stack = new MyProjStack(1000); + stack->StoreSecondaries(kTRUE); + stack->SetMinPoints(0); + geant4->SetStack(stack); - TString configm(gSystem->Getenv("VMCWORKDIR")); - TString configm1 = configm + "/gconfig/g4config.in"; - cout << " -I g4Config() using g4conf macro: " << configm1 << endl; + if (FairRunSim::Instance()->IsExtDecayer()) { + TVirtualMCDecayer* decayer = TPythia6Decayer::Instance(); + geant4->SetExternalDecayer(decayer); + } - //set geant4 specific stuff - geant4->SetMaxNStep(10000); // default is 30000 - geant4->ProcessGeantMacro(configm1.Data()); + /// 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 + geant4->SetMaxNStep(10000); // default is 30000 + geant4->ProcessGeantMacro(configm1.Data()); } diff --git a/templates/project_stl_containers/macro/eventDisplay.C b/templates/project_stl_containers/macro/eventDisplay.C index 648d564da2..68893c4d52 100644 --- a/templates/project_stl_containers/macro/eventDisplay.C +++ b/templates/project_stl_containers/macro/eventDisplay.C @@ -1,32 +1,29 @@ void eventDisplay() { - //-----User Settings:----------------------------------------------- - TString InputFile ="test.root"; - TString ParFile ="params.root"; - TString OutFile ="tst.root"; + //-----User Settings:----------------------------------------------- + TString InputFile = "test.root"; + TString ParFile = "params.root"; + TString OutFile = "tst.root"; + // ----- Reconstruction run ------------------------------------------- + FairRunAna *fRun = new FairRunAna(); + FairFileSource *fFileSource = new FairFileSource(InputFile); + fRun->SetSource(fFileSource); + fRun->SetSink(new FairRootFileSink(OutFile.Data())); - // ----- Reconstruction run ------------------------------------------- - FairRunAna *fRun= new FairRunAna(); - FairFileSource *fFileSource = new FairFileSource(InputFile); - fRun->SetSource(fFileSource); - fRun->SetSink(new FairRootFileSink(OutFile.Data())); + FairRuntimeDb *rtdb = fRun->GetRuntimeDb(); + FairParRootFileIo *parInput1 = new FairParRootFileIo(); + parInput1->open(ParFile.Data()); + rtdb->setFirstInput(parInput1); - FairRuntimeDb* rtdb = fRun->GetRuntimeDb(); - FairParRootFileIo* parInput1 = new FairParRootFileIo(); - parInput1->open(ParFile.Data()); - rtdb->setFirstInput(parInput1); + FairEventManager *fMan = new FairEventManager(); - FairEventManager *fMan= new FairEventManager(); + //----------------------Traks and points ------------------------------------- + FairMCTracks *Track = new FairMCTracks("Monte-Carlo Tracks"); + // FairMCPointDraw *TorinoDetectorPoints = new FairMCPointDraw("FairTestDetectorPoint", kRed, kFullSquare); - //----------------------Traks and points ------------------------------------- - FairMCTracks *Track = new FairMCTracks("Monte-Carlo Tracks"); -// FairMCPointDraw *TorinoDetectorPoints = new FairMCPointDraw("FairTestDetectorPoint", kRed, kFullSquare); - - fMan->AddTask(Track); -// fMan->AddTask(TorinoDetectorPoints); - - - fMan->Init(); + fMan->AddTask(Track); + // fMan->AddTask(TorinoDetectorPoints); + fMan->Init(); } diff --git a/templates/project_stl_containers/macro/run_sim.C b/templates/project_stl_containers/macro/run_sim.C index 5c413aac35..669205d0b4 100644 --- a/templates/project_stl_containers/macro/run_sim.C +++ b/templates/project_stl_containers/macro/run_sim.C @@ -1,111 +1,102 @@ void run_sim(Int_t nEvents = 100, TString mcEngine = "TGeant4", Bool_t isMT = false) { - - // Output file name - TString outFile ="test.root"; - - // Parameter file name - TString parFile="params.root"; - - // ----- Timer -------------------------------------------------------- - TStopwatch timer; - timer.Start(); - // ------------------------------------------------------------------------ - - // ----- Create simulation run ---------------------------------------- - FairRunSim* run = new FairRunSim(); - run->SetName(mcEngine); // Transport engine - run->SetSink(new FairRootFileSink(outFile)); // Output file - run->SetIsMT(isMT); - FairRuntimeDb* rtdb = run->GetRuntimeDb(); - // ------------------------------------------------------------------------ - - // ----- Create media ------------------------------------------------- - run->SetMaterials("media.geo"); // Materials - // ------------------------------------------------------------------------ - - // ----- Create geometry ---------------------------------------------- - - FairModule* cave= new MyCave("CAVE"); - cave->SetGeometryFileName("cave.geo"); - run->AddModule(cave); - - FairModule* magnet = new MyMagnet("Magnet"); - run->AddModule(magnet); - - FairModule* pipe = new MyPipe("Pipe"); - run->AddModule(pipe); - - FairDetector* NewDet = new NewDetector("TestDetector", kTRUE); - run->AddModule(NewDet); - - // ------------------------------------------------------------------------ + // Output file name + TString outFile = "test.root"; + + // Parameter file name + TString parFile = "params.root"; + + // ----- Timer -------------------------------------------------------- + TStopwatch timer; + timer.Start(); + // ------------------------------------------------------------------------ + + // ----- Create simulation run ---------------------------------------- + FairRunSim* run = new FairRunSim(); + run->SetName(mcEngine); // Transport engine + run->SetSink(new FairRootFileSink(outFile)); // Output file + run->SetIsMT(isMT); + FairRuntimeDb* rtdb = run->GetRuntimeDb(); + // ------------------------------------------------------------------------ + + // ----- Create media ------------------------------------------------- + run->SetMaterials("media.geo"); // Materials + // ------------------------------------------------------------------------ + + // ----- Create geometry ---------------------------------------------- + + FairModule* cave = new MyCave("CAVE"); + cave->SetGeometryFileName("cave.geo"); + run->AddModule(cave); + + FairModule* magnet = new MyMagnet("Magnet"); + run->AddModule(magnet); + + FairModule* pipe = new MyPipe("Pipe"); + run->AddModule(pipe); + + FairDetector* NewDet = new NewDetector("TestDetector", kTRUE); + run->AddModule(NewDet); + + // ------------------------------------------------------------------------ // ----- Magnetic field ------------------------------------------- // Constant Field - MyConstField *fMagField = new MyConstField(); - fMagField->SetField(0., 20. ,0. ); // values are in kG - fMagField->SetFieldRegion(-200, 200,-200, 200, -200, 200); // values are in cm - // (xmin,xmax,ymin,ymax,zmin,zmax) + MyConstField* fMagField = new MyConstField(); + fMagField->SetField(0., 20., 0.); // values are in kG + fMagField->SetFieldRegion(-200, 200, -200, 200, -200, 200); // values are in cm + // (xmin,xmax,ymin,ymax,zmin,zmax) run->SetField(fMagField); // -------------------------------------------------------------------- - - - // ----- Create PrimaryGenerator -------------------------------------- - FairPrimaryGenerator* primGen = new FairPrimaryGenerator(); - + // ----- Create PrimaryGenerator -------------------------------------- + FairPrimaryGenerator* primGen = new FairPrimaryGenerator(); + // Add a box generator also to the run - FairBoxGenerator* boxGen = new FairBoxGenerator(13, 5); // 13 = muon; 1 = multipl. - boxGen->SetPRange(20,25); // GeV/c - boxGen->SetPhiRange(0., 360.); // Azimuth angle range [degree] - boxGen->SetThetaRange(0., 90.); // Polar angle in lab system range [degree] - boxGen->SetXYZ(0., 0., 0.); // cm + FairBoxGenerator* boxGen = new FairBoxGenerator(13, 5); // 13 = muon; 1 = multipl. + boxGen->SetPRange(20, 25); // GeV/c + boxGen->SetPhiRange(0., 360.); // Azimuth angle range [degree] + boxGen->SetThetaRange(0., 90.); // Polar angle in lab system range [degree] + boxGen->SetXYZ(0., 0., 0.); // cm 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! - run->SetStoreTraj(kTRUE); - - - - // ----- Initialize simulation run ------------------------------------ - run->Init(); - // ------------------------------------------------------------------------ - - // ----- Runtime database --------------------------------------------- - - Bool_t kParameterMerged = kTRUE; - FairParRootFileIo* parOut = new FairParRootFileIo(kParameterMerged); - parOut->open(parFile.Data()); - rtdb->setOutput(parOut); - rtdb->saveOutput(); - rtdb->print(); - // ------------------------------------------------------------------------ - - // ----- Start run ---------------------------------------------------- - run->Run(nEvents); - - //You can export your ROOT geometry ot a separate file - run->CreateGeometryFile("geofile_full.root"); - // ------------------------------------------------------------------------ - - // ----- Finish ------------------------------------------------------- - timer.Stop(); - Double_t rtime = timer.RealTime(); - Double_t ctime = timer.CpuTime(); - cout << endl << endl; - cout << "Macro finished succesfully." << endl; - cout << "Output file is " << outFile << endl; - cout << "Parameter file is " << parFile << endl; - cout << "Real time " << rtime << " s, CPU time " << ctime - << "s" << endl << endl; - // ------------------------------------------------------------------------ -} + // ------------------------------------------------------------------------ + + //---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(kTRUE); + + // ----- Initialize simulation run ------------------------------------ + run->Init(); + // ------------------------------------------------------------------------ + // ----- Runtime database --------------------------------------------- + Bool_t kParameterMerged = kTRUE; + FairParRootFileIo* parOut = new FairParRootFileIo(kParameterMerged); + parOut->open(parFile.Data()); + rtdb->setOutput(parOut); + rtdb->saveOutput(); + rtdb->print(); + // ------------------------------------------------------------------------ + + // ----- Start run ---------------------------------------------------- + run->Run(nEvents); + + // You can export your ROOT geometry ot a separate file + run->CreateGeometryFile("geofile_full.root"); + // ------------------------------------------------------------------------ + + // ----- Finish ------------------------------------------------------- + timer.Stop(); + Double_t rtime = timer.RealTime(); + Double_t ctime = timer.CpuTime(); + cout << endl << endl; + cout << "Macro finished succesfully." << endl; + cout << "Output file is " << outFile << endl; + cout << "Parameter file is " << parFile << endl; + cout << "Real time " << rtime << " s, CPU time " << ctime << "s" << endl << endl; + // ------------------------------------------------------------------------ +} diff --git a/templates/project_stl_containers/passive/MyCave.cxx b/templates/project_stl_containers/passive/MyCave.cxx index 16ad4582b0..06fbc0df86 100644 --- a/templates/project_stl_containers/passive/MyCave.cxx +++ b/templates/project_stl_containers/passive/MyCave.cxx @@ -12,60 +12,53 @@ // ----- Created 26/03/14 by M. Al-Turany ----- // ------------------------------------------------------------------------- #include "MyCave.h" -#include "MyGeoCave.h" // for MyGeoCave -#include "FairGeoInterface.h" // for FairGeoInterface -#include "FairGeoLoader.h" // for FairGeoLoader -#include "FairGeoNode.h" // for FairGeoNode -#include "FairGeoVolume.h" // for FairGeoVolume -#include "FairRun.h" // for FairRun -#include "FairRuntimeDb.h" // for FairRuntimeDb -#include // for TListIter, TList (ptr only) -#include // for TObjArray -#include // for TString +#include "FairGeoInterface.h" // for FairGeoInterface +#include "FairGeoLoader.h" // for FairGeoLoader +#include "FairGeoNode.h" // for FairGeoNode +#include "FairGeoVolume.h" // for FairGeoVolume +#include "FairRun.h" // for FairRun +#include "FairRuntimeDb.h" // for FairRuntimeDb +#include "MyGeoCave.h" // for MyGeoCave -#include // for NULL +#include // for TListIter, TList (ptr only) +#include // for TObjArray +#include // for TString +#include // for NULL -ClassImp(MyCave) +ClassImp(MyCave); void MyCave::ConstructGeometry() { - FairGeoLoader* loader=FairGeoLoader::Instance(); - FairGeoInterface* GeoInterface =loader->getGeoInterface(); - MyGeoCave* MGeo=new MyGeoCave(); - MGeo->setGeomFile(GetGeometryFileName()); - GeoInterface->addGeoModule(MGeo); - Bool_t rc = GeoInterface->readSet(MGeo); - if ( rc ) { MGeo->create(loader->getGeoBuilder()); } - + FairGeoLoader* loader = FairGeoLoader::Instance(); + FairGeoInterface* GeoInterface = loader->getGeoInterface(); + MyGeoCave* MGeo = new MyGeoCave(); + MGeo->setGeomFile(GetGeometryFileName()); + GeoInterface->addGeoModule(MGeo); + Bool_t rc = GeoInterface->readSet(MGeo); + if (rc) { + MGeo->create(loader->getGeoBuilder()); + } } MyCave::MyCave() -:FairModule() -{ -} + : FairModule() +{} -MyCave::~MyCave() +MyCave::~MyCave() {} +MyCave::MyCave(const char* name, const char* Title) + : FairModule(name, Title) { - -} -MyCave::MyCave(const char* name, const char* Title) - : FairModule(name ,Title) -{ - world[0] = 0; - world[1] = 0; - world[2] = 0; + world[0] = 0; + world[1] = 0; + world[2] = 0; } MyCave::MyCave(const MyCave& right) - : FairModule(right) -{ - world[0] = right.world[0]; - world[1] = right.world[1]; - world[2] = right.world[2]; -} - -FairModule* MyCave::CloneModule() const + : FairModule(right) { - return new MyCave(*this); + world[0] = right.world[0]; + world[1] = right.world[1]; + world[2] = right.world[2]; } +FairModule* MyCave::CloneModule() const { return new MyCave(*this); } diff --git a/templates/project_stl_containers/passive/MyCave.h b/templates/project_stl_containers/passive/MyCave.h index fd496b0e7b..1c4c330608 100644 --- a/templates/project_stl_containers/passive/MyCave.h +++ b/templates/project_stl_containers/passive/MyCave.h @@ -11,18 +11,17 @@ // ----- Created 26/03/14 by M. Al-Turany ----- // ------------------------------------------------------------------------- - #ifndef Cave_H #define Cave_H -#include "FairModule.h" // for FairModule +#include "FairModule.h" // for FairModule -#include // for MyCave::Class, ClassDef, etc +#include // for MyCave::Class, ClassDef, etc class MyCave : public FairModule { public: - MyCave(const char* name, const char* Title="Exp Cave"); + MyCave(const char* name, const char* Title = "Exp Cave"); MyCave(); virtual ~MyCave(); virtual void ConstructGeometry(); @@ -35,8 +34,7 @@ class MyCave : public FairModule MyCave(const MyCave&); MyCave& operator=(const MyCave&); - ClassDef(MyCave,1) //PNDCaveSD + ClassDef(MyCave, 1) // PNDCaveSD }; -#endif //Cave_H - +#endif // Cave_H diff --git a/templates/project_stl_containers/passive/MyGeoCave.cxx b/templates/project_stl_containers/passive/MyGeoCave.cxx index be73eb5ef1..92ad4bddbe 100644 --- a/templates/project_stl_containers/passive/MyGeoCave.cxx +++ b/templates/project_stl_containers/passive/MyGeoCave.cxx @@ -20,108 +20,119 @@ #include "MyGeoCave.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 // for TList - -#include // for strcmp -#include // for cout +#include // for TList +#include // for cout +#include // for strcmp using namespace std; -ClassImp(MyGeoCave) +ClassImp(MyGeoCave); MyGeoCave::MyGeoCave() - : FairGeoSet(), - name("cave") + : FairGeoSet() + , name("cave") { - // Constructor - fName="cave"; - name="cave"; - maxModules=1; + // Constructor + fName = "cave"; + maxModules = 1; } -Bool_t MyGeoCave::read(fstream& fin,FairGeoMedia* media) +Bool_t MyGeoCave::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 MyGeoCave::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 MyGeoCave::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 MyGeoCave::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/templates/project_stl_containers/passive/MyGeoCave.h b/templates/project_stl_containers/passive/MyGeoCave.h index 0573e9640b..6a32ba9161 100644 --- a/templates/project_stl_containers/passive/MyGeoCave.h +++ b/templates/project_stl_containers/passive/MyGeoCave.h @@ -12,32 +12,32 @@ // ----- Created 26/03/14 by M. Al-Turany ----- // ------------------------------------------------------------------------- - #ifndef MYGEOCAVE_H #define MYGEOCAVE_H -#include "FairGeoSet.h" // for FairGeoSet -#include // for fstream -#include // for MyGeoCave::Class, Bool_t, etc -#include // for TString +#include "FairGeoSet.h" // for FairGeoSet -#include // for fstream +#include // for MyGeoCave::Class, Bool_t, etc +#include // for TString +#include // for fstream +#include // for fstream class FairGeoMedia; -class MyGeoCave : public FairGeoSet +class MyGeoCave : public FairGeoSet { protected: TString name; + public: MyGeoCave(); ~MyGeoCave() {} - 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(MyGeoCave,0) // Class for the geometry of CAVE + ClassDef(MyGeoCave, 0) // Class for the geometry of CAVE }; -#endif /* !PNDGEOCAVE_H */ +#endif /* !PNDGEOCAVE_H */ diff --git a/templates/project_stl_containers/passive/MyMagnet.cxx b/templates/project_stl_containers/passive/MyMagnet.cxx index 02eaf2cf99..22e3fdfc08 100644 --- a/templates/project_stl_containers/passive/MyMagnet.cxx +++ b/templates/project_stl_containers/passive/MyMagnet.cxx @@ -13,70 +13,63 @@ #include "MyMagnet.h" -#include -#include "FairRun.h" // for FairRun -#include "FairRuntimeDb.h" // for FairRuntimeDb -#include // for ostream -#include // for TListIter, TList (ptr only) -#include // for TObjArray -#include // for TString +#include "FairRun.h" // for FairRun +#include "FairRuntimeDb.h" // for FairRuntimeDb + #include #include -#include -#include #include +#include +#include #include -#include // for NULL -#include // for operator<<, basic_ostream, etc - - - -MyMagnet::~MyMagnet() -{ -} +#include +#include // for TListIter, TList (ptr only) +#include // for TObjArray +#include // for TString +#include // for ostream +#include // for operator<<, basic_ostream, etc +#include // for NULL + +MyMagnet::~MyMagnet() {} MyMagnet::MyMagnet() - : FairModule("MyMagnet", "") -{ -} + : FairModule("MyMagnet", "") +{} -MyMagnet::MyMagnet(const char* name, const char* Title) - : FairModule(name ,Title) -{ -} +MyMagnet::MyMagnet(const char *name, const char *Title) + : FairModule(name, Title) +{} -MyMagnet::MyMagnet(const MyMagnet& right) - : FairModule(right) -{ -} +MyMagnet::MyMagnet(const MyMagnet &right) + : FairModule(right) +{} void MyMagnet::ConstructGeometry() { - - TGeoVolume *top=gGeoManager->GetTopVolume(); - + + TGeoVolume *top = gGeoManager->GetTopVolume(); + // define some materials - TGeoMaterial *matFe = new TGeoMaterial("Fe", 55.84, 26, 7.9); + TGeoMaterial *matFe = new TGeoMaterial("Fe", 55.84, 26, 7.9); // define some media - TGeoMedium *Fe = new TGeoMedium("Fe", 5, matFe); - + TGeoMedium *Fe = new TGeoMedium("Fe", 5, matFe); // 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); + // magyoke->SetTransparency(50); top->AddNode(magyoke, 1, new TGeoTranslation(0, 0, 0)); - + // 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"); @@ -84,39 +77,20 @@ void MyMagnet::ConstructGeometry() 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); top->AddNode(magnet1, 1, new TGeoTranslation(0, 0, 0)); - + TGeoRotation m3; m3.SetAngles(180, 0, 0); TGeoTranslation m4(0, 0, 0); TGeoCombiTrans m5(m4, m3); TGeoHMatrix *m6 = new TGeoHMatrix(m5); top->AddNode(magnet1, 2, m6); - - -} - -FairModule* MyMagnet::CloneModule() const -{ - return new MyMagnet(*this); } -ClassImp(MyMagnet) - - - - - - - - - - - - - +FairModule *MyMagnet::CloneModule() const { return new MyMagnet(*this); } +ClassImp(MyMagnet); diff --git a/templates/project_stl_containers/passive/MyMagnet.h b/templates/project_stl_containers/passive/MyMagnet.h index 1d7799fae4..ed991c832b 100644 --- a/templates/project_stl_containers/passive/MyMagnet.h +++ b/templates/project_stl_containers/passive/MyMagnet.h @@ -11,18 +11,18 @@ // ----- Created 26/03/14 by M. Al-Turany ----- // ------------------------------------------------------------------------- - #ifndef MAGNET_H #define MAGNET_H -#include "FairModule.h" // for FairModule -#include // for MyMagnet::Class, Bool_t, etc -#include // for string +#include "FairModule.h" // for FairModule + +#include // for MyMagnet::Class, Bool_t, etc +#include // for string class MyMagnet : public FairModule { public: - MyMagnet(const char* name, const char* Title="MY Magnet"); + MyMagnet(const char* name, const char* Title = "MY Magnet"); MyMagnet(); virtual ~MyMagnet(); void ConstructGeometry(); @@ -33,8 +33,7 @@ class MyMagnet : public FairModule MyMagnet(const MyMagnet&); MyMagnet& operator=(const MyMagnet&); - ClassDef(MyMagnet,1) + ClassDef(MyMagnet, 1) }; -#endif //MAGNET_H - +#endif // MAGNET_H diff --git a/templates/project_stl_containers/passive/MyPassiveContFact.cxx b/templates/project_stl_containers/passive/MyPassiveContFact.cxx index 257031437d..72dcbe2ae3 100644 --- a/templates/project_stl_containers/passive/MyPassiveContFact.cxx +++ b/templates/project_stl_containers/passive/MyPassiveContFact.cxx @@ -11,7 +11,6 @@ // ----- Created 26/03/14 by M. Al-Turany ----- // ------------------------------------------------------------------------- - //*-- AUTHOR : Denis Bertini //*-- Created : 21/06/2005 @@ -24,50 +23,47 @@ ///////////////////////////////////////////////////////////// #include "MyPassiveContFact.h" -#include "FairRuntimeDb.h" // for FairRuntimeDb - -#include // for TList -#include // for TString +#include "FairRuntimeDb.h" // for FairRuntimeDb -#include // for strcmp, NULL +#include // for TList +#include // for TString +#include // for strcmp, NULL class FairParSet; using namespace std; -ClassImp(MyPassiveContFact) +ClassImp(MyPassiveContFact); static MyPassiveContFact gMyPassiveContFact; MyPassiveContFact::MyPassiveContFact() - : FairContFact() + : FairContFact() { - // Constructor (called when the library is loaded) - fName="MyPassiveContFact"; - fTitle="Factory for parameter containers in libPassive"; - setAllContainers(); - FairRuntimeDb::instance()->addContFactory(this); + // Constructor (called when the library is loaded) + fName = "MyPassiveContFact"; + fTitle = "Factory for parameter containers in libPassive"; + setAllContainers(); + FairRuntimeDb::instance()->addContFactory(this); } void MyPassiveContFact::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* MyPassiveContFact::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(); + /** 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()); @@ -75,4 +71,3 @@ FairParSet* MyPassiveContFact::createContainer(FairContainer* c) return p; */ } - diff --git a/templates/project_stl_containers/passive/MyPassiveContFact.h b/templates/project_stl_containers/passive/MyPassiveContFact.h index 51c245f9bc..fe2a0bbf80 100644 --- a/templates/project_stl_containers/passive/MyPassiveContFact.h +++ b/templates/project_stl_containers/passive/MyPassiveContFact.h @@ -11,12 +11,12 @@ // ----- Created 26/03/14 by M. Al-Turany ----- // ------------------------------------------------------------------------- - #ifndef PNDPASSIVECONTFACT_H #define PNDPASSIVECONTFACT_H -#include "FairContFact.h" // for FairContFact, etc -#include // for MyPassiveContFact::Class, etc +#include "FairContFact.h" // for FairContFact, etc + +#include // for MyPassiveContFact::Class, etc class FairParSet; @@ -24,11 +24,12 @@ class MyPassiveContFact : public FairContFact { private: void setAllContainers(); + public: MyPassiveContFact(); ~MyPassiveContFact() {} FairParSet* createContainer(FairContainer*); - ClassDef( MyPassiveContFact,0) // Factory for all Passive parameter containers + ClassDef(MyPassiveContFact, 0) // Factory for all Passive parameter containers }; -#endif /* !PNDPASSIVECONTFACT_H */ +#endif /* !PNDPASSIVECONTFACT_H */ diff --git a/templates/project_stl_containers/passive/MyPipe.cxx b/templates/project_stl_containers/passive/MyPipe.cxx index 3a6221c133..6a4632e22d 100644 --- a/templates/project_stl_containers/passive/MyPipe.cxx +++ b/templates/project_stl_containers/passive/MyPipe.cxx @@ -12,82 +12,68 @@ // ------------------------------------------------------------------------- #include "MyPipe.h" -#include -#include -#include -#include +#include #include #include -#include - +#include +#include +#include +#include -MyPipe::~MyPipe() -{ -} +MyPipe::~MyPipe() {} MyPipe::MyPipe() - : FairModule() -{ -} + : FairModule() +{} -MyPipe::MyPipe(const char * name, const char * title) - : FairModule(name ,title) -{ -} +MyPipe::MyPipe(const char* name, const char* title) + : FairModule(name, title) +{} MyPipe::MyPipe(const MyPipe& right) - : FairModule(right) -{ -} - + : FairModule(right) +{} // ----- ConstructGeometry -------------------------------------------------- void MyPipe::ConstructGeometry() { - TGeoVolume *top=gGeoManager->GetTopVolume(); - - TGeoMedium *Carbon = gGeoManager->GetMedium("C"); - if(Carbon==0){ - TGeoMaterial *matCarbon = new TGeoMaterial("C", 12.011, 6.0, 2.265); - Carbon = new TGeoMedium("C", 3, matCarbon); - } - - TGeoMaterial *matVacuum = new TGeoMaterial("Vacuum", 0, 0, 0); - TGeoMedium *Vacuum = new TGeoMedium("Vacuum", 4, matVacuum); - - - Int_t nSects=2; - Double_t z[] = { -100, 300}; // in cm - Double_t r[] = { 2.5, 2.5}; // in cm - Double_t Thickness = 0.05; // thickness of beam pipe [cm] + TGeoVolume* top = gGeoManager->GetTopVolume(); + + TGeoMedium* Carbon = gGeoManager->GetMedium("C"); + if (Carbon == 0) { + TGeoMaterial* matCarbon = new TGeoMaterial("C", 12.011, 6.0, 2.265); + Carbon = new TGeoMedium("C", 3, matCarbon); + } + + TGeoMaterial* matVacuum = new TGeoMaterial("Vacuum", 0, 0, 0); + TGeoMedium* Vacuum = new TGeoMedium("Vacuum", 4, matVacuum); + + Int_t nSects = 2; + Double_t z[] = {-100, 300}; // in cm + Double_t r[] = {2.5, 2.5}; // in cm + Double_t Thickness = 0.05; // thickness of beam pipe [cm] TGeoPcon* shape = new TGeoPcon(0., 360., nSects); for (Int_t iSect = 0; iSect < nSects; iSect++) { - shape->DefineSection(iSect, z[iSect], r[iSect], r[iSect]+Thickness); + shape->DefineSection(iSect, z[iSect], r[iSect], r[iSect] + Thickness); } - + // ---> Volume TGeoVolume* pipe = new TGeoVolume("MyPipe", shape, Carbon); - + // --Now create the same but diameter less by Thikness and vacuum instead of Carbon TGeoPcon* Vshape = new TGeoPcon(0., 360., nSects); for (Int_t iSect = 0; iSect < nSects; iSect++) { Vshape->DefineSection(iSect, z[iSect], r[iSect], r[iSect]); } - + // ---> Volume TGeoVolume* Vpipe = new TGeoVolume("MyPipe", shape, Vacuum); - + top->AddNode(pipe, 1); top->AddNode(Vpipe, 1); - - } // ---------------------------------------------------------------------------- -FairModule* MyPipe::CloneModule() const -{ - return new MyPipe(*this); -} - -ClassImp(MyPipe) +FairModule* MyPipe::CloneModule() const { return new MyPipe(*this); } +ClassImp(MyPipe); diff --git a/templates/project_stl_containers/passive/MyPipe.h b/templates/project_stl_containers/passive/MyPipe.h index 7695f9a3ff..f25552ee96 100644 --- a/templates/project_stl_containers/passive/MyPipe.h +++ b/templates/project_stl_containers/passive/MyPipe.h @@ -16,9 +16,10 @@ #include "FairModule.h" -class MyPipe : public FairModule { +class MyPipe : public FairModule +{ public: - MyPipe(const char * name, const char *Title="My Pipe"); + MyPipe(const char* name, const char* Title = "My Pipe"); MyPipe(); virtual ~MyPipe(); @@ -29,10 +30,8 @@ class MyPipe : public FairModule { private: MyPipe(const MyPipe&); MyPipe& operator=(const MyPipe&); - - ClassDef(MyPipe,1) //MyPIPE + ClassDef(MyPipe, 1) // MyPIPE }; -#endif //PIPE_H - +#endif // PIPE_H diff --git a/test/fairtools/_FairLoggerNewDeathTest2.cxx b/test/fairtools/_FairLoggerNewDeathTest2.cxx index 88e1260ac6..39aca0a576 100644 --- a/test/fairtools/_FairLoggerNewDeathTest2.cxx +++ b/test/fairtools/_FairLoggerNewDeathTest2.cxx @@ -7,4 +7,3 @@ TEST(FairToolsTestFatal, TestFatalError1) ASSERT_THROW(LOG(fatal) << "This is a another fatal problem", fair::FatalException); // TODO: check if cored dump is written to file } - diff --git a/test/fairtools/_FairLoggerNewTestAllVerbosityLevelsToScreenAndFile.cxx b/test/fairtools/_FairLoggerNewTestAllVerbosityLevelsToScreenAndFile.cxx index 8531666ad6..d10884061e 100644 --- a/test/fairtools/_FairLoggerNewTestAllVerbosityLevelsToScreenAndFile.cxx +++ b/test/fairtools/_FairLoggerNewTestAllVerbosityLevelsToScreenAndFile.cxx @@ -1,6 +1,5 @@ #include "_TestFairLoggerNew.h" - TEST_P(VerbosityLevelTest, testAllVerbosityLevelsToScreenAndFile) { gLogger->SetLogVerbosityLevel(fVerbosityLevel.c_str()); @@ -20,21 +19,19 @@ TEST_P(VerbosityLevelTest, testAllVerbosityLevelsToScreenAndFile) SCOPED_TRACE(fLogLevelSettingToTest); int lines = expected.size(); - for (int i = 0; i < lines; ++i) - { + for (int i = 0; i < lines; ++i) { EXPECT_TRUE(CheckVerboseOutput(expected[i], fOutputString, fVerbosityLevel, fHandler.GetCaptureLine(i))); } } - FairTestOutputHandler outputHandler(fOutFileName); { SCOPED_TRACE(fLogLevelSettingToTest); int lines = expected.size(); - for (int i = 0; i < lines; ++i) - { - EXPECT_TRUE(CheckVerboseOutput(expected[i], fOutputString, fVerbosityLevel, outputHandler.GetCaptureLine(i))); + for (int i = 0; i < lines; ++i) { + EXPECT_TRUE( + CheckVerboseOutput(expected[i], fOutputString, fVerbosityLevel, outputHandler.GetCaptureLine(i))); } } } diff --git a/test/fairtools/_FairLoggerNewTestManipToFile.cxx b/test/fairtools/_FairLoggerNewTestManipToFile.cxx index f4bc65aa4d..4f8dfc8631 100644 --- a/test/fairtools/_FairLoggerNewTestManipToFile.cxx +++ b/test/fairtools/_FairLoggerNewTestManipToFile.cxx @@ -28,8 +28,7 @@ TEST_F(FairToolsTest, ManipToFile) int minLines = std::min(expectedNumberOfLines, noLines); - for (int i = 0; i < minLines; ++i) - { + for (int i = 0; i < minLines; ++i) { EXPECT_EQ(expectedResult[i], outputHandler.GetCaptureLine(i)); } } diff --git a/test/fairtools/_FairLoggerNewTestManipToScreen.cxx b/test/fairtools/_FairLoggerNewTestManipToScreen.cxx index d875b8d716..c38da8055a 100644 --- a/test/fairtools/_FairLoggerNewTestManipToScreen.cxx +++ b/test/fairtools/_FairLoggerNewTestManipToScreen.cxx @@ -28,8 +28,7 @@ TEST_F(FairToolsTest, ManipToScreen) int minLines = std::min(expectedNumberOfLines, noLines); - for (int i = 0; i < minLines; ++i) - { + for (int i = 0; i < minLines; ++i) { EXPECT_EQ(expectedResult[i], fHandler.GetCaptureLine(i)); } } diff --git a/test/fairtools/_FairLoggerTestAllLogLevelsToScreenAndFile.cxx b/test/fairtools/_FairLoggerTestAllLogLevelsToScreenAndFile.cxx index 6306e0530a..c9090505d4 100644 --- a/test/fairtools/_FairLoggerTestAllLogLevelsToScreenAndFile.cxx +++ b/test/fairtools/_FairLoggerTestAllLogLevelsToScreenAndFile.cxx @@ -1,6 +1,5 @@ #include "_TestFairLogger.h" - TEST_P(LogLevelTest, testAllLogLevelsToScreenAndFile) { fLogger->SetLogFileLevel(fLogLevelSettingToTest.c_str()); diff --git a/test/fairtools/_FairLoggerTestAllVerbosityLevelsToScreenAndFile.cxx b/test/fairtools/_FairLoggerTestAllVerbosityLevelsToScreenAndFile.cxx index af896804fd..d167fb75af 100644 --- a/test/fairtools/_FairLoggerTestAllVerbosityLevelsToScreenAndFile.cxx +++ b/test/fairtools/_FairLoggerTestAllVerbosityLevelsToScreenAndFile.cxx @@ -19,8 +19,7 @@ TEST_P(VerbosityLevelTest, testAllVerbosityLevelsToScreenAndFile) SCOPED_TRACE(fLogLevelSettingToTest); int lines = expected.size(); - for (int i = 0; i < lines; ++i) - { + for (int i = 0; i < lines; ++i) { EXPECT_TRUE(CheckVerboseOutput(expected[i], fOutputString, fVerbosityLevel, fHandler.GetCaptureLine(i))); } } @@ -31,8 +30,7 @@ TEST_P(VerbosityLevelTest, testAllVerbosityLevelsToScreenAndFile) SCOPED_TRACE(fLogLevelSettingToTest); int lines = expected.size(); - for (int i = 0; i < lines; ++i) - { + for (int i = 0; i < lines; ++i) { EXPECT_TRUE(CheckVerboseOutput(expected[i], fOutputString, fVerbosityLevel, fileInfo[i])); } } diff --git a/test/fairtools/_TestFairLogger.h b/test/fairtools/_TestFairLogger.h index 8d69c7b694..f34f8d663e 100644 --- a/test/fairtools/_TestFairLogger.h +++ b/test/fairtools/_TestFairLogger.h @@ -5,37 +5,28 @@ * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ -#include "FairLogger.h" - #include "FairCaptureOutputNew.h" +#include "FairLogger.h" #include "FairTestOutputHandler.h" -#include "gtest/gtest.h" #include "gtest/gtest-spi.h" - +#include "gtest/gtest.h" +#include #include #include #include -#include #include -static const char* const LogString[] = { - "FATAL", "ERROR", "WARN", "INFO", - "DEBUG", "DEBUG1", "DEBUG2", "DEBUG3", "DEBUG4" -}; +static const char* const LogString[] = + {"FATAL", "ERROR", "WARN", "INFO", "DEBUG", "DEBUG1", "DEBUG2", "DEBUG3", "DEBUG4"}; -static const char* const TestLogs[] = { - "ERROR", "WARN", "INFO", - "DEBUG", "DEBUG1", "DEBUG2", "DEBUG3", "DEBUG4" -}; +static const char* const TestLogs[] = {"ERROR", "WARN", "INFO", "DEBUG", "DEBUG1", "DEBUG2", "DEBUG3", "DEBUG4"}; -static const char* const VerbosityLevelArray[] = { - "LOW", "MEDIUM", "HIGH", "VERYHIGH" -}; +static const char* const VerbosityLevelArray[] = {"LOW", "MEDIUM", "HIGH", "VERYHIGH"}; // Base class to use the same basic setup for parameterized and non-parameterized tests. // Here one defines everything which is common for all the different test cases -template +template class _TestFairLoggerBase : public T { protected: @@ -56,8 +47,7 @@ class _TestFairLoggerBase : public T _TestFairLoggerBase(const _TestFairLoggerBase&); _TestFairLoggerBase& operator=(const _TestFairLoggerBase&); - ~_TestFairLoggerBase() - {}; + ~_TestFairLoggerBase(){}; virtual void SetUp() { @@ -65,14 +55,12 @@ class _TestFairLoggerBase : public T SetOutFileName(); } - virtual void TearDown() - {} + virtual void TearDown() {} void SetOutFileName() { char fileName[25]; - if (tmpnam(fileName)) - { + if (tmpnam(fileName)) { fOutFileName = fileName; } } @@ -105,14 +93,13 @@ class _TestFairLoggerBase : public T std::vector levelNames(LogString, LogString + 9); std::vector::iterator pos = std::find(levelNames.begin(), levelNames.end(), logLevel); levelNames.erase(pos + 1, levelNames.end()); - levelNames.erase(levelNames.begin()); // don't use FATAL logLevel in this test + levelNames.erase(levelNames.begin()); // don't use FATAL logLevel in this test std::vector retVal; std::string fullOutputString; std::vector::iterator iter; - for (iter = levelNames.begin(); iter < levelNames.end(); iter++) - { + for (iter = levelNames.begin(); iter < levelNames.end(); iter++) { fullOutputString = "[" + *iter + "] " + outStr; retVal.push_back(fullOutputString); } @@ -136,8 +123,7 @@ class _TestFairLoggerBase : public T int minLines = std::min(expectedNumberOfLines, noLines); - for (int i = 0; i < minLines; ++i) - { + for (int i = 0; i < minLines; ++i) { EXPECT_EQ(v[i], fHandler.GetCaptureLine(i)); } } @@ -150,8 +136,7 @@ class _TestFairLoggerBase : public T int minLines = std::min(expectedNumberOfLines, noLines); - for (int i = 0; i < minLines; ++i) - { + for (int i = 0; i < minLines; ++i) { EXPECT_EQ(v[i], _handler.GetCaptureLine(i)); } } @@ -162,10 +147,8 @@ class _TestFairLoggerBase : public T std::string line; std::ifstream myfile(fileName.c_str()); - if (myfile.is_open()) - { - while (getline(myfile, line)) - { + if (myfile.is_open()) { + while (getline(myfile, line)) { list.push_back(line); } myfile.close(); @@ -174,7 +157,10 @@ class _TestFairLoggerBase : public T return list; } - bool CheckVerboseOutput(std::string logLevel, std::string outputString, std::string verbosity, std::string resultString) + bool CheckVerboseOutput(std::string logLevel, + std::string outputString, + std::string verbosity, + std::string resultString) { // Example Output for logging level INFO and different verbosity levels // LOW :[INFO] I am here. @@ -182,20 +168,16 @@ class _TestFairLoggerBase : public T // HIGH :[process_name][19:07:13:123456][INFO] I am here. // VERYHIGH :[process_name][19:07:13:123456][INFO][_TestFairTools.cxx:78:LogNoArguments] I am here. std::string regexString; - if (verbosity == "HIGH" || verbosity == "VERYHIGH") - { - regexString += "\\[.*]"; // process_name - regexString += "\\[\\d{2}:\\d{2}:\\d{2}.\\d{6}]"; // timestamp with ns - } - else if (verbosity == "MEDIUM") - { - regexString += "\\[\\d{2}:\\d{2}:\\d{2}]"; // timestamp without ns + if (verbosity == "HIGH" || verbosity == "VERYHIGH") { + regexString += "\\[.*]"; // process_name + regexString += "\\[\\d{2}:\\d{2}:\\d{2}.\\d{6}]"; // timestamp with ns + } else if (verbosity == "MEDIUM") { + regexString += "\\[\\d{2}:\\d{2}:\\d{2}]"; // timestamp without ns } - regexString += "\\[" + logLevel + "]"; // severity + regexString += "\\[" + logLevel + "]"; // severity - if (verbosity == "VERYHIGH") - { - regexString += "\\[.*:\\d{2}:.*]"; // file:line:function + if (verbosity == "VERYHIGH") { + regexString += "\\[.*:\\d{2}:.*]"; // file:line:function } regexString += "[ ]" + outputString + ".*"; @@ -208,7 +190,8 @@ class _TestFairLoggerBase : public T /* This is the derived class for the non-parameterized test cases. */ -class FairToolsTest : public _TestFairLoggerBase {}; +class FairToolsTest : public _TestFairLoggerBase +{}; /* This is the derived class for the parameterized test case diff --git a/test/fairtools/_TestFairLoggerNew.h b/test/fairtools/_TestFairLoggerNew.h index bf0238c5d8..1fc02fe2f0 100644 --- a/test/fairtools/_TestFairLoggerNew.h +++ b/test/fairtools/_TestFairLoggerNew.h @@ -5,38 +5,30 @@ * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ -#include "FairLogger.h" - #include "FairCaptureOutputNew.h" +#include "FairLogger.h" // #include "FairTestNewOutputHandler.h" #include "FairTestOutputHandler.h" #include "gtest/gtest.h" // #include "gtest/gtest-spi.h" +#include #include #include #include -#include #include -static const char* const LogString[] = { - "FATAL", "ERROR", "WARN", "INFO", - "DEBUG", "DEBUG1", "DEBUG2", "DEBUG3", "DEBUG4" -}; +static const char* const LogString[] = + {"FATAL", "ERROR", "WARN", "INFO", "DEBUG", "DEBUG1", "DEBUG2", "DEBUG3", "DEBUG4"}; -static const char* const TestLogs[] = { - "ERROR", "WARN", "INFO", - "DEBUG", "DEBUG1", "DEBUG2", "DEBUG3", "DEBUG4" -}; +static const char* const TestLogs[] = {"ERROR", "WARN", "INFO", "DEBUG", "DEBUG1", "DEBUG2", "DEBUG3", "DEBUG4"}; -static const char* const VerbosityLevelArray[] = { - "LOW", "MEDIUM", "HIGH", "VERYHIGH" -}; +static const char* const VerbosityLevelArray[] = {"LOW", "MEDIUM", "HIGH", "VERYHIGH"}; // Base class to use the same basic setup for parameterized and non-parameterized tests. // Here one defines everything which is common for all the different test cases -template +template class _TestFairLoggerBase : public T { protected: @@ -55,8 +47,7 @@ class _TestFairLoggerBase : public T _TestFairLoggerBase(const _TestFairLoggerBase&); _TestFairLoggerBase& operator=(const _TestFairLoggerBase&); - ~_TestFairLoggerBase() - {} + ~_TestFairLoggerBase() {} virtual void SetUp() { @@ -64,14 +55,12 @@ class _TestFairLoggerBase : public T SetOutFileName(); } - virtual void TearDown() - {} + virtual void TearDown() {} void SetOutFileName() { char fileName[25]; - if (tmpnam(fileName)) - { + if (tmpnam(fileName)) { fOutFileName = fileName; } } @@ -104,14 +93,13 @@ class _TestFairLoggerBase : public T std::vector levelNames(LogString, LogString + 9); std::vector::iterator pos = std::find(levelNames.begin(), levelNames.end(), loglevel); levelNames.erase(pos + 1, levelNames.end()); - levelNames.erase(levelNames.begin()); // don't use FATAL loglevel in this test + levelNames.erase(levelNames.begin()); // don't use FATAL loglevel in this test std::vector retVal; std::string fullOutputString; std::vector::iterator iter; - for (iter = levelNames.begin(); iter < levelNames.end(); iter++) - { + for (iter = levelNames.begin(); iter < levelNames.end(); iter++) { fullOutputString = "[" + *iter + "] " + outStr; retVal.push_back(fullOutputString); } @@ -135,8 +123,7 @@ class _TestFairLoggerBase : public T int minLines = std::min(expectedNumberOfLines, noLines); - for (int i = 0; i < minLines; ++i) - { + for (int i = 0; i < minLines; ++i) { EXPECT_EQ(v[i], fHandler.GetCaptureLine(i)); } } @@ -149,13 +136,15 @@ class _TestFairLoggerBase : public T int minLines = std::min(expectedNumberOfLines, noLines); - for (int i = 0; i < minLines; ++i) - { + for (int i = 0; i < minLines; ++i) { EXPECT_EQ(v[i], _handler.GetCaptureLine(i)); } } - bool CheckVerboseOutput(std::string logLevel, std::string outputString, std::string verbosity, std::string resultString) + bool CheckVerboseOutput(std::string logLevel, + std::string outputString, + std::string verbosity, + std::string resultString) { // Example Output for logging level INFO and different verbosity levels // LOW :[INFO] I am here. @@ -163,20 +152,16 @@ class _TestFairLoggerBase : public T // HIGH :[process_name][19:07:13:123456][INFO] I am here. // VERYHIGH :[process_name][19:07:13:123456][INFO][_TestFairTools.cxx:78:LogNoArguments] I am here. std::string regexString; - if (verbosity == "HIGH" || verbosity == "VERYHIGH") - { - regexString += "\\[.*]"; // process_name - regexString += "\\[\\d{2}:\\d{2}:\\d{2}.\\d{6}]"; // timestamp with ns - } - else if (verbosity == "MEDIUM") - { - regexString += "\\[\\d{2}:\\d{2}:\\d{2}]"; // timestamp without ns + if (verbosity == "HIGH" || verbosity == "VERYHIGH") { + regexString += "\\[.*]"; // process_name + regexString += "\\[\\d{2}:\\d{2}:\\d{2}.\\d{6}]"; // timestamp with ns + } else if (verbosity == "MEDIUM") { + regexString += "\\[\\d{2}:\\d{2}:\\d{2}]"; // timestamp without ns } - regexString += "\\[" + logLevel + "]"; // severity + regexString += "\\[" + logLevel + "]"; // severity - if (verbosity == "VERYHIGH") - { - regexString += "\\[.*:\\d{2}:.*]"; // file:line:function + if (verbosity == "VERYHIGH") { + regexString += "\\[.*:\\d{2}:.*]"; // file:line:function } regexString += "[ ]" + outputString + ".*"; @@ -189,7 +174,8 @@ class _TestFairLoggerBase : public T /* This is the derived class for the non-parameterized test cases. */ -class FairToolsTest : public _TestFairLoggerBase {}; +class FairToolsTest : public _TestFairLoggerBase +{}; /* This is the derived class for the parameterized test case diff --git a/test/fairtools/_TestFairTools.cxx b/test/fairtools/_TestFairTools.cxx index 1f61ee24cc..3010590077 100644 --- a/test/fairtools/_TestFairTools.cxx +++ b/test/fairtools/_TestFairTools.cxx @@ -1,65 +1,56 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ -#include "FairLogger.h" #include "FairCaptureOutput.h" +#include "FairLogger.h" #include "FairTestOutputHandler.h" -#include "gtest/gtest.h" #include "gtest/gtest-spi.h" +#include "gtest/gtest.h" +#include #include #include #include -#include #include -static const char* const LogString[] = { - "FATAL", "ERROR", "WARN", "INFO", - "DEBUG", "DEBUG1", "DEBUG2", "DEBUG3", "DEBUG4" -}; - -static const char* const TestLogs[] = { - "ERROR", "WARN", "INFO", - "DEBUG", "DEBUG1", "DEBUG2", "DEBUG3", "DEBUG4" -}; +static const char* const LogString[] = + {"FATAL", "ERROR", "WARN", "INFO", "DEBUG", "DEBUG1", "DEBUG2", "DEBUG3", "DEBUG4"}; -static const char* const VerbosityLevelArray[] = { - "LOW", "MEDIUM", "HIGH" -}; +static const char* const TestLogs[] = {"ERROR", "WARN", "INFO", "DEBUG", "DEBUG1", "DEBUG2", "DEBUG3", "DEBUG4"}; +static const char* const VerbosityLevelArray[] = {"LOW", "MEDIUM", "HIGH"}; TEST(FairToolsTestFatal, TestFatalError) { - FairLogger* fLogger; - fLogger = FairLogger::GetLogger(); - EXPECT_DEATH(fLogger->Fatal(MESSAGE_ORIGIN, "This is a fatal problem"), - "FATAL"); - // TODO: check if cored dump is written to file + FairLogger* fLogger; + fLogger = FairLogger::GetLogger(); + EXPECT_DEATH(fLogger->Fatal(MESSAGE_ORIGIN, "This is a fatal problem"), "FATAL"); + // TODO: check if cored dump is written to file } - // Base class to use the same basic setup for parameterized and // non-parameterized tests // Here one defines everything which is common for all the different // test cases -template class _TestFairLoggerBase : public T +template +class _TestFairLoggerBase : public T { protected: - std::string logLevelSettingToTest; std::string OutputString; FairLogger* fLogger; FairCaptureOutput handler; - virtual void SetUp() { - logLevelSettingToTest="INFO"; - OutputString = "I am here."; - fLogger = FairLogger::GetLogger(); - SetFairLoggerDefaultValues(); + virtual void SetUp() + { + logLevelSettingToTest = "INFO"; + OutputString = "I am here."; + fLogger = FairLogger::GetLogger(); + SetFairLoggerDefaultValues(); } /* @@ -71,323 +62,321 @@ template class _TestFairLoggerBase : public T // test to the SetUp function of the base class } */ - void SetFairLoggerDefaultValues() { - fLogger->SetLogToScreen(true); - fLogger->SetLogToFile(false); - fLogger->SetLogFileLevel("INFO"); - fLogger->SetLogScreenLevel("INFO"); - fLogger->SetLogVerbosityLevel("LOW"); + void SetFairLoggerDefaultValues() + { + fLogger->SetLogToScreen(true); + fLogger->SetLogToFile(false); + fLogger->SetLogFileLevel("INFO"); + fLogger->SetLogScreenLevel("INFO"); + fLogger->SetLogVerbosityLevel("LOW"); } - void LogNoArguments(FairLogger* fLogger, const std::string& OutputString) { - // Log same message for all log levels - fLogger->Error(MESSAGE_ORIGIN, OutputString.c_str()); - fLogger->Warning(MESSAGE_ORIGIN, OutputString.c_str()); - fLogger->Info(MESSAGE_ORIGIN, OutputString.c_str()); - fLogger->Debug(MESSAGE_ORIGIN, OutputString.c_str()); - fLogger->Debug1(MESSAGE_ORIGIN, OutputString.c_str()); - fLogger->Debug2(MESSAGE_ORIGIN, OutputString.c_str()); - fLogger->Debug3(MESSAGE_ORIGIN, OutputString.c_str()); - fLogger->Debug4(MESSAGE_ORIGIN, OutputString.c_str()); + void LogNoArguments(FairLogger* fLogger, const std::string& OutputString) + { + // Log same message for all log levels + fLogger->Error(MESSAGE_ORIGIN, OutputString.c_str()); + fLogger->Warning(MESSAGE_ORIGIN, OutputString.c_str()); + fLogger->Info(MESSAGE_ORIGIN, OutputString.c_str()); + fLogger->Debug(MESSAGE_ORIGIN, OutputString.c_str()); + fLogger->Debug1(MESSAGE_ORIGIN, OutputString.c_str()); + fLogger->Debug2(MESSAGE_ORIGIN, OutputString.c_str()); + fLogger->Debug3(MESSAGE_ORIGIN, OutputString.c_str()); + fLogger->Debug4(MESSAGE_ORIGIN, OutputString.c_str()); } - std::vector CreateExpectedOutputNoArguments(const std::string& loglevel, const std::string& outString, const std::string& filename = "") { - - //Put blanks to the string to have all strings the same length - int size = loglevel.size(); - int maxsize = 7; // length of string "WARNING" - for (int i=size; i levelNames(LogString, LogString+9); - std::vector::iterator position = - std::find(levelNames.begin(), levelNames.end(), loglevel); - levelNames.erase(position+1, levelNames.end()); - levelNames.erase(levelNames.begin()); // don't use FATAL loglevel in this test - - std::vector retVal; - std::string fullOutputString; - if ( filename.compare("") != 0) { - fullOutputString = "[INFO ] Openning log file: " + filename; - retVal.push_back(fullOutputString); - retVal.push_back(" "); - } - - std::vector::iterator iter; - for ( iter = levelNames.begin(); - iter < levelNames.end(); - iter++) { - fullOutputString = "[" + *iter + "] " + outString + " "; - retVal.push_back(fullOutputString); - } - - return retVal; + std::vector CreateExpectedOutputNoArguments(const std::string& loglevel, + const std::string& outString, + const std::string& filename = "") + { + + // Put blanks to the string to have all strings the same length + int size = loglevel.size(); + int maxsize = 7; // length of string "WARNING" + for (int i = size; i < maxsize; i++) { + loglevel += " "; + } + + std::vector levelNames(LogString, LogString + 9); + std::vector::iterator position = std::find(levelNames.begin(), levelNames.end(), loglevel); + levelNames.erase(position + 1, levelNames.end()); + levelNames.erase(levelNames.begin()); // don't use FATAL loglevel in this test + + std::vector retVal; + std::string fullOutputString; + if (filename.compare("") != 0) { + fullOutputString = "[INFO ] Openning log file: " + filename; + retVal.push_back(fullOutputString); + retVal.push_back(" "); + } + + std::vector::iterator iter; + for (iter = levelNames.begin(); iter < levelNames.end(); ++iter) { + fullOutputString = "[" + *iter + "] " + outString + " "; + retVal.push_back(fullOutputString); + } + + return retVal; } - std::vector CreateExpectedLogLevels(const std::string& loglevel) { + std::vector CreateExpectedLogLevels(const std::string& loglevel) + { - std::vector levelNames(TestLogs, TestLogs+8); - std::vector::iterator position = - std::find(levelNames.begin(), levelNames.end(), loglevel); - levelNames.erase(position+1, levelNames.end()); - return levelNames; + std::vector levelNames(TestLogs, TestLogs + 8); + std::vector::iterator position = std::find(levelNames.begin(), levelNames.end(), loglevel); + levelNames.erase(position + 1, levelNames.end()); + return levelNames; } - void CheckScreenOutput(FairCaptureOutput handler, const std::vector& v) { - int noLines = handler.GetNumberOfLines(); - int expectedNumberOfLines = v.size(); - EXPECT_EQ(expectedNumberOfLines,noLines); + void CheckScreenOutput(FairCaptureOutput handler, const std::vector& v) + { + int noLines = handler.GetNumberOfLines(); + int expectedNumberOfLines = v.size(); + EXPECT_EQ(expectedNumberOfLines, noLines); - int minLines = std::min(expectedNumberOfLines,noLines); + int minLines = std::min(expectedNumberOfLines, noLines); - for (int i = 0; i < minLines; ++i) { - EXPECT_EQ( v[i], handler.GetCaptureLine(i) ); - } + for (int i = 0; i < minLines; ++i) { + EXPECT_EQ(v[i], handler.GetCaptureLine(i)); + } } - void CheckFileOutput(FairTestOutputHandler handler, const std::vector& v) { - int noLines = handler.GetNumberOfLines(); - int expectedNumberOfLines = v.size(); - EXPECT_EQ(expectedNumberOfLines,noLines); + void CheckFileOutput(FairTestOutputHandler handler, const std::vector& v) + { + int noLines = handler.GetNumberOfLines(); + int expectedNumberOfLines = v.size(); + EXPECT_EQ(expectedNumberOfLines, noLines); - int minLines = std::min(expectedNumberOfLines,noLines); + int minLines = std::min(expectedNumberOfLines, noLines); - for (int i = 0; i < minLines; ++i) { - EXPECT_EQ( v[i], handler.GetCaptureLine(i) ); - } + for (int i = 0; i < minLines; ++i) { + EXPECT_EQ(v[i], handler.GetCaptureLine(i)); + } } - bool CheckVerboseOutput(std::string logLevel, std::string outputString, - std::string verboseLevel, std::string resultString - ) { - // Example Output for logging level INFO and different verbosity levels - // verbosity Level:Output - // LOW :[INFO ] I am here. - // MEDIUM :[INFO ] [_TestFairTools.cxx::LogNoArguments:78] I am here. - // HIGH :[INFO ] [05.12.2011 12:00:10] [_TestFairTools.cxx::LogNoArguments:78] I am here. - std::string regexString = "\\[" + logLevel + "[ ]*][ ]"; - if (verboseLevel.compare("HIGH") == 0) { - regexString = regexString + "\\[\\d{2}\\.\\d{2}\\.\\d{4}[ ]\\d{2}:\\d{2}:\\d{2}][ ]"; - regexString = regexString + "\\[.*::.*:\\d{2}][ ]"; - } - if (verboseLevel.compare("MEDIUM") == 0) { - regexString = regexString + "\\[.*::.*:\\d{2}][ ]"; - } - regexString = regexString + outputString + ".*"; - - const std::regex e(regexString); - return std::regex_match(resultString, e); + bool CheckVerboseOutput(const std::string& logLevel, + const std::string& outputString, + const std::string& verboseLevel, + const std::string& resultString) + { + // Example Output for logging level INFO and different verbosity levels + // verbosity Level:Output + // LOW :[INFO ] I am here. + // MEDIUM :[INFO ] [_TestFairTools.cxx::LogNoArguments:78] I am here. + // HIGH :[INFO ] [05.12.2011 12:00:10] [_TestFairTools.cxx::LogNoArguments:78] I am here. + std::string regexString = "\\[" + logLevel + "[ ]*][ ]"; + if (verboseLevel.compare("HIGH") == 0) { + regexString = regexString + "\\[\\d{2}\\.\\d{2}\\.\\d{4}[ ]\\d{2}:\\d{2}:\\d{2}][ ]"; + regexString = regexString + "\\[.*::.*:\\d{2}][ ]"; + } + if (verboseLevel.compare("MEDIUM") == 0) { + regexString = regexString + "\\[.*::.*:\\d{2}][ ]"; + } + regexString = regexString + outputString + ".*"; + + const std::regex e(regexString); + return std::regex_match(resultString, e); } }; // This is the derived class for the non-parameterized test cases. -class FairToolsTest : public _TestFairLoggerBase {}; +class FairToolsTest : public _TestFairLoggerBase +{}; // This is the derived class for the parameterized test cases. -class LogLevelTest : public _TestFairLoggerBase< - testing::TestWithParam > +class LogLevelTest : public _TestFairLoggerBase> { protected: - virtual void SetUp() { - logLevelSettingToTest=GetParam(); - OutputString = "I am here."; - fLogger = FairLogger::GetLogger(); - SetFairLoggerDefaultValues(); + virtual void SetUp() + { + logLevelSettingToTest = GetParam(); + OutputString = "I am here."; + fLogger = FairLogger::GetLogger(); + SetFairLoggerDefaultValues(); } }; -class VerbosityLevelTest : public _TestFairLoggerBase< - testing::TestWithParam > +class VerbosityLevelTest : public _TestFairLoggerBase> { protected: - virtual void SetUp() { - logLevelSettingToTest="INFO"; - verbosityLevel=GetParam(); - OutputString = "I am here."; - fLogger = FairLogger::GetLogger(); - SetFairLoggerDefaultValues(); + virtual void SetUp() + { + logLevelSettingToTest = "INFO"; + verbosityLevel = GetParam(); + OutputString = "I am here."; + fLogger = FairLogger::GetLogger(); + SetFairLoggerDefaultValues(); } std::string verbosityLevel; }; TEST_F(FairToolsTest, CheckDefaultSettings) { - handler.BeginCapture(); - LogNoArguments(fLogger, OutputString); - handler.EndCapture(); + handler.BeginCapture(); + LogNoArguments(fLogger, OutputString); + handler.EndCapture(); - std::vector v = CreateExpectedOutputNoArguments(logLevelSettingToTest, OutputString); - { - SCOPED_TRACE(logLevelSettingToTest); - CheckScreenOutput(handler, v); - } + std::vector v = CreateExpectedOutputNoArguments(logLevelSettingToTest, OutputString); + { + SCOPED_TRACE(logLevelSettingToTest); + CheckScreenOutput(handler, v); + } } - TEST_F(FairToolsTest, CheckOutputOnlyToFile) { - handler.BeginCapture(); + handler.BeginCapture(); - char fileName[25]; - tmpnam(fileName); - fLogger->SetLogFileName(fileName); - fLogger->SetLogToFile(true); - fLogger->SetLogToScreen(false); - LogNoArguments(fLogger, OutputString); + char fileName[25]; + tmpnam(fileName); + fLogger->SetLogFileName(fileName); + fLogger->SetLogToFile(true); + fLogger->SetLogToScreen(false); + LogNoArguments(fLogger, OutputString); - handler.EndCapture(); + handler.EndCapture(); - std::vector v = CreateExpectedOutputNoArguments(logLevelSettingToTest, OutputString); - FairTestOutputHandler outputhandler(fileName); - { - SCOPED_TRACE(logLevelSettingToTest); - CheckFileOutput(outputhandler, v); - } + std::vector v = CreateExpectedOutputNoArguments(logLevelSettingToTest, OutputString); + FairTestOutputHandler outputhandler(fileName); + { + SCOPED_TRACE(logLevelSettingToTest); + CheckFileOutput(outputhandler, v); + } } - TEST_F(FairToolsTest, CheckWrongLogLevelSettings) { - fLogger->SetLogToFile(false); - fLogger->SetLogToScreen(true); + fLogger->SetLogToFile(false); + fLogger->SetLogToScreen(true); - handler.BeginCapture(); - fLogger->SetLogScreenLevel("BLA"); - LogNoArguments(fLogger, OutputString); - handler.EndCapture(); + handler.BeginCapture(); + fLogger->SetLogScreenLevel("BLA"); + LogNoArguments(fLogger, OutputString); + handler.EndCapture(); - std::vector v = CreateExpectedOutputNoArguments(logLevelSettingToTest, OutputString); - std::string outString="Log level \"BLA\" not supported. Use default level \"INFO\"."; - std::vector::iterator it; - it = v.begin(); - it = v.insert ( it , outString ); + std::vector v = CreateExpectedOutputNoArguments(logLevelSettingToTest, OutputString); + std::string outString = "Log level \"BLA\" not supported. Use default level \"INFO\"."; + std::vector::iterator it; + it = v.begin(); + it = v.insert(it, outString); - { - SCOPED_TRACE(logLevelSettingToTest); - CheckScreenOutput(handler, v); - } + { + SCOPED_TRACE(logLevelSettingToTest); + CheckScreenOutput(handler, v); + } } TEST_F(FairToolsTest, CheckVerbosityLevelSettings) { - fLogger->SetLogToFile(false); - fLogger->SetLogToScreen(true); + fLogger->SetLogToFile(false); + fLogger->SetLogToScreen(true); - handler.BeginCapture(); - fLogger->SetLogVerbosityLevel("BLA"); - LogNoArguments(fLogger, OutputString); - handler.EndCapture(); + handler.BeginCapture(); + fLogger->SetLogVerbosityLevel("BLA"); + LogNoArguments(fLogger, OutputString); + handler.EndCapture(); - std::vector v = CreateExpectedOutputNoArguments(logLevelSettingToTest, OutputString); - std::string outString="Verbosity level \"BLA\" not supported. Use default level \"LOW\"."; - std::vector::iterator it; - it = v.begin(); - it = v.insert ( it , outString ); - - { - SCOPED_TRACE(logLevelSettingToTest); - CheckScreenOutput(handler, v); - } + std::vector v = CreateExpectedOutputNoArguments(logLevelSettingToTest, OutputString); + std::string outString = "Verbosity level \"BLA\" not supported. Use default level \"LOW\"."; + std::vector::iterator it; + it = v.begin(); + it = v.insert(it, outString); + { + SCOPED_TRACE(logLevelSettingToTest); + CheckScreenOutput(handler, v); + } } - TEST_F(FairToolsTest, testScreenAndFileOutputWithoutArgument) { - handler.BeginCapture(); + handler.BeginCapture(); - char fileName[25]; - tmpnam(fileName); - fLogger->SetLogFileName(fileName); - fLogger->SetLogToScreen(true); - fLogger->SetLogToFile(true); - LogNoArguments(fLogger, OutputString); + char fileName[25]; + tmpnam(fileName); + fLogger->SetLogFileName(fileName); + fLogger->SetLogToScreen(true); + fLogger->SetLogToFile(true); + LogNoArguments(fLogger, OutputString); - handler.EndCapture(); + handler.EndCapture(); - std::vector v = CreateExpectedOutputNoArguments(logLevelSettingToTest, OutputString, fileName); - { - SCOPED_TRACE(logLevelSettingToTest); - CheckScreenOutput(handler, v); - } + std::vector v = CreateExpectedOutputNoArguments(logLevelSettingToTest, OutputString, fileName); + { + SCOPED_TRACE(logLevelSettingToTest); + CheckScreenOutput(handler, v); + } - v = CreateExpectedOutputNoArguments(logLevelSettingToTest, OutputString); - FairTestOutputHandler outputhandler(fileName); + v = CreateExpectedOutputNoArguments(logLevelSettingToTest, OutputString); + FairTestOutputHandler outputhandler(fileName); - { - SCOPED_TRACE(logLevelSettingToTest); - CheckFileOutput(outputhandler, v); - } + { + SCOPED_TRACE(logLevelSettingToTest); + CheckFileOutput(outputhandler, v); + } } - - TEST_P(LogLevelTest, testAllLogLevelsToScreenAndFile) { - fLogger->SetLogFileLevel(logLevelSettingToTest.c_str()); - fLogger->SetLogScreenLevel(logLevelSettingToTest.c_str()); - - FairCaptureOutput handler(true, false); - handler.BeginCapture(); - char fileName[25]; - tmpnam(fileName); - fLogger->SetLogFileName(fileName); - fLogger->SetLogToScreen(true); - fLogger->SetLogToFile(true); - LogNoArguments(fLogger, OutputString); - handler.EndCapture(); - - std::vector v = CreateExpectedOutputNoArguments(logLevelSettingToTest, OutputString, fileName); - { - SCOPED_TRACE(logLevelSettingToTest); - CheckScreenOutput(handler, v); - } + fLogger->SetLogFileLevel(logLevelSettingToTest.c_str()); + fLogger->SetLogScreenLevel(logLevelSettingToTest.c_str()); + + FairCaptureOutput handler(true, false); + handler.BeginCapture(); + char fileName[25]; + tmpnam(fileName); + fLogger->SetLogFileName(fileName); + fLogger->SetLogToScreen(true); + fLogger->SetLogToFile(true); + LogNoArguments(fLogger, OutputString); + handler.EndCapture(); + + std::vector v = CreateExpectedOutputNoArguments(logLevelSettingToTest, OutputString, fileName); + { + SCOPED_TRACE(logLevelSettingToTest); + CheckScreenOutput(handler, v); + } - v = CreateExpectedOutputNoArguments(logLevelSettingToTest, OutputString); - FairTestOutputHandler outputhandler(fileName); - { - SCOPED_TRACE(logLevelSettingToTest); - CheckFileOutput(outputhandler, v); - } + v = CreateExpectedOutputNoArguments(logLevelSettingToTest, OutputString); + FairTestOutputHandler outputhandler(fileName); + { + SCOPED_TRACE(logLevelSettingToTest); + CheckFileOutput(outputhandler, v); + } } -INSTANTIATE_TEST_CASE_P(TestAllLogLevels, - LogLevelTest, - ::testing::ValuesIn(TestLogs)); +INSTANTIATE_TEST_CASE_P(TestAllLogLevels, LogLevelTest, ::testing::ValuesIn(TestLogs)); TEST_P(VerbosityLevelTest, testAllVerbosityLevelsToScreenAndFile) { - fLogger->SetLogVerbosityLevel(verbosityLevel.c_str()); + fLogger->SetLogVerbosityLevel(verbosityLevel.c_str()); - handler.BeginCapture(); + handler.BeginCapture(); - // char fileName[25]; - // tmpnam(fileName); - // fLogger->SetLogFileName(fileName); - fLogger->SetLogToScreen(true); - fLogger->SetLogToFile(false); - LogNoArguments(fLogger, OutputString); + // char fileName[25]; + // tmpnam(fileName); + // fLogger->SetLogFileName(fileName); + fLogger->SetLogToScreen(true); + fLogger->SetLogToFile(false); + LogNoArguments(fLogger, OutputString); - handler.EndCapture(); + handler.EndCapture(); - // std::vector v = CreateExpectedOutputNoArguments(logLevelSettingToTest, OutputString, fileName); - // std::vector v = CreateExpectedOutputNoArguments(logLevelSettingToTest, OutputString); - std::vector v = CreateExpectedLogLevels(logLevelSettingToTest); + // std::vector v = CreateExpectedOutputNoArguments(logLevelSettingToTest, OutputString, fileName); + // std::vector v = CreateExpectedOutputNoArguments(logLevelSettingToTest, OutputString); + std::vector v = CreateExpectedLogLevels(logLevelSettingToTest); + { + SCOPED_TRACE(logLevelSettingToTest); + int Lines = v.size(); - { - SCOPED_TRACE(logLevelSettingToTest); - int Lines = v.size(); - - for (int i = 0; i < Lines; ++i) { - EXPECT_TRUE( CheckVerboseOutput( v[i], OutputString, verbosityLevel, handler.GetCaptureLine(i) ) ); + for (int i = 0; i < Lines; ++i) { + EXPECT_TRUE(CheckVerboseOutput(v[i], OutputString, verbosityLevel, handler.GetCaptureLine(i))); + } } - } - /* + /* v = CreateExpectedOutputNoArguments(logLevelSettingToTest, OutputString); FairTestOutputHandler outputhandler(fileName); { @@ -399,11 +388,4 @@ TEST_P(VerbosityLevelTest, testAllVerbosityLevelsToScreenAndFile) // Switch this tests of for the time being, since they are not working - -INSTANTIATE_TEST_CASE_P(TestAllVerbosityLevels, - VerbosityLevelTest, - ::testing::ValuesIn(VerbosityLevelArray)); - - - - +INSTANTIATE_TEST_CASE_P(TestAllVerbosityLevels, VerbosityLevelTest, ::testing::ValuesIn(VerbosityLevelArray)); diff --git a/test/fairtools/test.cxx b/test/fairtools/test.cxx index e10014d113..a5a78a8b5b 100644 --- a/test/fairtools/test.cxx +++ b/test/fairtools/test.cxx @@ -7,20 +7,18 @@ ********************************************************************************/ #include "FairLogger.h" -#include +#include +#include #include #include -#include -#include +#include #include -#include //for sleep - -#include - +#include //for sleep +#include -//std::cout<<"Value: "<Info(MESSAGE_ORIGIN, "Value: %i", val); +// gLogger->Info(MESSAGE_ORIGIN, "Value: %i", val); /* std::cout<<"Das sollte schwarz sein."<Info(MESSAGE_ORIGIN, "Value: %i", val); - } + for (int i = 0; i < iterations; i++) { + Int_t val = i * i - (i - 1); + gLogger->Info(MESSAGE_ORIGIN, "Value: %i", val); + } } void logToLoggerCout(int iterations) { - for (int i=0; i < iterations; i++) { - Int_t val = i * i - (i-1); - LOG(info) << "Value: "<< val <<" "; - } + for (int i = 0; i < iterations; i++) { + Int_t val = i * i - (i - 1); + LOG(info) << "Value: " << val << " "; + } } void logToLoggerCoutTest(int iterations) { - for (int i=0; i < iterations; i++) { - Int_t val = i * i - (i-1); - LOG(info) << "Value: "<< val <<" "; - LOG(debug) << "Value: "<< val <<" "; - } + for (int i = 0; i < iterations; i++) { + Int_t val = i * i - (i - 1); + LOG(info) << "Value: " << val << " "; + LOG(debug) << "Value: " << val << " "; + } } void logTo(int) { -/* + /* for (int i=0; i < iterations; i++) { Int_t val = i * i - (i-1); } */ } -void setSyncOutput(bool decision) -{ - std::ios_base::sync_with_stdio(decision); -} +void setSyncOutput(bool decision) { std::ios_base::sync_with_stdio(decision); } void PrintHelpAndExit() { - std::cerr<<"Please call the program with the number of the test to run."< rtime, std::vector ctime) { - // Remove smallest and largest value - sort (rtime.begin(), rtime.end()); - rtime.erase(rtime.begin()); - rtime.pop_back(); - sort (ctime.begin(), ctime.end()); - ctime.erase(ctime.begin()); - ctime.pop_back(); - - Double_t ctime_sum = 0.0; - Double_t ctime_avg = 0.0; - Double_t rtime_sum = 0.0; - Double_t rtime_avg = 0.0; - for(unsigned int i = 0; i < rtime.size(); i++) { - rtime_sum += rtime.at(i); - ctime_sum += ctime.at(i); - } - - rtime_avg = rtime_sum/rtime.size(); - ctime_avg = ctime_sum/ctime.size(); + // Remove smallest and largest value + sort(rtime.begin(), rtime.end()); + rtime.erase(rtime.begin()); + rtime.pop_back(); + sort(ctime.begin(), ctime.end()); + ctime.erase(ctime.begin()); + ctime.pop_back(); + + Double_t ctime_sum = 0.0; + Double_t ctime_avg = 0.0; + Double_t rtime_sum = 0.0; + Double_t rtime_avg = 0.0; + for (unsigned int i = 0; i < rtime.size(); i++) { + rtime_sum += rtime.at(i); + ctime_sum += ctime.at(i); + } - Double_t ctime_min = *min_element(ctime.begin(),ctime.end()); - Double_t ctime_max = *max_element(ctime.begin(),ctime.end()); + rtime_avg = rtime_sum / rtime.size(); + ctime_avg = ctime_sum / ctime.size(); - // Double_t rtime_sum = accumulate(rtime.begin(), rtime.end(), 0); - // Double_t rtime_avg = rtime_sum/rtime.size(); - Double_t rtime_min = *min_element(rtime.begin(),rtime.end()); - Double_t rtime_max = *max_element(rtime.begin(),rtime.end()); - std::cout<<"Discarding the lowest and highest value the"<SetLogScreenLevel("BLA"); - //gLogger->SetLogToFile(false); - //gLogger->SetLogToScreen(false); - //gLogger->Fatal(MESSAGE_ORIGIN, "This is a fatal message."); - //LOG(info) << "This message should never be printed."; - //LOG(fatal) << "This is a fatal message"; - //exit(-42); + // gLogger->SetLogScreenLevel("BLA"); + // gLogger->SetLogToFile(false); + // gLogger->SetLogToScreen(false); + // gLogger->Fatal(MESSAGE_ORIGIN, "This is a fatal message."); + // LOG(info) << "This message should never be printed."; + // LOG(fatal) << "This is a fatal message"; + // exit(-42); - int iterations = 1000000; - int time_measurements = 12; + int iterations = 1000000; + int time_measurements = 12; - /* + /* for (int i=0; i < iterations; i++) { Int_t val = i * i - (i-1); printf("Value: %i\n",val); @@ -177,159 +168,155 @@ int main(int argc, char* argv[]) exit(0); */ - if (1 == argc) { - logToPrintf(iterations); - std::cout << "Using printf for output"< rtime; - std::vector ctime; - - switch (x) { - case 1: - for (int meas = 0; meas < time_measurements; meas++) { - timer.Start(); - logToPrintf(iterations); - timer.Stop(); - rtime.push_back(timer.RealTime()); - ctime.push_back(timer.CpuTime()); - sleep(4); - } - doCalculation(rtime, ctime); - std::cout << "Using printf for output"<SetColoredLog(false); - //gLogger->SetLogToFile(true); - //gLogger->SetLogToScreen(false); + if (2 < argc) { + PrintHelpAndExit(); + } + int x = atoi(argv[1]); + + TStopwatch timer; + std::vector rtime; + std::vector ctime; + + switch (x) { + case 1: + for (int meas = 0; meas < time_measurements; meas++) { + timer.Start(); + logToPrintf(iterations); + timer.Stop(); + rtime.push_back(timer.RealTime()); + ctime.push_back(timer.CpuTime()); + sleep(4); + } + doCalculation(rtime, ctime); + std::cout << "Using printf for output" << std::endl; + break; + case 2: + for (int meas = 0; meas < time_measurements; meas++) { + timer.Start(); + logToCout(iterations); + timer.Stop(); + rtime.push_back(timer.RealTime()); + ctime.push_back(timer.CpuTime()); + sleep(4); + } + doCalculation(rtime, ctime); + std::cout << "Using syncronised cout for output" << std::endl; + break; + case 3: + setSyncOutput(false); + for (int meas = 0; meas < time_measurements; meas++) { + timer.Start(); + logToCout(iterations); + timer.Stop(); + rtime.push_back(timer.RealTime()); + ctime.push_back(timer.CpuTime()); + sleep(4); + } + doCalculation(rtime, ctime); + std::cout << "Using non syncronised cout for output" << std::endl; + break; + case 4: + for (int meas = 0; meas < time_measurements; meas++) { + timer.Start(); + logToCerr(iterations); + timer.Stop(); + rtime.push_back(timer.RealTime()); + ctime.push_back(timer.CpuTime()); + sleep(4); + } + doCalculation(rtime, ctime); + std::cout << "Using syncronised cerr for output" << std::endl; + break; + case 5: + setSyncOutput(false); + for (int meas = 0; meas < time_measurements; meas++) { + timer.Start(); + logToCerr(iterations); + timer.Stop(); + rtime.push_back(timer.RealTime()); + ctime.push_back(timer.CpuTime()); + sleep(4); + } + doCalculation(rtime, ctime); + std::cout << "Using non syncronised cerr for output" << std::endl; + break; + case 6: + for (int meas = 0; meas < time_measurements; meas++) { + timer.Start(); + logToLoggerPrintf(iterations); + timer.Stop(); + rtime.push_back(timer.RealTime()); + ctime.push_back(timer.CpuTime()); + sleep(4); + } + doCalculation(rtime, ctime); + std::cout << "Using logger printf output" << std::endl; + break; + case 7: + for (int meas = 0; meas < time_measurements; meas++) { + timer.Start(); + logToLoggerCout(iterations); + timer.Stop(); + rtime.push_back(timer.RealTime()); + ctime.push_back(timer.CpuTime()); + sleep(4); + } + doCalculation(rtime, ctime); + std::cout << "Using logger cout output" << std::endl; + break; + case 8: + setSyncOutput(false); + for (int meas = 0; meas < time_measurements; meas++) { + timer.Start(); + logToLoggerPrintf(iterations); + timer.Stop(); + rtime.push_back(timer.RealTime()); + ctime.push_back(timer.CpuTime()); + sleep(4); + } + doCalculation(rtime, ctime); + std::cout << "Using logger printf output" << std::endl; + break; + case 9: + setSyncOutput(false); + for (int meas = 0; meas < time_measurements; meas++) { + timer.Start(); + logToLoggerCout(iterations); + timer.Stop(); + rtime.push_back(timer.RealTime()); + ctime.push_back(timer.CpuTime()); + sleep(4); + } + doCalculation(rtime, ctime); + std::cout << "Using logger cout output" << std::endl; + break; + case 10: + setSyncOutput(false); + for (int meas = 0; meas < time_measurements; meas++) { + timer.Start(); + logToLoggerCoutTest(iterations / 2); + timer.Stop(); + rtime.push_back(timer.RealTime()); + ctime.push_back(timer.CpuTime()); + sleep(4); + } + doCalculation(rtime, ctime); + std::cout << "Using logger cout output" << std::endl; + break; + default: + std::cout << "Option Unknown" << std::endl; + PrintHelpAndExit(); + } + // std::ios_base::sync_with_stdio(false); + // gLogger->SetColoredLog(false); + // gLogger->SetLogToFile(true); + // gLogger->SetLogToScreen(false); } diff --git a/test/testlib/FairCaptureOutputNew.cxx b/test/testlib/FairCaptureOutputNew.cxx index 99ff82df55..3c6f9d5d07 100644 --- a/test/testlib/FairCaptureOutputNew.cxx +++ b/test/testlib/FairCaptureOutputNew.cxx @@ -1,69 +1,59 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "FairCaptureOutputNew.h" #include - #include -FairCaptureOutputNew::FairCaptureOutputNew( bool captureStdErr, bool captureStdOut ) - : fLineVector(), - fCaptureStdOut(captureStdOut), - fCaptureStdErr(captureStdErr) -{ -} +FairCaptureOutputNew::FairCaptureOutputNew(bool captureStdErr, bool captureStdOut) + : fLineVector() + , fCaptureStdOut(captureStdOut) + , fCaptureStdErr(captureStdErr) +{} -FairCaptureOutputNew::~FairCaptureOutputNew() -{ -} +FairCaptureOutputNew::~FairCaptureOutputNew() {} void FairCaptureOutputNew::BeginCapture() { - if (fCaptureStdOut && fCaptureStdErr) { - std::cout << "Can't capture stdout and stderr at the same time." << std::endl; - exit(1); - } - if (fCaptureStdOut) { - // TODO: reimplement these tests via GTest function EXPECT_WRITE - // testing::internal::CaptureStdout(); - } - if (fCaptureStdErr) { - // TODO: reimplement these tests via GTest function EXPECT_WRITE - // testing::internal::CaptureStderr(); - } + if (fCaptureStdOut && fCaptureStdErr) { + std::cout << "Can't capture stdout and stderr at the same time." << std::endl; + exit(1); + } + if (fCaptureStdOut) { + // TODO: reimplement these tests via GTest function EXPECT_WRITE + // testing::internal::CaptureStdout(); + } + if (fCaptureStdErr) { + // TODO: reimplement these tests via GTest function EXPECT_WRITE + // testing::internal::CaptureStderr(); + } } void FairCaptureOutputNew::EndCapture() { - std::string tmpOutput; - if (fCaptureStdOut) { - // TODO: reimplement these tests via GTest function EXPECT_WRITE - // tmpOutput = testing::internal::GetCapturedStdout(); - } - if (fCaptureStdErr) { - // TODO: reimplement these tests via GTest function EXPECT_WRITE - // tmpOutput = testing::internal::GetCapturedStderr(); - } - - const std::string& sep = "\n"; - std::size_t start = 0, end = 0; - while ((end = tmpOutput.find(sep, start)) != std::string::npos) { - fLineVector.push_back(tmpOutput.substr(start, end - start)); - start = end + 1; - } + std::string tmpOutput; + if (fCaptureStdOut) { + // TODO: reimplement these tests via GTest function EXPECT_WRITE + // tmpOutput = testing::internal::GetCapturedStdout(); + } + if (fCaptureStdErr) { + // TODO: reimplement these tests via GTest function EXPECT_WRITE + // tmpOutput = testing::internal::GetCapturedStderr(); + } + + const std::string& sep = "\n"; + std::size_t start = 0, end = 0; + while ((end = tmpOutput.find(sep, start)) != std::string::npos) { + fLineVector.push_back(tmpOutput.substr(start, end - start)); + start = end + 1; + } } -std::string FairCaptureOutputNew::GetCaptureLine(int line) -{ - return fLineVector[line]; -} +std::string FairCaptureOutputNew::GetCaptureLine(int line) { return fLineVector[line]; } -int FairCaptureOutputNew::GetNumberOfLines() -{ - return fLineVector.size(); -} +int FairCaptureOutputNew::GetNumberOfLines() { return fLineVector.size(); } diff --git a/test/testlib/FairCaptureOutputNew.h b/test/testlib/FairCaptureOutputNew.h index 2a6bc11ee8..7436e5e7dc 100644 --- a/test/testlib/FairCaptureOutputNew.h +++ b/test/testlib/FairCaptureOutputNew.h @@ -25,7 +25,7 @@ class FairCaptureOutputNew int GetNumberOfLines(); private: - std::vector fLineVector; + std::vector fLineVector; bool fCaptureStdOut; bool fCaptureStdErr; diff --git a/test/testlib/FairTestOutputHandler.cxx b/test/testlib/FairTestOutputHandler.cxx index 9b6b646ba1..db42540cfd 100644 --- a/test/testlib/FairTestOutputHandler.cxx +++ b/test/testlib/FairTestOutputHandler.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #include "FairTestOutputHandler.h" @@ -10,63 +10,58 @@ #include FairTestOutputHandler::FairTestOutputHandler(const std::string& filename) - : fFileName(filename), - fFileContent(), - fFileContentIterator(), - fNumberOfLines(0), - fFileAlreadyRead(false) -{ -} + : fFileName(filename) + , fFileContent() + , fFileContentIterator() + , fNumberOfLines(0) + , fFileAlreadyRead(false) +{} FairTestOutputHandler::FairTestOutputHandler() - : fFileName(), - fFileContent(), - fFileContentIterator(), - fNumberOfLines(0), - fFileAlreadyRead(false) -{ -} + : fFileName() + , fFileContent() + , fFileContentIterator() + , fNumberOfLines(0) + , fFileAlreadyRead(false) +{} -FairTestOutputHandler::~FairTestOutputHandler() -{ - remove(fFileName.c_str()); -} +FairTestOutputHandler::~FairTestOutputHandler() { remove(fFileName.c_str()); } void FairTestOutputHandler::SetFileName(const std::string& filename) { - fFileName = filename; - fFileContent.clear(); - fNumberOfLines = 0; - fFileAlreadyRead =false; + fFileName = filename; + fFileContent.clear(); + fNumberOfLines = 0; + fFileAlreadyRead = false; } int FairTestOutputHandler::GetNumberOfLines() { - ReadContentFromFile(); - return fNumberOfLines; + ReadContentFromFile(); + return fNumberOfLines; } void FairTestOutputHandler::ReadContentFromFile() { - if ( !fFileAlreadyRead ) { - fFileContent.clear(); - fNumberOfLines = 0; + if (!fFileAlreadyRead) { + fFileContent.clear(); + fNumberOfLines = 0; - std::ifstream ifs(fFileName.c_str()); - std::string line; + std::ifstream ifs(fFileName.c_str()); + std::string line; - while( getline( ifs, line ) ) { - fFileContent.push_back( line ); - ++fNumberOfLines; + while (getline(ifs, line)) { + fFileContent.push_back(line); + ++fNumberOfLines; + } + fFileAlreadyRead = true; } - fFileAlreadyRead = true; - } } std::string FairTestOutputHandler::GetCaptureLine(int line) { - ReadContentFromFile(); + ReadContentFromFile(); - return fFileContent[line]; + return fFileContent[line]; } diff --git a/test/testlib/FairTestOutputHandler.h b/test/testlib/FairTestOutputHandler.h index cab92acc07..21db239a86 100644 --- a/test/testlib/FairTestOutputHandler.h +++ b/test/testlib/FairTestOutputHandler.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRTESTOUTPUTHANDLER_H_ diff --git a/trackbase/FairGeaneUtil.cxx b/trackbase/FairGeaneUtil.cxx index 5069fb35c2..e2e074a0d1 100644 --- a/trackbase/FairGeaneUtil.cxx +++ b/trackbase/FairGeaneUtil.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------ @@ -11,1838 +11,1912 @@ // ------------------------------------------------------------------ #include "FairGeaneUtil.h" -#include // for Sqrt, Cos, Sin, Power, sqrt, etc -#include // for Abs, Sign -#include // for TMatrixT, etc -#include // for TMatrixTBase -#include // for TMatrixTRow - -#include // for memset -#include // for pow +#include // for Sqrt, Cos, Sin, Power, sqrt, etc +#include // for Abs, Sign +#include // for TMatrixT, etc +#include // for TMatrixTBase +#include // for TMatrixTRow +#include // for pow +#include // for memset using namespace std; -FairGeaneUtil::FairGeaneUtil() : TObject() { } +FairGeaneUtil::FairGeaneUtil() + : TObject() +{} -FairGeaneUtil::~FairGeaneUtil() { } +FairGeaneUtil::~FairGeaneUtil() {} -void FairGeaneUtil::FromPtToSC(Double_t PC[3], Double_t RC[15], +void FairGeaneUtil::FromPtToSC(Double_t PC[3], + Double_t RC[15], // output - Double_t* PD, Double_t* RD, Int_t& IERR) + Double_t* PD, + Double_t* RD, + Int_t& IERR) { -// ------------------------------------------------------------- -// -// TRANSFORM ERROR MATRIX -// -// FROM SC VARIABLES (q/Pt,LAMBDA,PHI,YT,ZT) -// FROM SC VARIABLES (q/P,LAMBDA,PHI,YT,ZT) -// -// INPUT -// CH Charge of the paticle -// PC[3] (q/Pt, Lambda, Phi, Yt, Zt) -// RC[15] error matrix in upper triangular form -// -// OUTPUT -// PD[3] (q/P, Lambda, Phi, Yt, Zt) -// RD[15] error matrix in upper triangular form -// IERR =1 when track is perp to X-axis of Master -// -// Author EMC Collaboration -// Translated in C/Rot by A. Rotondi (June 2007) -// -// ------------------------------------------------------------------- - - Double_t A[5][5], S[15], COSL, SINL; - Double_t Vec[25]; - - IERR = 0; - memset(RD,0,sizeof(*RD)); - - COSL = cos(PC[1]); - - if(TMath::Abs(COSL) < 1.e-7) { - IERR =1; - return; - } - - SINL = sin(PC[1]); - - PD[0] = PC[0]*COSL; - PD[1] = PC[1]; - PD[2] = PC[2]; - - - for(Int_t I=0; I<5; I++) { - for(Int_t K=0; K<5; K++) { - A[I][K]=0.; - } - } - - // copy input in an internal vector S - for(Int_t I=0; I<15; I++) { S[I]=RC[I]; } - - A[0][0] = COSL; - A[1][1] = 1.0; - A[2][2] = 1.0; - A[3][3] = 1.0; - A[4][4] = 1.0; - - A[0][1] = -PC[0]*SINL; - - // transformation - FromMatToVec(A,Vec); - SymmProd(Vec,S,S); - - // copy the result in S in the output vector - for(Int_t I=0; I<15; I++) { RD[I]=S[I]; } + // ------------------------------------------------------------- + // + // TRANSFORM ERROR MATRIX + // + // FROM SC VARIABLES (q/Pt,LAMBDA,PHI,YT,ZT) + // FROM SC VARIABLES (q/P,LAMBDA,PHI,YT,ZT) + // + // INPUT + // CH Charge of the paticle + // PC[3] (q/Pt, Lambda, Phi, Yt, Zt) + // RC[15] error matrix in upper triangular form + // + // OUTPUT + // PD[3] (q/P, Lambda, Phi, Yt, Zt) + // RD[15] error matrix in upper triangular form + // IERR =1 when track is perp to X-axis of Master + // + // Author EMC Collaboration + // Translated in C/Rot by A. Rotondi (June 2007) + // + // ------------------------------------------------------------------- + + Double_t A[5][5], S[15], COSL, SINL; + Double_t Vec[25]; + + IERR = 0; + memset(RD, 0, sizeof(*RD)); + + COSL = cos(PC[1]); + + if (TMath::Abs(COSL) < 1.e-7) { + IERR = 1; + return; + } + + SINL = sin(PC[1]); + + PD[0] = PC[0] * COSL; + PD[1] = PC[1]; + PD[2] = PC[2]; + + for (Int_t I = 0; I < 5; I++) { + for (Int_t K = 0; K < 5; K++) { + A[I][K] = 0.; + } + } + + // copy input in an internal vector S + for (Int_t I = 0; I < 15; I++) { + S[I] = RC[I]; + } + + A[0][0] = COSL; + A[1][1] = 1.0; + A[2][2] = 1.0; + A[3][3] = 1.0; + A[4][4] = 1.0; + + A[0][1] = -PC[0] * SINL; + + // transformation + FromMatToVec(A, Vec); + SymmProd(Vec, S, S); + + // copy the result in S in the output vector + for (Int_t I = 0; I < 15; I++) { + RD[I] = S[I]; + } } -void FairGeaneUtil::FromPtToSD(Double_t PD[3], Double_t RD[15], Double_t H[3], Int_t CH, - Double_t SPU, Double_t DJ[3], Double_t DK[3], +void FairGeaneUtil::FromPtToSD(Double_t PD[3], + Double_t RD[15], + Double_t H[3], + Int_t CH, + Double_t SPU, + Double_t DJ[3], + Double_t DK[3], // output - Int_t& IERR, Double_t* PC, Double_t* RC) + Int_t& IERR, + Double_t* PC, + Double_t* RC) { -// -// ************************************************************************** -// -// *** TRANSFORMS ERROR MATRIX -// FROM VARIABLES (q/Pt,V',W',V,W) -// FROM VARIABLES (q/P, V',W',V,W) -// -// input -// PD[3] (q/P, Lambda, Phi, Yt, Zt) -// RD[15] error matrix in upper triangular form -// H[3] magnetic field -// CH CHARGE OF PARTICLE -// CHARGE AND MAGNETIC FIELD ARE NEEDED -// FOR CORRELATION TERMS (V',YT),(V',ZT),(W',YT),(W',ZT) -// THESE CORRELATION TERMS APPEAR BECAUSE RC IS ASSUMED -// TO BE THE ERROR MATRIX FOR FIXED S (PATH LENGTH) -// AND RD FOR FIXED U -// SPU SIGN OF U-COMPONENT OF PARTICLE MOMENTUM -// spu = sign[p·(DJ x DK)] -// DJ[3] UNIT VECTOR IN V-DIRECTION -// DK[3] UNIT VECTOR IN W-DIRECTION OF DETECTOR SYSTEM -// -// output -// PC[3] (q/Pt, Lambda, Phi, Yt, Zt) -// RC[15] error matrix in upper triangular form -// IERR =1 when track is perp to X-axis of Master -// -// Author EMC Collaboration -// Translated in C/Rot by A. Rotondi (June 2007) -// -// ------------------------------------------------------------------- -// - - - - Double_t A[5][5], S[15], TN[3], COSL, SINL, COSL1; - - Double_t PM, HM, UN[3], VN[3], DI[3], TVW[3]; - Double_t /* UJ, */ /* UK, */ VJ, VK, HA, HAM, Q, SINZ/* , COSZ */; - - Double_t CFACT8 = 2.997925e-04; - - Double_t Vec[25]; - - - // ------------------------------------------------------------------ - - IERR=0; - TVW[0]=1./TMath::Sqrt(1.+PD[1]*PD[1]+PD[2]*PD[2]); - if(SPU < 0.) { TVW[0]=-TVW[0]; } - TVW[1]=PD[1]*TVW[0]; - TVW[2]=PD[2]*TVW[0]; - - DI[0]=DJ[1]*DK[2]-DJ[2]*DK[1]; - DI[1]=DJ[2]*DK[0]-DJ[0]*DK[2]; - DI[2]=DJ[0]*DK[1]-DJ[1]*DK[0]; - - for(Int_t I=0; I<3; I++) { - TN[I]=TVW[0]*DI[I]+TVW[1]*DJ[I]+TVW[2]*DK[I]; - } - - COSL=TMath::Sqrt(TMath::Abs(1.-TN[2]*TN[2])); - if(COSL < 1.e-30) { COSL = 1.e-30; } - COSL1=1./COSL; - SINL = TN[2]; - - PC[0]=PD[0]*COSL; - PC[1]=PD[1]; - PC[2]=PD[2]; - PM=PC[0]; - - if(TMath::Abs (TN[0]) < 1.E-30) { TN[0] = 1.e-30; } - - UN[0]=-TN[1]*COSL1; - UN[1]=TN[0]*COSL1; - UN[2]=0.; - - VN[0]=-TN[2]*UN[1]; - VN[1]=TN[2]*UN[0]; - VN[2]=COSL; - - // UJ=UN[0]*DJ[0]+UN[1]*DJ[1]+UN[2]*DJ[2]; - // UK=UN[0]*DK[0]+UN[1]*DK[1]+UN[2]*DK[2]; - VJ=VN[0]*DJ[0]+VN[1]*DJ[1]+VN[2]*DJ[2]; - VK=VN[0]*DK[0]+VN[1]*DK[1]+VN[2]*DK[2]; - - - for(Int_t I=0; I<5; I++) { - for(Int_t K=0; K<5; K++) { - A[I][K]=0.; - } - } - - // copy input in an internal vector S - for(Int_t I=0; I<15; I++) { S[I]=RD[I]; } - - if(CH != 0.) { - HA=TMath::Sqrt(H[0]*H[0]+H[1]*H[1]+H[2]*H[2]); - HAM=HA*PM; - if(HAM != 0.) { - HM=CH/HA; - - Q=-HAM*CFACT8; - - SINZ=-(H[0]*UN[0]+H[1]*UN[1]+H[2]*UN[2])*HM; - // COSZ= (H[0]*VN[0]+H[1]*VN[1]+H[2]*VN[2])*HM; - A[0][3] = Q*TVW[1]*SINZ*(SINL*PD[0]); - A[0][4] = Q*TVW[2]*SINZ*(SINL*PD[0]); + // + // ************************************************************************** + // + // *** TRANSFORMS ERROR MATRIX + // FROM VARIABLES (q/Pt,V',W',V,W) + // FROM VARIABLES (q/P, V',W',V,W) + // + // input + // PD[3] (q/P, Lambda, Phi, Yt, Zt) + // RD[15] error matrix in upper triangular form + // H[3] magnetic field + // CH CHARGE OF PARTICLE + // CHARGE AND MAGNETIC FIELD ARE NEEDED + // FOR CORRELATION TERMS (V',YT),(V',ZT),(W',YT),(W',ZT) + // THESE CORRELATION TERMS APPEAR BECAUSE RC IS ASSUMED + // TO BE THE ERROR MATRIX FOR FIXED S (PATH LENGTH) + // AND RD FOR FIXED U + // SPU SIGN OF U-COMPONENT OF PARTICLE MOMENTUM + // spu = sign[p·(DJ x DK)] + // DJ[3] UNIT VECTOR IN V-DIRECTION + // DK[3] UNIT VECTOR IN W-DIRECTION OF DETECTOR SYSTEM + // + // output + // PC[3] (q/Pt, Lambda, Phi, Yt, Zt) + // RC[15] error matrix in upper triangular form + // IERR =1 when track is perp to X-axis of Master + // + // Author EMC Collaboration + // Translated in C/Rot by A. Rotondi (June 2007) + // + // ------------------------------------------------------------------- + // + + Double_t A[5][5], S[15], TN[3], COSL, SINL, COSL1; + + Double_t PM, HM, UN[3], VN[3], DI[3], TVW[3]; + Double_t /* UJ, */ /* UK, */ VJ, VK, HA, HAM, Q, SINZ /* , COSZ */; + + Double_t CFACT8 = 2.997925e-04; + + Double_t Vec[25]; + + // ------------------------------------------------------------------ + + IERR = 0; + TVW[0] = 1. / TMath::Sqrt(1. + PD[1] * PD[1] + PD[2] * PD[2]); + if (SPU < 0.) { + TVW[0] = -TVW[0]; } - } + TVW[1] = PD[1] * TVW[0]; + TVW[2] = PD[2] * TVW[0]; - A[0][0] = COSL; - A[1][1] = 1.; - A[2][2] = 1.; - A[3][3] = 1.; - A[4][4] = 1.; + DI[0] = DJ[1] * DK[2] - DJ[2] * DK[1]; + DI[1] = DJ[2] * DK[0] - DJ[0] * DK[2]; + DI[2] = DJ[0] * DK[1] - DJ[1] * DK[0]; - A[0][1] = -TVW[0]*VJ*(SINL*PD[0]); - A[0][2] = -TVW[0]*VK*(SINL*PD[0]); + for (Int_t I = 0; I < 3; I++) { + TN[I] = TVW[0] * DI[I] + TVW[1] * DJ[I] + TVW[2] * DK[I]; + } + COSL = TMath::Sqrt(TMath::Abs(1. - TN[2] * TN[2])); + if (COSL < 1.e-30) { + COSL = 1.e-30; + } + COSL1 = 1. / COSL; + SINL = TN[2]; - // transformation - FromMatToVec(A,Vec); - SymmProd(Vec,S,S); + PC[0] = PD[0] * COSL; + PC[1] = PD[1]; + PC[2] = PD[2]; + PM = PC[0]; - // copy the result in S in the output vector - for(Int_t I=0; I<15; I++) { RC[I]=S[I]; } -} + if (TMath::Abs(TN[0]) < 1.E-30) { + TN[0] = 1.e-30; + } + + UN[0] = -TN[1] * COSL1; + UN[1] = TN[0] * COSL1; + UN[2] = 0.; + + VN[0] = -TN[2] * UN[1]; + VN[1] = TN[2] * UN[0]; + VN[2] = COSL; + + // UJ=UN[0]*DJ[0]+UN[1]*DJ[1]+UN[2]*DJ[2]; + // UK=UN[0]*DK[0]+UN[1]*DK[1]+UN[2]*DK[2]; + VJ = VN[0] * DJ[0] + VN[1] * DJ[1] + VN[2] * DJ[2]; + VK = VN[0] * DK[0] + VN[1] * DK[1] + VN[2] * DK[2]; + + for (Int_t I = 0; I < 5; I++) { + for (Int_t K = 0; K < 5; K++) { + A[I][K] = 0.; + } + } + + // copy input in an internal vector S + for (Int_t I = 0; I < 15; I++) { + S[I] = RD[I]; + } + + if (CH != 0.) { + HA = TMath::Sqrt(H[0] * H[0] + H[1] * H[1] + H[2] * H[2]); + HAM = HA * PM; + if (HAM != 0.) { + HM = CH / HA; + Q = -HAM * CFACT8; -void FairGeaneUtil::FromSCToPt(Double_t PC[3], Double_t RC[15], + SINZ = -(H[0] * UN[0] + H[1] * UN[1] + H[2] * UN[2]) * HM; + // COSZ= (H[0]*VN[0]+H[1]*VN[1]+H[2]*VN[2])*HM; + A[0][3] = Q * TVW[1] * SINZ * (SINL * PD[0]); + A[0][4] = Q * TVW[2] * SINZ * (SINL * PD[0]); + } + } + + A[0][0] = COSL; + A[1][1] = 1.; + A[2][2] = 1.; + A[3][3] = 1.; + A[4][4] = 1.; + + A[0][1] = -TVW[0] * VJ * (SINL * PD[0]); + A[0][2] = -TVW[0] * VK * (SINL * PD[0]); + + // transformation + FromMatToVec(A, Vec); + SymmProd(Vec, S, S); + + // copy the result in S in the output vector + for (Int_t I = 0; I < 15; I++) { + RC[I] = S[I]; + } +} + +void FairGeaneUtil::FromSCToPt(Double_t PC[3], + Double_t RC[15], // output - Double_t* PD, Double_t* RD, Int_t& IERR) + Double_t* PD, + Double_t* RD, + Int_t& IERR) { -// ------------------------------------------------------------- -// -// TRANSFORM ERROR MATRIX -// -// FROM SC VARIABLES (q/P,LAMBDA,PHI,YT,ZT) -// FROM SC VARIABLES (q/Pt,LAMBDA,PHI,YT,ZT) -// -// INPUT -// PC[3] (q/P, Lambda, Phi, Yt, Zt) -// RC[15] error matrix in upper triangular form -// -// OUTPUT -// PD[3] (q/Pt, Lambda, Phi, Yt, Zt) -// RD[15] error matrix in upper triangular form -// IERR =1 when track is perp to X-axis of Master -// -// Author EMC Collaboration -// Translated in C/Rot by A. Rotondi (June 2007) -// -// ------------------------------------------------------------------- - - - Double_t A[5][5], S[15], COSL, COSL1; - Double_t TANL; - Double_t Vec[25]; - - IERR = 0; - memset(RD,0,sizeof(*RD)); - - COSL = cos(PC[1]); - if(TMath::Abs(COSL) < 1.e-7) { - IERR = 1; - return; - } - COSL1 = 1./COSL; - TANL = tan(PC[1]); - - PD[0] = PC[0]*COSL1; - PD[1] = PC[1]; - PD[2] = PC[2]; - - for(Int_t I=0; I<5; I++) { - for(Int_t K=0; K<5; K++) { - A[I][K]=0.; - } - } - - // copy input in an internal vector S - for(Int_t I=0; I<15; I++) { S[I]=RC[I]; } - - A[0][0] = COSL1; - A[1][1] = 1.0; - A[2][2] = 1.0; - A[3][3] = 1.0; - A[4][4] = 1.0; - - A[0][1] = PD[0]*TANL; - - // transformation - FromMatToVec(A,Vec); - SymmProd(Vec,S,S); - - // copy the result in S in the output vector - for(Int_t I=0; I<15; I++) { RD[I]=S[I]; } + // ------------------------------------------------------------- + // + // TRANSFORM ERROR MATRIX + // + // FROM SC VARIABLES (q/P,LAMBDA,PHI,YT,ZT) + // FROM SC VARIABLES (q/Pt,LAMBDA,PHI,YT,ZT) + // + // INPUT + // PC[3] (q/P, Lambda, Phi, Yt, Zt) + // RC[15] error matrix in upper triangular form + // + // OUTPUT + // PD[3] (q/Pt, Lambda, Phi, Yt, Zt) + // RD[15] error matrix in upper triangular form + // IERR =1 when track is perp to X-axis of Master + // + // Author EMC Collaboration + // Translated in C/Rot by A. Rotondi (June 2007) + // + // ------------------------------------------------------------------- + + Double_t A[5][5], S[15], COSL, COSL1; + Double_t TANL; + Double_t Vec[25]; + + IERR = 0; + memset(RD, 0, sizeof(*RD)); + + COSL = cos(PC[1]); + if (TMath::Abs(COSL) < 1.e-7) { + IERR = 1; + return; + } + COSL1 = 1. / COSL; + TANL = tan(PC[1]); + + PD[0] = PC[0] * COSL1; + PD[1] = PC[1]; + PD[2] = PC[2]; + + for (Int_t I = 0; I < 5; I++) { + for (Int_t K = 0; K < 5; K++) { + A[I][K] = 0.; + } + } + + // copy input in an internal vector S + for (Int_t I = 0; I < 15; I++) { + S[I] = RC[I]; + } + + A[0][0] = COSL1; + A[1][1] = 1.0; + A[2][2] = 1.0; + A[3][3] = 1.0; + A[4][4] = 1.0; + A[0][1] = PD[0] * TANL; + + // transformation + FromMatToVec(A, Vec); + SymmProd(Vec, S, S); + + // copy the result in S in the output vector + for (Int_t I = 0; I < 15; I++) { + RD[I] = S[I]; + } } -void FairGeaneUtil::FromSCToSD(Double_t PC[3], Double_t RC[15], Double_t H[3], Int_t CH, - Double_t DJ[3], Double_t DK[3], +void FairGeaneUtil::FromSCToSD(Double_t PC[3], + Double_t RC[15], + Double_t H[3], + Int_t CH, + Double_t DJ[3], + Double_t DK[3], // output - Int_t& IERR, Double_t& SPU, - Double_t* PD, Double_t* RD) + Int_t& IERR, + Double_t& SPU, + Double_t* PD, + Double_t* RD) { -// ---------------------------------------------------------------------- -// Transform Error Matrix -// FROM SC (transverse system) VARIABLES (q/P,LAMBDA,PHI,YT,ZT) -// TO SD (detector system) VARIABLES (q/P,V',W',V,W) - -// Authors: A. Haas and W. Wittek -// Translated in CRoot by A. Rotondi and A. Fontana June 2007 - -// INPUT -// PC(3) q/P,LAMBDA,PHI -// H(3) MAGNETIC FIELD -// RC(15) ERROR MATRIX IN SC VARIABLES (TRIANGLE) -// CH CHARGE OF PARTICLE -// CHARGE AND MAGNETIC FIELD ARE NEEDED -// FOR CORRELATION TERMS (V',YT),(V',ZT),(W',YT),(W',ZT) -// THESE CORRELATION TERMS APPEAR BECAUSE RC IS ASSUMED -// TO BE THE ERROR MATRIX FOR FIXED S (PATH LENGTH) -// AND RD FOR FIXED U -// DJ(3) UNIT VECTOR IN V-DIRECTION -// DK(3) UNIT VECTOR IN W-DIRECTION OF DETECTOR SYSTEM - -// OUTPUT -// RD(15) ERROR MATRIX IN q/P,V',W',V,W (TRIANGLE) -// PD(3) q/P,V',W' -// IERR = 1 PARTICLE MOVES PERPENDICULAR TO U-AXIS -// ( V',W' ARE NOT DEFINED ) -// SPU SIGN OF U-COMPONENT OF PARTICLE MOMENTUM -// spu = sign[p·(DJ x DK)] -// -// ------------------------------------------------------------------------ - - Double_t A[5][5], S[15], TN[3], COSL, COSP; - Double_t UN[3], VN[3], DI[3], TVW[3]; - - Double_t Vec[25]; - Double_t CFACT8= 2.997925e-04; - Double_t T1R, T2R, T3R, SINP, SINZ, COSZ, HA, HM, HAM; - Double_t Q, UI, VI, UJ, UK, VJ, VK; - - IERR=0; - memset(RD,0,sizeof(*RD)); - memset(PD,0,sizeof(*PD)); - - COSL=TMath::Cos(PC[1]); - SINP=TMath::Sin(PC[2]); - COSP=TMath::Cos(PC[2]); - - TN[0]=COSL*COSP; - TN[1]=COSL*SINP; - TN[2]=TMath::Sin(PC[1]); - - // DI = DJ x DK - DI[0]=DJ[1]*DK[2]-DJ[2]*DK[1]; - DI[1]=DJ[2]*DK[0]-DJ[0]*DK[2]; - DI[2]=DJ[0]*DK[1]-DJ[1]*DK[0]; - - TVW[0]=TN[0]*DI[0]+TN[1]*DI[1]+TN[2]*DI[2]; - SPU=1.; - if(TVW[0] < 0.) { SPU=-1.; } - TVW[1]=TN[0]*DJ[0]+TN[1]*DJ[1]+TN[2]*DJ[2]; - TVW[2]=TN[0]*DK[0]+TN[1]*DK[1]+TN[2]*DK[2]; - - // track lies in the detector plane: stop calculations - if(TMath::Abs(TVW[0]) < 1.e-7) { - IERR = 1; - return; - } - - T1R=1./TVW[0]; - PD[0] = PC[0]; - PD[1] = TVW[1]*T1R; - PD[2] = TVW[2]*T1R; - - UN[0] = -SINP; - UN[1] = COSP; - UN[2] = 0.; - - VN[0] =-TN[2]*UN[1]; - VN[1] = TN[2]*UN[0]; - VN[2] = COSL; - - UJ=UN[0]*DJ[0]+UN[1]*DJ[1]+UN[2]*DJ[2]; - UK=UN[0]*DK[0]+UN[1]*DK[1]+UN[2]*DK[2]; - VJ=VN[0]*DJ[0]+VN[1]*DJ[1]+VN[2]*DJ[2]; - VK=VN[0]*DK[0]+VN[1]*DK[1]+VN[2]*DK[2]; - - for(Int_t I=0; I<5; I++) { - for(Int_t K=0; K<5; K++) { - A[I][K]=0.; - } - } - - // copy input in an internal vector S - for(Int_t I=0; I<15; I++) { S[I]=RC[I]; } - - if(CH != 0.) { - //charged particles - HA=TMath::Sqrt(H[0]*H[0]+H[1]*H[1]+H[2]*H[2]); - HAM=HA*PC[0]; - if(HAM != 0.) { - // ... in a magnetic field - HM=CH/HA; - Q=-HAM*CFACT8; - SINZ=-(H[0]*UN[0]+H[1]*UN[1]+H[2]*UN[2])*HM; - COSZ= (H[0]*VN[0]+H[1]*VN[1]+H[2]*VN[2])*HM; - T3R=Q*pow(T1R,3); - UI=UN[0]*DI[0]+UN[1]*DI[1]+UN[2]*DI[2]; - VI=VN[0]*DI[0]+VN[1]*DI[1]+VN[2]*DI[2]; - A[1][3] = -UI*(VK*COSZ-UK*SINZ)*T3R; - A[1][4] = -VI*(VK*COSZ-UK*SINZ)*T3R; - A[2][3] = UI*(VJ*COSZ-UJ*SINZ)*T3R; - A[2][4] = VI*(VJ*COSZ-UJ*SINZ)*T3R; - } - } - - T2R=T1R*T1R; - - // Transformation matrix from SC to SD - - A[0][0] = 1.; - A[1][1] = -UK*T2R; - A[1][2] = VK*COSL*T2R; - A[2][1] = UJ*T2R; - A[2][2] = -VJ*COSL*T2R; - A[3][3] = VK*T1R; - A[3][4] = -UK*T1R; - A[4][3] = -VJ*T1R; - A[4][4] = UJ*T1R; - - // transformation - FromMatToVec(A,Vec); - SymmProd(Vec,S,S); - - // copy the result in S in the output vector - for(Int_t I=0; I<15; I++) { RD[I]=S[I]; } + // ---------------------------------------------------------------------- + // Transform Error Matrix + // FROM SC (transverse system) VARIABLES (q/P,LAMBDA,PHI,YT,ZT) + // TO SD (detector system) VARIABLES (q/P,V',W',V,W) + + // Authors: A. Haas and W. Wittek + // Translated in CRoot by A. Rotondi and A. Fontana June 2007 + + // INPUT + // PC(3) q/P,LAMBDA,PHI + // H(3) MAGNETIC FIELD + // RC(15) ERROR MATRIX IN SC VARIABLES (TRIANGLE) + // CH CHARGE OF PARTICLE + // CHARGE AND MAGNETIC FIELD ARE NEEDED + // FOR CORRELATION TERMS (V',YT),(V',ZT),(W',YT),(W',ZT) + // THESE CORRELATION TERMS APPEAR BECAUSE RC IS ASSUMED + // TO BE THE ERROR MATRIX FOR FIXED S (PATH LENGTH) + // AND RD FOR FIXED U + // DJ(3) UNIT VECTOR IN V-DIRECTION + // DK(3) UNIT VECTOR IN W-DIRECTION OF DETECTOR SYSTEM + + // OUTPUT + // RD(15) ERROR MATRIX IN q/P,V',W',V,W (TRIANGLE) + // PD(3) q/P,V',W' + // IERR = 1 PARTICLE MOVES PERPENDICULAR TO U-AXIS + // ( V',W' ARE NOT DEFINED ) + // SPU SIGN OF U-COMPONENT OF PARTICLE MOMENTUM + // spu = sign[p·(DJ x DK)] + // + // ------------------------------------------------------------------------ + + Double_t A[5][5], S[15], TN[3], COSL, COSP; + Double_t UN[3], VN[3], DI[3], TVW[3]; + + Double_t Vec[25]; + Double_t CFACT8 = 2.997925e-04; + Double_t T1R, T2R, T3R, SINP, SINZ, COSZ, HA, HM, HAM; + Double_t Q, UI, VI, UJ, UK, VJ, VK; + + IERR = 0; + memset(RD, 0, sizeof(*RD)); + memset(PD, 0, sizeof(*PD)); + + COSL = TMath::Cos(PC[1]); + SINP = TMath::Sin(PC[2]); + COSP = TMath::Cos(PC[2]); + + TN[0] = COSL * COSP; + TN[1] = COSL * SINP; + TN[2] = TMath::Sin(PC[1]); + + // DI = DJ x DK + DI[0] = DJ[1] * DK[2] - DJ[2] * DK[1]; + DI[1] = DJ[2] * DK[0] - DJ[0] * DK[2]; + DI[2] = DJ[0] * DK[1] - DJ[1] * DK[0]; + + TVW[0] = TN[0] * DI[0] + TN[1] * DI[1] + TN[2] * DI[2]; + SPU = 1.; + if (TVW[0] < 0.) { + SPU = -1.; + } + TVW[1] = TN[0] * DJ[0] + TN[1] * DJ[1] + TN[2] * DJ[2]; + TVW[2] = TN[0] * DK[0] + TN[1] * DK[1] + TN[2] * DK[2]; -} + // track lies in the detector plane: stop calculations + if (TMath::Abs(TVW[0]) < 1.e-7) { + IERR = 1; + return; + } + + T1R = 1. / TVW[0]; + PD[0] = PC[0]; + PD[1] = TVW[1] * T1R; + PD[2] = TVW[2] * T1R; + + UN[0] = -SINP; + UN[1] = COSP; + UN[2] = 0.; + + VN[0] = -TN[2] * UN[1]; + VN[1] = TN[2] * UN[0]; + VN[2] = COSL; + UJ = UN[0] * DJ[0] + UN[1] * DJ[1] + UN[2] * DJ[2]; + UK = UN[0] * DK[0] + UN[1] * DK[1] + UN[2] * DK[2]; + VJ = VN[0] * DJ[0] + VN[1] * DJ[1] + VN[2] * DJ[2]; + VK = VN[0] * DK[0] + VN[1] * DK[1] + VN[2] * DK[2]; -void FairGeaneUtil::FromSD1ToSD2(Double_t PD1[3], Double_t RD1[15],Double_t H[3], - Int_t CH, Double_t SP1, - Double_t DJ1[3], Double_t DK1[3], - Double_t DJ2[3], Double_t DK2[3], + for (Int_t I = 0; I < 5; I++) { + for (Int_t K = 0; K < 5; K++) { + A[I][K] = 0.; + } + } + + // copy input in an internal vector S + for (Int_t I = 0; I < 15; I++) { + S[I] = RC[I]; + } + + if (CH != 0.) { + // charged particles + HA = TMath::Sqrt(H[0] * H[0] + H[1] * H[1] + H[2] * H[2]); + HAM = HA * PC[0]; + if (HAM != 0.) { + // ... in a magnetic field + HM = CH / HA; + Q = -HAM * CFACT8; + SINZ = -(H[0] * UN[0] + H[1] * UN[1] + H[2] * UN[2]) * HM; + COSZ = (H[0] * VN[0] + H[1] * VN[1] + H[2] * VN[2]) * HM; + T3R = Q * pow(T1R, 3); + UI = UN[0] * DI[0] + UN[1] * DI[1] + UN[2] * DI[2]; + VI = VN[0] * DI[0] + VN[1] * DI[1] + VN[2] * DI[2]; + A[1][3] = -UI * (VK * COSZ - UK * SINZ) * T3R; + A[1][4] = -VI * (VK * COSZ - UK * SINZ) * T3R; + A[2][3] = UI * (VJ * COSZ - UJ * SINZ) * T3R; + A[2][4] = VI * (VJ * COSZ - UJ * SINZ) * T3R; + } + } + + T2R = T1R * T1R; + + // Transformation matrix from SC to SD + + A[0][0] = 1.; + A[1][1] = -UK * T2R; + A[1][2] = VK * COSL * T2R; + A[2][1] = UJ * T2R; + A[2][2] = -VJ * COSL * T2R; + A[3][3] = VK * T1R; + A[3][4] = -UK * T1R; + A[4][3] = -VJ * T1R; + A[4][4] = UJ * T1R; + + // transformation + FromMatToVec(A, Vec); + SymmProd(Vec, S, S); + + // copy the result in S in the output vector + for (Int_t I = 0; I < 15; I++) { + RD[I] = S[I]; + } +} + +void FairGeaneUtil::FromSD1ToSD2(Double_t PD1[3], + Double_t RD1[15], + Double_t H[3], + Int_t CH, + Double_t SP1, + Double_t DJ1[3], + Double_t DK1[3], + Double_t DJ2[3], + Double_t DK2[3], // output - Int_t& IERR, Double_t& SP2, - Double_t* PD2, Double_t* RD2) + Int_t& IERR, + Double_t& SP2, + Double_t* PD2, + Double_t* RD2) { -// ------------------------------------------------------------------------- -// -// TRANSFORMS ERROR MATRIX -// FROM VARIABLES (q/P,V1',W1',V1,W1) -// TO VARIABLES (q/P,V2',W2',V2,W2) -// -// Authors: A. Haas and W. Wittek -// Translated in C/Root by A. Fontana and A. Rotondi (June 2007) -// -// -// INPUT -// PD1[3] q/P,V1',W1' -// H[3] MAGNETIC FIELD -// RD1(15) ERROR MATRIX IN 1/P,V1',W1',V1,W1 (Triangular) -// CH CHARGE OF PARTICLE -// CHARGE AND MAGNETIC FIELD ARE NEEDED -// FOR CORRELATION TERMS (V2',V1),(V2',W1),(W2',V1),(W2',W1) -// THESE CORRELATION TERMS APPEAR BECAUSE RD1 IS ASSUMED -// TO BE THE ERROR MATRIX FOR FIXED U1 -// AND RD2 FOR FIXED U2 -// SP1 SIGN OF U1-COMPONENT OF PARTICLE MOMENTUM INPUT -// DJ1[3] UNIT VECTOR IN V1-DIRECTION -// DK1[3] UNIT VECTOR IN W1-DIRECTION OF SYSTEM 1 -// DJ2[3] UNIT VECTOR IN V2-DIRECTION -// DK2[3] UNIT VECTOR IN W2-DIRECTION OF SYSTEM 2 -// -// -// OUTPUT -// PD2[3] q/P,V2',W2' -// RD2[15] ERROR MATRIX IN 1/P,V2',W2',V2,W2 (Triangular) -// SP2 SIGN OF U2-COMPONENT OF PARTICLE MOMENTUM OUTPUT -// IERR = 0 TRANSFORMATION OK -// = 1 MOMENTUM PERPENDICULAR TO U2-DIRECTION -// (V2',W2' NOT DEFINed) -// = 2 MOMENTUM PERPENDICULAR TO X-AXIS -// -// ---------------------------------------------------------------------- - - Double_t A[5][5], S[15], TN[3], COSL, COSL1; - Double_t SINZ, COSZ, UN[3], VN[3]; - - Double_t Vec[25]; - Double_t PM, TR, TS, TT, HA, HM, HAM, Q; - Double_t UJ1, UK1, UJ2, UK2, VJ1, VJ2, VK1, VK2; - Double_t SJ1I2, SK1I2, SK2U, SK2V, SJ2U, SJ2V; - Double_t DI1[3], DI2[3], TVW1[3], TVW2[3]; - Double_t CFACT8= 2.997925e-04; - - IERR=0; - memset(PD2,0,sizeof(*PD2)); - memset(RD2,0,sizeof(*RD2)); - - PM=PD1[0]; - TVW1[0]=1./sqrt(1.+PD1[1]*PD1[1]+PD1[2]*PD1[2]); - if(SP1 < 0.) { TVW1[0]=-TVW1[0]; } - TVW1[1]=PD1[1]*TVW1[0]; - TVW1[2]=PD1[2]*TVW1[0]; - - DI1[0]=DJ1[1]*DK1[2]-DJ1[2]*DK1[1]; - DI1[1]=DJ1[2]*DK1[0]-DJ1[0]*DK1[2]; - DI1[2]=DJ1[0]*DK1[1]-DJ1[1]*DK1[0]; - - for(Int_t I=0; I<3; I++) { - TN[I]=TVW1[0]*DI1[I]+TVW1[1]*DJ1[I]+TVW1[2]*DK1[I]; - } - - DI2[0]=DJ2[1]*DK2[2]-DJ2[2]*DK2[1]; - DI2[1]=DJ2[2]*DK2[0]-DJ2[0]*DK2[2]; - DI2[2]=DJ2[0]*DK2[1]-DJ2[1]*DK2[0]; - - TVW2[0]=TN[0]*DI2[0]+TN[1]*DI2[1]+TN[2]*DI2[2]; - TVW2[1]=TN[0]*DJ2[0]+TN[1]*DJ2[1]+TN[2]*DJ2[2]; - TVW2[2]=TN[0]*DK2[0]+TN[1]*DK2[1]+TN[2]*DK2[2]; - - if(TMath::Abs(TVW2[0]) < 1.e-7) { - // track lies in the v-w plane: stop calculations - IERR = 1; - return; - } - TR=1./TVW2[0]; - SP2=1; - if(TVW2[0] < 0.) { SP2=-1; } - PD2[0]=PD1[0]; - PD2[1]=TVW2[1]*TR; - PD2[2]=TVW2[2]*TR; - - COSL=sqrt(TMath::Abs(1.-TN[2]*TN[2])); - if(TMath::Abs(COSL) < 1.e-7) { - // track perp to X-axis of Master: stop calculations - IERR=2; - return; - } - COSL1=1./COSL; - UN[0]=-TN[1]*COSL1; - UN[1]=TN[0]*COSL1; - UN[2]=0.; - - VN[0]=-TN[2]*UN[1]; - VN[1]=TN[2]*UN[0]; - VN[2]=COSL; - - UJ1=UN[0]*DJ1[0]+UN[1]*DJ1[1]+UN[2]*DJ1[2]; - UK1=UN[0]*DK1[0]+UN[1]*DK1[1]+UN[2]*DK1[2]; - VJ1=VN[0]*DJ1[0]+VN[1]*DJ1[1]+VN[2]*DJ1[2]; - VK1=VN[0]*DK1[0]+VN[1]*DK1[1]+VN[2]*DK1[2]; - - UJ2=UN[0]*DJ2[0]+UN[1]*DJ2[1]+UN[2]*DJ2[2]; - UK2=UN[0]*DK2[0]+UN[1]*DK2[1]+UN[2]*DK2[2]; - VJ2=VN[0]*DJ2[0]+VN[1]*DJ2[1]+VN[2]*DJ2[2]; - VK2=VN[0]*DK2[0]+VN[1]*DK2[1]+VN[2]*DK2[2]; - - // reset working vectors and matrices - for(Int_t I=0; I<5; I++) { - for(Int_t K=0; K<5; K++) { - A[I][K]=0.; - } - } - for(Int_t J=0; J<15; J++) { S[J]=RD1[J]; } - - if(CH != 0.) { - // a charged particle - HA=sqrt(H[0]*H[0]+H[1]*H[1]+H[2]*H[2]); - HAM=HA*PM; - if(HAM != 0.) { - // ...in a magnetic field - HM=CH/HA; - Q=-HAM*CFACT8; - TT=-Q*pow(TR,3); - SJ1I2=DJ1[0]*DI2[0]+DJ1[1]*DI2[1]+DJ1[2]*DI2[2]; - SK1I2=DK1[0]*DI2[0]+DK1[1]*DI2[1]+DK1[2]*DI2[2]; - SK2U=DK2[0]*UN[0]+DK2[1]*UN[1]+DK2[2]*UN[2]; - SK2V=DK2[0]*VN[0]+DK2[1]*VN[1]+DK2[2]*VN[2]; - SJ2U=DJ2[0]*UN[0]+DJ2[1]*UN[1]+DJ2[2]*UN[2]; - SJ2V=DJ2[0]*VN[0]+DJ2[1]*VN[1]+DJ2[2]*VN[2]; - - SINZ=-(H[0]*UN[0]+H[1]*UN[1]+H[2]*UN[2])*HM; - COSZ= (H[0]*VN[0]+H[1]*VN[1]+H[2]*VN[2])*HM; - A[1][3] = -TT*SJ1I2*(SK2U*SINZ-SK2V*COSZ); - A[1][4] = -TT*SK1I2*(SK2U*SINZ-SK2V*COSZ); - A[2][3] = TT*SJ1I2*(SJ2U*SINZ-SJ2V*COSZ); - A[2][4] = TT*SK1I2*(SJ2U*SINZ-SJ2V*COSZ); - - } - } - A[0][0] = 1.; - A[3][3] = TR*(UJ1*VK2-VJ1*UK2); - A[3][4] = TR*(UK1*VK2-VK1*UK2); - A[4][3] = TR*(VJ1*UJ2-UJ1*VJ2); - A[4][4] = TR*(VK1*UJ2-UK1*VJ2); - - TS=TR*TVW1[0]; - A[1][1] = A[3][3]*TS; - A[1][2] = A[3][4]*TS; - A[2][1] = A[4][3]*TS; - A[2][2] = A[4][4]*TS; - - // transformation A*SA - FromMatToVec(A,Vec); - SymmProd(Vec,S,S); - - // final error (covariance) matrix in upper-triangular form - - // std::cout<<"SD1toSD2: "< PD1(3,1); - PD1[0][0] = PD[0]; - PD1[1][0] = PD[1]; - PD1[2][0] = PD[2]; - - TMatrixT Rot1(3,3); - for(int i = 0; i < 3; i++) for(int j = 0; j < 3; j++) { - Rot1[i][j] = Rot[i][j]; - } - - // momentum components in the lcl cartesian frame - // with the x-y plane on the detectorr one - - TMatrixT Rot1xPD1(Rot1,TMatrixT::kMult,PD1); - PDD[0] = Rot1xPD1[0][0]; - PDD[1] = Rot1xPD1[1][0]; - PDD[2] = Rot1xPD1[2][0]; - - // jacobian for error matrix in MARS - - Rmat[0][0] = Rot[0][0]; - Rmat[0][1] = Rot[0][1]; - Rmat[0][2] = Rot[0][2]; - Rmat[1][0] = Rot[1][0]; - Rmat[1][1] = Rot[1][1]; - Rmat[1][2] = Rot[1][2]; - Rmat[2][0] = Rot[2][0]; - Rmat[2][1] = Rot[2][1]; - Rmat[2][2] = Rot[2][2]; - - Rmat[3][3] = Rot[0][0]; - Rmat[3][4] = Rot[0][1]; - Rmat[3][5] = Rot[0][2]; - Rmat[4][3] = Rot[1][0]; - Rmat[4][4] = Rot[1][1]; - Rmat[4][5] = Rot[1][2]; - Rmat[5][3] = Rot[2][0]; - Rmat[5][4] = Rot[2][1]; - Rmat[5][5] = Rot[2][2]; - -// transposed of the jacobian - - for(Int_t I=0; I<6; I++) { - for(Int_t K=0; K<6; K++) { - Rtra[K][I]=Rmat[I][K]; - } - } - - // product (J)(RD)(J+) - - for(Int_t i=0; i<6; i++) { - for(Int_t k=0; k<6; k++) { - for(Int_t l=0; l<6; l++) { - R6[i][k] += RD[i][l]*Rtra[l][k]; - } - } - } - - for(Int_t i=0; i<6; i++) { - for(Int_t k=0; k<6; k++) { - for(Int_t l=0; l<6; l++) { - RLC[i][k] += Rmat[i][l]*R6[l][k]; - } + // ---------------------------------------------------------------------- + // + // Tranform error matrix + // FROM SD (detector plane) VARIABLES (q/P,V',W',V,W) + // TO SC (transverse system) VARIABLES (q/P,LAMBDA,PHI,YT,ZT) + // + // Authors: A. Haas and W. Wittek + // Translated in C/Root by A. Rotondi and A. Fontana (June 2007) + // + // + // INPUT + // PD(3) q/P,V',W' + // H(3) MAGNETIC FIELD + // RD(15) ERROR MATRIX IN 1/P,V',W',V,W (Triangular) + // CH CHARGE OF PARTICLE + // CHARGE AND MAGNETIC FIELD ARE NEEDED + // FOR CORRELATION TERMS (LAMBDA,V),(LAMBDA,W),(PHI,V),(PHI,W) + // THESE CORRELATION TERMS APPEAR BECAUSE RC IS ASSUMED + // TO BE THE ERROR MATRIX FOR FIXED S (PATH LENGTH) + // AND RD FOR FIXED U + // SPU SIGN OF U-COMPONENT OF PARTICLE MOMENTUM + // spu = sign[p·(DJ x DK)] + // DJ(3) UNIT VECTOR IN V-DIRECTION + // DK(3) UNIT VECTOR IN W-DIRECTION OF DETECTOR SYSTEM + // + + // OUTPUT + // PC(3) q/P,LAMBDA,PHI + // RC(15) ERROR MATRIX IN SC VARIABLES + // IERR NOT USED + // + // --------------------------------------------------------------------- + + Double_t A[5][5], S[15], TN[3]; + Double_t SINZ, COSZ, COSL, COSL1; + Double_t UN[3], VN[3], DI[3], TVW[3]; + + Double_t Vec[25]; + Double_t CFACT8 = 2.997925e-04; + Double_t HA, HM, HAM, Q, UJ, UK, VJ, VK; + + Double_t PM; + + IERR = 0; + memset(RC, 0, sizeof(*RC)); + memset(PC, 0, sizeof(*PC)); + + PM = PD[0]; + TVW[0] = 1. / TMath::Sqrt(1. + PD[1] * PD[1] + PD[2] * PD[2]); + + if (SPU < 0.) { + TVW[0] = -TVW[0]; } - } - // go from local cartesian to the detector system SD - // x-y of local are v and w of SD. - // use of eq. (79) of the CMS report 2006/001 (Strandlie and Wittek) - // - - PM = TMath::Sqrt(PDD[0]*PDD[0]+PDD[1]*PDD[1]+PDD[2]*PDD[2]); - PM3 = TMath::Power(PM,3); - // PT = TMath::Sqrt(PDD[0]*PDD[0]+PDD[1]*PDD[1]); + TVW[1] = PD[1] * TVW[0]; + TVW[2] = PD[2] * TVW[0]; - // - // check if track lies in the x-y plane of the local cartesian frame - // if so, IERR=1 and exit - // - - if(TMath::Abs(PDD[2]) < 1.e-08) { - IERR = 1; - } - - else { + DI[0] = DJ[1] * DK[2] - DJ[2] * DK[1]; + DI[1] = DJ[2] * DK[0] - DJ[0] * DK[2]; + DI[2] = DJ[0] * DK[1] - DJ[1] * DK[0]; - // output q/p, v' and w' in SD - - PC[0] = CH/PM; - PC[1] = PDD[0]/PDD[2]; - PC[2] = PDD[1]/PDD[2];; - - // Jacobian Mars --> SD parallel to Mars x-y plane - // eq (79) of CMS note 2006/001 (Strandle and Wittek) + for (Int_t I = 0; I < 3; I++) { + TN[I] = TVW[0] * DI[I] + TVW[1] * DJ[I] + TVW[2] * DK[I]; + } - M56[0][0] = - CH*PDD[0]/PM3; - M56[0][1] = - CH*PDD[1]/PM3; - M56[0][2] = - CH*PDD[2]/PM3; + PC[0] = PD[0]; + PC[1] = TMath::ASin(TN[2]); + if (TMath::Abs(TN[0]) < 1.e-30) { + TN[0] = 1.e-30; + } - M56[1][0] = 1./PDD[2]; - M56[1][1] = 0.; - M56[1][2] = - PDD[0]/(PDD[2]*PDD[2]); + PC[2] = TMath::ATan2(TN[1], TN[0]); - M56[2][0] = 0.; - M56[2][1] = 1./PDD[2]; - M56[2][2] = - PDD[1]/(PDD[2]*PDD[2]); + COSL = TMath::Sqrt(TMath::Abs(1. - TN[2] * TN[2])); + if (COSL < 1.e-30) { + COSL = 1.e-30; + } + COSL1 = 1. / COSL; + UN[0] = -TN[1] * COSL1; + UN[1] = TN[0] * COSL1; + UN[2] = 0.; - M56[3][3] = 1.; - M56[4][4] = 1.; + VN[0] = -TN[2] * UN[1]; + VN[1] = TN[2] * UN[0]; + VN[2] = COSL; + UJ = UN[0] * DJ[0] + UN[1] * DJ[1] + UN[2] * DJ[2]; + UK = UN[0] * DK[0] + UN[1] * DK[1] + UN[2] * DK[2]; + VJ = VN[0] * DJ[0] + VN[1] * DJ[1] + VN[2] * DJ[2]; + VK = VN[0] * DK[0] + VN[1] * DK[1] + VN[2] * DK[2]; - // matrix multiplication with the Jacobian + // prepare matrices and vectors - for(Int_t k=0; k<5; k++) { - for(Int_t l=0; l<6; l++) { - M56T[l][k]= M56[k][l]; - } + for (Int_t I = 0; I < 5; I++) { + for (Int_t K = 0; K < 5; K++) { + A[I][K] = 0.; + } + } + for (Int_t J = 0; J < 15; J++) { + S[J] = RD[J]; } - for(Int_t i=0; i<6; i++) { - for(Int_t k=0; k<5; k++) { - for(Int_t l=0; l<6; l++) { - AJT[i][k] += RLC[i][l]*M56T[l][k]; + if (CH != 0.) { + // charged particle + HA = TMath::Sqrt(H[0] * H[0] + H[1] * H[1] + H[2] * H[2]); + HAM = HA * PM; + if (HAM != 0.) { + // .... in a magnetic field + HM = CH / HA; + Q = -HAM * CFACT8; + SINZ = -(H[0] * UN[0] + H[1] * UN[1] + H[2] * UN[2]) * HM; + COSZ = (H[0] * VN[0] + H[1] * VN[1] + H[2] * VN[2]) * HM; + A[1][3] = -Q * TVW[1] * SINZ; + A[1][4] = -Q * TVW[2] * SINZ; + A[2][3] = -Q * TVW[1] * COSZ * COSL1; + A[2][4] = -Q * TVW[2] * COSZ * COSL1; } - } } + A[0][0] = 1.; + A[1][1] = TVW[0] * VJ; + A[1][2] = TVW[0] * VK; + A[2][1] = TVW[0] * UJ * COSL1; + A[2][2] = TVW[0] * UK * COSL1; + A[3][3] = UJ; + A[3][4] = UK; + A[4][3] = VJ; + A[4][4] = VK; + + // transformation matrix + FromMatToVec(A, Vec); + SymmProd(Vec, S, S); + + // copy the result in S in the output vector + for (Int_t I = 0; I < 15; I++) { + RC[I] = S[I]; + } +} - for(Int_t i=0; i<5; i++) { - for(Int_t k=0; k<5; k++) { - for(Int_t l=0; l<6; l++) { - AJ[i][k] += M56[i][l]*AJT[l][k]; +void FairGeaneUtil::FromVec15ToMat25(Double_t V[15], fiveMat& A) +{ + // + // ------------------------------------------------------ + // Passage from a 15-dim vector to a symmetric 5x5 matrix + // following the upper triangular convention + // + // Author A. Rotondi June 2007 + // + // ------------------------------------------------------ + + A[0][0] = V[0]; + A[0][1] = V[1]; + A[0][2] = V[2]; + A[0][3] = V[3]; + A[0][4] = V[4]; + + A[1][1] = V[5]; + A[1][2] = V[6]; + A[1][3] = V[7]; + A[1][4] = V[8]; + + A[2][2] = V[9]; + A[2][3] = V[10]; + A[2][4] = V[11]; + + A[3][3] = V[12]; + A[3][4] = V[13]; + + A[4][4] = V[14]; + + for (Int_t I = 0; I < 5; I++) { + for (Int_t k = I; k < 5; k++) { + A[k][I] = A[I][k]; } - } } +} +void FairGeaneUtil::FromVecToMat(fiveMat& A, Double_t V[25]) +{ + // + // ------------------------------------------------------ + // Passage from 25-dim vector to a symmetric 5x5 matrix + // (FoRTRAN column convention) + // + // Author A. Rotondi June 2007 + // + // ------------------------------------------------------ + + A[0][0] = V[0]; + A[1][0] = V[1]; + A[2][0] = V[2]; + A[3][0] = V[3]; + A[4][0] = V[4]; + + A[0][1] = V[5]; + ; + A[1][1] = V[6]; + ; + A[2][1] = V[7]; + ; + A[3][1] = V[8]; + ; + A[4][1] = V[9]; + ; + + A[0][2] = V[10]; + A[1][2] = V[11]; + A[2][2] = V[12]; + A[3][2] = V[13]; + A[4][2] = V[14]; + + A[0][3] = V[15]; + A[1][3] = V[16]; + A[2][3] = V[17]; + A[3][3] = V[18]; + A[4][3] = V[19]; + + A[0][4] = V[20]; + A[1][4] = V[21]; + A[2][4] = V[22]; + A[3][4] = V[23]; + A[4][4] = V[24]; +} - // SD format output erro matrix RC(15) - FromMat25ToVec15(AJ,RC); +void FairGeaneUtil::FromMarsToSC(Double_t PD[3], + Double_t RD[6][6], + Double_t H[3], + Int_t CH, + // output + Double_t* PC, + Double_t* RC) +{ + // ---------------------------------------------------------------------- + // + // Tranform error matrix + // FROM MASTER VARIABLES (px, py,pz, x, y, z) + // TO SC (transverse system) VARIABLES (q/p, lambda, phi, yt, zt) + // momentum along x axis (GEANE convention) + // + // Method: the matrix in MARS is transformed in a detctor SD system + // with the detector plane coincident with the SC transverse plane. + // Then, the SD to SC routine is used. + // In this way the track length s is not modified by the transformation. + // + // Authors: A. Rotondi and A. Fontana (June 2007) + // rewritten by A. Rotondi and Lia Lavezzi (may 2008) + // + // INPUT + // PD(3) px, py, pz + // RD(6,6) ERROR MATRIX from MASTER Reference System + // covariances of (px, py, pz, x, y, z) + // + // CH CHARGE OF PARTICLE + // H(3) MAGNETIC FIELD components + // + // OUTPUT + // PC(3) q/p, lambda, phi + // RC(15) ERROR MATRIX IN SC VARIABLES + // + // + // --------------------------------------------------------------------- + + // Double_t PDD[3], RDD[15]; + + Double_t SPU, DJ[3], DK[3], PM /* , PM3 */ /* , PT */; + Int_t IERR; + Double_t clam, slam, cphi, sphi, PC1[3], RC1[15]; + // ------------------------------------------------------------------ + + // reset + + IERR = 0; + memset(RC, 0, sizeof(*RC)); + memset(PC, 0, sizeof(*PC)); + + PM = TMath::Sqrt(PD[0] * PD[0] + PD[1] * PD[1] + PD[2] * PD[2]); + // PM3 = TMath::Power(PM,3); + // PT = TMath::Sqrt(PD[0]*PD[0]+PD[1]*PD[1]); + + // prepare the director cosines of a virtual dtector system + // lying on the SC transverse plane + + slam = PD[2] / PM; + clam = TMath::Sqrt(1. - slam * slam); + + if (TMath::Abs(clam) < 1.e-10) { + clam = 0.; + slam = 1.; + cphi = 0.; + sphi = -1.; + } else { + cphi = PD[0] / (clam * PM); + sphi = PD[1] / (clam * PM); + } - SP1 = TMath::Sign(1., PD[0]*(DJ1[1]*DK1[2]-DJ1[2]*DK1[1])+ - PD[1]*(DJ1[2]*DK1[0]-DJ1[0]*DK1[2])+ - PD[2]*(DJ1[0]*DK1[1]-DJ1[1]*DK1[0]) ); - } -} + DJ[0] = -sphi; + DJ[1] = cphi; + DJ[2] = 0.; + DK[0] = -slam * cphi; + DK[1] = -slam * sphi; + DK[2] = clam; + FromMarsToSD(PD, RD, H, CH, DJ, DK, IERR, SPU, PC1, RC1); -void FairGeaneUtil::FromSDToMars(Double_t PC[3], Double_t RC[15], - Double_t[3] /*H[3]*/, Int_t CH, - Double_t SP1, Double_t DJ1[3], Double_t DK1[3], + // from SD to SC + + FromSDToSC(PC1, RC1, H, CH, SPU, DJ, DK, IERR, PC, RC); +} + +void FairGeaneUtil::FromSCToMars(Double_t PC[3], + Double_t RC[15], + Double_t H[3], + Int_t CH, // output - Double_t* PD, sixMat& RD) + Double_t* PD, + sixMat& RD) { -// ------------------------------------------------------------------------ -// -// Transform error matrix -// -// FROM SD (detector system system) (q/P,v'.w'.v.w) -// TO MASTER Reference System (MARS) (px, py, pz, z, y, z) -// -// Method: eq (80) of the report CMS 2006/001 is used -// to go from SD to the local cartesian frame. -// Then the error matrix in MARS is obtained through the jacobian -// between the local cartesian frame and MARS. -// -// Authors: A. Rotondi and A. Fontana (June 2007) -// Rewritten by A. Rotondi and Lia Lavezzi (may 2008) -// corrected for the q/p variable by A. Rotondi (10 june 2007) -// -// INPUT -// PC(3) q/p v' w' -// RC(15) ERROR MATRIX IN SD VARIABLES -// covariances of (px, py, pz, x, y, z) -// H(3) Magnetic field components -// CH CHARGE OF PARTICLE -// DJ1(3) Director cosines of axis v in MARS -// DK1(3) Director cosines of axis w in MARS -// SP1 SIGN OF U-COMPONENT OF PARTICLE MOMENTUM -// spu = sign[p·(DJ1 x DK1)] -// -// OUTPUT -// PD(3) px, py, pz -// RD(6,6) ERROR (Covariance) MATRIX in MASTER Reference System -// -// -// --------------------------------------------------------------------------- - - Double_t M65[6][5], M65T[5][6], AJ[5][6]; - Double_t RCM[5][5]; - Double_t PDD[3]; - Double_t Rot[3][3]; - - // TVector3 PD1, PD2; - TVector3 PD2; - - Double_t RD1[6][6], Rmat[6][6], AJJ[6][6], Rtra[6][6]; - - Double_t SPU, PM, PM2, PVW, PVW3; - - // ------------------------------------------------------------------------- - - memset(PD,0,sizeof(*PD)); - - // reset matrices - for(Int_t I=0; I<5; I++) { - for(Int_t K=0; K<6; K++) { - AJ[I][K]=0.; - M65[K][I]=0.; - M65T[I][K]=0.; - RD[I][K] = 0.; - RD1[I][K] = 0.; - Rmat[I][K] = 0.; - Rtra[I][K] = 0.; - AJJ[I][K] = 0.; - if (K < 5) RCM[I][K]=0.; - } - } - for(Int_t I=0; I<6; I++) { - RD[5][I] = 0.; - RD1[5][I] = 0.; - Rmat[5][I] = 0.; - Rtra[5][I] = 0.; - AJJ[5][I] = 0.; - } - - SPU = SP1; - - // jacobian from SD to local cartesian - - PM = 1.e+30; - if(PC[0] != 0.) { PM =CH/PC[0]; } - PM2 = PM*PM; - PVW = TMath::Sqrt(1.+PC[1]*PC[1]+PC[2]*PC[2]); - PVW3 = TMath::Power(PVW,3); - - // output px, py, pz (cartesian) - - PDD[0] = SPU*PM*PC[1]/PVW; - PDD[1] = SPU*PM*PC[2]/PVW; - PDD[2] = SPU*PM/PVW ; - - // Jacobian SD --> Mars - // eq (80) of CMS note 2006/001 (Strandlie and Wittek) - - M65[0][0] = - SPU*PM2*PC[1]/(CH*PVW); - M65[1][0] = - SPU*PM2*PC[2]/(CH*PVW); - M65[2][0] = - SPU*PM2/(CH*PVW); - - M65[0][1] = SPU*PM*(1.+PC[2]*PC[2])/PVW3; - M65[1][1] = - SPU*PM*PC[1]*PC[2]/PVW3; - M65[2][1] = - SPU*PM*PC[1]/PVW3; - - M65[0][2] = - SPU*PM*PC[1]*PC[2]/PVW3; - M65[1][2] = SPU*PM*(1.+PC[1]*PC[1])/PVW3; - M65[2][2] = - SPU*PM*PC[2]/PVW3; - - M65[3][3] = 1.; - M65[4][4] = 1.; - - FromVec15ToMat25(RC,RCM); - - - // transposed of the jacobian - - for(Int_t I=0; I<6; I++) { - for(Int_t K=0; K<5; K++) { - M65T[K][I]=M65[I][K]; - } - } - - // product (J)(RCM)(J+) - - for(Int_t i=0; i<5; i++) { - for(Int_t k=0; k<6; k++) { - for(Int_t l=0; l<5; l++) { - AJ[i][k] += RCM[i][l]*M65T[l][k]; - } - } - } - - for(Int_t i=0; i<6; i++) { - for(Int_t k=0; k<6; k++) { - for(Int_t l=0; l<5; l++) { - RD1[i][k] += M65[i][l]*AJ[l][k]; - } + // ------------------------------------------------------------------------ + // + // Transform error matrix + // + // FROM SC (transverse system) (q/P,LAMBDA,PHI,YT,ZT) + // TO MASTER Reference System (MARS) (px, py, pz, z, y, z) + // + // Method: the SC system is transformed in a SD system with the + // detector plane coincident with the transverse one. + // Then, the SD to MARS routine is used. + // + // Authors: A. Rotondi and A. Fontana (June 2007) + // rewritten by A. Rotondi and Lia Lavezzi (may 2008) + // In this way the track length s is not modified by the transformation. + // + // INPUT + // PC(3) q/p lambda phi + // RC(15) ERROR MATRIX IN SC VARIABLES + // covariances of (px, py, pz, x, y, z) + // H(3) Magnetic field components + // CH CHARGE OF PARTICLE + // + // OUTPUT + // PD(3) px, py, pz + // RD(6,6) ERROR MATRIX in MASTER Reference System + // + // + // --------------------------------------------------------------------------- + + // Double_t M65[6][5], M65T[5][6], AJ[5][6]; + // Double_t DJ[3], DK[3], RCM[5][5]; + Double_t DJ[3], DK[3]; + Double_t PDD[3], RDD[15]; + + Int_t IERR; + // Double_t SPU, PM, PM2, PM3, PVW, PVW3; + Double_t SPU; + Double_t clam, slam, cphi, sphi; + // ------------------------------------------------------------------------- + + IERR = 0; + memset(PD, 0, sizeof(*PD)); + + // reset matrices + for (Int_t I = 0; I < 6; I++) { + for (Int_t K = 0; K < 6; K++) { + RD[I][K] = 0.; + } } - } + // go from SC to SD with the same plane + // prepare the director cosines of a virtual dtector system + // lying on the SC transverse plane + + clam = TMath::Cos(PC[1]); + slam = TMath::Sin(PC[1]); + cphi = TMath::Cos(PC[2]); + sphi = TMath::Sin(PC[2]); + + // momentum is perpendicular to the x-y plane + if (TMath::Abs(clam) < 1.e-15) { + clam = 0.; + slam = 1.; + cphi = 0.; + sphi = -1.; + } + + // GEANE routines to go on SD + + DJ[0] = -sphi; + DJ[1] = cphi; + DJ[2] = 0.; - // now go from the local cartesian to MARS + DK[0] = -slam * cphi; + DK[1] = -slam * sphi; + DK[2] = clam; - // MARS - TVector3 MI(1.,0.,0.); - TVector3 MJ(0.,1.,0.); - TVector3 MK(0.,0.,1.); - //local cartesian - TVector3 DI(DJ1[0],DJ1[1],DJ1[2]); - TVector3 DJ(DK1[0],DK1[1],DK1[2]); - TVector3 DK= DI.Cross(DJ); - - // rotation: M.. final versors, D.. initial - // vectors are column matrices - - Rot[0][0] = MI.Dot(DI); - Rot[0][1] = MI.Dot(DJ); - Rot[0][2] = MI.Dot(DK); - Rot[1][0] = MJ.Dot(DI); - Rot[1][1] = MJ.Dot(DJ); - Rot[1][2] = MJ.Dot(DK); - Rot[2][0] = MK.Dot(DI); - Rot[2][1] = MK.Dot(DJ); - Rot[2][2] = MK.Dot(DK); + FromSCToSD(PC, RC, H, CH, DJ, DK, IERR, SPU, PDD, RDD); - TMatrixT PD1(3,1); - PD1[0][0] = PDD[0]; - PD1[1][0] = PDD[1]; - PD1[2][0] = PDD[2]; + if (IERR != 1) { - TMatrixT Rot1(3,3); - for(int i = 0; i < 3; i++) for(int j = 0; j < 3; j++) { - Rot1[i][j] = Rot[i][j]; + FromSDToMars(PDD, RDD, H, CH, SPU, DJ, DK, PD, RD); } +} + +void FairGeaneUtil::FromMarsToSD(Double_t PD[3], + Double_t RD[6][6], + Double_t[3] /*H[3]*/, + Int_t CH, + Double_t DJ1[3], + Double_t DK1[3], + // output + Int_t& IERR, + Double_t& SP1, + Double_t* PC, + Double_t* RC) +{ - TMatrixT Rot1xPD1(Rot1,TMatrixT::kMult,PD1); - PD[0] = Rot1xPD1[0][0]; - PD[1] = Rot1xPD1[1][0]; - PD[2] = Rot1xPD1[2][0]; + // ---------------------------------------------------------------------- + // + // Tranform error matrix + // FROM MASTER VARIABLES (px, py,pz, x, y, z) + // TO SD (transverse or local system) + // VARIABLES (q/p, v', w', v, w) + // + // Method: the MARS system is rotated to a local cartesia system + // with the x-y plane on the v-w one of SD. Hence eq (79) of the + // report CMS 2006/001 is used to go from canonical to SD variables. + // In this way the track length variation and the magnetic field + // effects are correctly taken into account. + // + // Authors: A. Rotondi and A. Fontana (July 2007) + // Rewritten by A. Rotondi and Lia Lavezzi (may 2008) + // corrected for the q/p variable by A. Rotondi (10 june 2007) + // + // INPUT + // PD(3) px, py, pz in MARS + // RD(6,6) ERROR MATRIX from MASTER Reference System + // covariances of (px, py, pz, x, y, z) + // + // CH CHARGE OF PARTICLE + // H(3) MAGNETIC FIELD components + // DJ1(3) Director cosines of axis v in MARS + // DK1(3) Director cosines of axis w in MARS + // + // OUTPUt + // IERR = 0 TRANSFORMATION OK + // = 1 MOMENTUM LIES IN THE DETECTOR PLANE + // + // PC(3) q/p, v', w' + // RC(15) ERROR MATRIX IN SD VARIABLES + // SP1 SIGN OF U-COMPONENT OF PARTICLE MOMENTUM + // SP1 = sign[p.(DJ x DK)] + // + // + // --------------------------------------------------------------------- + + // Double_t PDD[3], RDD[15]; + Double_t PDD[3]; + Double_t M56[5][6], M56T[6][5], AJ[5][5], AJT[6][5]; + Double_t R6[6][6], RLC[6][6]; + // Double_t SPU, PM, PM3, PT; + Double_t PM, PM3 /* , PT */; + Double_t Rot[3][3], Rmat[6][6], Rtra[6][6]; + // ------------------------------------------------------------------ + + // reset + + IERR = 0; + memset(RC, 0, sizeof(*RC)); + memset(PC, 0, sizeof(*PC)); + + for (Int_t I = 0; I < 5; I++) { + for (Int_t K = 0; K < 6; K++) { + AJT[K][I] = 0.; + M56[I][K] = 0.; + M56T[K][I] = 0.; + if (K != 5) { + AJ[I][K] = 0.; + } + } + } - // jacobian for error matrix in MARS + for (Int_t i = 0; i < 6; i++) { + for (Int_t k = 0; k < 6; k++) { + R6[i][k] = 0.; + RLC[i][k] = 0; + Rmat[i][k] = 0.; + Rtra[i][k] = 0.; + } + } - Rmat[0][0] = Rot[0][0]; - Rmat[0][1] = Rot[0][1]; - Rmat[0][2] = Rot[0][2]; - Rmat[1][0] = Rot[1][0]; - Rmat[1][1] = Rot[1][1]; - Rmat[1][2] = Rot[1][2]; - Rmat[2][0] = Rot[2][0]; - Rmat[2][1] = Rot[2][1]; - Rmat[2][2] = Rot[2][2]; + // to local cartesian frame + + TVector3 MI(1., 0., 0.); + TVector3 MJ(0., 1., 0.); + TVector3 MK(0., 0., 1.); + // local cartesian + TVector3 DI(DJ1[0], DJ1[1], DJ1[2]); + TVector3 DJ(DK1[0], DK1[1], DK1[2]); + TVector3 DK = DI.Cross(DJ); + + // rotation: D.. final versors, M.. initial + // vectors are column matrices + + Rot[0][0] = DI.Dot(MI); + Rot[0][1] = DI.Dot(MJ); + Rot[0][2] = DI.Dot(MK); + Rot[1][0] = DJ.Dot(MI); + Rot[1][1] = DJ.Dot(MJ); + Rot[1][2] = DJ.Dot(MK); + Rot[2][0] = DK.Dot(MI); + Rot[2][1] = DK.Dot(MJ); + Rot[2][2] = DK.Dot(MK); + + TMatrixT PD1(3, 1); + PD1[0][0] = PD[0]; + PD1[1][0] = PD[1]; + PD1[2][0] = PD[2]; + + TMatrixT Rot1(3, 3); + for (int i = 0; i < 3; i++) + for (int j = 0; j < 3; j++) { + Rot1[i][j] = Rot[i][j]; + } - Rmat[3][3] = Rot[0][0]; - Rmat[3][4] = Rot[0][1]; - Rmat[3][5] = Rot[0][2]; - Rmat[4][3] = Rot[1][0]; - Rmat[4][4] = Rot[1][1]; - Rmat[4][5] = Rot[1][2]; - Rmat[5][3] = Rot[2][0]; - Rmat[5][4] = Rot[2][1]; - Rmat[5][5] = Rot[2][2]; + // momentum components in the lcl cartesian frame + // with the x-y plane on the detectorr one + + TMatrixT Rot1xPD1(Rot1, TMatrixT::kMult, PD1); + PDD[0] = Rot1xPD1[0][0]; + PDD[1] = Rot1xPD1[1][0]; + PDD[2] = Rot1xPD1[2][0]; + + // jacobian for error matrix in MARS + + Rmat[0][0] = Rot[0][0]; + Rmat[0][1] = Rot[0][1]; + Rmat[0][2] = Rot[0][2]; + Rmat[1][0] = Rot[1][0]; + Rmat[1][1] = Rot[1][1]; + Rmat[1][2] = Rot[1][2]; + Rmat[2][0] = Rot[2][0]; + Rmat[2][1] = Rot[2][1]; + Rmat[2][2] = Rot[2][2]; + + Rmat[3][3] = Rot[0][0]; + Rmat[3][4] = Rot[0][1]; + Rmat[3][5] = Rot[0][2]; + Rmat[4][3] = Rot[1][0]; + Rmat[4][4] = Rot[1][1]; + Rmat[4][5] = Rot[1][2]; + Rmat[5][3] = Rot[2][0]; + Rmat[5][4] = Rot[2][1]; + Rmat[5][5] = Rot[2][2]; + + // transposed of the jacobian + + for (Int_t I = 0; I < 6; I++) { + for (Int_t K = 0; K < 6; K++) { + Rtra[K][I] = Rmat[I][K]; + } + } - // transposed of the jacobian + // product (J)(RD)(J+) - for(Int_t I=0; I<6; I++) { - for(Int_t K=0; K<6; K++) { - Rtra[K][I]=Rmat[I][K]; + for (Int_t i = 0; i < 6; i++) { + for (Int_t k = 0; k < 6; k++) { + for (Int_t l = 0; l < 6; l++) { + R6[i][k] += RD[i][l] * Rtra[l][k]; + } + } } - } - for(Int_t i=0; i<6; i++) { - for(Int_t k=0; k<6; k++) { - for(Int_t l=0; l<6; l++) { - AJJ[i][k] += RD1[i][l]*Rtra[l][k]; - } + for (Int_t i = 0; i < 6; i++) { + for (Int_t k = 0; k < 6; k++) { + for (Int_t l = 0; l < 6; l++) { + RLC[i][k] += Rmat[i][l] * R6[l][k]; + } + } + } + // go from local cartesian to the detector system SD + // x-y of local are v and w of SD. + // use of eq. (79) of the CMS report 2006/001 (Strandlie and Wittek) + // + + PM = TMath::Sqrt(PDD[0] * PDD[0] + PDD[1] * PDD[1] + PDD[2] * PDD[2]); + PM3 = TMath::Power(PM, 3); + // PT = TMath::Sqrt(PDD[0]*PDD[0]+PDD[1]*PDD[1]); + + // + // check if track lies in the x-y plane of the local cartesian frame + // if so, IERR=1 and exit + // + + if (TMath::Abs(PDD[2]) < 1.e-08) { + IERR = 1; } - } - - for(Int_t i=0; i<6; i++) { - for(Int_t k=0; k<6; k++) { - for(Int_t l=0; l<6; l++) { - RD[i][k] += Rmat[i][l]*AJJ[l][k]; - } - } - } -} + else { + // output q/p, v' and w' in SD + PC[0] = CH / PM; + PC[1] = PDD[0] / PDD[2]; + PC[2] = PDD[1] / PDD[2]; + ; -void FairGeaneUtil::FromMat25ToVec15(Double_t A[5][5], Double_t* V) -{ - // - // ------------------------------------------------------ - // Passage from a symmetric 5x5 matrix to a 15-dim vector - // following the upper triangular convention - // - // Author A. Rotondi June 2007 - // - // ------------------------------------------------------ + // Jacobian Mars --> SD parallel to Mars x-y plane + // eq (79) of CMS note 2006/001 (Strandle and Wittek) - V[0] = A[0][0]; - V[1] = A[0][1]; - V[2] = A[0][2]; - V[3] = A[0][3]; - V[4] = A[0][4]; + M56[0][0] = -CH * PDD[0] / PM3; + M56[0][1] = -CH * PDD[1] / PM3; + M56[0][2] = -CH * PDD[2] / PM3; - V[5] = A[1][1]; - V[6] = A[1][2]; - V[7] = A[1][3]; - V[8] = A[1][4]; + M56[1][0] = 1. / PDD[2]; + M56[1][1] = 0.; + M56[1][2] = -PDD[0] / (PDD[2] * PDD[2]); - V[ 9] = A[2][2]; - V[10] = A[2][3]; - V[11] = A[2][4]; + M56[2][0] = 0.; + M56[2][1] = 1. / PDD[2]; + M56[2][2] = -PDD[1] / (PDD[2] * PDD[2]); - V[12] = A[3][3]; - V[13] = A[3][4]; + M56[3][3] = 1.; + M56[4][4] = 1.; - V[14] = A[4][4]; + // matrix multiplication with the Jacobian + for (Int_t k = 0; k < 5; k++) { + for (Int_t l = 0; l < 6; l++) { + M56T[l][k] = M56[k][l]; + } + } -} + for (Int_t i = 0; i < 6; i++) { + for (Int_t k = 0; k < 5; k++) { + for (Int_t l = 0; l < 6; l++) { + AJT[i][k] += RLC[i][l] * M56T[l][k]; + } + } + } -void FairGeaneUtil::FromMatToVec(Double_t A[5][5], Double_t* V) -{ - // - // ------------------------------------------------------ - // Passage from a 5x5 matrix to a 25-dim vector - // - // Author A. Rotondi June 2007 - // - // ------------------------------------------------------ - - V[0] = A[0][0]; - V[1] = A[1][0]; - V[2] = A[2][0]; - V[3] = A[3][0]; - V[4] = A[4][0]; - - V[5] = A[0][1]; - V[6] = A[1][1]; - V[7] = A[2][1]; - V[8] = A[3][1]; - V[9] = A[4][1]; - - V[10] = A[0][2]; - V[11] = A[1][2]; - V[12] = A[2][2]; - V[13] = A[3][2]; - V[14] = A[4][2]; - - - V[15] = A[0][3]; - V[16] = A[1][3]; - V[17] = A[2][3]; - V[18] = A[3][3]; - V[19] = A[4][3]; - - V[20] = A[0][4]; - V[21] = A[1][4]; - V[22] = A[2][4]; - V[23] = A[3][4]; - V[24] = A[4][4]; + for (Int_t i = 0; i < 5; i++) { + for (Int_t k = 0; k < 5; k++) { + for (Int_t l = 0; l < 6; l++) { + AJ[i][k] += M56[i][l] * AJT[l][k]; + } + } + } + // SD format output erro matrix RC(15) + FromMat25ToVec15(AJ, RC); + + SP1 = TMath::Sign(1., + PD[0] * (DJ1[1] * DK1[2] - DJ1[2] * DK1[1]) + PD[1] * (DJ1[2] * DK1[0] - DJ1[0] * DK1[2]) + + PD[2] * (DJ1[0] * DK1[1] - DJ1[1] * DK1[0])); + } } -void FairGeaneUtil::SymmProd(Double_t A[25], Double_t S[15], Double_t* R) +void FairGeaneUtil::FromSDToMars(Double_t PC[3], + Double_t RC[15], + Double_t[3] /*H[3]*/, + Int_t CH, + Double_t SP1, + Double_t DJ1[3], + Double_t DK1[3], + // output + Double_t* PD, + sixMat& RD) { - // - // --------------------------------------------------------- - // TRANSFORMATION OF SYMMETRIC 5X5 MATRIX S: - // A*S*AT -> R. - // A is a 25-dim vector corresonding to the 5x5 transformation - // matrix - // S and R ARE SYMMETRIC ERROR (COVARIANCE) MATRICES STORED - // IN TRIANGULAR FORM. - // - // INPUT - // A[25] transformation matrix 5x5 - // S[15] error matrix in triangular form - // - // OUTPUT - // R[15] error matrix in triangular form - // - // NB: S AND R MAY WELL BE THE SAME MATRIX. - // - // Author: A. Haas (Freiburg University) 5/7/81 - // transported with modifications - // in C/Root by A. Rotondi (June 2007) - // - // * ------------------------------------------------------ - - Double_t Q[15],T1,T2,T3,T4,T5; - - for(Int_t i=0; i<15; i++) { Q[i]=S[i]; } - - Int_t K =0; - for(Int_t J=0; J<5; J++) { - T1=A[J ]; - T2=A[J+ 5]; - T3=A[J+10]; - T4=A[J+15]; - T5=A[J+20]; - for(Int_t I=J; I<5; I++) { - R[K]=A[I ]*(Q[0]*T1+Q[1]*T2+Q[ 2]*T3+Q[ 3]*T4+Q[ 4]*T5) - +A[I+ 5]*(Q[1]*T1+Q[5]*T2+Q[ 6]*T3+Q[ 7]*T4+Q[ 8]*T5) - +A[I+10]*(Q[2]*T1+Q[6]*T2+Q[ 9]*T3+Q[10]*T4+Q[11]*T5) - +A[I+15]*(Q[3]*T1+Q[7]*T2+Q[10]*T3+Q[12]*T4+Q[13]*T5) - +A[I+20]*(Q[4]*T1+Q[8]*T2+Q[11]*T3+Q[13]*T4+Q[14]*T5); - K++; - } - } -} + // ------------------------------------------------------------------------ + // + // Transform error matrix + // + // FROM SD (detector system system) (q/P,v'.w'.v.w) + // TO MASTER Reference System (MARS) (px, py, pz, z, y, z) + // + // Method: eq (80) of the report CMS 2006/001 is used + // to go from SD to the local cartesian frame. + // Then the error matrix in MARS is obtained through the jacobian + // between the local cartesian frame and MARS. + // + // Authors: A. Rotondi and A. Fontana (June 2007) + // Rewritten by A. Rotondi and Lia Lavezzi (may 2008) + // corrected for the q/p variable by A. Rotondi (10 june 2007) + // + // INPUT + // PC(3) q/p v' w' + // RC(15) ERROR MATRIX IN SD VARIABLES + // covariances of (px, py, pz, x, y, z) + // H(3) Magnetic field components + // CH CHARGE OF PARTICLE + // DJ1(3) Director cosines of axis v in MARS + // DK1(3) Director cosines of axis w in MARS + // SP1 SIGN OF U-COMPONENT OF PARTICLE MOMENTUM + // spu = sign[p·(DJ1 x DK1)] + // + // OUTPUT + // PD(3) px, py, pz + // RD(6,6) ERROR (Covariance) MATRIX in MASTER Reference System + // + // + // --------------------------------------------------------------------------- + + Double_t M65[6][5], M65T[5][6], AJ[5][6]; + Double_t RCM[5][5]; + Double_t PDD[3]; + Double_t Rot[3][3]; + + // TVector3 PD1, PD2; + TVector3 PD2; + + Double_t RD1[6][6], Rmat[6][6], AJJ[6][6], Rtra[6][6]; + + Double_t SPU, PM, PM2, PVW, PVW3; + + // ------------------------------------------------------------------------- + + memset(PD, 0, sizeof(*PD)); + + // reset matrices + for (Int_t I = 0; I < 5; I++) { + for (Int_t K = 0; K < 6; K++) { + AJ[I][K] = 0.; + M65[K][I] = 0.; + M65T[I][K] = 0.; + RD[I][K] = 0.; + RD1[I][K] = 0.; + Rmat[I][K] = 0.; + Rtra[I][K] = 0.; + AJJ[I][K] = 0.; + if (K < 5) + RCM[I][K] = 0.; + } + } + for (Int_t I = 0; I < 6; I++) { + RD[5][I] = 0.; + RD1[5][I] = 0.; + Rmat[5][I] = 0.; + Rtra[5][I] = 0.; + AJJ[5][I] = 0.; + } -// ------------------------- modifiche 27 jul 2007 -------------------------- + SPU = SP1; -TVector3 FairGeaneUtil::FromMARSToSDCoord(TVector3 xyz, TVector3 o, TVector3 di, TVector3 dj, TVector3 dk) -{ + // jacobian from SD to local cartesian - TMatrixT matrix(3,3); - // rotation matrix (u,v,w) = (fmatrix) * (x,y,z) - matrix[0][0] = di[0]; - matrix[0][1] = di[1]; - matrix[0][2] = di[2]; - matrix[1][0] = dj[0]; - matrix[1][1] = dj[1]; - matrix[1][2] = dj[2]; - matrix[2][0] = dk[0]; - matrix[2][1] = dk[1]; - matrix[2][2] = dk[2]; + PM = 1.e+30; + if (PC[0] != 0.) { + PM = CH / PC[0]; + } + PM2 = PM * PM; + PVW = TMath::Sqrt(1. + PC[1] * PC[1] + PC[2] * PC[2]); + PVW3 = TMath::Power(PVW, 3); + // output px, py, pz (cartesian) + PDD[0] = SPU * PM * PC[1] / PVW; + PDD[1] = SPU * PM * PC[2] / PVW; + PDD[2] = SPU * PM / PVW; - TMatrixT xyzvec(3,1); - xyzvec[0][0] = xyz.X(); - xyzvec[1][0] = xyz.Y(); - xyzvec[2][0] = xyz.Z(); + // Jacobian SD --> Mars + // eq (80) of CMS note 2006/001 (Strandlie and Wittek) + M65[0][0] = -SPU * PM2 * PC[1] / (CH * PVW); + M65[1][0] = -SPU * PM2 * PC[2] / (CH * PVW); + M65[2][0] = -SPU * PM2 / (CH * PVW); - TMatrixT origin(3,1); - origin[0][0] = o.X(); - origin[1][0] = o.Y(); - origin[2][0] = o.Z(); + M65[0][1] = SPU * PM * (1. + PC[2] * PC[2]) / PVW3; + M65[1][1] = -SPU * PM * PC[1] * PC[2] / PVW3; + M65[2][1] = -SPU * PM * PC[1] / PVW3; - xyzvec -= origin; + M65[0][2] = -SPU * PM * PC[1] * PC[2] / PVW3; + M65[1][2] = SPU * PM * (1. + PC[1] * PC[1]) / PVW3; + M65[2][2] = -SPU * PM * PC[2] / PVW3; - TMatrixT uvwvec(matrix, TMatrixT::kMult, xyzvec); + M65[3][3] = 1.; + M65[4][4] = 1.; - TVector3 uvw = TVector3(uvwvec[0][0], uvwvec[1][0], uvwvec[2][0]); - return uvw; -} + FromVec15ToMat25(RC, RCM); -TVector3 FairGeaneUtil::FromSDToMARSCoord(TVector3 uvw, TVector3 o, TVector3 di, TVector3 dj, TVector3 dk) -{ - TMatrixT matrix(3,3); - matrix[0][0] = di[0]; - matrix[0][1] = di[1]; - matrix[0][2] = di[2]; - matrix[1][0] = dj[0]; - matrix[1][1] = dj[1]; - matrix[1][2] = dj[2]; - matrix[2][0] = dk[0]; - matrix[2][1] = dk[1]; - matrix[2][2] = dk[2]; + // transposed of the jacobian + for (Int_t I = 0; I < 6; I++) { + for (Int_t K = 0; K < 5; K++) { + M65T[K][I] = M65[I][K]; + } + } - TMatrixT uvwvec(3,1); - uvwvec[0][0] = uvw.X(); - uvwvec[1][0] = uvw.Y(); - uvwvec[2][0] = uvw.Z(); + // product (J)(RCM)(J+) - TMatrixT uvwrot(matrix, TMatrixT::kTransposeMult, uvwvec); + for (Int_t i = 0; i < 5; i++) { + for (Int_t k = 0; k < 6; k++) { + for (Int_t l = 0; l < 5; l++) { + AJ[i][k] += RCM[i][l] * M65T[l][k]; + } + } + } - TMatrixT origin(3,1); - origin[0][0] = o.X(); - origin[1][0] = o.Y(); - origin[2][0] = o.Z(); + for (Int_t i = 0; i < 6; i++) { + for (Int_t k = 0; k < 6; k++) { + for (Int_t l = 0; l < 5; l++) { + RD1[i][k] += M65[i][l] * AJ[l][k]; + } + } + } - TMatrixT xyzvec(3,1); - xyzvec = uvwrot + origin; + // now go from the local cartesian to MARS + + // MARS + TVector3 MI(1., 0., 0.); + TVector3 MJ(0., 1., 0.); + TVector3 MK(0., 0., 1.); + // local cartesian + TVector3 DI(DJ1[0], DJ1[1], DJ1[2]); + TVector3 DJ(DK1[0], DK1[1], DK1[2]); + TVector3 DK = DI.Cross(DJ); + + // rotation: M.. final versors, D.. initial + // vectors are column matrices + + Rot[0][0] = MI.Dot(DI); + Rot[0][1] = MI.Dot(DJ); + Rot[0][2] = MI.Dot(DK); + Rot[1][0] = MJ.Dot(DI); + Rot[1][1] = MJ.Dot(DJ); + Rot[1][2] = MJ.Dot(DK); + Rot[2][0] = MK.Dot(DI); + Rot[2][1] = MK.Dot(DJ); + Rot[2][2] = MK.Dot(DK); + + TMatrixT PD1(3, 1); + PD1[0][0] = PDD[0]; + PD1[1][0] = PDD[1]; + PD1[2][0] = PDD[2]; + + TMatrixT Rot1(3, 3); + for (int i = 0; i < 3; i++) + for (int j = 0; j < 3; j++) { + Rot1[i][j] = Rot[i][j]; + } + TMatrixT Rot1xPD1(Rot1, TMatrixT::kMult, PD1); + PD[0] = Rot1xPD1[0][0]; + PD[1] = Rot1xPD1[1][0]; + PD[2] = Rot1xPD1[2][0]; + + // jacobian for error matrix in MARS + + Rmat[0][0] = Rot[0][0]; + Rmat[0][1] = Rot[0][1]; + Rmat[0][2] = Rot[0][2]; + Rmat[1][0] = Rot[1][0]; + Rmat[1][1] = Rot[1][1]; + Rmat[1][2] = Rot[1][2]; + Rmat[2][0] = Rot[2][0]; + Rmat[2][1] = Rot[2][1]; + Rmat[2][2] = Rot[2][2]; + + Rmat[3][3] = Rot[0][0]; + Rmat[3][4] = Rot[0][1]; + Rmat[3][5] = Rot[0][2]; + Rmat[4][3] = Rot[1][0]; + Rmat[4][4] = Rot[1][1]; + Rmat[4][5] = Rot[1][2]; + Rmat[5][3] = Rot[2][0]; + Rmat[5][4] = Rot[2][1]; + Rmat[5][5] = Rot[2][2]; + + // transposed of the jacobian + + for (Int_t I = 0; I < 6; I++) { + for (Int_t K = 0; K < 6; K++) { + Rtra[K][I] = Rmat[I][K]; + } + } - TVector3 xyz = TVector3(xyzvec[0][0], xyzvec[1][0], xyzvec[2][0]); + for (Int_t i = 0; i < 6; i++) { + for (Int_t k = 0; k < 6; k++) { + for (Int_t l = 0; l < 6; l++) { + AJJ[i][k] += RD1[i][l] * Rtra[l][k]; + } + } + } + + for (Int_t i = 0; i < 6; i++) { + for (Int_t k = 0; k < 6; k++) { + for (Int_t l = 0; l < 6; l++) { + RD[i][k] += Rmat[i][l] * AJJ[l][k]; + } + } + } +} + +void FairGeaneUtil::FromMat25ToVec15(Double_t A[5][5], Double_t* V) +{ + // + // ------------------------------------------------------ + // Passage from a symmetric 5x5 matrix to a 15-dim vector + // following the upper triangular convention + // + // Author A. Rotondi June 2007 + // + // ------------------------------------------------------ + + V[0] = A[0][0]; + V[1] = A[0][1]; + V[2] = A[0][2]; + V[3] = A[0][3]; + V[4] = A[0][4]; + + V[5] = A[1][1]; + V[6] = A[1][2]; + V[7] = A[1][3]; + V[8] = A[1][4]; + + V[9] = A[2][2]; + V[10] = A[2][3]; + V[11] = A[2][4]; + + V[12] = A[3][3]; + V[13] = A[3][4]; + + V[14] = A[4][4]; +} + +void FairGeaneUtil::FromMatToVec(Double_t A[5][5], Double_t* V) +{ + // + // ------------------------------------------------------ + // Passage from a 5x5 matrix to a 25-dim vector + // + // Author A. Rotondi June 2007 + // + // ------------------------------------------------------ + + V[0] = A[0][0]; + V[1] = A[1][0]; + V[2] = A[2][0]; + V[3] = A[3][0]; + V[4] = A[4][0]; + + V[5] = A[0][1]; + V[6] = A[1][1]; + V[7] = A[2][1]; + V[8] = A[3][1]; + V[9] = A[4][1]; + + V[10] = A[0][2]; + V[11] = A[1][2]; + V[12] = A[2][2]; + V[13] = A[3][2]; + V[14] = A[4][2]; + + V[15] = A[0][3]; + V[16] = A[1][3]; + V[17] = A[2][3]; + V[18] = A[3][3]; + V[19] = A[4][3]; + + V[20] = A[0][4]; + V[21] = A[1][4]; + V[22] = A[2][4]; + V[23] = A[3][4]; + V[24] = A[4][4]; +} - return xyz; +void FairGeaneUtil::SymmProd(Double_t A[25], Double_t S[15], Double_t* R) +{ + // + // --------------------------------------------------------- + // TRANSFORMATION OF SYMMETRIC 5X5 MATRIX S: + // A*S*AT -> R. + // A is a 25-dim vector corresonding to the 5x5 transformation + // matrix + // S and R ARE SYMMETRIC ERROR (COVARIANCE) MATRICES STORED + // IN TRIANGULAR FORM. + // + // INPUT + // A[25] transformation matrix 5x5 + // S[15] error matrix in triangular form + // + // OUTPUT + // R[15] error matrix in triangular form + // + // NB: S AND R MAY WELL BE THE SAME MATRIX. + // + // Author: A. Haas (Freiburg University) 5/7/81 + // transported with modifications + // in C/Root by A. Rotondi (June 2007) + // + // * ------------------------------------------------------ + + Double_t Q[15], T1, T2, T3, T4, T5; + + for (Int_t i = 0; i < 15; i++) { + Q[i] = S[i]; + } + + Int_t K = 0; + for (Int_t J = 0; J < 5; J++) { + T1 = A[J]; + T2 = A[J + 5]; + T3 = A[J + 10]; + T4 = A[J + 15]; + T5 = A[J + 20]; + for (Int_t I = J; I < 5; I++) { + R[K] = A[I] * (Q[0] * T1 + Q[1] * T2 + Q[2] * T3 + Q[3] * T4 + Q[4] * T5) + + A[I + 5] * (Q[1] * T1 + Q[5] * T2 + Q[6] * T3 + Q[7] * T4 + Q[8] * T5) + + A[I + 10] * (Q[2] * T1 + Q[6] * T2 + Q[9] * T3 + Q[10] * T4 + Q[11] * T5) + + A[I + 15] * (Q[3] * T1 + Q[7] * T2 + Q[10] * T3 + Q[12] * T4 + Q[13] * T5) + + A[I + 20] * (Q[4] * T1 + Q[8] * T2 + Q[11] * T3 + Q[13] * T4 + Q[14] * T5); + K++; + } + } } +// ------------------------- modifiche 27 jul 2007 -------------------------- -ClassImp(FairGeaneUtil) +TVector3 FairGeaneUtil::FromMARSToSDCoord(TVector3 xyz, TVector3 o, TVector3 di, TVector3 dj, TVector3 dk) +{ + + TMatrixT matrix(3, 3); + // rotation matrix (u,v,w) = (fmatrix) * (x,y,z) + matrix[0][0] = di[0]; + matrix[0][1] = di[1]; + matrix[0][2] = di[2]; + matrix[1][0] = dj[0]; + matrix[1][1] = dj[1]; + matrix[1][2] = dj[2]; + matrix[2][0] = dk[0]; + matrix[2][1] = dk[1]; + matrix[2][2] = dk[2]; + + TMatrixT xyzvec(3, 1); + xyzvec[0][0] = xyz.X(); + xyzvec[1][0] = xyz.Y(); + xyzvec[2][0] = xyz.Z(); + + TMatrixT origin(3, 1); + origin[0][0] = o.X(); + origin[1][0] = o.Y(); + origin[2][0] = o.Z(); + + xyzvec -= origin; + + TMatrixT uvwvec(matrix, TMatrixT::kMult, xyzvec); + + TVector3 uvw = TVector3(uvwvec[0][0], uvwvec[1][0], uvwvec[2][0]); + return uvw; +} + +TVector3 FairGeaneUtil::FromSDToMARSCoord(TVector3 uvw, TVector3 o, TVector3 di, TVector3 dj, TVector3 dk) +{ + TMatrixT matrix(3, 3); + matrix[0][0] = di[0]; + matrix[0][1] = di[1]; + matrix[0][2] = di[2]; + matrix[1][0] = dj[0]; + matrix[1][1] = dj[1]; + matrix[1][2] = dj[2]; + matrix[2][0] = dk[0]; + matrix[2][1] = dk[1]; + matrix[2][2] = dk[2]; + + TMatrixT uvwvec(3, 1); + uvwvec[0][0] = uvw.X(); + uvwvec[1][0] = uvw.Y(); + uvwvec[2][0] = uvw.Z(); + + TMatrixT uvwrot(matrix, TMatrixT::kTransposeMult, uvwvec); + + TMatrixT origin(3, 1); + origin[0][0] = o.X(); + origin[1][0] = o.Y(); + origin[2][0] = o.Z(); + + TMatrixT xyzvec(3, 1); + xyzvec = uvwrot + origin; + + TVector3 xyz = TVector3(xyzvec[0][0], xyzvec[1][0], xyzvec[2][0]); + + return xyz; +} +ClassImp(FairGeaneUtil); diff --git a/trackbase/FairGeaneUtil.h b/trackbase/FairGeaneUtil.h index 1d53fdec50..dffd893916 100644 --- a/trackbase/FairGeaneUtil.h +++ b/trackbase/FairGeaneUtil.h @@ -1,17 +1,16 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRGEANEUTIL_H #define FAIRGEANEUTIL_H -#include // for TObject - -#include // for Double_t, Int_t, etc -#include // for TVector3 +#include // for Double_t, Int_t, etc +#include // for TObject +#include // for TVector3 class FairGeaneUtil : public TObject { @@ -20,54 +19,93 @@ class FairGeaneUtil : public TObject ~FairGeaneUtil(); // frame changing - void FromPtToSC(Double_t PC[3], Double_t RC[15], - Double_t* PD, Double_t* RD, Int_t& IERR); - - void FromPtToSD(Double_t PD[3], Double_t RD[15], Double_t H[3],Int_t CH, - Double_t SPU, Double_t DJ[3], Double_t DK[3], - Int_t& IERR, Double_t* PC, Double_t* RC); - - void FromSCToPt(Double_t PC[3], Double_t RC[15], - Double_t* PD, Double_t* RD, Int_t& IERR); - - void FromSCToSD(Double_t PC[3], Double_t RC[15], Double_t H[3], Int_t CH, - Double_t DJ[3], Double_t DK[3], - Int_t& IERR, Double_t& SPU, - Double_t* PD, Double_t* RD); - - void FromSD1ToSD2(Double_t PD1[3], Double_t RD1[15],Double_t H[3], - Int_t CH, Double_t SP1, - Double_t DJ1[3], Double_t DK1[3], - Double_t DJ2[3], Double_t DK2[3], - Int_t& IERR, Double_t& SP2, - Double_t* PD2, Double_t* RD2); - - void FromSDToPt(Double_t PD[3], Double_t RD[15], Double_t H[3], - Int_t CH, Double_t SPU, Double_t DJ[3], Double_t DK[3], - Int_t& IERR, Double_t* PC, Double_t* RC); - - void FromSDToSC(Double_t PD[3], Double_t RD[15], Double_t H[3], Int_t CH, - Double_t SPU, Double_t DJ[3], Double_t DK[3], - Int_t& IERR, Double_t* PC, Double_t* RC); + void FromPtToSC(Double_t PC[3], Double_t RC[15], Double_t* PD, Double_t* RD, Int_t& IERR); + + void FromPtToSD(Double_t PD[3], + Double_t RD[15], + Double_t H[3], + Int_t CH, + Double_t SPU, + Double_t DJ[3], + Double_t DK[3], + Int_t& IERR, + Double_t* PC, + Double_t* RC); + + void FromSCToPt(Double_t PC[3], Double_t RC[15], Double_t* PD, Double_t* RD, Int_t& IERR); + + void FromSCToSD(Double_t PC[3], + Double_t RC[15], + Double_t H[3], + Int_t CH, + Double_t DJ[3], + Double_t DK[3], + Int_t& IERR, + Double_t& SPU, + Double_t* PD, + Double_t* RD); + + void FromSD1ToSD2(Double_t PD1[3], + Double_t RD1[15], + Double_t H[3], + Int_t CH, + Double_t SP1, + Double_t DJ1[3], + Double_t DK1[3], + Double_t DJ2[3], + Double_t DK2[3], + Int_t& IERR, + Double_t& SP2, + Double_t* PD2, + Double_t* RD2); + + void FromSDToPt(Double_t PD[3], + Double_t RD[15], + Double_t H[3], + Int_t CH, + Double_t SPU, + Double_t DJ[3], + Double_t DK[3], + Int_t& IERR, + Double_t* PC, + Double_t* RC); + + void FromSDToSC(Double_t PD[3], + Double_t RD[15], + Double_t H[3], + Int_t CH, + Double_t SPU, + Double_t DJ[3], + Double_t DK[3], + Int_t& IERR, + Double_t* PC, + Double_t* RC); typedef Double_t sixMat[6][6]; - void FromSCToMars(Double_t PC[3], Double_t RC[15], Double_t H[3], Int_t CH, - Double_t* PD, sixMat& RD); - - void FromMarsToSC(Double_t PD[3], Double_t RD[6][6], Double_t H[3], - Int_t CH, - Double_t* PC, Double_t* RC); + void FromSCToMars(Double_t PC[3], Double_t RC[15], Double_t H[3], Int_t CH, Double_t* PD, sixMat& RD); - void FromSDToMars(Double_t PC[3], Double_t RC[15], - Double_t H[3], Int_t CH, - Double_t SP1, Double_t DJ1[3], Double_t DK1[3], - Double_t* PD, sixMat& RD); + void FromMarsToSC(Double_t PD[3], Double_t RD[6][6], Double_t H[3], Int_t CH, Double_t* PC, Double_t* RC); - void FromMarsToSD(Double_t PD[3], Double_t RD[6][6], - Double_t H[3], Int_t CH, - Double_t DJ1[3], Double_t DK1[3], - Int_t& IERR, Double_t& SP1, - Double_t* PC, Double_t* RC); + void FromSDToMars(Double_t PC[3], + Double_t RC[15], + Double_t H[3], + Int_t CH, + Double_t SP1, + Double_t DJ1[3], + Double_t DK1[3], + Double_t* PD, + sixMat& RD); + + void FromMarsToSD(Double_t PD[3], + Double_t RD[6][6], + Double_t H[3], + Int_t CH, + Double_t DJ1[3], + Double_t DK1[3], + Int_t& IERR, + Double_t& SP1, + Double_t* PC, + Double_t* RC); void FromMat25ToVec15(Double_t A[5][5], Double_t* V); void FromMatToVec(Double_t A[5][5], Double_t* V); @@ -80,7 +118,7 @@ class FairGeaneUtil : public TObject TVector3 FromMARSToSDCoord(TVector3 xyz, TVector3 o, TVector3 di, TVector3 dj, TVector3 dk); TVector3 FromSDToMARSCoord(TVector3 uvw, TVector3 o, TVector3 di, TVector3 dj, TVector3 dk); - ClassDef(FairGeaneUtil,1); + ClassDef(FairGeaneUtil, 1); }; #endif diff --git a/trackbase/FairPropagator.cxx b/trackbase/FairPropagator.cxx index 63c57aa3d1..ed0e53191b 100644 --- a/trackbase/FairPropagator.cxx +++ b/trackbase/FairPropagator.cxx @@ -9,17 +9,13 @@ #include "FairPropagator.h" FairPropagator::FairPropagator() - : TNamed("FairPropagator", "Base class for propagators") -{ -} + : TNamed("FairPropagator", "Base class for propagators") +{} FairPropagator::FairPropagator(const TString& name, const TString& title) - : TNamed(name, title) -{ -} + : TNamed(name, title) +{} -FairPropagator::~FairPropagator() -{ -} +FairPropagator::~FairPropagator() {} -ClassImp(FairPropagator) +ClassImp(FairPropagator); diff --git a/trackbase/FairPropagator.h b/trackbase/FairPropagator.h index dc2b7777cd..f90a73b749 100644 --- a/trackbase/FairPropagator.h +++ b/trackbase/FairPropagator.h @@ -23,7 +23,8 @@ class FairTrackPar; class FairTrackParH; class FairTrackParP; -struct PCAOutputStruct { +struct PCAOutputStruct +{ // OUTPUT STRUCT ---------------------------------------- // .. PCAStatusFlag 0 by success, else otherwise // .. Radius : radius if the found circle @@ -31,14 +32,20 @@ struct PCAOutputStruct { // .. OnWirePCA : point of closest approach on wire // .. Distance : distance between track and wire in the PCA // .. TrackLength : track length to add to the GEANE one - PCAOutputStruct() : PCAStatusFlag(1), Radius(0.), OnTrackPCA(TVector3(0.,0.,0.)), OnWirePCA(TVector3(0.,0.,0.)), Distance(0.), TrackLength(0.){ - } - int PCAStatusFlag; - double Radius; - TVector3 OnTrackPCA; - TVector3 OnWirePCA; - double Distance; - float TrackLength; + PCAOutputStruct() + : PCAStatusFlag(1) + , Radius(0.) + , OnTrackPCA(TVector3(0., 0., 0.)) + , OnWirePCA(TVector3(0., 0., 0.)) + , Distance(0.) + , TrackLength(0.) + {} + int PCAStatusFlag; + double Radius; + TVector3 OnTrackPCA; + TVector3 OnWirePCA; + double Distance; + float TrackLength; }; class FairPropagator : public TNamed @@ -50,41 +57,45 @@ class FairPropagator : public TNamed virtual ~FairPropagator(); - virtual void Init(FairTrackPar* /* TParam */) {}; + virtual void Init(FairTrackPar* /* TParam */){}; /**New method to set the plane to propagate particles to @v0 v1 v2 Plane defining vectors */ - virtual bool SetDestinationPlane(TVector3& /* v0 */, TVector3& /* v1 */, TVector3& /* v2 */) {return false;} + virtual bool SetDestinationPlane(TVector3& /* v0 */, TVector3& /* v1 */, TVector3& /* v2 */) { return false; } /**New method to set the plane to propagate particles from @v0 v1 Plane defining vectors */ - virtual bool SetOriginPlane(TVector3& /* v0 */, TVector3& /* v1 */) {return false;} + virtual bool SetOriginPlane(TVector3& /* v0 */, TVector3& /* v1 */) { return false; } /**New method to set the volume to propagate particles to @volName Volume name @copyNo Copy number @option Option */ - virtual bool SetDestinationVolume(std::string /* volName */, int /* copyNo */, int /* option */) {return false;} + virtual bool SetDestinationVolume(std::string /* volName */, int /* copyNo */, int /* option */) { return false; } /**New method to set the length to propagate particles to @length Track length */ - virtual bool SetDestinationLength(float length) {return false;} + virtual bool SetDestinationLength(float length) { return false; } /**New method to set to propagate only parameters - */ - virtual bool SetPropagateOnlyParameters() {return false;} + */ + virtual bool SetPropagateOnlyParameters() { return false; } virtual bool Propagate(FairTrackParH* /* TStart */, FairTrackParH* /* TEnd */, int /* PDG */) { return false; } virtual bool Propagate(FairTrackParP* /* TStart */, FairTrackParH* /* TEnd */, int /* PDG */) { return false; } virtual bool Propagate(FairTrackParP* /* TStart */, FairTrackParP* /* TEnd */, int /* PDG */) { return false; } virtual bool Propagate(FairTrackParH* /* TStart */, FairTrackParP* /* TEnd */, int /* PDG */) { return false; } - virtual bool Propagate(float* /* x1 */, float* /* p1 */, float* /* x2 */, float* /* p2 */, int /* PDG */) { return false; } + virtual bool Propagate(float* /* x1 */, float* /* p1 */, float* /* x2 */, float* /* p2 */, int /* PDG */) + { + return false; + } - /* =========================================================================================================================================== */ + /* =========================================================================================================================================== + */ // Set PCA propagation: // .. pca = ic = 1 closest approach to point @@ -103,7 +114,15 @@ class FairPropagator : public TNamed // .. point point with respect to which calculate the closest approach // .. wire, wire2 line with respect to which calculate the closest approach // .. maxdistance = geometrical distance[start - point/wire extr] * 2 - virtual PCAOutputStruct FindPCA(int PCA, int PDGCode, TVector3 Point, TVector3 Wire1, TVector3 Wire2, double MaxDistance) { return PCAOutputStruct(); } + virtual PCAOutputStruct FindPCA(int PCA, + int PDGCode, + TVector3 Point, + TVector3 Wire1, + TVector3 Wire2, + double MaxDistance) + { + return PCAOutputStruct(); + } ClassDef(FairPropagator, 1) }; diff --git a/trackbase/FairRKPropagator.cxx b/trackbase/FairRKPropagator.cxx index 540ffcebf1..e8e4cb121d 100644 --- a/trackbase/FairRKPropagator.cxx +++ b/trackbase/FairRKPropagator.cxx @@ -7,17 +7,15 @@ ********************************************************************************/ #include "FairRKPropagator.h" -#include "FairField.h" // for FairField - +#include "FairField.h" // for FairField #include "FairTrackParH.h" #include "FairTrackParP.h" -#include "TVector3.h" - #include "TDatabasePDG.h" -#include "TMath.h" // for Sqrt -#include "TMathBase.h" // for Abs +#include "TMath.h" // for Sqrt +#include "TMathBase.h" // for Abs +#include "TVector3.h" -#include // for printf +#include // for printf ClassImp(FairRKPropagator); @@ -25,7 +23,7 @@ ClassImp(FairRKPropagator); FairRKPropagator::FairRKPropagator(FairField* field) : FairPropagator("FairRKPropagator", "Runge-Kutta propagator") , fMaxStep(10.0) - , fMagField (field) + , fMagField(field) , fPropagationFlag(NONE) , fDefPlaneV0() , fDefPlaneV1() @@ -35,37 +33,40 @@ FairRKPropagator::FairRKPropagator(FairField* field) , fPCAPropagationPar(nullptr) { - // fMaxStep=10.0; + // fMaxStep=10.0; } //______________________________________________________________________________ FairRKPropagator::~FairRKPropagator() { - // Destructor. + // Destructor. } -double FairRKPropagator::GetChargeFromPDG(int pdg) { +double FairRKPropagator::GetChargeFromPDG(int pdg) +{ TDatabasePDG* pdgDB = TDatabasePDG::Instance(); - return pdgDB->GetParticle(pdg)->Charge()/3.; // Charge(): charge in units of |e|/3 + return pdgDB->GetParticle(pdg)->Charge() / 3.; // Charge(): charge in units of |e|/3 } -bool FairRKPropagator::Propagate(FairTrackParH* TStart, FairTrackParH* TEnd, int PDG) { - if ( fPropagationFlag == TOPLANE ) { - float x1[3] = {(float)TStart->GetX (),(float)TStart->GetY (),(float)TStart->GetZ ()}; - float p1[3] = {(float)TStart->GetPx(),(float)TStart->GetPy(),(float)TStart->GetPz()}; - float x2[3] = {0.,0.,0.}; - float p2[3] = {0.,0.,0.}; - bool ret = Propagate(x1,p1,x2,p2,PDG); - if ( !ret ) return false; - TEnd->SetX (x2[0]); - TEnd->SetY (x2[1]); - TEnd->SetZ (x2[2]); - TEnd->SetPx (p2[0]); - TEnd->SetPy (p2[1]); - TEnd->SetPz (p2[2]); - TEnd->SetQp (GetChargeFromPDG(PDG)/sqrt(p2[0]*p2[0]+p2[1]*p2[1]+p2[2]*p2[2])); - TEnd->SetDX (0.); - TEnd->SetDY (0.); - TEnd->SetDZ (0.); +bool FairRKPropagator::Propagate(FairTrackParH* TStart, FairTrackParH* TEnd, int PDG) +{ + if (fPropagationFlag == TOPLANE) { + float x1[3] = {(float)TStart->GetX(), (float)TStart->GetY(), (float)TStart->GetZ()}; + float p1[3] = {(float)TStart->GetPx(), (float)TStart->GetPy(), (float)TStart->GetPz()}; + float x2[3] = {0., 0., 0.}; + float p2[3] = {0., 0., 0.}; + bool ret = Propagate(x1, p1, x2, p2, PDG); + if (!ret) + return false; + TEnd->SetX(x2[0]); + TEnd->SetY(x2[1]); + TEnd->SetZ(x2[2]); + TEnd->SetPx(p2[0]); + TEnd->SetPy(p2[1]); + TEnd->SetPz(p2[2]); + TEnd->SetQp(GetChargeFromPDG(PDG) / sqrt(p2[0] * p2[0] + p2[1] * p2[1] + p2[2] * p2[2])); + TEnd->SetDX(0.); + TEnd->SetDY(0.); + TEnd->SetDZ(0.); TEnd->SetDPx(0.); TEnd->SetDPy(0.); TEnd->SetDPz(0.); @@ -75,24 +76,26 @@ bool FairRKPropagator::Propagate(FairTrackParH* TStart, FairTrackParH* TEnd, int return false; } -bool FairRKPropagator::Propagate(FairTrackParP* TStart, FairTrackParH* TEnd, int PDG) { - if ( fPropagationFlag == TOPLANE ) { - float x1[3] = {(float)TStart->GetX (),(float)TStart->GetY (),(float)TStart->GetZ ()}; - float p1[3] = {(float)TStart->GetPx(),(float)TStart->GetPy(),(float)TStart->GetPz()}; - float x2[3] = {0.,0.,0.}; - float p2[3] = {0.,0.,0.}; - bool ret = Propagate(x1,p1,x2,p2,PDG); - if ( !ret ) return false; - TEnd->SetX (x2[0]); - TEnd->SetY (x2[1]); - TEnd->SetZ (x2[2]); - TEnd->SetPx (p2[0]); - TEnd->SetPy (p2[1]); - TEnd->SetPz (p2[2]); - TEnd->SetQp (GetChargeFromPDG(PDG)/sqrt(p2[0]*p2[0]+p2[1]*p2[1]+p2[2]*p2[2])); - TEnd->SetDX (0.); - TEnd->SetDY (0.); - TEnd->SetDZ (0.); +bool FairRKPropagator::Propagate(FairTrackParP* TStart, FairTrackParH* TEnd, int PDG) +{ + if (fPropagationFlag == TOPLANE) { + float x1[3] = {(float)TStart->GetX(), (float)TStart->GetY(), (float)TStart->GetZ()}; + float p1[3] = {(float)TStart->GetPx(), (float)TStart->GetPy(), (float)TStart->GetPz()}; + float x2[3] = {0., 0., 0.}; + float p2[3] = {0., 0., 0.}; + bool ret = Propagate(x1, p1, x2, p2, PDG); + if (!ret) + return false; + TEnd->SetX(x2[0]); + TEnd->SetY(x2[1]); + TEnd->SetZ(x2[2]); + TEnd->SetPx(p2[0]); + TEnd->SetPy(p2[1]); + TEnd->SetPz(p2[2]); + TEnd->SetQp(GetChargeFromPDG(PDG) / sqrt(p2[0] * p2[0] + p2[1] * p2[1] + p2[2] * p2[2])); + TEnd->SetDX(0.); + TEnd->SetDY(0.); + TEnd->SetDZ(0.); TEnd->SetDPx(0.); TEnd->SetDPy(0.); TEnd->SetDPz(0.); @@ -102,24 +105,26 @@ bool FairRKPropagator::Propagate(FairTrackParP* TStart, FairTrackParH* TEnd, int return false; } -bool FairRKPropagator::Propagate(FairTrackParP* TStart, FairTrackParP* TEnd, int PDG) { - if ( fPropagationFlag == TOPLANE ) { - float x1[3] = {(float)TStart->GetX (),(float)TStart->GetY (),(float)TStart->GetZ ()}; - float p1[3] = {(float)TStart->GetPx(),(float)TStart->GetPy(),(float)TStart->GetPz()}; - float x2[3] = {0.,0.,0.}; - float p2[3] = {0.,0.,0.}; - bool ret = Propagate(x1,p1,x2,p2,PDG); - if ( !ret ) return false; - TEnd->SetX (x2[0]); - TEnd->SetY (x2[1]); - TEnd->SetZ (x2[2]); - TEnd->SetPx (p2[0]); - TEnd->SetPy (p2[1]); - TEnd->SetPz (p2[2]); - TEnd->SetQp (GetChargeFromPDG(PDG)/sqrt(p2[0]*p2[0]+p2[1]*p2[1]+p2[2]*p2[2])); - TEnd->SetDX (0.); - TEnd->SetDY (0.); - TEnd->SetDZ (0.); +bool FairRKPropagator::Propagate(FairTrackParP* TStart, FairTrackParP* TEnd, int PDG) +{ + if (fPropagationFlag == TOPLANE) { + float x1[3] = {(float)TStart->GetX(), (float)TStart->GetY(), (float)TStart->GetZ()}; + float p1[3] = {(float)TStart->GetPx(), (float)TStart->GetPy(), (float)TStart->GetPz()}; + float x2[3] = {0., 0., 0.}; + float p2[3] = {0., 0., 0.}; + bool ret = Propagate(x1, p1, x2, p2, PDG); + if (!ret) + return false; + TEnd->SetX(x2[0]); + TEnd->SetY(x2[1]); + TEnd->SetZ(x2[2]); + TEnd->SetPx(p2[0]); + TEnd->SetPy(p2[1]); + TEnd->SetPz(p2[2]); + TEnd->SetQp(GetChargeFromPDG(PDG) / sqrt(p2[0] * p2[0] + p2[1] * p2[1] + p2[2] * p2[2])); + TEnd->SetDX(0.); + TEnd->SetDY(0.); + TEnd->SetDZ(0.); TEnd->SetDPx(0.); TEnd->SetDPy(0.); TEnd->SetDPz(0.); @@ -129,24 +134,26 @@ bool FairRKPropagator::Propagate(FairTrackParP* TStart, FairTrackParP* TEnd, int return false; } -bool FairRKPropagator::Propagate(FairTrackParH* TStart, FairTrackParP* TEnd, int PDG) { - if ( fPropagationFlag == TOPLANE ) { - float x1[3] = {(float)TStart->GetX (),(float)TStart->GetY (),(float)TStart->GetZ ()}; - float p1[3] = {(float)TStart->GetPx(),(float)TStart->GetPy(),(float)TStart->GetPz()}; - float x2[3] = {0.,0.,0.}; - float p2[3] = {0.,0.,0.}; - bool ret = Propagate(x1,p1,x2,p2,PDG); - if ( !ret ) return false; - TEnd->SetX (x2[0]); - TEnd->SetY (x2[1]); - TEnd->SetZ (x2[2]); - TEnd->SetPx (p2[0]); - TEnd->SetPy (p2[1]); - TEnd->SetPz (p2[2]); - TEnd->SetQp (GetChargeFromPDG(PDG)/sqrt(p2[0]*p2[0]+p2[1]*p2[1]+p2[2]*p2[2])); - TEnd->SetDX (0.); - TEnd->SetDY (0.); - TEnd->SetDZ (0.); +bool FairRKPropagator::Propagate(FairTrackParH* TStart, FairTrackParP* TEnd, int PDG) +{ + if (fPropagationFlag == TOPLANE) { + float x1[3] = {(float)TStart->GetX(), (float)TStart->GetY(), (float)TStart->GetZ()}; + float p1[3] = {(float)TStart->GetPx(), (float)TStart->GetPy(), (float)TStart->GetPz()}; + float x2[3] = {0., 0., 0.}; + float p2[3] = {0., 0., 0.}; + bool ret = Propagate(x1, p1, x2, p2, PDG); + if (!ret) + return false; + TEnd->SetX(x2[0]); + TEnd->SetY(x2[1]); + TEnd->SetZ(x2[2]); + TEnd->SetPx(p2[0]); + TEnd->SetPy(p2[1]); + TEnd->SetPz(p2[2]); + TEnd->SetQp(GetChargeFromPDG(PDG) / sqrt(p2[0] * p2[0] + p2[1] * p2[1] + p2[2] * p2[2])); + TEnd->SetDX(0.); + TEnd->SetDY(0.); + TEnd->SetDZ(0.); TEnd->SetDPx(0.); TEnd->SetDPy(0.); TEnd->SetDPz(0.); @@ -156,28 +163,29 @@ bool FairRKPropagator::Propagate(FairTrackParH* TStart, FairTrackParP* TEnd, int return false; } -bool FairRKPropagator::Propagate(float* x1, float* p1, float* x2, float* p2, int PDG) { +bool FairRKPropagator::Propagate(float* x1, float* p1, float* x2, float* p2, int PDG) +{ double charge = GetChargeFromPDG(PDG); - double momIn = TMath::Sqrt(p1[0]*p1[0]+p1[1]*p1[1]+p1[2]*p1[2]); - if ( momIn == 0. ) return false; - double vecIn[7] = {x1[0] ,x1[1] ,x1[2], - p1[0]/momIn,p1[1]/momIn,p1[2]/momIn, - momIn}; + double momIn = TMath::Sqrt(p1[0] * p1[0] + p1[1] * p1[1] + p1[2] * p1[2]); + if (momIn == 0.) + return false; + double vecIn[7] = {x1[0], x1[1], x1[2], p1[0] / momIn, p1[1] / momIn, p1[2] / momIn, momIn}; double vecOut[7]; - double vec1[3] = {fDefPlaneV1.X(),fDefPlaneV1.Y(),fDefPlaneV1.Z()}; - double vec2[3] = {fDefPlaneV2.X(),fDefPlaneV2.Y(),fDefPlaneV2.Z()}; - double vec3[3] = {fDefPlaneV0.X(),fDefPlaneV0.Y(),fDefPlaneV0.Z()}; - PropagateToPlane(charge,vecIn,vec1,vec2,vec3,vecOut); + double vec1[3] = {fDefPlaneV1.X(), fDefPlaneV1.Y(), fDefPlaneV1.Z()}; + double vec2[3] = {fDefPlaneV2.X(), fDefPlaneV2.Y(), fDefPlaneV2.Z()}; + double vec3[3] = {fDefPlaneV0.X(), fDefPlaneV0.Y(), fDefPlaneV0.Z()}; + PropagateToPlane(charge, vecIn, vec1, vec2, vec3, vecOut); x2[0] = vecOut[0]; x2[1] = vecOut[1]; x2[2] = vecOut[2]; - p2[0] = vecOut[3]*vecOut[6]; - p2[1] = vecOut[4]*vecOut[6]; - p2[2] = vecOut[5]*vecOut[6]; + p2[0] = vecOut[3] * vecOut[6]; + p2[1] = vecOut[4] * vecOut[6]; + p2[2] = vecOut[5] * vecOut[6]; return true; } -bool FairRKPropagator::SetDestinationPlane(TVector3& v0, TVector3& v1, TVector3& v2) { +bool FairRKPropagator::SetDestinationPlane(TVector3& v0, TVector3& v1, TVector3& v2) +{ fDefPlaneV0 = v0; fDefPlaneV1 = v1; fDefPlaneV2 = v2; @@ -185,104 +193,132 @@ bool FairRKPropagator::SetDestinationPlane(TVector3& v0, TVector3& v1, TVector3& return true; } -bool FairRKPropagator::SetOriginPlane(TVector3& v0, TVector3& v1) { +bool FairRKPropagator::SetOriginPlane(TVector3& v0, TVector3& v1) +{ LOG(warning) << "FairRKPropagator::SetLengthToPropagateTo not implemented yet"; return false; } -bool FairRKPropagator::SetDestinationVolume(std::string volName, int copyNo, int option) { +bool FairRKPropagator::SetDestinationVolume(std::string volName, int copyNo, int option) +{ LOG(warning) << "FairRKPropagator::SetDestinationVolume not implemented yet"; return false; } -bool FairRKPropagator::SetDestinationLength(float length) { +bool FairRKPropagator::SetDestinationLength(float length) +{ LOG(warning) << "FairRKPropagator::SetDestinationLength not implemented yet"; return false; } //______________________________________________________________________________ -bool FairRKPropagator::SetPCAPropagation(int pca, int dir, FairTrackParP* par) { - if ( abs(dir) != 1 ) { +bool FairRKPropagator::SetPCAPropagation(int pca, int dir, FairTrackParP* par) +{ + if (abs(dir) != 1) { LOG(warning) << "Set PCA dir to +1 or -1."; return false; } fPCAPropagationType = pca; - fPCAPropagationDir = dir; - fPCAPropagationPar = par; + fPCAPropagationDir = dir; + fPCAPropagationPar = par; return true; } //______________________________________________________________________________ -PCAOutputStruct FairRKPropagator::FindPCA(int PCA, int PDGCode, TVector3 Point, TVector3 Wire1, TVector3 Wire2, double MaxDistance) { +PCAOutputStruct FairRKPropagator::FindPCA(int PCA, + int PDGCode, + TVector3 Point, + TVector3 Wire1, + TVector3 Wire2, + double MaxDistance) +{ PCAOutputStruct pcastruct = PCAOutputStruct(); - if ( PCA != 1 && PCA != 2 ) { + if (PCA != 1 && PCA != 2) { LOG(info) << "FairRKPropagator::FindPCA implemented for point (pca=1) and wire (pca=2) only"; return pcastruct; } double charge = GetChargeFromPDG(PDGCode); - double momIn = fPCAPropagationDir* // if set to -1, it will back propagate - TMath::Sqrt(fPCAPropagationPar->GetPx()*fPCAPropagationPar->GetPx()+ - fPCAPropagationPar->GetPy()*fPCAPropagationPar->GetPy()+ - fPCAPropagationPar->GetPz()*fPCAPropagationPar->GetPz()); - if ( momIn == 0. ) return pcastruct; - double vecIn[7] = {fPCAPropagationPar->GetX(), fPCAPropagationPar->GetY(), fPCAPropagationPar->GetZ(), - fPCAPropagationPar->GetPx()/momIn, fPCAPropagationPar->GetPy()/momIn, fPCAPropagationPar->GetPz()/momIn, + double momIn = fPCAPropagationDir * // if set to -1, it will back propagate + TMath::Sqrt(fPCAPropagationPar->GetPx() * fPCAPropagationPar->GetPx() + + fPCAPropagationPar->GetPy() * fPCAPropagationPar->GetPy() + + fPCAPropagationPar->GetPz() * fPCAPropagationPar->GetPz()); + if (momIn == 0.) + return pcastruct; + double vecIn[7] = {fPCAPropagationPar->GetX(), + fPCAPropagationPar->GetY(), + fPCAPropagationPar->GetZ(), + fPCAPropagationPar->GetPx() / momIn, + fPCAPropagationPar->GetPy() / momIn, + fPCAPropagationPar->GetPz() / momIn, momIn}; double diff; - if ( PCA == 1 ) - diff = sqrt((vecIn[0]-Point.X())*(vecIn[0]-Point.X())+ - (vecIn[1]-Point.Y())*(vecIn[1]-Point.Y())+ - (vecIn[2]-Point.Z())*(vecIn[2]-Point.Z())); - else //if ( PCA == 2 ) - diff = CalculatePointToWireDistance(TVector3(fPCAPropagationPar->GetX(), fPCAPropagationPar->GetY(), fPCAPropagationPar->GetZ()), Wire1, Wire2, pcastruct.OnWirePCA); - - fMaxStep = diff/25; - double res_old= diff; + if (PCA == 1) + diff = sqrt((vecIn[0] - Point.X()) * (vecIn[0] - Point.X()) + (vecIn[1] - Point.Y()) * (vecIn[1] - Point.Y()) + + (vecIn[2] - Point.Z()) * (vecIn[2] - Point.Z())); + else // if ( PCA == 2 ) + diff = CalculatePointToWireDistance( + TVector3(fPCAPropagationPar->GetX(), fPCAPropagationPar->GetY(), fPCAPropagationPar->GetZ()), + Wire1, + Wire2, + pcastruct.OnWirePCA); + + fMaxStep = diff / 25; + double res_old = diff; double res = 100.0; double vecOut[7]; double vecOutT[7]; - for (int i=0; i< 7; i++) {vecOut[i]=0; vecOutT[i]=0;} + for (int i = 0; i < 7; i++) { + vecOut[i] = 0; + vecOutT[i] = 0; + } - int nIter=0; + int nIter = 0; pcastruct.TrackLength = 0.; do { - double stepLength = Step(charge,vecIn,vecOut); + double stepLength = Step(charge, vecIn, vecOut); double newDiff; - if ( PCA == 1 ) - newDiff = sqrt((vecOut[0]-Point.X())*(vecOut[0]-Point.X())+ - (vecOut[1]-Point.Y())*(vecOut[1]-Point.Y())+ - (vecOut[2]-Point.Z())*(vecOut[2]-Point.Z())); - else //if ( PCA == 2 ) - newDiff = CalculatePointToWireDistance(TVector3(vecOut[0], vecOut[1], vecOut[2]), Wire1, Wire2, pcastruct.OnWirePCA); - - res=newDiff/diff; - if( TMath::Abs(res)< 0.01 || res >res_old ) { + if (PCA == 1) + newDiff = sqrt((vecOut[0] - Point.X()) * (vecOut[0] - Point.X()) + + (vecOut[1] - Point.Y()) * (vecOut[1] - Point.Y()) + + (vecOut[2] - Point.Z()) * (vecOut[2] - Point.Z())); + else // if ( PCA == 2 ) + newDiff = CalculatePointToWireDistance( + TVector3(vecOut[0], vecOut[1], vecOut[2]), Wire1, Wire2, pcastruct.OnWirePCA); + + res = newDiff / diff; + if (TMath::Abs(res) < 0.01 || res > res_old) { break; } else { - for (int i=0; i< 7; i++) { - vecOutT[i]=vecOut[i]; - vecIn [i]=vecOut[i]; + for (int i = 0; i < 7; i++) { + vecOutT[i] = vecOut[i]; + vecIn[i] = vecOut[i]; } - res_old=res; + res_old = res; pcastruct.TrackLength += stepLength; } - if(nIter++>1000) { break; } - } while(1); - if (res > res_old) for (int k=0; k< 7; k++) { vecOut[k]=vecOutT[k]; } + if (nIter++ > 1000) { + break; + } + } while (1); + if (res > res_old) + for (int k = 0; k < 7; k++) { + vecOut[k] = vecOutT[k]; + } pcastruct.OnTrackPCA.SetX(vecOut[0]); pcastruct.OnTrackPCA.SetY(vecOut[1]); pcastruct.OnTrackPCA.SetZ(vecOut[2]); - if ( PCA == 1 ) - pcastruct.Distance = sqrt((vecOut[0]-Point.X())*(vecOut[0]-Point.X())+ - (vecOut[1]-Point.Y())*(vecOut[1]-Point.Y())+ - (vecOut[2]-Point.Z())*(vecOut[2]-Point.Z())); - else //if ( pcastruct.PCA == 2 ) - pcastruct.Distance = CalculatePointToWireDistance(TVector3(vecOut[0], vecOut[1], vecOut[2]), Wire1, Wire2, pcastruct.OnWirePCA); + if (PCA == 1) + pcastruct.Distance = + sqrt((vecOut[0] - Point.X()) * (vecOut[0] - Point.X()) + (vecOut[1] - Point.Y()) * (vecOut[1] - Point.Y()) + + (vecOut[2] - Point.Z()) * (vecOut[2] - Point.Z())); + else // if ( pcastruct.PCA == 2 ) + pcastruct.Distance = + CalculatePointToWireDistance(TVector3(vecOut[0], vecOut[1], vecOut[2]), Wire1, Wire2, pcastruct.OnWirePCA); pcastruct.PCAStatusFlag = 0; return pcastruct; } @@ -294,359 +330,392 @@ double FairRKPropagator::CalculatePointToWireDistance(TVector3 point, TVector3 w TVector3 ab = wire2 - wire1; TVector3 av = point - wire1; - if ( av.Dot(ab) <= 0.0 ) { // Point is lagging behind start of the segment, so perpendicular distance is not viable + if (av.Dot(ab) <= 0.0) { // Point is lagging behind start of the segment, so perpendicular distance is not viable vwi = wire1; - return av.Mag(); // Use distance to start of segment instead + return av.Mag(); // Use distance to start of segment instead } TVector3 bv = point - wire2; - if ( bv.Dot(ab) >= 0.0 ) { // Point is advanced past the end of the segment, so perpendicular distance is not viable + if (bv.Dot(ab) >= 0.0) { // Point is advanced past the end of the segment, so perpendicular distance is not viable vwi = wire2; - return bv.Mag(); // Use distance to end of the segment instead + return bv.Mag(); // Use distance to end of the segment instead } - vwi = ( ab.Dot(av) / ab.Mag() / ab.Mag() ) * ab; + vwi = (ab.Dot(av) / ab.Mag() / ab.Mag()) * ab; vwi += wire1; - return (ab.Cross(av)).Mag() / ab.Mag(); // Perpendicular distance of point to segment + return (ab.Cross(av)).Mag() / ab.Mag(); // Perpendicular distance of point to segment } //______________________________________________________________________________ //______________________________________________________________________________ -void FairRKPropagator::PropagateToPlane(double Charge, double* vecRKIn, double* vec1, double* vec2, double* vec3, double* vecOut) +void FairRKPropagator::PropagateToPlane(double Charge, + double* vecRKIn, + double* vec1, + double* vec2, + double* vec3, + double* vecOut) { - /** + /** vec1 & vec2 are vectors on the plane vec3 a point on the plane */ - double Norm[3]; - double Mag; - double dist[3]; - double distance[3]; - double vecRKoutT[7]; - - for (int i=0; i< 7; i++) {vecRKoutT[i]=0;} - - Norm[0]=vec1[1]*vec2[2] - vec2[2] * vec2[1]; // a2b3 − a3b2, - Norm[1]=vec1[2]*vec2[0] - vec1[0] * vec2[2]; // a3b1 − a1b3; - Norm[2]=vec1[0]*vec2[1] - vec1[1] * vec2[0]; - - Mag=TMath::Sqrt(Norm[0]*Norm[0]+Norm[1]*Norm[1]+Norm[2]*Norm[2]); - - // printf(" Mag = %f \n ", Mag); - - Norm[0]=Norm[0]/Mag; - Norm[1]=Norm[1]/Mag; - Norm[2]=Norm[2]/Mag; - // printf(" after normalization : Normal = %f %f %f \n ", Norm[0],Norm[1],Norm[2]); - - dist[0]=vecRKIn[0]-vec3[0]; - dist[1]=vecRKIn[1]-vec3[1]; - dist[2]=vecRKIn[2]-vec3[2]; - - distance[0]=Norm[0]*dist[0]; - distance[1]=Norm[1]*dist[1]; - distance[2]=Norm[2]*dist[2]; -// printf(" distance = %f %f %f \n ", distance[0],distance[1],distance[2]); - double diff = TMath::Abs(distance[0]+distance[1]+distance[2]); - fMaxStep = diff; - double res = 100.0; - double res_old = 100.0; - - double vecRKOut[7]; - // for (int i=0; i< 7; i++) {vecRKOut[i]=0;} - int nIter=0; - - // printf("I am in CPU code %f %f %f res= %f diff = %f \n ", vecRKIn[0], vecRKIn[1],vecRKIn[2], res, diff); - - do { - Step(Charge,vecRKIn,vecRKOut); - dist[0]=(vecRKOut[0]-vec3[0])*Norm[0]; - dist[1]=(vecRKOut[1]-vec3[1])*Norm[1]; - dist[2]=(vecRKOut[2]-vec3[2])*Norm[2]; - fMaxStep=TMath::Sqrt(dist[0]*dist[0]+dist[1]*dist[1]+dist[2]*dist[2]); - res=TMath::Abs(fMaxStep/diff); - // printf("After %i step %f %f %f res = %f \n", nIter ,vecRKOut[0], vecRKOut[1],vecRKOut[2] , res); - if( res< 0.001 || res >res_old ) { - break; - } else { - for (int i=0; i< 7; i++) { - vecRKIn[i]=vecRKOut[i]; - vecRKoutT[i]=vecRKOut[i]; - } - res_old=res; + double Norm[3]; + double Mag; + double dist[3]; + double distance[3]; + double vecRKoutT[7]; + + for (int i = 0; i < 7; i++) { + vecRKoutT[i] = 0; + } + + Norm[0] = vec1[1] * vec2[2] - vec2[2] * vec2[1]; // a2b3 − a3b2, + Norm[1] = vec1[2] * vec2[0] - vec1[0] * vec2[2]; // a3b1 − a1b3; + Norm[2] = vec1[0] * vec2[1] - vec1[1] * vec2[0]; + + Mag = TMath::Sqrt(Norm[0] * Norm[0] + Norm[1] * Norm[1] + Norm[2] * Norm[2]); + + // printf(" Mag = %f \n ", Mag); + + Norm[0] = Norm[0] / Mag; + Norm[1] = Norm[1] / Mag; + Norm[2] = Norm[2] / Mag; + // printf(" after normalization : Normal = %f %f %f \n ", Norm[0],Norm[1],Norm[2]); + + dist[0] = vecRKIn[0] - vec3[0]; + dist[1] = vecRKIn[1] - vec3[1]; + dist[2] = vecRKIn[2] - vec3[2]; + + distance[0] = Norm[0] * dist[0]; + distance[1] = Norm[1] * dist[1]; + distance[2] = Norm[2] * dist[2]; + // printf(" distance = %f %f %f \n ", distance[0],distance[1],distance[2]); + double diff = TMath::Abs(distance[0] + distance[1] + distance[2]); + fMaxStep = diff; + double res = 100.0; + double res_old = 100.0; + + double vecRKOut[7]; + // for (int i=0; i< 7; i++) {vecRKOut[i]=0;} + int nIter = 0; + + // printf("I am in CPU code %f %f %f res= %f diff = %f \n ", vecRKIn[0], vecRKIn[1],vecRKIn[2], res, diff); + + do { + Step(Charge, vecRKIn, vecRKOut); + dist[0] = (vecRKOut[0] - vec3[0]) * Norm[0]; + dist[1] = (vecRKOut[1] - vec3[1]) * Norm[1]; + dist[2] = (vecRKOut[2] - vec3[2]) * Norm[2]; + fMaxStep = TMath::Sqrt(dist[0] * dist[0] + dist[1] * dist[1] + dist[2] * dist[2]); + res = TMath::Abs(fMaxStep / diff); + // printf("After %i step %f %f %f res = %f \n", nIter ,vecRKOut[0], vecRKOut[1],vecRKOut[2] , res); + if (res < 0.001 || res > res_old) { + break; + } else { + for (int i = 0; i < 7; i++) { + vecRKIn[i] = vecRKOut[i]; + vecRKoutT[i] = vecRKOut[i]; + } + res_old = res; + } + if (nIter++ > 1000) { + break; + } + } while (1); + // printf("The results is %f %f %f , no of iter %i \n", vecRKOut[0],vecRKOut[1],vecRKOut[2], nIter); + // printf("\n"); + for (int i = 0; i < 7; i++) { + if (res > res_old) { + vecOut[i] = vecRKoutT[i]; + } else { + vecOut[i] = vecRKOut[i]; + } } - if(nIter++>1000) { break; } - } while(1); -// printf("The results is %f %f %f , no of iter %i \n", vecRKOut[0],vecRKOut[1],vecRKOut[2], nIter); -// printf("\n"); - for (int i=0; i< 7; i++) { - if (res > res_old) { vecOut[i]=vecRKoutT[i]; } - else { vecOut[i]=vecRKOut[i]; } - } } //______________________________________________________________________________ void FairRKPropagator::Propagate(double Charge, double* vecRKIn, double* Pos) { - double diff = Pos[2] - vecRKIn[2]; - fMaxStep = diff/25; - double res_old= diff; - double res = 100.0; - double vecRKOut[7]; - double vecRKOutT[7]; - for (int i=0; i< 7; i++) {vecRKOut[i]=0; vecRKOutT[i]=0;} - - int nIter=0; - do { - Step(Charge,vecRKIn,vecRKOut); - res=(vecRKOut[2]-Pos[2])/diff; - if( TMath::Abs(res)< 0.01 || res >res_old ) { - break; - } else { - for (int i=0; i< 7; i++) { - vecRKOutT[i]=vecRKOut[i]; - vecRKIn[i]=vecRKOut[i]; - } + double diff = Pos[2] - vecRKIn[2]; + fMaxStep = diff / 25; + double res_old = diff; + double res = 100.0; + double vecRKOut[7]; + double vecRKOutT[7]; + for (int i = 0; i < 7; i++) { + vecRKOut[i] = 0; + vecRKOutT[i] = 0; + } + + int nIter = 0; + do { + Step(Charge, vecRKIn, vecRKOut); + res = (vecRKOut[2] - Pos[2]) / diff; + if (TMath::Abs(res) < 0.01 || res > res_old) { + break; + } else { + for (int i = 0; i < 7; i++) { + vecRKOutT[i] = vecRKOut[i]; + vecRKIn[i] = vecRKOut[i]; + } + } + if (nIter++ > 1000) { + break; + } + } while (1); + if (res > res_old) + for (int k = 0; k < 7; k++) { + vecRKOut[k] = vecRKOutT[k]; + } + for (int k = 0; k < 3; k++) { + printf(" vecRKOut[%i] =%f ", k, vecRKOut[k]); } - if(nIter++>1000) { break; } - } while(1); - if (res > res_old) for (int k=0; k< 7; k++) { vecRKOut[k]=vecRKOutT[k]; } - for (int k=0; k< 3; k++) { printf(" vecRKOut[%i] =%f ", k, vecRKOut[k] ); } - printf("\n"); + printf("\n"); } //______________________________________________________________________________ double FairRKPropagator::Step(double Charge, double* vecRKIn, double* vecOut) { - double vecRKOut[7]; - for (int i=0; i< 7; i++) { vecRKOut[i]=0; } -// for (int i=0; i< 7; i++) printf( "vectRKIn(%i)=%f \n",i ,vecRKIn[i]); -// printf(" ---------------------------------------------------------------- \n"); - double stepLength = OneStepRungeKutta(Charge,fMaxStep, vecRKIn, vecRKOut); - // printf(" now at x=%f y=%f z=%f \n", vecRKOut[0],vecRKOut[1],vecRKOut[2]); - vecOut[0] = vecRKOut[0]; - vecOut[1] = vecRKOut[1]; - vecOut[2] = vecRKOut[2]; - vecOut[6] = vecRKOut[6]; - vecOut[3] = vecRKOut[3]; - vecOut[4] = vecRKOut[4]; - vecOut[5] = vecRKOut[5]; - - return stepLength; + double vecRKOut[7]; + for (int i = 0; i < 7; i++) { + vecRKOut[i] = 0; + } + // for (int i=0; i< 7; i++) printf( "vectRKIn(%i)=%f \n",i ,vecRKIn[i]); + // printf(" ---------------------------------------------------------------- \n"); + double stepLength = OneStepRungeKutta(Charge, fMaxStep, vecRKIn, vecRKOut); + // printf(" now at x=%f y=%f z=%f \n", vecRKOut[0],vecRKOut[1],vecRKOut[2]); + vecOut[0] = vecRKOut[0]; + vecOut[1] = vecRKOut[1]; + vecOut[2] = vecRKOut[2]; + vecOut[6] = vecRKOut[6]; + vecOut[3] = vecRKOut[3]; + vecOut[4] = vecRKOut[4]; + vecOut[5] = vecRKOut[5]; + + return stepLength; } //______________________________________________________________________________ -double FairRKPropagator::OneStepRungeKutta(double charge, double step, - double* vect, double* vout) +double FairRKPropagator::OneStepRungeKutta(double charge, double step, double* vect, double* vout) { - // Wrapper to step with method RungeKutta. - - /// ****************************************************************** - /// * * - /// * Runge-Kutta method for tracking a particle through a magnetic * - /// * field. Uses Nystroem algorithm (See Handbook Nat. Bur. of * - /// * Standards, procedure 25.5.20) * - /// * * - /// * Input parameters * - /// * CHARGE Particle charge * - /// * STEP Step size * - /// * VECT Initial co-ords,direction cosines,momentum * - /// * Output parameters * - /// * VOUT Output co-ords,direction cosines,momentum * - /// * User routine called * - /// * CALL GUFLD(X,F) * - /// * * - /// * ==>Called by : , GUSWIM * - /// * Authors R.Brun, M.Hansroul ********* * - /// * V.Perevoztchikov (CUT STEP implementation) * - /// * * - /// * * - /// ****************************************************************** - - double f[4]; - double xyzt[3]; - double secxs[4],secys[4],seczs[4]; //hxp[3]; - // double /*g1 , g2, g3, g4, g5, g6,*/; - // double /*f1, f2, f3, f4, rho, tet, hnorm, hp, rho1, sint, cost*/; - - double track_length = 0.; - - double maxit = 1992; - double maxcut = 11; - - const double hmin = 1e-4; // !!! MT ADD, should be member - const double kdlt = 1e-6; // !!! MT CHANGE from 1e-4, should be member - const double kdlt32 = kdlt/32.; - const double kthird = 1./3.; - const double khalf = 0.5; - const double kec = 2.99792458e-4; - const double kpisqua = 9.86960440109; - /* const int kix = 0; + // Wrapper to step with method RungeKutta. + + /// ****************************************************************** + /// * * + /// * Runge-Kutta method for tracking a particle through a magnetic * + /// * field. Uses Nystroem algorithm (See Handbook Nat. Bur. of * + /// * Standards, procedure 25.5.20) * + /// * * + /// * Input parameters * + /// * CHARGE Particle charge * + /// * STEP Step size * + /// * VECT Initial co-ords,direction cosines,momentum * + /// * Output parameters * + /// * VOUT Output co-ords,direction cosines,momentum * + /// * User routine called * + /// * CALL GUFLD(X,F) * + /// * * + /// * ==>Called by : , GUSWIM * + /// * Authors R.Brun, M.Hansroul ********* * + /// * V.Perevoztchikov (CUT STEP implementation) * + /// * * + /// * * + /// ****************************************************************** + + double f[4]; + double xyzt[3]; + double secxs[4], secys[4], seczs[4]; // hxp[3]; + // double /*g1 , g2, g3, g4, g5, g6,*/; + // double /*f1, f2, f3, f4, rho, tet, hnorm, hp, rho1, sint, cost*/; + + double track_length = 0.; + + double maxit = 1992; + double maxcut = 11; + + const double hmin = 1e-4; // !!! MT ADD, should be member + const double kdlt = 1e-6; // !!! MT CHANGE from 1e-4, should be member + const double kdlt32 = kdlt / 32.; + const double kthird = 1. / 3.; + const double khalf = 0.5; + const double kec = 2.99792458e-4; + const double kpisqua = 9.86960440109; + /* const int kix = 0; const int kiy = 1; const int kiz = 2; const int kipx = 3; const int kipy = 4; const int kipz = 5; */ - // *. - // *. ------------------------------------------------------------------ - // *. - // * this constant is for units cm,gev/c and kgauss - // * - int iter = 0; - int ncut = 0; - for(int j = 0; j < 7; j++) { - vout[j] = vect[j]; - } - - double pinv = kec * charge / vect[6]; - double tl = 0.; - double h = step; - - do { - double rest = step - tl; - //printf(" Step no. %i x=%f y=%f z=%f px/p = %f py/p =%f pz/p= %f \n", iter, x,y,z,a,b,c); - if (TMath::Abs(h) > TMath::Abs(rest)) { - h = rest; + // *. + // *. ------------------------------------------------------------------ + // *. + // * this constant is for units cm,gev/c and kgauss + // * + int iter = 0; + int ncut = 0; + for (int j = 0; j < 7; j++) { + vout[j] = vect[j]; } + double pinv = kec * charge / vect[6]; + double tl = 0.; + double h = step; - fMagField->GetFieldValue( vout, f); - - // * start of integration - double x = vout[0]; - double y = vout[1]; - double z = vout[2]; - double a = vout[3]; - double b = vout[4]; - double c = vout[5]; - - double h2 = khalf * h; - double h4 = khalf * h2; - double ph = pinv * h; - double ph2 = khalf * ph; - -// printf(" ------------------------------------------- h2 = %f\n",h2); - - secxs[0] = (b * f[2] - c * f[1]) * ph2; - secys[0] = (c * f[0] - a * f[2]) * ph2; - seczs[0] = (a * f[1] - b * f[0]) * ph2; - double ang2 = (secxs[0]*secxs[0] + secys[0]*secys[0] + seczs[0]*seczs[0]); - if (ang2 > kpisqua) { break; } - - double dxt = h2 * a + h4 * secxs[0]; - double dyt = h2 * b + h4 * secys[0]; - double dzt = h2 * c + h4 * seczs[0]; - double xt = x + dxt; - double yt = y + dyt; - double zt = z + dzt; -// printf(" Position 1 at xt=%f yt=%f zt=%f \n", xt, yt, zt); -// printf(" differance dxt=%f dyt=%f dzt=%f \n", dxt, dyt, dzt); - // * second intermediate point - double est = TMath::Abs(dxt) + TMath::Abs(dyt) + TMath::Abs(dzt); - if (est > h) { - if (ncut++ > maxcut) { break; } - h *= khalf; - continue; - } + do { + double rest = step - tl; + // printf(" Step no. %i x=%f y=%f z=%f px/p = %f py/p =%f pz/p= %f \n", iter, x,y,z,a,b,c); + if (TMath::Abs(h) > TMath::Abs(rest)) { + h = rest; + } - xyzt[0] = xt; - xyzt[1] = yt; - xyzt[2] = zt; - - fMagField->GetFieldValue( xyzt, f); - - - - double at = a + secxs[0]; - double bt = b + secys[0]; - double ct = c + seczs[0]; - - secxs[1] = (bt * f[2] - ct * f[1]) * ph2; - secys[1] = (ct * f[0] - at * f[2]) * ph2; - seczs[1] = (at * f[1] - bt * f[0]) * ph2; - at = a + secxs[1]; - bt = b + secys[1]; - ct = c + seczs[1]; - secxs[2] = (bt * f[2] - ct * f[1]) * ph2; - secys[2] = (ct * f[0] - at * f[2]) * ph2; - seczs[2] = (at * f[1] - bt * f[0]) * ph2; - dxt = h * (a + secxs[2]); - dyt = h * (b + secys[2]); - dzt = h * (c + seczs[2]); - xt = x + dxt; - yt = y + dyt; - zt = z + dzt; - at = a + 2.*secxs[2]; - bt = b + 2.*secys[2]; - ct = c + 2.*seczs[2]; - // printf(" Position 2 at xt=%f yt=%f zt=%f \n", xt, yt, zt); - - est = TMath::Abs(dxt)+TMath::Abs(dyt)+TMath::Abs(dzt); - if (est > 2.*TMath::Abs(h)) { - if (ncut++ > maxcut) { break; } - h *= khalf; - continue; - } + fMagField->GetFieldValue(vout, f); - xyzt[0] = xt; - xyzt[1] = yt; - xyzt[2] = zt; - - fMagField->GetFieldValue( xyzt, f); - - z = z + (c + (seczs[0] + seczs[1] + seczs[2]) * kthird) * h; - y = y + (b + (secys[0] + secys[1] + secys[2]) * kthird) * h; - x = x + (a + (secxs[0] + secxs[1] + secxs[2]) * kthird) * h; - // printf(" Position 3 at x=%f y=%f z=%f \n", x, y, z); - secxs[3] = (bt*f[2] - ct*f[1])* ph2; - secys[3] = (ct*f[0] - at*f[2])* ph2; - seczs[3] = (at*f[1] - bt*f[0])* ph2; - a = a+(secxs[0]+secxs[3]+2. * (secxs[1]+secxs[2])) * kthird; - b = b+(secys[0]+secys[3]+2. * (secys[1]+secys[2])) * kthird; - c = c+(seczs[0]+seczs[3]+2. * (seczs[1]+seczs[2])) * kthird; - - est = TMath::Abs(secxs[0]+secxs[3] - (secxs[1]+secxs[2])) - + TMath::Abs(secys[0]+secys[3] - (secys[1]+secys[2])) - + TMath::Abs(seczs[0]+seczs[3] - (seczs[1]+seczs[2])); - - if (est > kdlt && TMath::Abs(h) > hmin) { - if (ncut++ > maxcut) { break; } - h *= khalf; - continue; - } + // * start of integration + double x = vout[0]; + double y = vout[1]; + double z = vout[2]; + double a = vout[3]; + double b = vout[4]; + double c = vout[5]; - ncut = 0; - // * if too many iterations, go to helix - if (iter++ > maxit) { break; } + double h2 = khalf * h; + double h4 = khalf * h2; + double ph = pinv * h; + double ph2 = khalf * ph; - tl += h; - if (est < kdlt32) { - h *= 2.; - } - double cba = 1./ TMath::Sqrt(a*a + b*b + c*c); - vout[0] = x; - vout[1] = y; - vout[2] = z; - vout[3] = cba*a; - vout[4] = cba*b; - vout[5] = cba*c; + // printf(" ------------------------------------------- h2 = %f\n",h2); + secxs[0] = (b * f[2] - c * f[1]) * ph2; + secys[0] = (c * f[0] - a * f[2]) * ph2; + seczs[0] = (a * f[1] - b * f[0]) * ph2; + double ang2 = (secxs[0] * secxs[0] + secys[0] * secys[0] + seczs[0] * seczs[0]); + if (ang2 > kpisqua) { + break; + } - rest = step - tl; - track_length = tl; - // printf(" Position 4 at x=%f y=%f z=%f Step = %f \n", x, y, z, step ); + double dxt = h2 * a + h4 * secxs[0]; + double dyt = h2 * b + h4 * secys[0]; + double dzt = h2 * c + h4 * seczs[0]; + double xt = x + dxt; + double yt = y + dyt; + double zt = z + dzt; + // printf(" Position 1 at xt=%f yt=%f zt=%f \n", xt, yt, zt); + // printf(" differance dxt=%f dyt=%f dzt=%f \n", dxt, dyt, dzt); + // * second intermediate point + double est = TMath::Abs(dxt) + TMath::Abs(dyt) + TMath::Abs(dzt); + if (est > h) { + if (ncut++ > maxcut) { + break; + } + h *= khalf; + continue; + } - if (step < 0.) { rest = -rest; } - if (rest < 1.e-5*TMath::Abs(step)) { return track_length; } + xyzt[0] = xt; + xyzt[1] = yt; + xyzt[2] = zt; + + fMagField->GetFieldValue(xyzt, f); + + double at = a + secxs[0]; + double bt = b + secys[0]; + double ct = c + seczs[0]; + + secxs[1] = (bt * f[2] - ct * f[1]) * ph2; + secys[1] = (ct * f[0] - at * f[2]) * ph2; + seczs[1] = (at * f[1] - bt * f[0]) * ph2; + at = a + secxs[1]; + bt = b + secys[1]; + ct = c + seczs[1]; + secxs[2] = (bt * f[2] - ct * f[1]) * ph2; + secys[2] = (ct * f[0] - at * f[2]) * ph2; + seczs[2] = (at * f[1] - bt * f[0]) * ph2; + dxt = h * (a + secxs[2]); + dyt = h * (b + secys[2]); + dzt = h * (c + seczs[2]); + xt = x + dxt; + yt = y + dyt; + zt = z + dzt; + at = a + 2. * secxs[2]; + bt = b + 2. * secys[2]; + ct = c + 2. * seczs[2]; + // printf(" Position 2 at xt=%f yt=%f zt=%f \n", xt, yt, zt); + + est = TMath::Abs(dxt) + TMath::Abs(dyt) + TMath::Abs(dzt); + if (est > 2. * TMath::Abs(h)) { + if (ncut++ > maxcut) { + break; + } + h *= khalf; + continue; + } - } while(1); + xyzt[0] = xt; + xyzt[1] = yt; + xyzt[2] = zt; + + fMagField->GetFieldValue(xyzt, f); + + z = z + (c + (seczs[0] + seczs[1] + seczs[2]) * kthird) * h; + y = y + (b + (secys[0] + secys[1] + secys[2]) * kthird) * h; + x = x + (a + (secxs[0] + secxs[1] + secxs[2]) * kthird) * h; + // printf(" Position 3 at x=%f y=%f z=%f \n", x, y, z); + secxs[3] = (bt * f[2] - ct * f[1]) * ph2; + secys[3] = (ct * f[0] - at * f[2]) * ph2; + seczs[3] = (at * f[1] - bt * f[0]) * ph2; + a = a + (secxs[0] + secxs[3] + 2. * (secxs[1] + secxs[2])) * kthird; + b = b + (secys[0] + secys[3] + 2. * (secys[1] + secys[2])) * kthird; + c = c + (seczs[0] + seczs[3] + 2. * (seczs[1] + seczs[2])) * kthird; + + est = TMath::Abs(secxs[0] + secxs[3] - (secxs[1] + secxs[2])) + + TMath::Abs(secys[0] + secys[3] - (secys[1] + secys[2])) + + TMath::Abs(seczs[0] + seczs[3] - (seczs[1] + seczs[2])); + + if (est > kdlt && TMath::Abs(h) > hmin) { + if (ncut++ > maxcut) { + break; + } + h *= khalf; + continue; + } - return track_length; + ncut = 0; + // * if too many iterations, go to helix + if (iter++ > maxit) { + break; + } - // angle too big, use helix - /* + tl += h; + if (est < kdlt32) { + h *= 2.; + } + double cba = 1. / TMath::Sqrt(a * a + b * b + c * c); + vout[0] = x; + vout[1] = y; + vout[2] = z; + vout[3] = cba * a; + vout[4] = cba * b; + vout[5] = cba * c; + + rest = step - tl; + track_length = tl; + // printf(" Position 4 at x=%f y=%f z=%f Step = %f \n", x, y, z, step ); + + if (step < 0.) { + rest = -rest; + } + if (rest < 1.e-5 * TMath::Abs(step)) { + return track_length; + } + + } while (1); + + return track_length; + + // angle too big, use helix + /* f1 = f[0]; f2 = f[1]; f3 = f[2]; @@ -684,5 +753,4 @@ double FairRKPropagator::OneStepRungeKutta(double charge, double step, vout[kipy] = vect[kipy] + g4*vect[kipy] + g5*hxp[1] + g6*f2; vout[kipz] = vect[kipz] + g4*vect[kipz] + g5*hxp[2] + g6*f3; */ - } diff --git a/trackbase/FairRKPropagator.h b/trackbase/FairRKPropagator.h index 7300f3e01c..ee93280595 100644 --- a/trackbase/FairRKPropagator.h +++ b/trackbase/FairRKPropagator.h @@ -6,11 +6,11 @@ * copied verbatim in the file "LICENSE" * ********************************************************************************/ /** -* Runge-Kutte Track propagator -* @author M. Al-Turany -* @version 0.2 -* @since 22.1.10 -*/ + * Runge-Kutte Track propagator + * @author M. Al-Turany + * @version 0.2 + * @since 22.1.10 + */ #ifndef RKPropagator #define RKPropagator @@ -21,24 +21,30 @@ class FairField; class FairTrackParP; class TVector3; -enum PropagationFlag {NONE, TOPLANE, TOVOLUME, TOLENGTH}; +enum PropagationFlag +{ + NONE, + TOPLANE, + TOVOLUME, + TOLENGTH +}; class FairRKPropagator : public FairPropagator { private: - FairRKPropagator(const FairRKPropagator&); // Not implemented - FairRKPropagator& operator=(const FairRKPropagator&); // Not implemented + FairRKPropagator(const FairRKPropagator&); // Not implemented + FairRKPropagator& operator=(const FairRKPropagator&); // Not implemented double fMaxStep; - FairField* fMagField; + FairField* fMagField; - PropagationFlag fPropagationFlag; - TVector3 fDefPlaneV0; - TVector3 fDefPlaneV1; - TVector3 fDefPlaneV2; + PropagationFlag fPropagationFlag; + TVector3 fDefPlaneV0; + TVector3 fDefPlaneV1; + TVector3 fDefPlaneV2; - int fPCAPropagationType; - int fPCAPropagationDir; - FairTrackParP* fPCAPropagationPar; + int fPCAPropagationType; + int fPCAPropagationDir; + FairTrackParP* fPCAPropagationPar; double GetChargeFromPDG(int pdg); double CalculatePointToWireDistance(TVector3 point, TVector3 wire1, TVector3 wire2, TVector3& vwi); @@ -66,7 +72,8 @@ class FairRKPropagator : public FairPropagator void PropagateToPlane(double Charge, double* vecRKIn, double* vec1, double* vec2, double* vec3, double* vecOut); - /* =========================================================================================================================================== */ + /* =========================================================================================================================================== + */ /**New method to set the plane to propagate particles to @v0 v1 v2 Plane defining vectors @@ -91,8 +98,8 @@ class FairRKPropagator : public FairPropagator virtual bool SetDestinationLength(float length); /**New method to set to propagate only parameters - */ - virtual bool SetPropagateOnlyParameters() {return true;} + */ + virtual bool SetPropagateOnlyParameters() { return true; } virtual bool Propagate(FairTrackParH* TStart, FairTrackParH* TEnd, int PDG); virtual bool Propagate(FairTrackParP* TStart, FairTrackParH* TEnd, int PDG); @@ -102,7 +109,12 @@ class FairRKPropagator : public FairPropagator virtual bool SetPCAPropagation(int pca, int dir = 1, FairTrackParP* par = nullptr); - virtual PCAOutputStruct FindPCA(int PCA, int PDGCode, TVector3 Point, TVector3 Wire1, TVector3 Wire2, double MaxDistance); + virtual PCAOutputStruct FindPCA(int PCA, + int PDGCode, + TVector3 Point, + TVector3 Wire1, + TVector3 Wire2, + double MaxDistance); virtual ~FairRKPropagator(); ClassDef(FairRKPropagator, 2); diff --git a/trackbase/FairTrackPar.cxx b/trackbase/FairTrackPar.cxx index e1b076489b..fbd7fb5535 100644 --- a/trackbase/FairTrackPar.cxx +++ b/trackbase/FairTrackPar.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- @@ -11,101 +11,113 @@ #include "FairTrackPar.h" -#include -#include "FairLogger.h" -#include "FairRunAna.h" // for GetFieldValue #include "FairField.h" +#include "FairLogger.h" +#include "FairRunAna.h" // for GetFieldValue + +#include using namespace std; FairTrackPar::FairTrackPar() - : TObject(), - fX (0.), - fY (0.), - fZ (0.), - fDX (0.), - fDY (0.), - fDZ (0.), - fPx (0.), - fPy (0.), - fPz (0.), - fDPx (0.), - fDPy (0.), - fDPz (0.), - fQp (0.), - fDQp (0.), - fq (1) -{ -} + : TObject() + , fX(0.) + , fY(0.) + , fZ(0.) + , fDX(0.) + , fDY(0.) + , fDZ(0.) + , fPx(0.) + , fPy(0.) + , fPz(0.) + , fDPx(0.) + , fDPy(0.) + , fDPz(0.) + , fQp(0.) + , fDQp(0.) + , fq(1) +{} -FairTrackPar::FairTrackPar(Double_t x, Double_t y, Double_t z, - Double_t px, Double_t py, Double_t pz, Int_t q) +FairTrackPar::FairTrackPar(Double_t x, Double_t y, Double_t z, Double_t px, Double_t py, Double_t pz, Int_t q) - : TObject(), - fX (x), - fY (y), - fZ (z), - fDX (x), - fDY (y), - fDZ (z), - fPx (px), - fPy (py), - fPz (pz), - fDPx (px), - fDPy (py), - fDPz (pz), - fQp (0.), - fDQp (0.), - fq (q) + : TObject() + , fX(x) + , fY(y) + , fZ(z) + , fDX(x) + , fDY(y) + , fDZ(z) + , fPx(px) + , fPy(py) + , fPz(pz) + , fDPx(px) + , fDPy(py) + , fDPz(pz) + , fQp(0.) + , fDQp(0.) + , fq(q) { - Double_t p=TMath::Sqrt(fPx*fPx +fPy*fPy +fPz*fPz ); - if (p!=0) { fQp = q/p; } + Double_t p = TMath::Sqrt(fPx * fPx + fPy * fPy + fPz * fPz); + if (p != 0) { + fQp = q / p; + } } -FairTrackPar::FairTrackPar(Double_t x, Double_t y, Double_t z, Double_t dx, Double_t dy, Double_t dz, - Double_t px, Double_t py, Double_t pz, Double_t dpx, Double_t dpy, Double_t dpz, +FairTrackPar::FairTrackPar(Double_t x, + Double_t y, + Double_t z, + Double_t dx, + Double_t dy, + Double_t dz, + Double_t px, + Double_t py, + Double_t pz, + Double_t dpx, + Double_t dpy, + Double_t dpz, Int_t q) -: TObject(), - fX (x), - fY (y), - fZ (z), - fDX (dx), - fDY (dy), - fDZ (dz), - fPx (px), - fPy (py), - fPz (pz), - fDPx (dpx), - fDPy (dpy), - fDPz (dpz), - fQp (0.), - fDQp (0.), - fq (q) + : TObject() + , fX(x) + , fY(y) + , fZ(z) + , fDX(dx) + , fDY(dy) + , fDZ(dz) + , fPx(px) + , fPy(py) + , fPz(pz) + , fDPx(dpx) + , fDPy(dpy) + , fDPz(dpz) + , fQp(0.) + , fDQp(0.) + , fq(q) { - Double_t p=TMath::Sqrt(fPx*fPx +fPy*fPy +fPz*fPz ); - if (p!=0) { fQp = q/p; } + Double_t p = TMath::Sqrt(fPx * fPx + fPy * fPy + fPz * fPz); + if (p != 0) { + fQp = q / p; + } } FairTrackPar::~FairTrackPar() {} void FairTrackPar::Print(Option_t* /*option*/) const { - LOG(info) << "Position :(" << fX << "," << fY << "," << fZ << ")"; - LOG(info) << "Momentum :(" << fPx << "," << fPy << "," << fPz << ")"; + LOG(info) << "Position :(" << fX << "," << fY << "," << fZ << ")"; + LOG(info) << "Momentum :(" << fPx << "," << fPy << "," << fPz << ")"; } void FairTrackPar::GetFieldValue(const Double_t point[3], Double_t* bField) { - FairRunAna* fRun = FairRunAna::Instance(); - if (fRun->GetField() != 0) - fRun->GetField()->GetFieldValue(point, bField); - else { - bField[0] = .0; - bField[1] = .0; - bField[2] = .0; - } + FairRunAna* fRun = FairRunAna::Instance(); + if (fRun->GetField() != 0) + fRun->GetField()->GetFieldValue(point, bField); + else { + bField[0] = .0; + bField[1] = .0; + bField[2] = .0; + } } -ClassImp(FairTrackPar) - +ClassImp(FairTrackPar); diff --git a/trackbase/FairTrackPar.h b/trackbase/FairTrackPar.h index 5e6d658cdf..c3cefa6d47 100644 --- a/trackbase/FairTrackPar.h +++ b/trackbase/FairTrackPar.h @@ -1,17 +1,16 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ #ifndef FAIRSTSTRACKPAR #define FAIRSTSTRACKPAR 1 -#include // for TObject - -#include // for Double_t, Int_t, etc -#include // for TVector3 +#include // for Double_t, Int_t, etc +#include // for TObject +#include // for TVector3 class FairTrackPar : public TObject { @@ -20,29 +19,38 @@ class FairTrackPar : public TObject FairTrackPar(); /** Constructor with all variables **/ - FairTrackPar(Double_t x, Double_t y, Double_t z, - Double_t px, Double_t py, Double_t pz, Int_t q); - - FairTrackPar(Double_t x, Double_t y, Double_t z, Double_t dx, Double_t dy, Double_t dz, - Double_t px, Double_t py, Double_t pz, Double_t dpx, Double_t dpy, Double_t dpz, + FairTrackPar(Double_t x, Double_t y, Double_t z, Double_t px, Double_t py, Double_t pz, Int_t q); + + FairTrackPar(Double_t x, + Double_t y, + Double_t z, + Double_t dx, + Double_t dy, + Double_t dz, + Double_t px, + Double_t py, + Double_t pz, + Double_t dpx, + Double_t dpy, + Double_t dpz, Int_t q); /** Destructor **/ virtual ~FairTrackPar(); /** Output to screen **/ - virtual void Print(Option_t* option = "") const; + virtual void Print(Option_t* option = "") const; /** Accessors **/ virtual TVector3 GetPosition() const { return TVector3(fX, fY, fZ); } virtual Double_t GetX() { return fX; } virtual Double_t GetY() { return fY; } virtual Double_t GetZ() { return fZ; } - Int_t GetQ() const { return fq; } + Int_t GetQ() const { return fq; } - virtual Double_t GetDX() const { return fDX; } - virtual Double_t GetDY() const { return fDY; } - virtual Double_t GetDZ() const { return fDZ; } + virtual Double_t GetDX() const { return fDX; } + virtual Double_t GetDY() const { return fDY; } + virtual Double_t GetDZ() const { return fDZ; } virtual TVector3 GetMomentum() const { return TVector3(fPx, fPy, fPz); } @@ -58,10 +66,9 @@ class FairTrackPar : public TObject virtual void GetFieldValue(const Double_t point[3], Double_t* bField); - - virtual void SetX(Double_t x) { fX = x; } - virtual void SetY(Double_t y) { fY = y; } - virtual void SetZ(Double_t z) { fZ = z; } + virtual void SetX(Double_t x) { fX = x; } + virtual void SetY(Double_t y) { fY = y; } + virtual void SetZ(Double_t z) { fZ = z; } virtual void SetDX(Double_t dx) { fDX = dx; } virtual void SetDY(Double_t dy) { fDY = dy; } @@ -119,7 +126,7 @@ class FairTrackPar : public TObject /** charge*/ Int_t fq; - ClassDef(FairTrackPar,2); + ClassDef(FairTrackPar, 2); }; #endif diff --git a/trackbase/FairTrackParH.cxx b/trackbase/FairTrackParH.cxx index b9c1e34408..ebed6472ec 100644 --- a/trackbase/FairTrackParH.cxx +++ b/trackbase/FairTrackParH.cxx @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // Class for the representation of a track as helix (SC system) @@ -15,663 +15,673 @@ // and the covariance matrix. Or using position and momentum in LAB referance. #include "FairTrackParH.h" -#include "FairGeaneUtil.h" // for FairGeaneUtil -#include "FairTrackParP.h" // for FairTrackParP -#include // for pow, Sqrt, sqrt, Sin, Cos, etc -#include // for Abs, Sign +#include "FairGeaneUtil.h" // for FairGeaneUtil +#include "FairTrackParP.h" // for FairTrackParP -#include // for operator<<, basic_ostream, etc +#include // for pow, Sqrt, sqrt, Sin, Cos, etc +#include // for Abs, Sign +#include // IWYU pragma: keep for fabs #include -#include // IWYU pragma: keep for fabs +#include // for operator<<, basic_ostream, etc // IWYU pragma: no_include using std::cout; using std::endl; -ClassImp(FairTrackParH) +ClassImp(FairTrackParH); FairTrackParH::FairTrackParH() - : FairTrackPar(), - fLm (0.), - fPhi (0.), - fDLm(0.), - fDPhi(0.), - fX_sc (0.), - fY_sc (0.), - fZ_sc (0.), - fDX_sc(0.), - fDY_sc(0.), - fDZ_sc(0.), - cLm(0.), - sLm(0.), - cphi(0.), - sphi(0.) + : FairTrackPar() + , fLm(0.) + , fPhi(0.) + , fDLm(0.) + , fDPhi(0.) + , fX_sc(0.) + , fY_sc(0.) + , fZ_sc(0.) + , fDX_sc(0.) + , fDY_sc(0.) + , fDZ_sc(0.) + , cLm(0.) + , sLm(0.) + , cphi(0.) + , sphi(0.) { - for(Int_t i=0; i<15; i++) { - fCovMatrix[i]=0; - } - for(int i = 0; i < 6; i++) for(int j = 0; j < 6; j++) { fCovMatrix66[i][j] = 0.; } - + for (Int_t i = 0; i < 15; i++) { + fCovMatrix[i] = 0; + } + for (int i = 0; i < 6; i++) + for (int j = 0; j < 6; j++) { + fCovMatrix66[i][j] = 0.; + } } // constructor in SC -FairTrackParH::FairTrackParH(Double_t x, Double_t y, Double_t z, - Double_t lm, Double_t phi, Double_t qp, +FairTrackParH::FairTrackParH(Double_t x, + Double_t y, + Double_t z, + Double_t lm, + Double_t phi, + Double_t qp, Double_t CovMatrix[15]) - : FairTrackPar(), - fLm (lm), - fPhi (phi), - fDLm(0.), - fDPhi(0.), - fX_sc (x), - fY_sc (y), - fZ_sc (z), - fDX_sc(0.), - fDY_sc(0.), - fDZ_sc(0.), - cLm(TMath::Cos(lm)), - sLm(TMath::Sin(lm)), - cphi(TMath::Cos(phi)), - sphi(TMath::Sin(phi)) + : FairTrackPar() + , fLm(lm) + , fPhi(phi) + , fDLm(0.) + , fDPhi(0.) + , fX_sc(x) + , fY_sc(y) + , fZ_sc(z) + , fDX_sc(0.) + , fDY_sc(0.) + , fDZ_sc(0.) + , cLm(TMath::Cos(lm)) + , sLm(TMath::Sin(lm)) + , cphi(TMath::Cos(phi)) + , sphi(TMath::Sin(phi)) { - /* + /* fLm = lm; fPhi = phi; */ - fQp = qp; - Double_t P = TMath::Abs(1/fQp); - //fq= int (P * fQp); - fq = static_cast(TMath::Sign(1.0, fQp)); - for(Int_t i=0; i<15; i++) { - fCovMatrix[i]=CovMatrix[i]; - } - /* + fQp = qp; + Double_t P = TMath::Abs(1 / fQp); + // fq= int (P * fQp); + fq = static_cast(TMath::Sign(1.0, fQp)); + for (Int_t i = 0; i < 15; i++) { + fCovMatrix[i] = CovMatrix[i]; + } + /* cLm= TMath::Cos(fLm); sLm= TMath::Sin(fLm); cphi= TMath::Cos(fPhi); sphi= TMath::Sin(fPhi); */ - fPx = P * cLm* cphi; - fPy = P * cLm* sphi; - fPz = P * sLm; - + fPx = P * cLm * cphi; + fPy = P * cLm * sphi; + fPz = P * sLm; - /* + /* fX_sc = x; fY_sc = y; fZ_sc = z; */ - fX =fX_sc*cLm*cphi -fY_sc*sphi -fZ_sc*cphi*sLm; - fY =fX_sc*cLm*sphi +fY_sc*cphi -fZ_sc*sphi*sLm; - fZ =fX_sc*sLm +fZ_sc*cLm; - - fDQp = TMath::Sqrt(fabs(fCovMatrix[0])); - fDLm = TMath::Sqrt(fabs(fCovMatrix[5])); - fDPhi = TMath::Sqrt(fabs(fCovMatrix[9])); - fDX_sc = 0.; - fDY_sc = TMath::Sqrt(fabs(fCovMatrix[12])); - fDZ_sc = TMath::Sqrt(fabs(fCovMatrix[14])); - - Double_t PD[3],RD[6][6],H[3],PC[3],RC[15]; - Int_t CH; - PC[0] = fQp; - PC[1] = fLm; - PC[2] = fPhi; - - for(Int_t i=0; i<15; i++) { - RC[i]=fCovMatrix[i]; - } - - // retrieve field - Double_t pnt[3]; - pnt[0] = fX; - pnt[1] = fY; - pnt[2] = fZ; - - GetFieldValue(pnt, H); - - - CH=fq; - FairGeaneUtil util; - util.FromSCToMars(PC,RC,H,CH,PD,RD); - - // test - fDPx = sqrt(fabs(RD[0][0])); - fDPy = sqrt(fabs(RD[1][1])); - fDPz = sqrt(fabs(RD[2][2])); - fDX = sqrt(fabs(RD[3][3])); - fDY = sqrt(fabs(RD[4][4])); - fDZ = sqrt(fabs(RD[5][5])); - - for(int i = 0; i < 6; i++) for(int j = 0; j < 6; j++) { fCovMatrix66[i][j] = RD[i][j]; } + fX = fX_sc * cLm * cphi - fY_sc * sphi - fZ_sc * cphi * sLm; + fY = fX_sc * cLm * sphi + fY_sc * cphi - fZ_sc * sphi * sLm; + fZ = fX_sc * sLm + fZ_sc * cLm; + + fDQp = TMath::Sqrt(fabs(fCovMatrix[0])); + fDLm = TMath::Sqrt(fabs(fCovMatrix[5])); + fDPhi = TMath::Sqrt(fabs(fCovMatrix[9])); + fDX_sc = 0.; + fDY_sc = TMath::Sqrt(fabs(fCovMatrix[12])); + fDZ_sc = TMath::Sqrt(fabs(fCovMatrix[14])); + + Double_t PD[3], RD[6][6], H[3], PC[3], RC[15]; + Int_t CH; + PC[0] = fQp; + PC[1] = fLm; + PC[2] = fPhi; + + for (Int_t i = 0; i < 15; i++) { + RC[i] = fCovMatrix[i]; + } + // retrieve field + Double_t pnt[3]; + pnt[0] = fX; + pnt[1] = fY; + pnt[2] = fZ; + + GetFieldValue(pnt, H); + + CH = fq; + FairGeaneUtil util; + util.FromSCToMars(PC, RC, H, CH, PD, RD); + + // test + fDPx = sqrt(fabs(RD[0][0])); + fDPy = sqrt(fabs(RD[1][1])); + fDPz = sqrt(fabs(RD[2][2])); + fDX = sqrt(fabs(RD[3][3])); + fDY = sqrt(fabs(RD[4][4])); + fDZ = sqrt(fabs(RD[5][5])); + + for (int i = 0; i < 6; i++) + for (int j = 0; j < 6; j++) { + fCovMatrix66[i][j] = RD[i][j]; + } } -//constructor in LAB +// constructor in LAB FairTrackParH::FairTrackParH(TVector3 pos, TVector3 Mom, TVector3 posErr, TVector3 MomErr, Int_t q) - : FairTrackPar(pos.x(),pos.y(),pos.z(),Mom.x(),Mom.y(),Mom.z(),q), - fLm (0.), - fPhi (0.), - fDLm(0.), - fDPhi(0.), - fX_sc (0.), - fY_sc (0.), - fZ_sc (0.), - fDX_sc(0.), - fDY_sc(0.), - fDZ_sc(0.), - cLm(0.), - sLm(0.), - cphi(0.), - sphi(0.) + : FairTrackPar(pos.x(), pos.y(), pos.z(), Mom.x(), Mom.y(), Mom.z(), q) + , fLm(0.) + , fPhi(0.) + , fDLm(0.) + , fDPhi(0.) + , fX_sc(0.) + , fY_sc(0.) + , fZ_sc(0.) + , fDX_sc(0.) + , fDY_sc(0.) + , fDZ_sc(0.) + , cLm(0.) + , sLm(0.) + , cphi(0.) + , sphi(0.) { - Reset(); - SetPx(Mom.x()); - SetPy(Mom.y()); - SetPz(Mom.z()); - - SetX(pos.x()); //x (lab) - SetY(pos.y()); //y (lab) - SetZ(pos.z()); //z (lab) - - - - fq= int (q/TMath::Abs(q)); - Double_t P =TMath::Sqrt(fPx*fPx+fPy*fPy+fPz*fPz); - fLm = TMath::ASin(fPz/P); - - fPhi = TMath::ATan2(fPy,fPx); - fQp = fq/P; - - cLm= TMath::Cos(fLm); - sLm= TMath::Sin(fLm); - cphi= TMath::Cos(fPhi); - sphi= TMath::Sin(fPhi); - - fDPx= MomErr.x(); //dpx - fDPy= MomErr.y(); //dpy - fDPz= MomErr.z(); //dpz - - fX_sc = fX*cphi*cLm+ fY*cLm*sphi+fZ*sLm; - fY_sc = fY*cphi-fX*sphi; - fZ_sc = fZ*cLm-fY*sLm*sphi-fX*sLm*cphi; - - fDX = posErr.x(); //dx (lab) - fDY = posErr.y(); //dy (lab) - fDZ = posErr.z(); //dz (lab) - - - - Double_t PD[3],RD[6][6],H[3],PC[3],RC[15]; - Int_t CH; - PD[0]=Mom.x(); - PD[1]=Mom.y(); - PD[2]=Mom.z(); - for(Int_t i=0; i<6; i++) for(Int_t j=0; j<6; j++) { - RD[i][j]=0; + Reset(); + SetPx(Mom.x()); + SetPy(Mom.y()); + SetPz(Mom.z()); + + SetX(pos.x()); // x (lab) + SetY(pos.y()); // y (lab) + SetZ(pos.z()); // z (lab) + + fq = int(q / TMath::Abs(q)); + Double_t P = TMath::Sqrt(fPx * fPx + fPy * fPy + fPz * fPz); + fLm = TMath::ASin(fPz / P); + + fPhi = TMath::ATan2(fPy, fPx); + fQp = fq / P; + + cLm = TMath::Cos(fLm); + sLm = TMath::Sin(fLm); + cphi = TMath::Cos(fPhi); + sphi = TMath::Sin(fPhi); + + fDPx = MomErr.x(); // dpx + fDPy = MomErr.y(); // dpy + fDPz = MomErr.z(); // dpz + + fX_sc = fX * cphi * cLm + fY * cLm * sphi + fZ * sLm; + fY_sc = fY * cphi - fX * sphi; + fZ_sc = fZ * cLm - fY * sLm * sphi - fX * sLm * cphi; + + fDX = posErr.x(); // dx (lab) + fDY = posErr.y(); // dy (lab) + fDZ = posErr.z(); // dz (lab) + + Double_t PD[3], RD[6][6], H[3], PC[3], RC[15]; + Int_t CH; + PD[0] = Mom.x(); + PD[1] = Mom.y(); + PD[2] = Mom.z(); + for (Int_t i = 0; i < 6; i++) + for (Int_t j = 0; j < 6; j++) { + RD[i][j] = 0; + } + RD[0][0] = fDPx * fDPx; + RD[1][1] = fDPy * fDPy; + RD[2][2] = fDPz * fDPz; + RD[3][3] = fDX * fDX; + RD[4][4] = fDY * fDY; + RD[5][5] = fDZ * fDZ; + + // retrieve field + Double_t pnt[3]; + pnt[0] = fX; + pnt[1] = fY; + pnt[2] = fZ; + + GetFieldValue(pnt, H); + + CH = fq; + FairGeaneUtil util; + + util.FromMarsToSC(PD, RD, H, CH, PC, RC); + + for (Int_t i = 0; i < 15; i++) { + fCovMatrix[i] = RC[i]; } - RD[0][0] = fDPx * fDPx; - RD[1][1] = fDPy * fDPy; - RD[2][2] = fDPz * fDPz; - RD[3][3] = fDX * fDX; - RD[4][4] = fDY * fDY; - RD[5][5] = fDZ * fDZ; - - // retrieve field - Double_t pnt[3]; - pnt[0] = fX; - pnt[1] = fY; - pnt[2] = fZ; - - GetFieldValue(pnt, H); - - - CH=fq; - FairGeaneUtil util; - - util.FromMarsToSC(PD,RD,H,CH,PC,RC); - - for(Int_t i=0; i<15; i++) { - fCovMatrix[i]=RC[i]; - } - - fDX_sc = 0; - fDY_sc = TMath::Sqrt(fabs(fCovMatrix[12])); - fDZ_sc = TMath::Sqrt(fabs(fCovMatrix[14])); - for(int i = 0; i < 6; i++) for(int j = 0; j < 6; j++) { fCovMatrix66[i][j] = RD[i][j]; } + fDX_sc = 0; + fDY_sc = TMath::Sqrt(fabs(fCovMatrix[12])); + fDZ_sc = TMath::Sqrt(fabs(fCovMatrix[14])); + for (int i = 0; i < 6; i++) + for (int j = 0; j < 6; j++) { + fCovMatrix66[i][j] = RD[i][j]; + } } FairTrackParH::FairTrackParH(FairTrackParP* parab, Int_t& ierr) - : FairTrackPar(), - fLm (0.), - fPhi (0.), - fDLm(0.), - fDPhi(0.), - fX_sc (0.), - fY_sc (0.), - fZ_sc (0.), - fDX_sc(0.), - fDY_sc(0.), - fDZ_sc(0.), - cLm(0.), - sLm(0.), - cphi(0.), - sphi(0.) + : FairTrackPar() + , fLm(0.) + , fPhi(0.) + , fDLm(0.) + , fDPhi(0.) + , fX_sc(0.) + , fY_sc(0.) + , fZ_sc(0.) + , fDX_sc(0.) + , fDY_sc(0.) + , fDZ_sc(0.) + , cLm(0.) + , sLm(0.) + , cphi(0.) + , sphi(0.) { - // q/p, v', w' --> q/p, lambda, phi - Double_t PD[3] = {parab->GetQp(), parab->GetTV(), parab->GetTW()}; - Double_t RD[15]; - parab->GetCov(RD); - // retrieve field - TVector3 xyz(parab->GetX(), parab->GetY(), parab->GetZ()); - Double_t H[3], pnt[3]; - pnt[0] = xyz.X(); - pnt[1] = xyz.Y(); - pnt[2] = xyz.Z(); + // q/p, v', w' --> q/p, lambda, phi + Double_t PD[3] = {parab->GetQp(), parab->GetTV(), parab->GetTW()}; + Double_t RD[15]; + parab->GetCov(RD); + // retrieve field + TVector3 xyz(parab->GetX(), parab->GetY(), parab->GetZ()); + Double_t H[3], pnt[3]; + pnt[0] = xyz.X(); + pnt[1] = xyz.Y(); + pnt[2] = xyz.Z(); - GetFieldValue(pnt, H); + GetFieldValue(pnt, H); + Int_t CH = parab->GetQ(); - Int_t CH = parab->GetQ(); + Double_t DJ[3] = {parab->GetJVer().X(), parab->GetJVer().Y(), parab->GetJVer().Z()}; + Double_t DK[3] = {parab->GetKVer().X(), parab->GetKVer().Y(), parab->GetKVer().Z()}; - Double_t DJ[3] = {parab->GetJVer().X(), parab->GetJVer().Y(), parab->GetJVer().Z()}; - Double_t DK[3] = {parab->GetKVer().X(), parab->GetKVer().Y(), parab->GetKVer().Z()}; + Double_t SPU = parab->GetSPU(); - Double_t SPU = parab->GetSPU(); + Int_t IERR = 0; + Double_t PC[3], RC[15]; - Int_t IERR = 0; - Double_t PC[3], RC[15]; + FairGeaneUtil util; + util.FromSDToSC(PD, RD, H, CH, SPU, DJ, DK, IERR, PC, RC); - FairGeaneUtil util; - util.FromSDToSC(PD, RD, H, CH, SPU, DJ, DK, - IERR, PC, RC); - - ierr = IERR; - - if(ierr == 0) SetTrackPar(parab->GetX(), parab->GetY(), parab->GetZ(), - parab->GetPx(), parab->GetPy(), parab->GetPz(), - CH, RC); - else { cout << "FairTrackParH(FairTrackParP *) contructor ERROR: CANNOT convert parabola to helix" << endl; } + ierr = IERR; + if (ierr == 0) + SetTrackPar( + parab->GetX(), parab->GetY(), parab->GetZ(), parab->GetPx(), parab->GetPy(), parab->GetPz(), CH, RC); + else { + cout << "FairTrackParH(FairTrackParP *) contructor ERROR: CANNOT convert parabola to helix" << endl; + } } // track definition in LAB -void FairTrackParH::SetTrackPar(Double_t X, Double_t Y, Double_t Z, - Double_t Px, Double_t Py, Double_t Pz, Int_t Q, - Double_t CovMatrix[15]) +void FairTrackParH::SetTrackPar(Double_t X, + Double_t Y, + Double_t Z, + Double_t Px, + Double_t Py, + Double_t Pz, + Int_t Q, + Double_t CovMatrix[15]) { - Reset(); - Double_t P =TMath::Sqrt(Px*Px+Py*Py+Pz*Pz); - fLm = TMath::ASin(Pz/P); - - fPhi = TMath::ATan2(Py,Px); - if (Q!=0) { fq = int (TMath::Abs(Q)/Q); } - fQp = fq/P; + Reset(); + Double_t P = TMath::Sqrt(Px * Px + Py * Py + Pz * Pz); + fLm = TMath::ASin(Pz / P); - cLm= TMath::Cos(fLm); - sLm= TMath::Sin(fLm); - cphi= TMath::Cos(fPhi); - sphi= TMath::Sin(fPhi); - - SetX(X); - SetY(Y); - SetZ(Z); - - SetPx(Px); - SetPy(Py); - SetPz(Pz); - - fX_sc = fX*cphi*cLm+ fY*cLm*sphi+fZ*sLm; - fY_sc = fY*cphi-fX*sphi; - fZ_sc = fZ*cLm-fY*sLm*sphi-fX*sLm*cphi; - - for(Int_t i=0; i<15; i++) { - fCovMatrix[i]=CovMatrix[i]; - } - - fDQp = TMath::Sqrt(fabs(fCovMatrix[0])); - fDLm = TMath::Sqrt(fabs(fCovMatrix[5])); - fDPhi = TMath::Sqrt(fabs(fCovMatrix[9])); - fDX_sc = 0; - fDY_sc = TMath::Sqrt(fabs(fCovMatrix[12])); - fDZ_sc = TMath::Sqrt(fabs(fCovMatrix[14])); - - fDPx= GetDPx(); - fDPy= GetDPy(); - fDPz= GetDPz(); - - - Double_t PD[3],RD[6][6],H[3],PC[3],RC[15]; - Int_t CH; - PC[0] = fQp; - PC[1] = fLm; - PC[2] = fPhi; - - for(Int_t i=0; i<15; i++) { - RC[i]=fCovMatrix[i]; - } + fPhi = TMath::ATan2(Py, Px); + if (Q != 0) { + fq = int(TMath::Abs(Q) / Q); + } + fQp = fq / P; - // retrieve field - Double_t pnt[3]; - pnt[0] = fX; - pnt[1] = fY; - pnt[2] = fZ; + cLm = TMath::Cos(fLm); + sLm = TMath::Sin(fLm); + cphi = TMath::Cos(fPhi); + sphi = TMath::Sin(fPhi); - GetFieldValue(pnt, H); + SetX(X); + SetY(Y); + SetZ(Z); + SetPx(Px); + SetPy(Py); + SetPz(Pz); - CH=fq; - FairGeaneUtil util; - util.FromSCToMars(PC,RC,H,CH,PD,RD); + fX_sc = fX * cphi * cLm + fY * cLm * sphi + fZ * sLm; + fY_sc = fY * cphi - fX * sphi; + fZ_sc = fZ * cLm - fY * sLm * sphi - fX * sLm * cphi; - fDPx = sqrt(fabs(RD[0][0])); - fDPy = sqrt(fabs(RD[1][1])); - fDPz = sqrt(fabs(RD[2][2])); - fDX = sqrt(fabs(RD[3][3])); - fDY = sqrt(fabs(RD[4][4])); - fDZ = sqrt(fabs(RD[5][5])); + for (Int_t i = 0; i < 15; i++) { + fCovMatrix[i] = CovMatrix[i]; + } - for(int i = 0; i < 6; i++) for(int j = 0; j < 6; j++) { fCovMatrix66[i][j] = RD[i][j]; } + fDQp = TMath::Sqrt(fabs(fCovMatrix[0])); + fDLm = TMath::Sqrt(fabs(fCovMatrix[5])); + fDPhi = TMath::Sqrt(fabs(fCovMatrix[9])); + fDX_sc = 0; + fDY_sc = TMath::Sqrt(fabs(fCovMatrix[12])); + fDZ_sc = TMath::Sqrt(fabs(fCovMatrix[14])); + + fDPx = GetDPx(); + fDPy = GetDPy(); + fDPz = GetDPz(); + + Double_t PD[3], RD[6][6], H[3], PC[3], RC[15]; + Int_t CH; + PC[0] = fQp; + PC[1] = fLm; + PC[2] = fPhi; + + for (Int_t i = 0; i < 15; i++) { + RC[i] = fCovMatrix[i]; + } + // retrieve field + Double_t pnt[3]; + pnt[0] = fX; + pnt[1] = fY; + pnt[2] = fZ; + + GetFieldValue(pnt, H); + + CH = fq; + FairGeaneUtil util; + util.FromSCToMars(PC, RC, H, CH, PD, RD); + + fDPx = sqrt(fabs(RD[0][0])); + fDPy = sqrt(fabs(RD[1][1])); + fDPz = sqrt(fabs(RD[2][2])); + fDX = sqrt(fabs(RD[3][3])); + fDY = sqrt(fabs(RD[4][4])); + fDZ = sqrt(fabs(RD[5][5])); + + for (int i = 0; i < 6; i++) + for (int j = 0; j < 6; j++) { + fCovMatrix66[i][j] = RD[i][j]; + } } -//track definition in SC -void FairTrackParH::SetTrackPar(Double_t x, Double_t y, Double_t z, - Double_t qp, Double_t lm, Double_t phi, Double_t CovMatrix[15]) +// track definition in SC +void FairTrackParH::SetTrackPar(Double_t x, + Double_t y, + Double_t z, + Double_t qp, + Double_t lm, + Double_t phi, + Double_t CovMatrix[15]) { - fLm = lm; - fPhi = phi; - fQp = qp; - Double_t P = TMath::Abs(1/fQp); -// fq= int (P * fQp); - fq = static_cast(TMath::Sign(1.0, fQp)); - for(Int_t i=0; i<15; i++) { - fCovMatrix[i]=CovMatrix[i]; - - } - - cLm= TMath::Cos(fLm); - sLm= TMath::Sin(fLm); - cphi= TMath::Cos(fPhi); - sphi= TMath::Sin(fPhi); - - fPx = P * cLm* cphi; - fPy = P * cLm* sphi; - fPz = P * sLm; - - fX_sc = x; - fY_sc = y; - fZ_sc = z; - - fX =fX_sc*cLm*cphi -fY_sc*sphi -fZ_sc*cphi*sLm; - fY =fX_sc*cLm*sphi +fY_sc*cphi -fZ_sc*sphi*sLm; - fZ =fX_sc*sLm +fZ_sc*cLm; - - fDQp = TMath::Sqrt(fabs(fCovMatrix[0])); - fDLm = TMath::Sqrt(fabs(fCovMatrix[5])); - fDPhi = TMath::Sqrt(fabs(fCovMatrix[9])); - fDX_sc = 0; - fDY_sc = TMath::Sqrt(fabs(fCovMatrix[12])); - fDZ_sc = TMath::Sqrt(fabs(fCovMatrix[14])); - - fDPx= GetDPx() ; - fDPy= GetDPy() ; - fDPz= GetDPz() ; - - - Double_t PD[3],RD[6][6],H[3],PC[3],RC[15]; - Int_t CH; - PC[0] = fQp; - PC[1] = fLm; - PC[2] = fPhi; - - for(Int_t i=0; i<15; i++) { - RC[i]=fCovMatrix[i]; - } - - // retrieve field - Double_t pnt[3]; - pnt[0] = fX; - pnt[1] = fY; - pnt[2] = fZ; - - GetFieldValue(pnt, H); - - - CH=fq; - FairGeaneUtil util; - util.FromSCToMars(PC,RC,H,CH,PD,RD); + fLm = lm; + fPhi = phi; + fQp = qp; + Double_t P = TMath::Abs(1 / fQp); + // fq= int (P * fQp); + fq = static_cast(TMath::Sign(1.0, fQp)); + for (Int_t i = 0; i < 15; i++) { + fCovMatrix[i] = CovMatrix[i]; + } - // test - fDPx = sqrt(fabs(RD[0][0])); - fDPy = sqrt(fabs(RD[1][1])); - fDPz = sqrt(fabs(RD[2][2])); - fDX = sqrt(fabs(RD[3][3])); - fDY = sqrt(fabs(RD[4][4])); - fDZ = sqrt(fabs(RD[5][5])); + cLm = TMath::Cos(fLm); + sLm = TMath::Sin(fLm); + cphi = TMath::Cos(fPhi); + sphi = TMath::Sin(fPhi); + + fPx = P * cLm * cphi; + fPy = P * cLm * sphi; + fPz = P * sLm; + + fX_sc = x; + fY_sc = y; + fZ_sc = z; + + fX = fX_sc * cLm * cphi - fY_sc * sphi - fZ_sc * cphi * sLm; + fY = fX_sc * cLm * sphi + fY_sc * cphi - fZ_sc * sphi * sLm; + fZ = fX_sc * sLm + fZ_sc * cLm; + + fDQp = TMath::Sqrt(fabs(fCovMatrix[0])); + fDLm = TMath::Sqrt(fabs(fCovMatrix[5])); + fDPhi = TMath::Sqrt(fabs(fCovMatrix[9])); + fDX_sc = 0; + fDY_sc = TMath::Sqrt(fabs(fCovMatrix[12])); + fDZ_sc = TMath::Sqrt(fabs(fCovMatrix[14])); + + fDPx = GetDPx(); + fDPy = GetDPy(); + fDPz = GetDPz(); + + Double_t PD[3], RD[6][6], H[3], PC[3], RC[15]; + Int_t CH; + PC[0] = fQp; + PC[1] = fLm; + PC[2] = fPhi; + + for (Int_t i = 0; i < 15; i++) { + RC[i] = fCovMatrix[i]; + } - for(int i = 0; i < 6; i++) for(int j = 0; j < 6; j++) { fCovMatrix66[i][j] = RD[i][j]; } + // retrieve field + Double_t pnt[3]; + pnt[0] = fX; + pnt[1] = fY; + pnt[2] = fZ; + + GetFieldValue(pnt, H); + + CH = fq; + FairGeaneUtil util; + util.FromSCToMars(PC, RC, H, CH, PD, RD); + + // test + fDPx = sqrt(fabs(RD[0][0])); + fDPy = sqrt(fabs(RD[1][1])); + fDPz = sqrt(fabs(RD[2][2])); + fDX = sqrt(fabs(RD[3][3])); + fDY = sqrt(fabs(RD[4][4])); + fDZ = sqrt(fabs(RD[5][5])); + + for (int i = 0; i < 6; i++) + for (int j = 0; j < 6; j++) { + fCovMatrix66[i][j] = RD[i][j]; + } } - void FairTrackParH::CalCov() { - fDPx= GetDPx(); - fDPy= GetDPy(); - fDPz= GetDPz(); - - Double_t fP =sqrt(fPx*fPx+fPy*fPy+fPz*fPz); - Double_t fDP= (2*fPx*fDPx+2*fPy*fDPy+2*fPz*fDPz)/(2*fP); //dp - fDQp = - fDP/(fP*fP); // d(1/p) - - Double_t fDPQDLm = - sLm * cphi / fPx; // d(1/p)/dLambda - Double_t fDPQDPhi= - cLm * TMath::Sin(fPhi) / fPx; // d(1/p)/dphi - - Double_t fDPQDX_sc = (fX_sc*pow(fZ,3))/(fPz*pow(pow(fX_sc,2) + pow(fY_sc,2),2.5)* - pow(1 + pow(fZ_sc,2)/(pow(fX_sc,2) + pow(fY_sc,2)),1.5)) - - (fX_sc*fZ_sc)/(fPz*pow(pow(fX_sc,2) + - pow(fY_sc,2),1.5)*TMath::Sqrt(1 + pow(fZ_sc,2)/(pow(fX_sc,2) + pow(fY_sc,2)))); //d(1/p)/dx - - Double_t fDPQDY_sc = (fY_sc*pow(fZ_sc,3))/(fPz*pow(pow(fX_sc,2) + pow(fY_sc,2),2.5)* - pow(1 + pow(fZ_sc,2)/(pow(fX_sc,2) + pow(fY_sc,2)),1.5)) - - (fY_sc*fZ_sc)/(fPz*pow(pow(fX_sc,2) + pow(fY_sc,2),1.5)* - TMath::Sqrt(1 + pow(fZ_sc,2)/(pow(fX_sc,2) + pow(fY_sc,2)))); //d(1/p)/dy - - fDLm= (-((fPz*fDP)/pow(fP,2)) + fDPz/fP)/ TMath::Sqrt(1 - pow(fPz,2)/pow(fP,2)); // d(Lambda) - - Double_t fDLmDPhi =-((fPx*TMath::Tan(fPhi)/cphi)/ - (fP*TMath::Sqrt(1 - (pow(fPx,2)*pow(1/cphi,2))/pow(fP,2)))); // dLambda/dPhi - - Double_t fDLmDX_sc = -((fX_sc*fZ_sc)/(pow(pow(fX_sc,2) + pow(fY_sc,2),1.5)* - (1 + pow(fZ_sc,2)/(pow(fX_sc,2) + pow(fY_sc,2))))); // dLambda/dX - - Double_t fDLmDY_sc = -((fY_sc*fZ_sc)/(pow(pow(fX_sc,2) + pow(fY_sc,2),1.5)* - (1 + pow(fZ_sc,2)/(pow(fX_sc,2) + pow(fY_sc,2))))); // dLambda/dY - - fDPhi= (-((fPy*fDP/cLm)/pow(fP,2)) + - (fDPy/cLm)/fP +(fPy*fDLm*TMath::Tan(fLm)/cLm)/fP) /TMath::Sqrt(1 - (pow(fPy,2)*pow(1/cLm,2))/pow(fP,2)); // d(Phi) - - Double_t fDPhiDx_sc = -(fY_sc/(pow(fX_sc,2)*(1 + pow(fY_sc,2)/pow(fX_sc,2)))); // dPhi/dx - - Double_t fDPhiDy_sc = 1/(fX_sc*(1 + pow(fY_sc,2)/pow(fX_sc,2))); // dPhi/dy - - Double_t fDXDY_sc = 1/TMath::Tan(fPhi); // dX/dY - - if(fDQp==0 && fDLm==0 && fDPhi ==0 ) { - cout << "FairTrackParH::CalCov() No Errors" << endl; - } else { - fCovMatrix[0] =fDQp*fDQp; - fCovMatrix[1] =fDPQDLm; - fCovMatrix[2] =fDPQDPhi; - fCovMatrix[3] =fDPQDX_sc; - fCovMatrix[4] =fDPQDY_sc; - fCovMatrix[5] =fDLm*fDLm; - fCovMatrix[6] =fDLmDPhi; - fCovMatrix[7] =fDLmDX_sc; - fCovMatrix[8] =fDLmDY_sc; - fCovMatrix[9] =fDPhi*fDPhi; - fCovMatrix[10] =fDPhiDx_sc; - fCovMatrix[11] =fDPhiDy_sc; - fCovMatrix[12] =fDX_sc*fDX_sc; - fCovMatrix[13] =fDXDY_sc; - fCovMatrix[14] =fDY_sc*fDY_sc; - } + fDPx = GetDPx(); + fDPy = GetDPy(); + fDPz = GetDPz(); + + Double_t fP = sqrt(fPx * fPx + fPy * fPy + fPz * fPz); + Double_t fDP = (2 * fPx * fDPx + 2 * fPy * fDPy + 2 * fPz * fDPz) / (2 * fP); // dp + fDQp = -fDP / (fP * fP); // d(1/p) + + Double_t fDPQDLm = -sLm * cphi / fPx; // d(1/p)/dLambda + Double_t fDPQDPhi = -cLm * TMath::Sin(fPhi) / fPx; // d(1/p)/dphi + + Double_t fDPQDX_sc = (fX_sc * pow(fZ, 3)) + / (fPz * pow(pow(fX_sc, 2) + pow(fY_sc, 2), 2.5) + * pow(1 + pow(fZ_sc, 2) / (pow(fX_sc, 2) + pow(fY_sc, 2)), 1.5)) + - (fX_sc * fZ_sc) + / (fPz * pow(pow(fX_sc, 2) + pow(fY_sc, 2), 1.5) + * TMath::Sqrt(1 + pow(fZ_sc, 2) / (pow(fX_sc, 2) + pow(fY_sc, 2)))); // d(1/p)/dx + + Double_t fDPQDY_sc = (fY_sc * pow(fZ_sc, 3)) + / (fPz * pow(pow(fX_sc, 2) + pow(fY_sc, 2), 2.5) + * pow(1 + pow(fZ_sc, 2) / (pow(fX_sc, 2) + pow(fY_sc, 2)), 1.5)) + - (fY_sc * fZ_sc) + / (fPz * pow(pow(fX_sc, 2) + pow(fY_sc, 2), 1.5) + * TMath::Sqrt(1 + pow(fZ_sc, 2) / (pow(fX_sc, 2) + pow(fY_sc, 2)))); // d(1/p)/dy + + fDLm = (-((fPz * fDP) / pow(fP, 2)) + fDPz / fP) / TMath::Sqrt(1 - pow(fPz, 2) / pow(fP, 2)); // d(Lambda) + + Double_t fDLmDPhi = -((fPx * TMath::Tan(fPhi) / cphi) + / (fP * TMath::Sqrt(1 - (pow(fPx, 2) * pow(1 / cphi, 2)) / pow(fP, 2)))); // dLambda/dPhi + + Double_t fDLmDX_sc = -((fX_sc * fZ_sc) + / (pow(pow(fX_sc, 2) + pow(fY_sc, 2), 1.5) + * (1 + pow(fZ_sc, 2) / (pow(fX_sc, 2) + pow(fY_sc, 2))))); // dLambda/dX + + Double_t fDLmDY_sc = -((fY_sc * fZ_sc) + / (pow(pow(fX_sc, 2) + pow(fY_sc, 2), 1.5) + * (1 + pow(fZ_sc, 2) / (pow(fX_sc, 2) + pow(fY_sc, 2))))); // dLambda/dY + + fDPhi = (-((fPy * fDP / cLm) / pow(fP, 2)) + (fDPy / cLm) / fP + (fPy * fDLm * TMath::Tan(fLm) / cLm) / fP) + / TMath::Sqrt(1 - (pow(fPy, 2) * pow(1 / cLm, 2)) / pow(fP, 2)); // d(Phi) + + Double_t fDPhiDx_sc = -(fY_sc / (pow(fX_sc, 2) * (1 + pow(fY_sc, 2) / pow(fX_sc, 2)))); // dPhi/dx + + Double_t fDPhiDy_sc = 1 / (fX_sc * (1 + pow(fY_sc, 2) / pow(fX_sc, 2))); // dPhi/dy + + Double_t fDXDY_sc = 1 / TMath::Tan(fPhi); // dX/dY + + if (fDQp == 0 && fDLm == 0 && fDPhi == 0) { + cout << "FairTrackParH::CalCov() No Errors" << endl; + } else { + fCovMatrix[0] = fDQp * fDQp; + fCovMatrix[1] = fDPQDLm; + fCovMatrix[2] = fDPQDPhi; + fCovMatrix[3] = fDPQDX_sc; + fCovMatrix[4] = fDPQDY_sc; + fCovMatrix[5] = fDLm * fDLm; + fCovMatrix[6] = fDLmDPhi; + fCovMatrix[7] = fDLmDX_sc; + fCovMatrix[8] = fDLmDY_sc; + fCovMatrix[9] = fDPhi * fDPhi; + fCovMatrix[10] = fDPhiDx_sc; + fCovMatrix[11] = fDPhiDy_sc; + fCovMatrix[12] = fDX_sc * fDX_sc; + fCovMatrix[13] = fDXDY_sc; + fCovMatrix[14] = fDY_sc * fDY_sc; + } } FairTrackParH::FairTrackParH(FairTrackPar& Trkbase) - : FairTrackPar(Trkbase), - fLm (0.), - fPhi (0.), - fDLm(0.), - fDPhi(0.), - fX_sc (0.), - fY_sc (0.), - fZ_sc (0.), - fDX_sc(0.), - fDY_sc(0.), - fDZ_sc(0.), - cLm(0.), - sLm(0.), - cphi(0.), - sphi(0.) + : FairTrackPar(Trkbase) + , fLm(0.) + , fPhi(0.) + , fDLm(0.) + , fDPhi(0.) + , fX_sc(0.) + , fY_sc(0.) + , fZ_sc(0.) + , fDX_sc(0.) + , fDY_sc(0.) + , fDZ_sc(0.) + , cLm(0.) + , sLm(0.) + , cphi(0.) + , sphi(0.) { - cout << "FairTrackParH::FairTrackParH(FairTrackPar &Trkbase)" << endl; - Reset(); - fX = Trkbase.GetX(); - fY = Trkbase.GetY(); - fZ = Trkbase.GetZ(); - - fPx = Trkbase.GetPx(); - fPy = Trkbase.GetPy(); - fPz = Trkbase.GetPz(); - fq = Trkbase.GetQ(); - Double_t fP=TMath::Sqrt(fPx*fPx +fPy*fPy +fPz*fPz ); - if (fP!=0) { fQp = fq/fP; } - else { fQp=0; } - fLm = TMath::ASin(fPz/fP); - fPhi = TMath::ATan2(fPy,fPx); + cout << "FairTrackParH::FairTrackParH(FairTrackPar &Trkbase)" << endl; + Reset(); + fX = Trkbase.GetX(); + fY = Trkbase.GetY(); + fZ = Trkbase.GetZ(); + + fPx = Trkbase.GetPx(); + fPy = Trkbase.GetPy(); + fPz = Trkbase.GetPz(); + fq = Trkbase.GetQ(); + Double_t fP = TMath::Sqrt(fPx * fPx + fPy * fPy + fPz * fPz); + if (fP != 0) { + fQp = fq / fP; + } else { + fQp = 0; + } + fLm = TMath::ASin(fPz / fP); + fPhi = TMath::ATan2(fPy, fPx); - cLm= TMath::Cos(fLm); - sLm= TMath::Sin(fLm); - cphi= TMath::Cos(fPhi); - sphi= TMath::Sin(fPhi); + cLm = TMath::Cos(fLm); + sLm = TMath::Sin(fLm); + cphi = TMath::Cos(fPhi); + sphi = TMath::Sin(fPhi); - fDPx = Trkbase.GetDPx(); - fDPy = Trkbase.GetDPy(); - fDPz = Trkbase.GetDPz(); - - fDX = Trkbase.GetDX(); - fDY = Trkbase.GetDY(); - fDZ = Trkbase.GetDZ(); - - fX_sc = fX*cphi*cLm+ fY*cLm*sphi+fZ*sLm; - fY_sc = fY*cphi-fX*sphi; - fZ_sc = fZ*cLm-fY*sLm*sphi-fX*sLm*cphi; - - for(Int_t i=0; i<15; i++) { - fCovMatrix[i]=0; - } - - Double_t PD[3],RD[6][6],H[3],PC[3],RC[15]; - Int_t CH; - PD[0]=fPx; - PD[1]=fPy; - PD[2]=fPz; - for(Int_t i=0; i<6; i++) for(Int_t j=0; j<6; j++) { - RD[i][j]=0; - } - RD[0][0] = fDPx * fDPx; - RD[1][1] = fDPy * fDPy; - RD[2][2] = fDPz * fDPz; - RD[3][3] = fDX * fDX; - RD[4][4] = fDY * fDY; - RD[5][5] = fDZ * fDZ; - - // retrieve field - Double_t pnt[3]; - pnt[0] = fX; - pnt[1] = fY; - pnt[2] = fZ; - - GetFieldValue(pnt, H); - - - CH=fq; - FairGeaneUtil fUtil; - fUtil.FromMarsToSC(PD,RD,H,CH,PC,RC); - for(Int_t i=0; i<15; i++) { - fCovMatrix[i]=RC[i]; - } - fDX_sc = 0; - fDY_sc = TMath::Sqrt(fabs(fCovMatrix[12])); - fDZ_sc = TMath::Sqrt(fabs(fCovMatrix[14])); - - for(int i = 0; i < 6; i++) for(int j = 0; j < 6; j++) { fCovMatrix66[i][j] = RD[i][j]; } + fDPx = Trkbase.GetDPx(); + fDPy = Trkbase.GetDPy(); + fDPz = Trkbase.GetDPz(); -} + fDX = Trkbase.GetDX(); + fDY = Trkbase.GetDY(); + fDZ = Trkbase.GetDZ(); -FairTrackParH::~FairTrackParH() -{ + fX_sc = fX * cphi * cLm + fY * cLm * sphi + fZ * sLm; + fY_sc = fY * cphi - fX * sphi; + fZ_sc = fZ * cLm - fY * sLm * sphi - fX * sLm * cphi; -} -void FairTrackParH::Print(Option_t* /*option*/) const -{ - cout << this<< endl; - cout << "Position : " - << std::setprecision(2) << fX << ", " << fY << ", " << fZ << ")" << endl; - cout << std::setprecision(2) << "Angles : Lambda = " << fLm << ", Phi = " << fPhi << endl; - cout << "q/p = " << fQp << endl; - for(Int_t i=0; i<15; i++) { - cout << std::setprecision(2) << "fCovMatrix[" << i << "] = " << this << " " << fCovMatrix[i] << endl; - } + for (Int_t i = 0; i < 15; i++) { + fCovMatrix[i] = 0; + } -} -Double_t FairTrackParH::GetDX_sc() -{ - return fDX_sc; + Double_t PD[3], RD[6][6], H[3], PC[3], RC[15]; + Int_t CH; + PD[0] = fPx; + PD[1] = fPy; + PD[2] = fPz; + for (Int_t i = 0; i < 6; i++) + for (Int_t j = 0; j < 6; j++) { + RD[i][j] = 0; + } + RD[0][0] = fDPx * fDPx; + RD[1][1] = fDPy * fDPy; + RD[2][2] = fDPz * fDPz; + RD[3][3] = fDX * fDX; + RD[4][4] = fDY * fDY; + RD[5][5] = fDZ * fDZ; + + // retrieve field + Double_t pnt[3]; + pnt[0] = fX; + pnt[1] = fY; + pnt[2] = fZ; + + GetFieldValue(pnt, H); + + CH = fq; + FairGeaneUtil fUtil; + fUtil.FromMarsToSC(PD, RD, H, CH, PC, RC); + for (Int_t i = 0; i < 15; i++) { + fCovMatrix[i] = RC[i]; + } + fDX_sc = 0; + fDY_sc = TMath::Sqrt(fabs(fCovMatrix[12])); + fDZ_sc = TMath::Sqrt(fabs(fCovMatrix[14])); + + for (int i = 0; i < 6; i++) + for (int j = 0; j < 6; j++) { + fCovMatrix66[i][j] = RD[i][j]; + } } -Double_t FairTrackParH::GetDY_sc() +FairTrackParH::~FairTrackParH() {} +void FairTrackParH::Print(Option_t* /*option*/) const { - return fDY_sc; -} -Double_t FairTrackParH::GetDZ_sc() -{ - return fDZ_sc; + cout << this << endl; + cout << "Position : " << std::setprecision(2) << fX << ", " << fY << ", " << fZ << ")" << endl; + cout << std::setprecision(2) << "Angles : Lambda = " << fLm << ", Phi = " << fPhi << endl; + cout << "q/p = " << fQp << endl; + for (Int_t i = 0; i < 15; i++) { + cout << std::setprecision(2) << "fCovMatrix[" << i << "] = " << this << " " << fCovMatrix[i] << endl; + } } +Double_t FairTrackParH::GetDX_sc() { return fDX_sc; } + +Double_t FairTrackParH::GetDY_sc() { return fDY_sc; } +Double_t FairTrackParH::GetDZ_sc() { return fDZ_sc; } Double_t FairTrackParH::GetX() { - if(fX==0) { - fX =fX_sc*cLm*cphi -fY_sc*sphi -fZ_sc*cphi*sLm; - } - return fX; + if (fX == 0) { + fX = fX_sc * cLm * cphi - fY_sc * sphi - fZ_sc * cphi * sLm; + } + return fX; } Double_t FairTrackParH::GetY() { - if(fY==0) { - fY =fX_sc*cLm*sphi +fY_sc*cphi -fZ_sc*sphi*sLm; - } - return fY; + if (fY == 0) { + fY = fX_sc * cLm * sphi + fY_sc * cphi - fZ_sc * sphi * sLm; + } + return fY; } Double_t FairTrackParH::GetZ() { - if(fZ==0) { - fZ =fX_sc*sLm +fZ_sc*cLm; - } - return fZ; + if (fZ == 0) { + fZ = fX_sc * sLm + fZ_sc * cLm; + } + return fZ; } - /*Double_t FairTrackParH::GetDPx() { return fDPx; @@ -690,49 +700,44 @@ Double_t FairTrackParH::GetDQp() return fDQp; } */ -Double_t FairTrackParH::GetDLambda() -{ - return fDLm; -}; -Double_t FairTrackParH::GetDPhi() -{ - return fDPhi; -}; +Double_t FairTrackParH::GetDLambda() { return fDLm; }; +Double_t FairTrackParH::GetDPhi() { return fDPhi; }; -void FairTrackParH::Reset() +void FairTrackParH::Reset() { - fLm=0; - fPhi=0; - fDLm=0; - fDPhi=0; - fX_sc= fY_sc= fZ_sc=0; - fDX_sc= fDY_sc= fDZ_sc =0; - cLm =sLm= cphi =sphi=0; - for(Int_t i= 0; i<15; i++) { fCovMatrix[i] =0; } - - //base class members - - fX= fY= fZ=0; - fDX= fDY= fDZ=0; - fPx= fPy= fPz=0; - fDPx= fDPy= fDPz=0; - fQp=fDQp=fq=0; + fLm = 0; + fPhi = 0; + fDLm = 0; + fDPhi = 0; + fX_sc = fY_sc = fZ_sc = 0; + fDX_sc = fDY_sc = fDZ_sc = 0; + cLm = sLm = cphi = sphi = 0; + for (Int_t i = 0; i < 15; i++) { + fCovMatrix[i] = 0; + } + // base class members + fX = fY = fZ = 0; + fDX = fDY = fDZ = 0; + fPx = fPy = fPz = 0; + fDPx = fDPy = fDPz = 0; + fQp = fDQp = fq = 0; } void FairTrackParH::GetCovQ(Double_t* CovQ) { - // return error matrix in 1/p instead of q/p - - for(int i = 0; i < 15; i++) { - CovQ[i] = fCovMatrix[i]; - if(fq!=0) { - if(i == 0) { CovQ[i] = CovQ[i] / (fq * fq); } - if(i > 0 && i < 5) { CovQ[i] = CovQ[i] / fq; } + // return error matrix in 1/p instead of q/p + + for (int i = 0; i < 15; i++) { + CovQ[i] = fCovMatrix[i]; + if (fq != 0) { + if (i == 0) { + CovQ[i] = CovQ[i] / (fq * fq); + } + if (i > 0 && i < 5) { + CovQ[i] = CovQ[i] / fq; + } + } } - } } - - - diff --git a/trackbase/FairTrackParH.h b/trackbase/FairTrackParH.h index 38f4772e02..645cc88ba1 100644 --- a/trackbase/FairTrackParH.h +++ b/trackbase/FairTrackParH.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // Class for the representation of a track as helix (SC system) @@ -17,10 +17,10 @@ #ifndef FAIRSTSTRACKPARH #define FAIRSTSTRACKPARH 1 -#include "FairTrackPar.h" // for FairTrackPar +#include "FairTrackPar.h" // for FairTrackPar -#include // for Double_t, Int_t, etc -#include // for TVector3 +#include // for Double_t, Int_t, etc +#include // for TVector3 class FairTrackParP; @@ -31,8 +31,12 @@ class FairTrackParH : public FairTrackPar FairTrackParH(); /** Constructor with track variables (in SC) **/ - FairTrackParH(Double_t x, Double_t y, Double_t z, - Double_t lambda, Double_t phi, Double_t qp, + FairTrackParH(Double_t x, + Double_t y, + Double_t z, + Double_t lambda, + Double_t phi, + Double_t qp, Double_t CovMatrix[15]); /** Constructor track parameters with position and momentum (in LAB)**/ @@ -42,7 +46,7 @@ class FairTrackParH : public FairTrackPar /** copy Constructor **/ FairTrackParH(FairTrackPar& Trkbase); - //FairTrackParH(FairTrackParH &Trk); + // FairTrackParH(FairTrackParH &Trk); FairTrackParH(FairTrackParP* parab, Int_t& ierr); @@ -50,52 +54,73 @@ class FairTrackParH : public FairTrackPar virtual ~FairTrackParH(); /** Output to screen **/ -// void Print(); - virtual void Print(Option_t* option = "") const; + // void Print(); + virtual void Print(Option_t* option = "") const; /** Accessors **/ Double_t GetLambda() { return fLm; }; Double_t GetPhi() { return fPhi; }; - Double_t GetDLambda() ; /**Get Error in Lambda*/ - Double_t GetDPhi() ; /**Get Error in Phi*/ + Double_t GetDLambda(); /**Get Error in Lambda*/ + Double_t GetDPhi(); /**Get Error in Phi*/ /**Get the coveriant matrix*/ - void GetCov(Double_t* Cov) {for(Int_t i=0; i<15; i++) { Cov[i]=fCovMatrix[i]; }} + void GetCov(Double_t* Cov) + { + for (Int_t i = 0; i < 15; i++) { + Cov[i] = fCovMatrix[i]; + } + } void GetCovQ(Double_t* CovQ); // MARS - void GetMARSCov(Double_t Cov66[6][6]) {for(Int_t i=0; i<6; i++) for(Int_t j=0; j<6; j++) { Cov66[i][j] = fCovMatrix66[i][j]; } } - Double_t GetDX_sc(); /**Get dx in SC*/ - Double_t GetDY_sc(); /**Get dy in SC*/ - Double_t GetDZ_sc(); /**Get dz in SC*/ - Double_t GetX_sc() {return fX_sc;} /**Get x in SC*/ - Double_t GetY_sc() {return fY_sc;} /**Get y in SC*/ - Double_t GetZ_sc() {return fZ_sc;} /**Get z in SC*/ -// Double_t GetDPx() ; /**Get error in Px (in SC frame)*/ -// Double_t GetDPy() ; /**Get error in Py (in SC frame)*/ -// Double_t GetDPz() ; /**Get error in Pz (in SC frame)*/ -// Double_t GetDQp() ; /**Get error in Q/P*/ - Double_t GetX(); /**Get X in Lab*/ - Double_t GetY(); /**Get Y in Lab*/ - Double_t GetZ(); /**Get Z in Lab*/ + void GetMARSCov(Double_t Cov66[6][6]) + { + for (Int_t i = 0; i < 6; i++) + for (Int_t j = 0; j < 6; j++) { + Cov66[i][j] = fCovMatrix66[i][j]; + } + } + Double_t GetDX_sc(); /**Get dx in SC*/ + Double_t GetDY_sc(); /**Get dy in SC*/ + Double_t GetDZ_sc(); /**Get dz in SC*/ + Double_t GetX_sc() { return fX_sc; } /**Get x in SC*/ + Double_t GetY_sc() { return fY_sc; } /**Get y in SC*/ + Double_t GetZ_sc() { return fZ_sc; } /**Get z in SC*/ + // Double_t GetDPx() ; /**Get error in Px (in SC frame)*/ + // Double_t GetDPy() ; /**Get error in Py (in SC frame)*/ + // Double_t GetDPz() ; /**Get error in Pz (in SC frame)*/ + // Double_t GetDQp() ; /**Get error in Q/P*/ + Double_t GetX(); /**Get X in Lab*/ + Double_t GetY(); /**Get Y in Lab*/ + Double_t GetZ(); /**Get Z in Lab*/ /** Modifiers **/ - void SetLambda(Double_t Lm ) { fLm = Lm; }; + void SetLambda(Double_t Lm) { fLm = Lm; }; void SetPhi(Double_t Phi) { fPhi = Phi; }; - void SetDLambda(Double_t DLm ) { fDLm = DLm; }; + void SetDLambda(Double_t DLm) { fDLm = DLm; }; void SetDPhi(Double_t DPhi) { fDPhi = DPhi; }; - void SetX_sc(Double_t x) {fX_sc =x;} /**Set x in SC*/ - void SetY_sc(Double_t y) {fY_sc =y;} /**Set y in SC*/ - void SetZ_sc(Double_t z) {fZ_sc =z;} /**Set z in SC*/ - void SetCov(Double_t* Cov) {for(Int_t i=0; i<15; i++) { fCovMatrix[i]=Cov[i]; }} - void SetTrackPar(Double_t x, Double_t y, Double_t z, - Double_t Px, Double_t Py, Double_t Pz, Int_t Q, - Double_t CovMatrix[15]); - - void SetTrackPar(Double_t x, Double_t y, Double_t z, - Double_t pq, Double_t lm, Double_t phi, Double_t CovMatrix[15]); + void SetX_sc(Double_t x) { fX_sc = x; } /**Set x in SC*/ + void SetY_sc(Double_t y) { fY_sc = y; } /**Set y in SC*/ + void SetZ_sc(Double_t z) { fZ_sc = z; } /**Set z in SC*/ + void SetCov(Double_t* Cov) + { + for (Int_t i = 0; i < 15; i++) { + fCovMatrix[i] = Cov[i]; + } + } + void SetTrackPar(Double_t x, + Double_t y, + Double_t z, + Double_t Px, + Double_t Py, + Double_t Pz, + Int_t Q, + Double_t CovMatrix[15]); + + void + SetTrackPar(Double_t x, Double_t y, Double_t z, Double_t pq, Double_t lm, Double_t phi, Double_t CovMatrix[15]); void Reset(); - ClassDef(FairTrackParH,1); + ClassDef(FairTrackParH, 1); private: /** fLm = Dip angle **/ @@ -125,7 +150,7 @@ class FairTrackParH : public FairTrackPar sphi = Sin(Phi) //! do not streame this to the file */ - Double_t cLm,sLm, cphi ,sphi; //! + Double_t cLm, sLm, cphi, sphi; //! }; #endif diff --git a/trackbase/FairTrackParP.cxx b/trackbase/FairTrackParP.cxx index 437936f843..ae90c6d664 100644 --- a/trackbase/FairTrackParP.cxx +++ b/trackbase/FairTrackParP.cxx @@ -16,456 +16,503 @@ #include "FairTrackParP.h" -#include "FairGeaneUtil.h" // for FairGeaneUtil -#include "FairTrackParH.h" // for FairTrackParH +#include "FairGeaneUtil.h" // for FairGeaneUtil +#include "FairTrackParH.h" // for FairTrackParH -#include // for Sqrt -#include // for Abs, Sign - -#include // for operator<<, basic_ostream, etc +#include // for Sqrt +#include // for Abs, Sign +#include // IWYU pragma: keep for fabs #include -#include // IWYU pragma: keep for fabs +#include // for operator<<, basic_ostream, etc // IWYU pragma: no_include using std::cout; using std::endl; -ClassImp(FairTrackParP) +ClassImp(FairTrackParP); FairTrackParP::FairTrackParP() - : FairTrackPar(), - fU (0.), - fV (0.), - fW (0.), - fTV(0.), - fTW(0.), - fPx_sd(0.), - fPy_sd(0.), - fPz_sd(0.), - fDU(0.), - fDV(0.), - fDW(0.), - fDTV(0.), - fDTW(0.), - forigin(TVector3(0,0,0)), - fiver(TVector3(0,0,0)), - fjver(TVector3(0,0,0)), - fkver(TVector3(0,0,0)), - fSPU(0.) -{ - // Reset(); - for(Int_t i=0; i<15; i++) { - fCovMatrix[i]=0; - } - for(int i = 0; i < 6; i++) for(int j = 0; j < 6; j++) { fCovMatrix66[i][j] = 0; } + : FairTrackPar() + , fU(0.) + , fV(0.) + , fW(0.) + , fTV(0.) + , fTW(0.) + , fPx_sd(0.) + , fPy_sd(0.) + , fPz_sd(0.) + , fDU(0.) + , fDV(0.) + , fDW(0.) + , fDTV(0.) + , fDTW(0.) + , forigin(TVector3(0, 0, 0)) + , fiver(TVector3(0, 0, 0)) + , fjver(TVector3(0, 0, 0)) + , fkver(TVector3(0, 0, 0)) + , fSPU(0.) +{ + // Reset(); + for (Int_t i = 0; i < 15; i++) { + fCovMatrix[i] = 0; + } + for (int i = 0; i < 6; i++) + for (int j = 0; j < 6; j++) { + fCovMatrix66[i][j] = 0; + } } // Constructor with track parameters in SD -FairTrackParP::FairTrackParP(Double_t v, Double_t w, Double_t Tv, - Double_t Tw, Double_t qp, +FairTrackParP::FairTrackParP(Double_t v, + Double_t w, + Double_t Tv, + Double_t Tw, + Double_t qp, Double_t CovMatrix[15], - TVector3 o, TVector3 dj, TVector3 dk) - : FairTrackPar(), - fU (0.), - fV (v), - fW (w), - fTV(Tv), - fTW(Tw), - fPx_sd(0.), - fPy_sd(0.), - fPz_sd(0.), - fDU(0.), - fDV(0.), - fDW(0.), - fDTV(0.), - fDTW(0.), - forigin(TVector3(0,0,0)), - fiver(TVector3(0,0,0)), - fjver(TVector3(0,0,0)), - fkver(TVector3(0,0,0)), - fSPU(0.) -{ -// Reset(); - SetPlane(o, dj, dk); -// fV = v; -// fW = w; -// fTV = Tv; -// fTW = Tw; - fQp = qp; - - Double_t P = TMath::Abs(1/fQp); - //fq= int (P * fQp); - fq = static_cast(TMath::Sign(1.0, fQp)); - for(Int_t i=0; i<15; i++) { - fCovMatrix[i]=CovMatrix[i]; - } - - - fPx_sd = TMath::Sqrt( P*P / ( fTV*fTV + fTW*fTW + 1 ) ); - fPy_sd = fTV * fPx_sd; - fPz_sd = fTW * fPx_sd; - - -// fU = 0.; - - FairGeaneUtil util; - TVector3 position = util.FromSDToMARSCoord(TVector3(fU, fV, fW), forigin, fiver, fjver, fkver); - fX = position.X(); - fY = position.Y(); - fZ = position.Z(); - - fDQp = TMath::Sqrt(fabs(fCovMatrix[0])); - fDTV = TMath::Sqrt(fabs(fCovMatrix[5])); - fDTW = TMath::Sqrt(fabs(fCovMatrix[9])); - fDV = TMath::Sqrt(fabs(fCovMatrix[12])); - fDW = TMath::Sqrt(fabs(fCovMatrix[14])); - - - Double_t PD[3],RD[6][6],H[3],PC[3],RC[15], SP1; - Int_t CH; - PC[0] = fQp; - PC[1] = fTV; - PC[2] = fTW; - - for(Int_t i=0; i<15; i++) { - RC[i]=fCovMatrix[i]; - } - - // initialize RD - for(Int_t i=0; i<6; i++) { - for(Int_t k=0; k<6; k++) { - RD[i][k] = 0; + TVector3 o, + TVector3 dj, + TVector3 dk) + : FairTrackPar() + , fU(0.) + , fV(v) + , fW(w) + , fTV(Tv) + , fTW(Tw) + , fPx_sd(0.) + , fPy_sd(0.) + , fPz_sd(0.) + , fDU(0.) + , fDV(0.) + , fDW(0.) + , fDTV(0.) + , fDTW(0.) + , forigin(TVector3(0, 0, 0)) + , fiver(TVector3(0, 0, 0)) + , fjver(TVector3(0, 0, 0)) + , fkver(TVector3(0, 0, 0)) + , fSPU(0.) +{ + // Reset(); + SetPlane(o, dj, dk); + // fV = v; + // fW = w; + // fTV = Tv; + // fTW = Tw; + fQp = qp; + + Double_t P = TMath::Abs(1 / fQp); + // fq= int (P * fQp); + fq = static_cast(TMath::Sign(1.0, fQp)); + for (Int_t i = 0; i < 15; i++) { + fCovMatrix[i] = CovMatrix[i]; } - } - - // retrieve field - Double_t pnt[3]; - pnt[0] = fX; - pnt[1] = fY; - pnt[2] = fZ; - - GetFieldValue(pnt, H); + fPx_sd = TMath::Sqrt(P * P / (fTV * fTV + fTW * fTW + 1)); + fPy_sd = fTV * fPx_sd; + fPz_sd = fTW * fPx_sd; - CH=fq; + // fU = 0.; - TVector3 momsd = TVector3(fPx_sd,fPy_sd,fPz_sd); - SP1 = (momsd.Dot(fjver.Cross(fkver)))/TMath::Abs(momsd.Dot(fjver.Cross(fkver))); - fSPU=SP1; + FairGeaneUtil util; + TVector3 position = util.FromSDToMARSCoord(TVector3(fU, fV, fW), forigin, fiver, fjver, fkver); + fX = position.X(); + fY = position.Y(); + fZ = position.Z(); - util.FromSDToMars(PC, RC, H, CH, SP1, fDJ, fDK, PD, RD); + fDQp = TMath::Sqrt(fabs(fCovMatrix[0])); + fDTV = TMath::Sqrt(fabs(fCovMatrix[5])); + fDTW = TMath::Sqrt(fabs(fCovMatrix[9])); + fDV = TMath::Sqrt(fabs(fCovMatrix[12])); + fDW = TMath::Sqrt(fabs(fCovMatrix[14])); - fPx = PD[0]; - fPy = PD[1]; - fPz = PD[2]; - - for(int i = 0; i < 6; i++) for(int j = 0; j < 6; j++) { fCovMatrix66[i][j] = RD[i][j]; } - - fDPx = TMath::Sqrt(fabs(RD[0][0])); - fDPy = TMath::Sqrt(fabs(RD[1][1])); - fDPz = TMath::Sqrt(fabs(RD[2][2])); - fDX = TMath::Sqrt(fabs(RD[3][3])); - fDY = TMath::Sqrt(fabs(RD[4][4])); - fDZ = TMath::Sqrt(fabs(RD[5][5])); - -} - -// Constructor with track parameters in SD -FairTrackParP::FairTrackParP(Double_t v, Double_t w, Double_t Tv, - Double_t Tw, Double_t qp, - Double_t CovMatrix[15], - TVector3 o, TVector3 dj, TVector3 dk, Double_t spu) - : FairTrackPar(), - fU (0.), - fV (v), - fW (w), - fTV(Tv), - fTW(Tw), - fPx_sd(0.), - fPy_sd(0.), - fPz_sd(0.), - fDU(0.), - fDV(0.), - fDW(0.), - fDTV(0.), - fDTW(0.), - forigin(TVector3(0,0,0)), - fiver(TVector3(0,0,0)), - fjver(TVector3(0,0,0)), - fkver(TVector3(0,0,0)), - fSPU(spu) + Double_t PD[3], RD[6][6], H[3], PC[3], RC[15], SP1; + Int_t CH; + PC[0] = fQp; + PC[1] = fTV; + PC[2] = fTW; -{ -// Reset(); - SetPlane(o, dj, dk); -// fV = v; -// fW = w; -// fTV = Tv; -// fTW = Tw; - fQp = qp; -// fSPU = spu; - Double_t P=0; - if(0!=fQp) { - P = TMath::Abs(1/fQp); - fq = static_cast(TMath::Sign(1.0, fQp)); - //fq= int (P * fQp); - } else { fq=1; } - for(Int_t i=0; i<15; i++) { - fCovMatrix[i]=CovMatrix[i]; - } - - fPx_sd = fSPU*TMath::Sqrt( P*P / ( fTV*fTV + fTW*fTW + 1 ) ); - fPy_sd = fTV * fPx_sd; - fPz_sd = fTW * fPx_sd; - -// fU = 0.; - - FairGeaneUtil util; - TVector3 position = util.FromSDToMARSCoord(TVector3(fU, fV, fW), forigin, fiver, fjver, fkver); - fX = position.X(); - fY = position.Y(); - fZ = position.Z(); - - fDQp = TMath::Sqrt(fabs(fCovMatrix[0])); - fDTV = TMath::Sqrt(fabs(fCovMatrix[5])); - fDTW = TMath::Sqrt(fabs(fCovMatrix[9])); - fDV = TMath::Sqrt(fabs(fCovMatrix[12])); - fDW = TMath::Sqrt(fabs(fCovMatrix[14])); - - Double_t PD[3],RD[6][6],H[3],PC[3],RC[15], SP1; - Int_t CH; - PC[0] = fQp; - PC[1] = fTV; - PC[2] = fTW; - - // initialize RD - for(Int_t i=0; i<6; i++) { - for(Int_t k=0; k<6; k++) { - RD[i][k] = 0; + for (Int_t i = 0; i < 15; i++) { + RC[i] = fCovMatrix[i]; } - } - for(Int_t i=0; i<15; i++) { - RC[i]=fCovMatrix[i]; - } + // initialize RD + for (Int_t i = 0; i < 6; i++) { + for (Int_t k = 0; k < 6; k++) { + RD[i][k] = 0; + } + } - // retrieve field - Double_t pnt[3]; - pnt[0] = fX; - pnt[1] = fY; - pnt[2] = fZ; + // retrieve field + Double_t pnt[3]; + pnt[0] = fX; + pnt[1] = fY; + pnt[2] = fZ; - GetFieldValue(pnt, H); + GetFieldValue(pnt, H); - CH=fq; + CH = fq; - TVector3 momsd = TVector3(fPx_sd,fPy_sd,fPz_sd); - // SP1 = (momsd.Dot(fjver.Cross(fkver)))/TMath::Abs(momsd.Dot(fjver.Cross(fkver))); - SP1 = fSPU; // correct calculation of SP1 + TVector3 momsd = TVector3(fPx_sd, fPy_sd, fPz_sd); + SP1 = (momsd.Dot(fjver.Cross(fkver))) / TMath::Abs(momsd.Dot(fjver.Cross(fkver))); + fSPU = SP1; - util.FromSDToMars(PC, RC, H, CH, SP1, fDJ, fDK, PD, RD); + util.FromSDToMars(PC, RC, H, CH, SP1, fDJ, fDK, PD, RD); - fPx = PD[0]; - fPy = PD[1]; - fPz = PD[2]; + fPx = PD[0]; + fPy = PD[1]; + fPz = PD[2]; - for(int i = 0; i < 6; i++) for(int j = 0; j < 6; j++) { fCovMatrix66[i][j] = RD[i][j]; } + for (int i = 0; i < 6; i++) + for (int j = 0; j < 6; j++) { + fCovMatrix66[i][j] = RD[i][j]; + } - fDPx = TMath::Sqrt(fabs(RD[0][0])); - fDPy = TMath::Sqrt(fabs(RD[1][1])); - fDPz = TMath::Sqrt(fabs(RD[2][2])); - fDX = TMath::Sqrt(fabs(RD[3][3])); - fDY = TMath::Sqrt(fabs(RD[4][4])); - fDZ = TMath::Sqrt(fabs(RD[5][5])); + fDPx = TMath::Sqrt(fabs(RD[0][0])); + fDPy = TMath::Sqrt(fabs(RD[1][1])); + fDPz = TMath::Sqrt(fabs(RD[2][2])); + fDX = TMath::Sqrt(fabs(RD[3][3])); + fDY = TMath::Sqrt(fabs(RD[4][4])); + fDZ = TMath::Sqrt(fabs(RD[5][5])); } -// Constructor with track parameters in LAB -FairTrackParP::FairTrackParP(TVector3 pos, TVector3 Mom, TVector3 posErr, TVector3 MomErr, Int_t Q, TVector3 o, TVector3 dj, TVector3 dk) - : FairTrackPar(pos.x(),pos.y(),pos.z(),Mom.x(),Mom.y(),Mom.z(),Q), - fU (0.), - fV (0), - fW (0), - fTV(0), - fTW(0), - fPx_sd(0.), - fPy_sd(0.), - fPz_sd(0.), - fDU(0.), - fDV(0.), - fDW(0.), - fDTV(0.), - fDTW(0.), - forigin(TVector3(0,0,0)), - fiver(TVector3(0,0,0)), - fjver(TVector3(0,0,0)), - fkver(TVector3(0,0,0)), - fSPU(0.) -{ -// Reset(); - SetPlane(o, dj, dk); - - SetPx(Mom.x()); - SetPy(Mom.y()); - SetPz(Mom.z()); - - SetX(pos.x()); //x (lab) - SetY(pos.y()); //y (lab) - SetZ(pos.z()); //z (lab) - Double_t P = TMath::Sqrt(fPx*fPx +fPy*fPy +fPz*fPz ); - if(Q!=0) { fq= Q/TMath::Abs(Q); } +// Constructor with track parameters in SD +FairTrackParP::FairTrackParP(Double_t v, + Double_t w, + Double_t Tv, + Double_t Tw, + Double_t qp, + Double_t CovMatrix[15], + TVector3 o, + TVector3 dj, + TVector3 dk, + Double_t spu) + : FairTrackPar() + , fU(0.) + , fV(v) + , fW(w) + , fTV(Tv) + , fTW(Tw) + , fPx_sd(0.) + , fPy_sd(0.) + , fPz_sd(0.) + , fDU(0.) + , fDV(0.) + , fDW(0.) + , fDTV(0.) + , fDTW(0.) + , forigin(TVector3(0, 0, 0)) + , fiver(TVector3(0, 0, 0)) + , fjver(TVector3(0, 0, 0)) + , fkver(TVector3(0, 0, 0)) + , fSPU(spu) + +{ + // Reset(); + SetPlane(o, dj, dk); + // fV = v; + // fW = w; + // fTV = Tv; + // fTW = Tw; + fQp = qp; + // fSPU = spu; + Double_t P = 0; + if (0 != fQp) { + P = TMath::Abs(1 / fQp); + fq = static_cast(TMath::Sign(1.0, fQp)); + // fq= int (P * fQp); + } else { + fq = 1; + } + for (Int_t i = 0; i < 15; i++) { + fCovMatrix[i] = CovMatrix[i]; + } - FairGeaneUtil util; - TVector3 positionsd = util.FromMARSToSDCoord(TVector3(fX, fY, fZ), forigin, fiver, fjver, fkver); - fU = positionsd.X(); - fV = positionsd.Y(); - fW = positionsd.Z(); - fQp = fq/P; + fPx_sd = fSPU * TMath::Sqrt(P * P / (fTV * fTV + fTW * fTW + 1)); + fPy_sd = fTV * fPx_sd; + fPz_sd = fTW * fPx_sd; + + // fU = 0.; + + FairGeaneUtil util; + TVector3 position = util.FromSDToMARSCoord(TVector3(fU, fV, fW), forigin, fiver, fjver, fkver); + fX = position.X(); + fY = position.Y(); + fZ = position.Z(); + + fDQp = TMath::Sqrt(fabs(fCovMatrix[0])); + fDTV = TMath::Sqrt(fabs(fCovMatrix[5])); + fDTW = TMath::Sqrt(fabs(fCovMatrix[9])); + fDV = TMath::Sqrt(fabs(fCovMatrix[12])); + fDW = TMath::Sqrt(fabs(fCovMatrix[14])); + + Double_t PD[3], RD[6][6], H[3], PC[3], RC[15], SP1; + Int_t CH; + PC[0] = fQp; + PC[1] = fTV; + PC[2] = fTW; + + // initialize RD + for (Int_t i = 0; i < 6; i++) { + for (Int_t k = 0; k < 6; k++) { + RD[i][k] = 0; + } + } - fDPx = MomErr.x(); //dpx - fDPy = MomErr.y(); //dpy - fDPz = MomErr.z(); //dpz - fDX = posErr.x(); //dpx - fDY = posErr.y(); //dpy - fDZ = posErr.z(); //dpz + for (Int_t i = 0; i < 15; i++) { + RC[i] = fCovMatrix[i]; + } - Double_t PD[3], RD[6][6], H[3], SP1, PC[3], RC[15]; + // retrieve field + Double_t pnt[3]; + pnt[0] = fX; + pnt[1] = fY; + pnt[2] = fZ; - Int_t CH, IERR; + GetFieldValue(pnt, H); - PD[0] = fPx; - PD[1] = fPy; - PD[2] = fPz; + CH = fq; - for(int i = 0; i < 6; i++) for(int j = 0; j < 6; j++) { RD[i][j] = 0.; } - RD[0][0] = fDPx * fDPx; - RD[1][1] = fDPy * fDPy; - RD[2][2] = fDPz * fDPz; - RD[3][3] = fDX * fDX; - RD[4][4] = fDY * fDY; - RD[5][5] = fDZ * fDZ; + TVector3 momsd = TVector3(fPx_sd, fPy_sd, fPz_sd); + // SP1 = (momsd.Dot(fjver.Cross(fkver)))/TMath::Abs(momsd.Dot(fjver.Cross(fkver))); + SP1 = fSPU; // correct calculation of SP1 - for(int i = 0; i < 6; i++) for(int j = 0; j < 6; j++) { fCovMatrix66[i][j] = RD[i][j]; } + util.FromSDToMars(PC, RC, H, CH, SP1, fDJ, fDK, PD, RD); - // retrieve field - Double_t pnt[3]; - pnt[0] = fX; - pnt[1] = fY; - pnt[2] = fZ; + fPx = PD[0]; + fPy = PD[1]; + fPz = PD[2]; - GetFieldValue(pnt, H); + for (int i = 0; i < 6; i++) + for (int j = 0; j < 6; j++) { + fCovMatrix66[i][j] = RD[i][j]; + } - CH=fq; + fDPx = TMath::Sqrt(fabs(RD[0][0])); + fDPy = TMath::Sqrt(fabs(RD[1][1])); + fDPz = TMath::Sqrt(fabs(RD[2][2])); + fDX = TMath::Sqrt(fabs(RD[3][3])); + fDY = TMath::Sqrt(fabs(RD[4][4])); + fDZ = TMath::Sqrt(fabs(RD[5][5])); +} - util.FromMarsToSD(PD, RD, H, CH, fDJ, fDK, IERR, SP1, PC, RC); +// Constructor with track parameters in LAB +FairTrackParP::FairTrackParP(TVector3 pos, + TVector3 Mom, + TVector3 posErr, + TVector3 MomErr, + Int_t Q, + TVector3 o, + TVector3 dj, + TVector3 dk) + : FairTrackPar(pos.x(), pos.y(), pos.z(), Mom.x(), Mom.y(), Mom.z(), Q) + , fU(0.) + , fV(0) + , fW(0) + , fTV(0) + , fTW(0) + , fPx_sd(0.) + , fPy_sd(0.) + , fPz_sd(0.) + , fDU(0.) + , fDV(0.) + , fDW(0.) + , fDTV(0.) + , fDTW(0.) + , forigin(TVector3(0, 0, 0)) + , fiver(TVector3(0, 0, 0)) + , fjver(TVector3(0, 0, 0)) + , fkver(TVector3(0, 0, 0)) + , fSPU(0.) +{ + // Reset(); + SetPlane(o, dj, dk); + + SetPx(Mom.x()); + SetPy(Mom.y()); + SetPz(Mom.z()); + + SetX(pos.x()); // x (lab) + SetY(pos.y()); // y (lab) + SetZ(pos.z()); // z (lab) + Double_t P = TMath::Sqrt(fPx * fPx + fPy * fPy + fPz * fPz); + if (Q != 0) { + fq = Q / TMath::Abs(Q); + } - for(Int_t i=0; i<15; i++) { fCovMatrix[i] = RC[i]; } + FairGeaneUtil util; + TVector3 positionsd = util.FromMARSToSDCoord(TVector3(fX, fY, fZ), forigin, fiver, fjver, fkver); + fU = positionsd.X(); + fV = positionsd.Y(); + fW = positionsd.Z(); + fQp = fq / P; + + fDPx = MomErr.x(); // dpx + fDPy = MomErr.y(); // dpy + fDPz = MomErr.z(); // dpz + fDX = posErr.x(); // dpx + fDY = posErr.y(); // dpy + fDZ = posErr.z(); // dpz + + Double_t PD[3], RD[6][6], H[3], SP1, PC[3], RC[15]; + + Int_t CH, IERR; + + PD[0] = fPx; + PD[1] = fPy; + PD[2] = fPz; + + for (int i = 0; i < 6; i++) + for (int j = 0; j < 6; j++) { + RD[i][j] = 0.; + } + RD[0][0] = fDPx * fDPx; + RD[1][1] = fDPy * fDPy; + RD[2][2] = fDPz * fDPz; + RD[3][3] = fDX * fDX; + RD[4][4] = fDY * fDY; + RD[5][5] = fDZ * fDZ; + + for (int i = 0; i < 6; i++) + for (int j = 0; j < 6; j++) { + fCovMatrix66[i][j] = RD[i][j]; + } + + // retrieve field + Double_t pnt[3]; + pnt[0] = fX; + pnt[1] = fY; + pnt[2] = fZ; + + GetFieldValue(pnt, H); + + CH = fq; + + util.FromMarsToSD(PD, RD, H, CH, fDJ, fDK, IERR, SP1, PC, RC); + + for (Int_t i = 0; i < 15; i++) { + fCovMatrix[i] = RC[i]; + } - fTV = PC[1]; - fTW = PC[2]; + fTV = PC[1]; + fTW = PC[2]; - fDQp = TMath::Sqrt(fabs(fCovMatrix[0])); - fDTV = TMath::Sqrt(fabs(fCovMatrix[5])); - fDTW = TMath::Sqrt(fabs(fCovMatrix[9])); - fDV = TMath::Sqrt(fabs(fCovMatrix[12])); - fDW = TMath::Sqrt(fabs(fCovMatrix[14])); + fDQp = TMath::Sqrt(fabs(fCovMatrix[0])); + fDTV = TMath::Sqrt(fabs(fCovMatrix[5])); + fDTW = TMath::Sqrt(fabs(fCovMatrix[9])); + fDV = TMath::Sqrt(fabs(fCovMatrix[12])); + fDW = TMath::Sqrt(fabs(fCovMatrix[14])); - fSPU = SP1; + fSPU = SP1; - fPx_sd = fSPU*TMath::Sqrt( P*P / ( fTV*fTV + fTW*fTW + 1 ) ); - fPy_sd = fTV * fPx_sd; - fPz_sd = fTW * fPx_sd; + fPx_sd = fSPU * TMath::Sqrt(P * P / (fTV * fTV + fTW * fTW + 1)); + fPy_sd = fTV * fPx_sd; + fPz_sd = fTW * fPx_sd; } // Constructor with track parameters in LAB (with complete covariance matrix in MARS) -FairTrackParP::FairTrackParP(TVector3 pos, TVector3 Mom, - Double_t covMARS[6][6], Int_t Q, - TVector3 o, TVector3 dj, TVector3 dk) - : FairTrackPar(pos.x(),pos.y(),pos.z(),Mom.x(),Mom.y(),Mom.z(),Q), - fU (0.), - fV (0), - fW (0), - fTV(0), - fTW(0), - fPx_sd(0.), - fPy_sd(0.), - fPz_sd(0.), - fDU(0.), - fDV(0.), - fDW(0.), - fDTV(0.), - fDTW(0.), - forigin(TVector3(0,0,0)), - fiver(TVector3(0,0,0)), - fjver(TVector3(0,0,0)), - fkver(TVector3(0,0,0)), - fSPU(0.) -{ -// Reset(); - SetPlane(o, dj, dk); - - SetPx(Mom.x()); - SetPy(Mom.y()); - SetPz(Mom.z()); - - SetX(pos.x()); //x (lab) - SetY(pos.y()); //y (lab) - SetZ(pos.z()); //z (lab) - Double_t P = TMath::Sqrt(fPx*fPx +fPy*fPy +fPz*fPz ); - if(Q!=0) { fq= Q/TMath::Abs(Q); } - - FairGeaneUtil util; - TVector3 positionsd = util.FromMARSToSDCoord(TVector3(fX, fY, fZ), forigin, fiver, fjver, fkver); - fU = positionsd.X(); - fV = positionsd.Y(); - fW = positionsd.Z(); - fQp = fq/P; - - fDPx = TMath::Sqrt(fabs(covMARS[0][0])); //dpx - fDPy = TMath::Sqrt(fabs(covMARS[1][1])); //dpy - fDPz = TMath::Sqrt(fabs(covMARS[2][2])); //dpz - fDX = TMath::Sqrt(fabs(covMARS[3][3])); //dpx - fDY = TMath::Sqrt(fabs(covMARS[4][4])); //dpy - fDZ = TMath::Sqrt(fabs(covMARS[5][5])); //dpz - - Double_t PD[3], RD[6][6], H[3], SP1, PC[3], RC[15]; - Int_t IERR, CH; - - PD[0] = fPx; - PD[1] = fPy; - PD[2] = fPz; - - for(int i = 0; i < 6; i++) for(int j = 0; j < 6; j++) { RD[i][j] = covMARS[i][j]; } - for(int i = 0; i < 6; i++) for(int j = 0; j < 6; j++) { fCovMatrix66[i][j] = RD[i][j]; } - - // retrieve field - Double_t pnt[3]; - pnt[0] = fX; - pnt[1] = fY; - pnt[2] = fZ; - - GetFieldValue(pnt, H); - - CH=fq; - - util.FromMarsToSD(PD, RD, H, CH, fDJ, fDK, IERR, SP1, PC, RC); +FairTrackParP::FairTrackParP(TVector3 pos, + TVector3 Mom, + Double_t covMARS[6][6], + Int_t Q, + TVector3 o, + TVector3 dj, + TVector3 dk) + : FairTrackPar(pos.x(), pos.y(), pos.z(), Mom.x(), Mom.y(), Mom.z(), Q) + , fU(0.) + , fV(0) + , fW(0) + , fTV(0) + , fTW(0) + , fPx_sd(0.) + , fPy_sd(0.) + , fPz_sd(0.) + , fDU(0.) + , fDV(0.) + , fDW(0.) + , fDTV(0.) + , fDTW(0.) + , forigin(TVector3(0, 0, 0)) + , fiver(TVector3(0, 0, 0)) + , fjver(TVector3(0, 0, 0)) + , fkver(TVector3(0, 0, 0)) + , fSPU(0.) +{ + // Reset(); + SetPlane(o, dj, dk); + + SetPx(Mom.x()); + SetPy(Mom.y()); + SetPz(Mom.z()); + + SetX(pos.x()); // x (lab) + SetY(pos.y()); // y (lab) + SetZ(pos.z()); // z (lab) + Double_t P = TMath::Sqrt(fPx * fPx + fPy * fPy + fPz * fPz); + if (Q != 0) { + fq = Q / TMath::Abs(Q); + } - for(Int_t i=0; i<15; i++) { fCovMatrix[i] = RC[i]; } + FairGeaneUtil util; + TVector3 positionsd = util.FromMARSToSDCoord(TVector3(fX, fY, fZ), forigin, fiver, fjver, fkver); + fU = positionsd.X(); + fV = positionsd.Y(); + fW = positionsd.Z(); + fQp = fq / P; + + fDPx = TMath::Sqrt(fabs(covMARS[0][0])); // dpx + fDPy = TMath::Sqrt(fabs(covMARS[1][1])); // dpy + fDPz = TMath::Sqrt(fabs(covMARS[2][2])); // dpz + fDX = TMath::Sqrt(fabs(covMARS[3][3])); // dpx + fDY = TMath::Sqrt(fabs(covMARS[4][4])); // dpy + fDZ = TMath::Sqrt(fabs(covMARS[5][5])); // dpz + + Double_t PD[3], RD[6][6], H[3], SP1, PC[3], RC[15]; + Int_t IERR, CH; + + PD[0] = fPx; + PD[1] = fPy; + PD[2] = fPz; + + for (int i = 0; i < 6; i++) + for (int j = 0; j < 6; j++) { + RD[i][j] = covMARS[i][j]; + } + for (int i = 0; i < 6; i++) + for (int j = 0; j < 6; j++) { + fCovMatrix66[i][j] = RD[i][j]; + } + + // retrieve field + Double_t pnt[3]; + pnt[0] = fX; + pnt[1] = fY; + pnt[2] = fZ; + + GetFieldValue(pnt, H); + + CH = fq; + + util.FromMarsToSD(PD, RD, H, CH, fDJ, fDK, IERR, SP1, PC, RC); + + for (Int_t i = 0; i < 15; i++) { + fCovMatrix[i] = RC[i]; + } - fTV = PC[1]; - fTW = PC[2]; + fTV = PC[1]; + fTW = PC[2]; - fDQp = TMath::Sqrt(fabs(fCovMatrix[0])); - fDTV = TMath::Sqrt(fabs(fCovMatrix[5])); - fDTW = TMath::Sqrt(fabs(fCovMatrix[9])); - fDV = TMath::Sqrt(fabs(fCovMatrix[12])); - fDW = TMath::Sqrt(fabs(fCovMatrix[14])); + fDQp = TMath::Sqrt(fabs(fCovMatrix[0])); + fDTV = TMath::Sqrt(fabs(fCovMatrix[5])); + fDTW = TMath::Sqrt(fabs(fCovMatrix[9])); + fDV = TMath::Sqrt(fabs(fCovMatrix[12])); + fDW = TMath::Sqrt(fabs(fCovMatrix[14])); - fSPU = SP1; + fSPU = SP1; - fPx_sd = fSPU*TMath::Sqrt( P*P / ( fTV*fTV + fTW*fTW + 1 ) ); - fPy_sd = fTV * fPx_sd; - fPz_sd = fTW * fPx_sd; + fPx_sd = fSPU * TMath::Sqrt(P * P / (fTV * fTV + fTW * fTW + 1)); + fPy_sd = fTV * fPx_sd; + fPz_sd = fTW * fPx_sd; } // ctor from helix to parabola --------------------------------------------------------------- @@ -475,242 +522,269 @@ FairTrackParP::FairTrackParP(TVector3 pos, TVector3 Mom, // IERR = 1 [when the particle moves perpendicular to u-axis (i.e. ON the CHOSEN PLANE) // ==> v', w' are not definded.] FairTrackParP::FairTrackParP(FairTrackParH* helix, TVector3 dj, TVector3 dk, Int_t& ierr) - : FairTrackPar(), - fU (0.), - fV (0), - fW (0), - fTV(0), - fTW(0), - fPx_sd(0.), - fPy_sd(0.), - fPz_sd(0.), - fDU(0.), - fDV(0.), - fDW(0.), - fDTV(0.), - fDTW(0.), - forigin(TVector3(0,0,0)), - fiver(TVector3(0,0,0)), - fjver(TVector3(0,0,0)), - fkver(TVector3(0,0,0)), - fSPU(0.) -{ - - // q/p, lambda, phi --> q/p, v', w' - Double_t PC[3] = {helix->GetQp(), helix->GetLambda(), helix->GetPhi()}; - Double_t RC[15]; - helix->GetCov(RC); - // retrieve field - TVector3 xyz(helix->GetX(), helix->GetY(), helix->GetZ()); - Double_t H[3], pnt[3]; - pnt[0] = xyz.X(); - pnt[1] = xyz.Y(); - pnt[2] = xyz.Z(); - - GetFieldValue(pnt, H); - - Int_t CH = helix->GetQ(); - - Double_t DJ[3] = {dj.X(), dj.Y(), dj.Z()}; - Double_t DK[3] = {dk.X(), dk.Y(), dk.Z()}; - - Int_t IERR = 0; - Double_t SPU = 0; - Double_t PD[3], RD[15]; - - FairGeaneUtil util; - util.FromSCToSD(PC, RC, H, CH, DJ, DK, IERR, SPU, PD, RD); - - ierr = IERR; - - // MARS coordinates - TVector3 o(xyz.X(), xyz.Y(), xyz.Z()); - TVector3 di = dj.Cross(dk); - TVector3 uvm = util.FromMARSToSDCoord(xyz, o, di, dj, dk); - - if(ierr == 0) SetTrackPar(uvm.Y(), uvm.Z(), - PD[1], PD[2], PD[0], - RD, - o, di, dj, dk, SPU); - else { cout << "FairTrackParP(FairTrackParH *) contructor ERROR: CANNOT convert helix to parabola" << endl; } + : FairTrackPar() + , fU(0.) + , fV(0) + , fW(0) + , fTV(0) + , fTW(0) + , fPx_sd(0.) + , fPy_sd(0.) + , fPz_sd(0.) + , fDU(0.) + , fDV(0.) + , fDW(0.) + , fDTV(0.) + , fDTW(0.) + , forigin(TVector3(0, 0, 0)) + , fiver(TVector3(0, 0, 0)) + , fjver(TVector3(0, 0, 0)) + , fkver(TVector3(0, 0, 0)) + , fSPU(0.) +{ + + // q/p, lambda, phi --> q/p, v', w' + Double_t PC[3] = {helix->GetQp(), helix->GetLambda(), helix->GetPhi()}; + Double_t RC[15]; + helix->GetCov(RC); + // retrieve field + TVector3 xyz(helix->GetX(), helix->GetY(), helix->GetZ()); + Double_t H[3], pnt[3]; + pnt[0] = xyz.X(); + pnt[1] = xyz.Y(); + pnt[2] = xyz.Z(); + + GetFieldValue(pnt, H); + + Int_t CH = helix->GetQ(); + + Double_t DJ[3] = {dj.X(), dj.Y(), dj.Z()}; + Double_t DK[3] = {dk.X(), dk.Y(), dk.Z()}; + + Int_t IERR = 0; + Double_t SPU = 0; + Double_t PD[3], RD[15]; + + FairGeaneUtil util; + util.FromSCToSD(PC, RC, H, CH, DJ, DK, IERR, SPU, PD, RD); + + ierr = IERR; + + // MARS coordinates + TVector3 o(xyz.X(), xyz.Y(), xyz.Z()); + TVector3 di = dj.Cross(dk); + TVector3 uvm = util.FromMARSToSDCoord(xyz, o, di, dj, dk); + + if (ierr == 0) + SetTrackPar(uvm.Y(), uvm.Z(), PD[1], PD[2], PD[0], RD, o, di, dj, dk, SPU); + else { + cout << "FairTrackParP(FairTrackParH *) contructor ERROR: CANNOT convert helix to parabola" << endl; + } } // define track in LAB -void FairTrackParP::SetTrackPar(Double_t X, Double_t Y, Double_t Z, - Double_t Px, Double_t Py, Double_t Pz, Int_t Q, - Double_t CovMatrix[15], - TVector3 o, TVector3 /*di*/, TVector3 dj, TVector3 dk) -{ - Reset(); - SetPlane(o, dj, dk); - - Double_t P =TMath::Sqrt(Px*Px+Py*Py+Pz*Pz); - - if (Q!=0) { fq = TMath::Abs(Q)/Q; } - fQp = fq/P; - - SetX(X); - SetY(Y); - SetZ(Z); - - SetPx(Px); - SetPy(Py); - SetPz(Pz); - - for(Int_t i=0; i<15; i++) { - fCovMatrix[i]=CovMatrix[i]; - } - - FairGeaneUtil util; - - TVector3 positionsd = util.FromMARSToSDCoord(TVector3(fX, fY, fZ), forigin, fiver, fjver, fkver); - fU = positionsd.X(); - fV = positionsd.Y(); - fW = positionsd.Z(); - fQp = fq/P; - - - Double_t PD[3], RD[6][6], H[3], SP1, PC[3], RC[15]; - Int_t IERR, CH; - PD[0] = Px; - PD[1] = Py; - PD[2] = Pz; - - for(int i = 0; i < 6; i++) for(int j = 0; j < 6; j++) { RD[i][j] = 0.; } - // retrieve field - Double_t pnt[3]; - pnt[0] = fX; - pnt[1] = fY; - pnt[2] = fZ; - - GetFieldValue(pnt, H); - - CH=fq; - util.FromMarsToSD(PD, RD, H, CH, fDJ, fDK, IERR, SP1, PC, RC); - fTV = PC[1]; - fTW = PC[2]; +void FairTrackParP::SetTrackPar(Double_t X, + Double_t Y, + Double_t Z, + Double_t Px, + Double_t Py, + Double_t Pz, + Int_t Q, + Double_t CovMatrix[15], + TVector3 o, + TVector3 /*di*/, + TVector3 dj, + TVector3 dk) +{ + Reset(); + SetPlane(o, dj, dk); + + Double_t P = TMath::Sqrt(Px * Px + Py * Py + Pz * Pz); + + if (Q != 0) { + fq = TMath::Abs(Q) / Q; + } + fQp = fq / P; - fDQp = TMath::Sqrt(fabs(fCovMatrix[0])); - fDTV = TMath::Sqrt(fabs(fCovMatrix[5])); - fDTW = TMath::Sqrt(fabs(fCovMatrix[9])); - fDV = TMath::Sqrt(fabs(fCovMatrix[12])); - fDW = TMath::Sqrt(fabs(fCovMatrix[14])); + SetX(X); + SetY(Y); + SetZ(Z); - for(Int_t i=0; i<15; i++) { RC[i] = fCovMatrix[i]; } + SetPx(Px); + SetPy(Py); + SetPz(Pz); - util.FromSDToMars(PC, RC, H, CH, SP1, fDJ, fDK, PD, RD); + for (Int_t i = 0; i < 15; i++) { + fCovMatrix[i] = CovMatrix[i]; + } - for(int i = 0; i < 6; i++) for(int j = 0; j < 6; j++) { fCovMatrix66[i][j] = RD[i][j]; } + FairGeaneUtil util; + + TVector3 positionsd = util.FromMARSToSDCoord(TVector3(fX, fY, fZ), forigin, fiver, fjver, fkver); + fU = positionsd.X(); + fV = positionsd.Y(); + fW = positionsd.Z(); + fQp = fq / P; + + Double_t PD[3], RD[6][6], H[3], SP1, PC[3], RC[15]; + Int_t IERR, CH; + PD[0] = Px; + PD[1] = Py; + PD[2] = Pz; + + for (int i = 0; i < 6; i++) + for (int j = 0; j < 6; j++) { + RD[i][j] = 0.; + } + // retrieve field + Double_t pnt[3]; + pnt[0] = fX; + pnt[1] = fY; + pnt[2] = fZ; + + GetFieldValue(pnt, H); + + CH = fq; + util.FromMarsToSD(PD, RD, H, CH, fDJ, fDK, IERR, SP1, PC, RC); + fTV = PC[1]; + fTW = PC[2]; + + fDQp = TMath::Sqrt(fabs(fCovMatrix[0])); + fDTV = TMath::Sqrt(fabs(fCovMatrix[5])); + fDTW = TMath::Sqrt(fabs(fCovMatrix[9])); + fDV = TMath::Sqrt(fabs(fCovMatrix[12])); + fDW = TMath::Sqrt(fabs(fCovMatrix[14])); + + for (Int_t i = 0; i < 15; i++) { + RC[i] = fCovMatrix[i]; + } - fDPx = TMath::Sqrt(fabs(RD[0][0])); - fDPy = TMath::Sqrt(fabs(RD[1][1])); - fDPz = TMath::Sqrt(fabs(RD[2][2])); - fDX = TMath::Sqrt(fabs(RD[3][3])); - fDY = TMath::Sqrt(fabs(RD[4][4])); - fDZ = TMath::Sqrt(fabs(RD[5][5])); + util.FromSDToMars(PC, RC, H, CH, SP1, fDJ, fDK, PD, RD); + + for (int i = 0; i < 6; i++) + for (int j = 0; j < 6; j++) { + fCovMatrix66[i][j] = RD[i][j]; + } + + fDPx = TMath::Sqrt(fabs(RD[0][0])); + fDPy = TMath::Sqrt(fabs(RD[1][1])); + fDPz = TMath::Sqrt(fabs(RD[2][2])); + fDX = TMath::Sqrt(fabs(RD[3][3])); + fDY = TMath::Sqrt(fabs(RD[4][4])); + fDZ = TMath::Sqrt(fabs(RD[5][5])); + + fSPU = SP1; +} + +// define track in SD +void FairTrackParP::SetTrackPar(Double_t v, + Double_t w, + Double_t Tv, + Double_t Tw, + Double_t qp, + Double_t CovMatrix[15], + TVector3 o, + TVector3 /*di*/, + TVector3 dj, + TVector3 dk, + Double_t spu) +{ + Reset(); + SetPlane(o, dj, dk); + fU = 0; + fV = v; + fW = w; + fTV = Tv; + fTW = Tw; + fQp = qp; + fSPU = spu; + + Double_t P = TMath::Abs(1 / fQp); + // fq= int (P * fQp); + fq = static_cast(TMath::Sign(1.0, fQp)); + for (Int_t i = 0; i < 15; i++) { + fCovMatrix[i] = CovMatrix[i]; + } - fSPU = SP1; -} + fPx_sd = fSPU * TMath::Sqrt(P * P / (fTV * fTV + fTW * fTW + 1)); + fPy_sd = fTV * fPx_sd; + fPz_sd = fTW * fPx_sd; + + FairGeaneUtil util; + TVector3 position = util.FromSDToMARSCoord(TVector3(fU, fV, fW), forigin, fiver, fjver, fkver); + fX = position.X(); + fY = position.Y(); + fZ = position.Z(); + + fDQp = TMath::Sqrt(fabs(fCovMatrix[0])); + fDTV = TMath::Sqrt(fabs(fCovMatrix[5])); + fDTW = TMath::Sqrt(fabs(fCovMatrix[9])); + fDV = TMath::Sqrt(fabs(fCovMatrix[12])); + fDW = TMath::Sqrt(fabs(fCovMatrix[14])); + + Double_t PD[3], RD[6][6], H[3], PC[3], RC[15], SP1; + Int_t CH; + PC[0] = fQp; + PC[1] = fTV; + PC[2] = fTW; + + for (Int_t i = 0; i < 15; i++) { + RC[i] = fCovMatrix[i]; + } -//define track in SD -void FairTrackParP::SetTrackPar(Double_t v, Double_t w, Double_t Tv, - Double_t Tw, Double_t qp, - Double_t CovMatrix[15], - TVector3 o, TVector3 /*di*/, TVector3 dj, TVector3 dk, Double_t spu) -{ - Reset(); - SetPlane(o, dj, dk); - fU = 0; - fV = v; - fW = w; - fTV = Tv; - fTW = Tw; - fQp = qp; - fSPU = spu; - - Double_t P = TMath::Abs(1/fQp); - //fq= int (P * fQp); - fq = static_cast(TMath::Sign(1.0, fQp)); - for(Int_t i=0; i<15; i++) { - fCovMatrix[i]=CovMatrix[i]; - } - - fPx_sd = fSPU*TMath::Sqrt( P*P / ( fTV*fTV + fTW*fTW + 1 ) ); - fPy_sd = fTV * fPx_sd; - fPz_sd = fTW * fPx_sd; - - FairGeaneUtil util; - TVector3 position = util.FromSDToMARSCoord(TVector3(fU, fV, fW), forigin, fiver, fjver, fkver); - fX = position.X(); - fY = position.Y(); - fZ = position.Z(); - - fDQp = TMath::Sqrt(fabs(fCovMatrix[0])); - fDTV = TMath::Sqrt(fabs(fCovMatrix[5])); - fDTW = TMath::Sqrt(fabs(fCovMatrix[9])); - fDV = TMath::Sqrt(fabs(fCovMatrix[12])); - fDW = TMath::Sqrt(fabs(fCovMatrix[14])); - - Double_t PD[3],RD[6][6],H[3],PC[3],RC[15], SP1; - Int_t CH; - PC[0] = fQp; - PC[1] = fTV; - PC[2] = fTW; - - for(Int_t i=0; i<15; i++) { - RC[i]=fCovMatrix[i]; - } - - // initialize RD - for(Int_t i=0; i<6; i++) { - for(Int_t k=0; k<6; k++) { - RD[i][k] = 0; + // initialize RD + for (Int_t i = 0; i < 6; i++) { + for (Int_t k = 0; k < 6; k++) { + RD[i][k] = 0; + } } - } - // retrieve field - Double_t pnt[3]; - pnt[0] = fX; - pnt[1] = fY; - pnt[2] = fZ; + // retrieve field + Double_t pnt[3]; + pnt[0] = fX; + pnt[1] = fY; + pnt[2] = fZ; - GetFieldValue(pnt, H); + GetFieldValue(pnt, H); - CH=fq; + CH = fq; - TVector3 momsd = TVector3(fPx_sd,fPy_sd,fPz_sd); - // SP1 = (momsd.Dot(fjver.Cross(fkver)))/TMath::Abs(momsd.Dot(fjver.Cross(fkver))); - SP1=fSPU; + TVector3 momsd = TVector3(fPx_sd, fPy_sd, fPz_sd); + // SP1 = (momsd.Dot(fjver.Cross(fkver)))/TMath::Abs(momsd.Dot(fjver.Cross(fkver))); + SP1 = fSPU; - util.FromSDToMars(PC, RC, H, CH, SP1, fDJ, fDK, PD, RD); + util.FromSDToMars(PC, RC, H, CH, SP1, fDJ, fDK, PD, RD); - fPx = PD[0]; - fPy = PD[1]; - fPz = PD[2]; + fPx = PD[0]; + fPy = PD[1]; + fPz = PD[2]; - for(int i = 0; i < 6; i++) for(int j = 0; j < 6; j++) { fCovMatrix66[i][j] = RD[i][j]; } + for (int i = 0; i < 6; i++) + for (int j = 0; j < 6; j++) { + fCovMatrix66[i][j] = RD[i][j]; + } - fDPx = TMath::Sqrt(fabs(RD[0][0])); - fDPy = TMath::Sqrt(fabs(RD[1][1])); - fDPz = TMath::Sqrt(fabs(RD[2][2])); - fDX = TMath::Sqrt(fabs(RD[3][3])); - fDY = TMath::Sqrt(fabs(RD[4][4])); - fDZ = TMath::Sqrt(fabs(RD[5][5])); + fDPx = TMath::Sqrt(fabs(RD[0][0])); + fDPy = TMath::Sqrt(fabs(RD[1][1])); + fDPz = TMath::Sqrt(fabs(RD[2][2])); + fDX = TMath::Sqrt(fabs(RD[3][3])); + fDY = TMath::Sqrt(fabs(RD[4][4])); + fDZ = TMath::Sqrt(fabs(RD[5][5])); } void FairTrackParP::CalCov() { - //not needed + // not needed } FairTrackParP::~FairTrackParP() {} void FairTrackParP::Print(Option_t* /*option*/) const { - cout << "Position : ("; - cout << std::setprecision(2) << fX << ", " << fY << ", " << fZ << ")" << endl; - cout << std::setprecision(2) << "Slopes : dx/dz = " << fTV << ", dy/dz = " << fTW << endl; - cout << std::setprecision(2) << "q/p = " << fQp << endl; + cout << "Position : ("; + cout << std::setprecision(2) << fX << ", " << fY << ", " << fZ << ")" << endl; + cout << std::setprecision(2) << "Slopes : dx/dz = " << fTV << ", dy/dz = " << fTW << endl; + cout << std::setprecision(2) << "q/p = " << fQp << endl; } /*Double_t FairTrackParP::GetDX() @@ -721,45 +795,21 @@ Double_t FairTrackParP::GetDZ() { return fDZ; } */ -Double_t FairTrackParP::GetV() -{ - return fV; -} +Double_t FairTrackParP::GetV() { return fV; } -Double_t FairTrackParP::GetW() -{ - return fW; -} +Double_t FairTrackParP::GetW() { return fW; } -Double_t FairTrackParP::GetTV() -{ - return fTV; -} +Double_t FairTrackParP::GetTV() { return fTV; } -Double_t FairTrackParP::GetTW() -{ - return fTW; -} +Double_t FairTrackParP::GetTW() { return fTW; } -Double_t FairTrackParP::GetDV() -{ - return fDV; -} +Double_t FairTrackParP::GetDV() { return fDV; } -Double_t FairTrackParP::GetDW() -{ - return fDW; -} +Double_t FairTrackParP::GetDW() { return fDW; } -Double_t FairTrackParP::GetDTV() -{ - return fDTV; -} +Double_t FairTrackParP::GetDTV() { return fDTV; } -Double_t FairTrackParP::GetDTW() -{ - return fDTW; -} +Double_t FairTrackParP::GetDTW() { return fDTW; } /* Double_t FairTrackParP::GetX() { @@ -795,103 +845,103 @@ Double_t FairTrackParP::GetDQp() return fDQp; } */ -TVector3 FairTrackParP::GetOrigin() -{ - return forigin; -} +TVector3 FairTrackParP::GetOrigin() { return forigin; } -TVector3 FairTrackParP::GetIVer() -{ - return fiver; -} +TVector3 FairTrackParP::GetIVer() { return fiver; } -TVector3 FairTrackParP::GetJVer() -{ - return fjver; -} +TVector3 FairTrackParP::GetJVer() { return fjver; } -TVector3 FairTrackParP::GetKVer() -{ - return fkver; -} +TVector3 FairTrackParP::GetKVer() { return fkver; } void FairTrackParP::Reset() { - fU = 0.; - fV = 0.; - fW = 0.; - fTV = 0.; - fTW = 0.; - fDV = 0.; - fDW = 0.; - fDTV = 0.; - fDTW = 0.; - for(Int_t i= 0; i<15; i++) { fCovMatrix[i] = 0.; } - fPx_sd = 0.; - fPy_sd = 0.; - fPz_sd = 0.; - - //base class members - fX = fY = fZ = 0.; - fDX = fDY = fDZ = 0.; - fPx = fPy = fPz = 0.; - fDPx = fDPy = fDPz = 0.; - fQp = fDQp = fq = 0; + fU = 0.; + fV = 0.; + fW = 0.; + fTV = 0.; + fTW = 0.; + fDV = 0.; + fDW = 0.; + fDTV = 0.; + fDTW = 0.; + for (Int_t i = 0; i < 15; i++) { + fCovMatrix[i] = 0.; + } + fPx_sd = 0.; + fPy_sd = 0.; + fPz_sd = 0.; + + // base class members + fX = fY = fZ = 0.; + fDX = fDY = fDZ = 0.; + fPx = fPy = fPz = 0.; + fDPx = fDPy = fDPz = 0.; + fQp = fDQp = fq = 0; } void FairTrackParP::SetPlane(TVector3 o, TVector3 j, TVector3 k) { - // origin - forigin = TVector3(o.X(), o.Y(), o.Z()); - - // check unity - j.SetMag(1.); - k.SetMag(1.); - // check orthogonality - if(j* k != 0) { - - k = (j.Cross(k)).Cross(j); - } - - // plane - // i - TVector3 i = j.Cross(k); - i.SetMag(1.); - fDI[0] = i.X(); - fDI[1] = i.Y(); - fDI[2] = i.Z(); - fiver = TVector3(fDI[0],fDI[1],fDI[2]); - // j - fDJ[0] = j.X(); - fDJ[1] = j.Y(); - fDJ[2] = j.Z(); - fjver = TVector3(fDJ[0],fDJ[1],fDJ[2]); - // k - fDK[0] = k.X(); - fDK[1] = k.Y(); - fDK[2] = k.Z(); - fkver = TVector3(fDK[0],fDK[1],fDK[2]); + // origin + forigin = TVector3(o.X(), o.Y(), o.Z()); + + // check unity + j.SetMag(1.); + k.SetMag(1.); + // check orthogonality + if (j * k != 0) { + + k = (j.Cross(k)).Cross(j); + } + + // plane + // i + TVector3 i = j.Cross(k); + i.SetMag(1.); + fDI[0] = i.X(); + fDI[1] = i.Y(); + fDI[2] = i.Z(); + fiver = TVector3(fDI[0], fDI[1], fDI[2]); + // j + fDJ[0] = j.X(); + fDJ[1] = j.Y(); + fDJ[2] = j.Z(); + fjver = TVector3(fDJ[0], fDJ[1], fDJ[2]); + // k + fDK[0] = k.X(); + fDK[1] = k.Y(); + fDK[2] = k.Z(); + fkver = TVector3(fDK[0], fDK[1], fDK[2]); } void FairTrackParP::SetTransportMatrix(Double_t mat[][5]) { - for(int i = 0; i < 5; i++) for(int j = 0; j < 5; j++) { ftrmat[i][j] = mat[i][j]; } + for (int i = 0; i < 5; i++) + for (int j = 0; j < 5; j++) { + ftrmat[i][j] = mat[i][j]; + } } void FairTrackParP::GetTransportMatrix(Double_t mat[][5]) { - for(int i = 0; i < 5; i++) for(int j = 0; j < 5; j++) { mat[i][j] = ftrmat[i][j]; } + for (int i = 0; i < 5; i++) + for (int j = 0; j < 5; j++) { + mat[i][j] = ftrmat[i][j]; + } } void FairTrackParP::GetCovQ(Double_t* CovQ) { - // return error matrix in 1/p instead of q/p - - for(int i = 0; i < 15; i++) { - CovQ[i] = fCovMatrix[i]; - if(fq!=0) { - if(i == 0) { CovQ[i] = CovQ[i] / (fq * fq); } - if(i > 0 && i < 5) { CovQ[i] = CovQ[i] / fq; } + // return error matrix in 1/p instead of q/p + + for (int i = 0; i < 15; i++) { + CovQ[i] = fCovMatrix[i]; + if (fq != 0) { + if (i == 0) { + CovQ[i] = CovQ[i] / (fq * fq); + } + if (i > 0 && i < 5) { + CovQ[i] = CovQ[i] / fq; + } + } } - } } diff --git a/trackbase/FairTrackParP.h b/trackbase/FairTrackParP.h index b0c08f7c3e..321a4b1084 100644 --- a/trackbase/FairTrackParP.h +++ b/trackbase/FairTrackParP.h @@ -1,8 +1,8 @@ /******************************************************************************** * 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, * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // Class for the representation of a track as parabola (SD system) @@ -17,10 +17,10 @@ #ifndef FAIRSTSTRACKPARP #define FAIRSTSTRACKPARP 1 -#include "FairTrackPar.h" // for FairTrackPar +#include "FairTrackPar.h" // for FairTrackPar -#include // for Double_t, Int_t, etc -#include // for TVector3 +#include // for Double_t, Int_t, etc +#include // for TVector3 class FairTrackParH; @@ -28,7 +28,6 @@ class FairTrackParP : public FairTrackPar { public: - /** Constructor **/ FairTrackParP(); @@ -38,26 +37,39 @@ class FairTrackParP : public FairTrackPar // DJ(3) UNIT VECTOR IN V-DIRECTION // DK(3) UNIT VECTOR IN W-DIRECTION OF DETECTOR SYSTEM - - FairTrackParP(Double_t v, Double_t w, - Double_t Tv, Double_t Tw, Double_t qp, + FairTrackParP(Double_t v, + Double_t w, + Double_t Tv, + Double_t Tw, + Double_t qp, Double_t CovMatrix[15], - TVector3 o, TVector3 dj, TVector3 dk); + TVector3 o, + TVector3 dj, + TVector3 dk); // constructor with spu, to be used when spu is needed as input - FairTrackParP(Double_t v, Double_t w, - Double_t Tv, Double_t Tw, Double_t qp, + FairTrackParP(Double_t v, + Double_t w, + Double_t Tv, + Double_t Tw, + Double_t qp, Double_t CovMatrix[15], - TVector3 o, TVector3 dj, TVector3 dk, Double_t spu); + TVector3 o, + TVector3 dj, + TVector3 dk, + Double_t spu); /** Constructor with position and momentum track in LAB **/ // DIAGONAL MARS covariance matrix - FairTrackParP(TVector3 pos, TVector3 Mom, - TVector3 posErr, TVector3 MomErr, Int_t q, - TVector3 o, TVector3 dj, TVector3 dk); + FairTrackParP(TVector3 pos, + TVector3 Mom, + TVector3 posErr, + TVector3 MomErr, + Int_t q, + TVector3 o, + TVector3 dj, + TVector3 dk); // NON DIAGONAL MARS covariance matrix - FairTrackParP(TVector3 pos, TVector3 Mom, - Double_t covMARS[6][6], Int_t q, - TVector3 o, TVector3 dj, TVector3 dk); + FairTrackParP(TVector3 pos, TVector3 Mom, Double_t covMARS[6][6], Int_t q, TVector3 o, TVector3 dj, TVector3 dk); // constructor from helix FairTrackParP(FairTrackParH* helix, TVector3 dj, TVector3 dk, Int_t& ierr); @@ -65,25 +77,45 @@ class FairTrackParP : public FairTrackPar virtual ~FairTrackParP(); /** copy Constructor **/ - //to be implemented - + // to be implemented /** Output to screen **/ - virtual void Print(Option_t* option = "") const; - - //define track parameters in LAB - void SetTrackPar(Double_t X, Double_t Y, Double_t Z, Double_t Px, Double_t Py, Double_t Pz, Int_t Q, Double_t CovMatrix[15], TVector3 o, TVector3 di, TVector3 dj, TVector3 dk); - //void SetTrackPar(Double_t X, Double_t Y, Double_t Z, Double_t Px, Double_t Py, Double_t Pz, Int_t Q, Double_t CovMatrix[15]); - //define track parameters in SD - void SetTrackPar(Double_t v, Double_t w, Double_t Tv, Double_t Tw, Double_t qp,Double_t CovMatrix[15], TVector3 o, TVector3 di, TVector3 dj, TVector3 dk, Double_t spu); - //void SetTrackPar(Double_t v, Double_t w, Double_t Tv, Double_t Tw, Double_t qp,Double_t CovMatrix[15]); + virtual void Print(Option_t* option = "") const; + + // define track parameters in LAB + void SetTrackPar(Double_t X, + Double_t Y, + Double_t Z, + Double_t Px, + Double_t Py, + Double_t Pz, + Int_t Q, + Double_t CovMatrix[15], + TVector3 o, + TVector3 di, + TVector3 dj, + TVector3 dk); + // void SetTrackPar(Double_t X, Double_t Y, Double_t Z, Double_t Px, Double_t Py, Double_t Pz, Int_t Q, Double_t + // CovMatrix[15]); define track parameters in SD + void SetTrackPar(Double_t v, + Double_t w, + Double_t Tv, + Double_t Tw, + Double_t qp, + Double_t CovMatrix[15], + TVector3 o, + TVector3 di, + TVector3 dj, + TVector3 dk, + Double_t spu); + // void SetTrackPar(Double_t v, Double_t w, Double_t Tv, Double_t Tw, Double_t qp,Double_t CovMatrix[15]); /** Modifiers **/ void SetTV(Double_t tv) { fTV = tv; }; void SetTW(Double_t tw) { fTW = tw; }; void Reset(); - ClassDef(FairTrackParP,1); + ClassDef(FairTrackParP, 1); /** Accessors **/ @@ -100,11 +132,22 @@ class FairTrackParP : public FairTrackPar Double_t GetZ(); */ // MARS - void GetMARSCov(Double_t Cov66[6][6]) {for(Int_t i=0; i<6; i++) for(Int_t j=0; j<6; j++) { Cov66[i][j] = fCovMatrix66[i][j]; } } + void GetMARSCov(Double_t Cov66[6][6]) + { + for (Int_t i = 0; i < 6; i++) + for (Int_t j = 0; j < 6; j++) { + Cov66[i][j] = fCovMatrix66[i][j]; + } + } // SD - Double_t* GetCov() {return fCovMatrix;}; - void GetCov(Double_t* Cov) {for(Int_t i=0; i<15; i++) { Cov[i]=fCovMatrix[i]; }} + Double_t* GetCov() { return fCovMatrix; }; + void GetCov(Double_t* Cov) + { + for (Int_t i = 0; i < 15; i++) { + Cov[i] = fCovMatrix[i]; + } + } void GetCovQ(Double_t* CovQ); Double_t GetV(); Double_t GetW(); @@ -116,7 +159,7 @@ class FairTrackParP : public FairTrackPar Double_t GetDTW(); // SD MOMENTUM - TVector3 GetSDMomentum() {return TVector3(fPx_sd, fPy_sd, fPz_sd);} + TVector3 GetSDMomentum() { return TVector3(fPx_sd, fPy_sd, fPz_sd); } // plane TVector3 GetOrigin(); @@ -126,14 +169,13 @@ class FairTrackParP : public FairTrackPar void SetPlane(TVector3 o, TVector3 dj, TVector3 dk); // spu - Double_t GetSPU() {return fSPU;}; + Double_t GetSPU() { return fSPU; }; // set/get transport matrix void SetTransportMatrix(Double_t mat[5][5]); void GetTransportMatrix(Double_t mat[5][5]); private: - /** Points coordinates in SD system */ Double_t fU, fV, fW, fTV, fTW; /** momentum id SD **/ @@ -154,15 +196,13 @@ class FairTrackParP : public FairTrackPar TVector3 fiver; TVector3 fjver; TVector3 fkver; - Double_t fDI[3]; //! - Double_t fDJ[3]; //! - Double_t fDK[3]; //! + Double_t fDI[3]; //! + Double_t fDJ[3]; //! + Double_t fDK[3]; //! // spu Double_t fSPU; // transport matrix - Double_t ftrmat[5][5]; //! - + Double_t ftrmat[5][5]; //! }; - #endif