Commit c32bffea authored by Valentina Fioretti's avatar Valentina Fioretti
Browse files

MongoDB output added. Changes in Makefile

parent 8a55fd76
Loading
Loading
Loading
Loading
+30 −8
Original line number Diff line number Diff line
@@ -5,6 +5,7 @@ if(${CMAKE_VERSION} VERSION_LESS 3.12)
  cmake_policy(VERSION ${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION})
endif()
project(bogemms)
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/CMakeModules")

#----------------------------------------------------------------------------
# Find Geant4 package, activating all available UI and Vis drivers by default
@@ -30,6 +31,7 @@ add_definitions(${GEANT4_VERSION})

option(NOROOTBUILD "Build without ROOT" ON)
option(SQLBUILD "Build with SQLite" OFF)
option(MONGODBBUILD "Build with MongoDB" OFF)

if(NOROOTBUILD)
    set(NOROOT "-D WITHOUTROOT" CACHE STRING "Build without ROOT" FORCE)
@@ -41,11 +43,25 @@ if(SQLBUILD)
    add_definitions(${WITHSQL})
endif()

if(MONGODBBUILD)
    set(WITHMONGODB "-D MONGODB" CACHE STRING "Build with MongoDB" FORCE)
    add_definitions(${WITHMONGODB})

    # Find MongoDB C++ Driver
    find_package(mongocxx REQUIRED)
    find_package(bsoncxx REQUIRED)

    # Add MongoDB include directories
    include_directories(${mongocxx_INCLUDE_DIRS} ${bsoncxx_INCLUDE_DIRS})
endif()

# Print the values of options
message(STATUS "GEANT4 VERSION: ${GEANT4_VERSION}")
message(STATUS "NO ROOT BUILDING OPTIONS: ${NOROOTBUILD}")
message(STATUS "SQLite BUILDING OPTIONS: ${SQLBUILD}")
message(STATUS "MongoDB BUILDING OPTIONS: ${MONGODBBUILD}")

message(STATUS "library: ${mongocxx_LIBRARIES}")

#----------------------------------------------------------------------------
# Setup Geant4 include directories and compile definitions
@@ -66,26 +82,32 @@ file(GLOB headers_code ${PROJECT_SOURCE_DIR}/code/*.hh)
file(GLOB headers_phys ${PROJECT_SOURCE_DIR}/phys/*.hh)
file(GLOB headers_geom ${PROJECT_SOURCE_DIR}/geom/*.hh)


# Add definitions
#----------------------------------------------------------------------------
add_definitions(-DPROJECT_SOURCE_DIR="${PROJECT_SOURCE_DIR}")

#----------------------------------------------------------------------------
# Add the executable, and link it to the Geant4 libraries
# Set up additional libraries based on options
#

if(SQLBUILD)
  SET(EXTRALIBS "-lcfitsio -lsqlite3")
if(SQLBUILD AND NOT MONGODBBUILD)
    set(EXTRALIBS "-lcfitsio -lsqlite3")
elseif(SQLBUILD AND MONGODBBUILD)
    set(EXTRALIBS "-lcfitsio -lsqlite3 -l${mongocxx_LIBRARIES} -l${bsoncxx_LIBRARIES}")
elseif(NOT SQLBUILD AND MONGODBBUILD)
    set(EXTRALIBS "-lcfitsio -l${mongocxx_LIBRARIES} -l${bsoncxx_LIBRARIES}")
else()
  SET(EXTRALIBS "-lcfitsio")
    set(EXTRALIBS "-lcfitsio")
endif()

#----------------------------------------------------------------------------
# Add the executable, and link it to the Geant4 libraries
#
add_executable(bogemms ${PROJECT_SOURCE_DIR}/code/bogemms.cc ${sources_code} ${sources_phys} ${sources_geom} ${headers_code} ${headers_phys} ${headers_geom})
target_link_libraries(bogemms ${G4mpi_LIBRARIES} ${Geant4_LIBRARIES} ${EXTRALIBS})

#----------------------------------------------------------------------------
# Copy all scripts to the build directory, i.e. the directory in which we
# Copy all scripts to the build directory, i.e., the directory in which we
# build bogemms. This is so that we can run the executable directly because it
# relies on these scripts being in the current working directory.
#
+47 −0
Original line number Diff line number Diff line
# Findbsoncxx.cmake - Locate bsoncxx C++ driver for bsonDB

# This file defines the following variables:
#   - `bsoncxx_FOUND`: Whether the library was found.
#   - `bsoncxx_INCLUDE_DIRS`: Include directory for bsoncxx headers.
#   - `bsoncxx_LIBRARIES`: Libraries needed to link with bsoncxx.

# Use `pkg-config` to find bsoncxx if available
find_package(PkgConfig)
pkg_check_modules(PC_bsonCXX libbsoncxx)

if(PC_bsonCXX_FOUND)
    set(bsoncxx_FOUND TRUE)
    set(bsoncxx_INCLUDE_DIRS ${PC_bsonCXX_INCLUDE_DIRS})
    set(bsoncxx_LIBRARIES ${PC_bsonCXX_LIBRARIES})
else()
    # Manually specify the paths if `pkg-config` isn't available
    find_path(bsoncxx_INCLUDE_DIRS
        PATHS ${BSONDB_INCLUDE_PATH}
    )

    find_library(bsoncxx_LIBRARIES
        NAMES libbsoncxx
        PATHS ${BSONDB_LIB_PATH}
    )

    # Check if both include and library paths were found
    if(bsoncxx_INCLUDE_DIRS AND bsoncxx_LIBRARIES)
        set(bsoncxx_FOUND TRUE)
    else()
        set(bsoncxx_FOUND FALSE)
    endif()
endif()

# Report the results
if(bsoncxx_FOUND)
    message(STATUS "Found bsoncxx: ${bsoncxx_LIBRARIES}")
else()
    message(WARNING "Could not find bsoncxx library")
endif()

# Export the variables to the parent scope
mark_as_advanced(
    bsoncxx_INCLUDE_DIRS
    bsoncxx_LIBRARIES
)
+47 −0
Original line number Diff line number Diff line
# Findmongocxx.cmake - Locate mongocxx C++ driver for MongoDB

# This file defines the following variables:
#   - `mongocxx_FOUND`: Whether the library was found.
#   - `mongocxx_INCLUDE_DIRS`: Include directory for mongocxx headers.
#   - `mongocxx_LIBRARIES`: Libraries needed to link with mongocxx.

# Use `pkg-config` to find mongocxx if available
find_package(PkgConfig)
pkg_check_modules(PC_MONGOCXX libmongocxx)

if(PC_MONGOCXX_FOUND)
    set(mongocxx_FOUND TRUE)
    set(mongocxx_INCLUDE_DIRS ${PC_MONGOCXX_INCLUDE_DIRS})
    set(mongocxx_LIBRARIES ${PC_MONGOCXX_LIBRARIES})
else()
    # Manually specify the paths if `pkg-config` isn't available
    find_path(mongocxx_INCLUDE_DIRS
        PATHS ${MONGODB_INCLUDE_PATH}
    )

    find_library(mongocxx_LIBRARIES
        NAMES libmongocxx
        PATHS ${MONGODB_LIB_PATH}
    )

    # Check if both include and library paths were found
    if(mongocxx_INCLUDE_DIRS AND mongocxx_LIBRARIES)
        set(mongocxx_FOUND TRUE)
    else()
        set(mongocxx_FOUND FALSE)
    endif()
endif()

# Report the results
if(mongocxx_FOUND)
    message(STATUS "Found mongocxx: ${mongocxx_LIBRARIES}")
else()
    message(WARNING "Could not find mongocxx library")
endif()

# Export the variables to the parent scope
mark_as_advanced(
    mongocxx_INCLUDE_DIRS
    mongocxx_LIBRARIES
)
+15 −17
Original line number Diff line number Diff line
@@ -29,21 +29,6 @@
// * use  in  resulting  scientific  publications,  and indicate your *
// * acceptance of all terms of the Geant4 Software license.          *
// ********************************************************************
//
// Copyright 2025 Valentina Fioretti
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// **********************************************************************


#include "CXYZSD.hh"
@@ -66,6 +51,7 @@
#include "THELGlobalMemory.hh"
#include "FITSOutput_XYZ.hh"
#include "SQLliteOutput_XYZ.hh"
#include "MongoOutput_XYZ.hh"

#include <mutex>

@@ -384,7 +370,6 @@ int CXYZSD::GetMotherID(int flag, int ndepth, G4Step* aStep) {
}
void CXYZSD::EndOfEvent(G4HCofThisEvent* HCE) {

    mutex_write.lock();
    CXYZVector.clear();


@@ -392,6 +377,7 @@ void CXYZSD::EndOfEvent(G4HCofThisEvent* HCE) {

    if(gm.enableWriteFITS && gm.enableWriteXYZ) {
        // 		G4cout << "{" << NbHits << "}";
        mutex_write.lock();
        if(NbHits > 0) {

            for (G4int i=0; i<NbHits; i++) {
@@ -400,8 +386,8 @@ void CXYZSD::EndOfEvent(G4HCofThisEvent* HCE) {
                gm.fits_xyz->writeData(hit, i);
            }
        }
    }
        mutex_write.unlock();
    }
	


@@ -417,6 +403,18 @@ void CXYZSD::EndOfEvent(G4HCofThisEvent* HCE) {
	}
#endif

G4cout << MONGODB << G4endl;
#ifdef MONGODB
    if(gm.enableWriteMONGODB && gm.enableWriteXYZ) {
        if(NbHits > 0) {
            for (G4int i=0; i<NbHits; i++) {
                CXYZHit* hit = (*xyzhitCollection)[i];
                //gm.root_xyz->open();
                gm.mongodb_xyz->writeData(hit, i);
            }
        }
    }
#endif
}


+239 −0
Original line number Diff line number Diff line
#ifdef MONGODB

#include "MongoOutput_XYZ.hh"

#include "THELGlobalMemory.hh"
#include "ConfigFile.hh"
#include "CXYZHit.hh"

#if defined(GEANT4_11_1)
#include "G4SystemOfUnits.hh"
#include "G4PhysicalConstants.hh"
#endif

#include <iostream>

#include "G4MPImanager.hh"

#include <bsoncxx/json.hpp>
#include <bsoncxx/builder/basic/document.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/uri.hpp>
#include <mongocxx/exception/exception.hpp>
#include <iomanip>
#include <sstream>
#include <string>

using namespace std;
using bsoncxx::builder::basic::kvp;
using bsoncxx::builder::basic::make_document;

#define G4_TYPE G4float

static mongocxx::instance instance{};

MongoOutput_XYZ::MongoOutput_XYZ() : client(mongocxx::uri("mongodb://localhost:27017")){
    //current_event_id = -1;
    lastevent = -1;
    nmaxevents = 0;
    gm.config->readInto(nmaxevents, "IOXYZ.NRows");
    
    MTFlag = 0;
    gm.config->readInto(MTFlag, "RUN.MT.ACTIVATE");
    
    //volume selection
    volselectionN = 0;
    gm.config->readInto(volselectionN, "IOXYZ.volumeselection.number");
    char c[512];
    for(int i=0; i<volselectionN; i++) {
        snprintf(c, sizeof(c), "IOXYZ.volumeselection.%i.start", i);
        gm.config->readInto(volselectionstart[i], c);
        snprintf(c, sizeof(c), "IOXYZ.volumeselection.%i.end", i);
        gm.config->readInto(volselectionend[i], c);
    }

    writeonlyifenergydeposit = 0;
    gm.config->readInto(writeonlyifenergydeposit, "IOXYZ.writeonlyifenergydeposit");
    
    removeWorldEvent = 0;
    gm.config->readInto(removeWorldEvent, "IOXYZ.removeWorldEvent");
    cout << "IOXYZ.removeWorldEvent: " << removeWorldEvent << endl;
    
    //INIT
    outputXYZCollectionNameMongoDB_base = (char*)gm.GetOutputMongoXYZCollectionName().data();
    
    auto database = client[database_name];
    collection = database[outputXYZCollectionNameMongoDB_base];
     
    
    newfile = true;
    nrows_file = 0;
}

MongoOutput_XYZ::~MongoOutput_XYZ() {
    cout << "MongoOutput_XYZ::~MongoOutput_XYZ()" << endl;
}

bool MongoOutput_XYZ::init() {
    cout << "MongoDB init end" << endl;
    return true;
}

void MongoOutput_XYZ::writeData(CXYZHit* hitting, G4int i) {


    char *err_msg = 0;
    
    long evtid;
    long ttrkid;
    long parenttrkid;
    char * volumename;
    long volumeid;
    long motherid;
    double energyDep;
    double x_ent;
    double y_ent;
    double z_ent;
    double x_exit;
    double y_exit;
    double z_exit;
    double momx_ent;
    double momy_ent;
    double momz_ent;
    double momx_exit;
    double momy_exit;
    double momz_exit;
    double ekin_ent;
    double ekin_exit;
    long tpart;
    char * tpartname;
    long tproc;
    char * tprocname;
    double gtime_ent;
    double gtime_exit;

    evtid = hitting->GetEventID();
    
    
    bool newevent = false;
    if(lastevent != evtid) {
        newevent = true;
        lastevent = evtid;
    } else
        newevent = false;
    
    if (!MTFlag) {
            newfile = true;
    }

    long v1 = hitting->GetVolumeID();

    bool volumein = false;
    bool layerin = false;
    bool trackerin = false;
    
    if(volselectionN != 0) {
        for(int ii=0; ii<volselectionN; ii++) {
            if(v1 >= volselectionstart[ii] && v1 <= volselectionend[ii])
                volumein = true;
        }
    }
    
    long LayerRealNumber;
    G4int layer_div;
    
    if (volumein) {
            
        volumeid = v1; //2
        
        energyDep = hitting->GetEdep() / keV; //3
        tpart = hitting->GetParticleID(); //4
        
        if(volumeid != 1) {
            if(writeonlyifenergydeposit && energyDep == 0)
                return;
            if(removeWorldEvent && tpart == 0)
                return;
        }

        
        ttrkid = hitting->GetTrackID(); //5
        parenttrkid = hitting->GetParentTrackID();
        volumename = (char*)hitting->GetVolumeName().data();

        motherid = hitting->GetMotherID();
        x_ent = hitting->GetPosEntrance()[0] / mm;
        y_ent = hitting->GetPosEntrance()[1] / mm;
        z_ent = hitting->GetPosEntrance()[2] / mm;
        x_exit =  hitting->GetPosExit()[0] / mm;
        y_exit =  hitting->GetPosExit()[1] / mm;
        z_exit =  hitting->GetPosExit()[2] / mm;
        ekin_ent = hitting->GetEkinEntrance() / keV;
        ekin_exit = hitting->GetEkinExit() / keV;
        momx_ent = hitting->GetMomDirEntrance()[0] / mm;
        momy_ent = hitting->GetMomDirEntrance()[1] / mm;
        momz_ent = hitting->GetMomDirEntrance()[2] / mm;
        momx_exit =  hitting->GetMomDirExit()[0] / mm;
        momy_exit =  hitting->GetMomDirExit()[1] / mm;
        momz_exit =  hitting->GetMomDirExit()[2] / mm;
        tpartname = (char*)hitting->GetParticleType().data();

        tproc = hitting->GetProcessCreatorID();
        tprocname = (char*)hitting->GetProcessCreator().data();
        
        G4_TYPE time = hitting->GetGlobalTimeEntrance()/ns;
        gtime_ent = time;
        time = hitting->GetGlobalTimeExit()/ns;
        gtime_exit = time; //18

        // Construct MongoDB document from data

        /*
        vector<bsoncxx::document::value> documents;
        documents.push_back(make_document(kvp("EVT_ID", "prova1")));
        documents.push_back(make_document(kvp("TRK_ID", "prova2")));
        */
        
        bsoncxx::builder::basic::document doc{};
        doc.append(kvp("EVT_ID", std::to_string(evtid)));
        doc.append(kvp("TRK_ID", std::to_string(ttrkid)));
        doc.append(kvp("PARENT_TRK_ID", std::to_string(parenttrkid)));
        doc.append(kvp("VOLUME_ID", std::to_string(volumeid)));
        doc.append(kvp("VOLUME_NAME", volumename));
        doc.append(kvp("MOTHER_ID", std::to_string(motherid)));
        doc.append(kvp("E_DEP", std::to_string(energyDep)));
        doc.append(kvp("X_ENT", std::to_string(x_ent)));
        doc.append(kvp("Y_ENT", std::to_string(y_ent)));
        doc.append(kvp("Z_ENT", std::to_string(z_ent)));
        doc.append(kvp("X_EXIT", std::to_string(x_exit)));
        doc.append(kvp("Y_EXIT", std::to_string(y_exit)));
        doc.append(kvp("Z_EXIT", std::to_string(z_exit)));
        doc.append(kvp("E_KIN_ENT", std::to_string(ekin_ent)));
        doc.append(kvp("E_KIN_EXIT", std::to_string(ekin_exit)));
        doc.append(kvp("MDX_ENT", std::to_string(momx_ent)));
        doc.append(kvp("MDY_ENT", std::to_string(momy_ent)));
        doc.append(kvp("MDZ_ENT", std::to_string(momz_ent)));
        doc.append(kvp("MDX_EXIT", std::to_string(momx_exit)));
        doc.append(kvp("MDY_EXIT", std::to_string(momy_exit)));
        doc.append(kvp("MDZ_EXIT", std::to_string(momz_exit)));
        doc.append(kvp("GTIME_ENT", std::to_string(gtime_ent)));
        doc.append(kvp("GTIME_EXIT", std::to_string(gtime_exit)));
        doc.append(kvp("PARTICLE_ID", std::to_string(tpart)));
        doc.append(kvp("PARTICLE_NAME", tpartname));
        doc.append(kvp("PROCESS_ID", std::to_string(tproc)));
        doc.append(kvp("PROCESS_NAME", tprocname));

        collection.insert_one(doc.view());
        
        nrows_file++;
         
    }
}

bool MongoOutput_XYZ::close() {
    cout << "MongoDB: closing connection" << endl;
    return true;
}

#endif
Loading