15#include "HepPDT/ParticleData.hh"
16#include "HepPDT/ParticleDataTable.hh"
18#include "CLHEP/Random/RandGauss.h"
19#include "CLHEP/Random/RandFlat.h"
21#if defined(__FastCaloSimStandAlone__)
22#include "CLHEP/Random/TRandomEngine.h"
24#include <CLHEP/Random/RanluxEngine.h>
33#include "lwtnn/LightweightGraph.hh"
34#include "lwtnn/parse_json.hh"
82 int pid,
int etaMin,
const std::string &FastCaloGANInputFolderName) {
88 "Using FastCaloGANInputFolderName: " << FastCaloGANInputFolderName);
90 int etaMax = etaMin + 5;
102 std::string inputFile = std::format(
"{}/neural_net_{}_eta_{}_{}.json",
103 FastCaloGANInputFolderName, pid, etaMin, etaMax);
104 ATH_MSG_INFO(
"For pid: " << pid <<
" and eta " << etaMin <<
"-" << etaMax
105 <<
", loading json file " << inputFile);
106 std::ifstream input(inputFile);
107 if (!input.is_open()) {
108 ATH_MSG_ERROR(std::format(
"Could not open json file: {}", inputFile));
111 std::stringstream sin;
112 sin << input.rdbuf();
115 auto config = lwt::parse_json_graph(sin);
116 m_graph =
new lwt::LightweightGraph(config);
121 m_input =
new std::string(sin.str());
126 GetBinning(pid, (etaMin + etaMax) / 2, FastCaloGANInputFolderName);
137 int pid,
int etaMid,
const std::string &FastCaloGANInputFolderName) {
138 const std::string xmlFullFileName = std::format(
"{}/binning.xml", FastCaloGANInputFolderName);
141 std::vector<Binning> AllBinning;
142 std::vector<int> EtaMaxList;
145 std::unique_ptr<XMLCoreNode> doc = p.parse (xmlFullFileName);
147 int nodePid =
bin->get_int_attrib (
"pid");
148 int nodeEtaMax =
bin->get_int_attrib (
"etaMax");
151 bool correctentry =
true;
153 correctentry =
false;
155 for (
const XMLCoreNode* nodeLayer :
bin->get_children (
"Layer")) {
156 std::vector<double> edges;
157 std::string s = nodeLayer->get_attrib (
"r_edges");
158 std::istringstream
ss(s);
161 while (std::getline(
ss, token,
',')) {
162 edges.push_back(atof(token.c_str()));
165 int binsInAlpha = nodeLayer->get_int_attrib (
"n_bin_alpha");
166 int layer = nodeLayer->get_int_attrib (
"id");
170 << nodeEtaMax <<
" Layer: " << layer
171 <<
" binsInAlpha: " << binsInAlpha
174 std::string name =
"hist_pid_" + std::to_string(nodePid) +
176 std::to_string(EtaMaxList.size()) +
"_layer_" +
177 std::to_string(layer);
178 int xBins = edges.size() - 1;
185 TH2D(name.c_str(), name.c_str(), xBins, &edges[0],
186 binsInAlpha, -TMath::Pi(), TMath::Pi());
187 binsInLayer[layer].SetDirectory(
nullptr);
192 AllBinning.push_back(std::move(binsInLayer));
193 EtaMaxList.push_back(nodeEtaMax);
197 for (
int etaMax : EtaMaxList) {
198 if (etaMid < etaMax) {
212 Form(
"layer=%d", simulstate.
getAuxInfo<
int>(
"GANlayer"_FCShash)));
220 trueEnergy = truth->P();
221 double randUniformZ = 0.;
224 randUniformZ = CLHEP::RandFlat::shoot(simulstate.
randomEngine(), -1., 1.);
225 inputs[
"node_0"].insert(
226 std::pair<std::string, double>(std::to_string(i), randUniformZ));
231 inputs[
"node_1"].insert(
232 std::pair<std::string, double>(
"0", trueEnergy / (std::pow(2, 22))));
241 const int pdgId = truth->
pdgid();
242 const float charge = HepPDT::ParticleID(pdgId).charge();
245 const float Ekin = truth->
Ekin();
247 Einit = simulstate.
E();
267 for (
const auto& element : binsInLayers) {
268 int layer = element.first;
270 const TH2D *
h = &element.second;
271 int xBinNum =
h->GetNbinsX();
276 <<
" has only one bin in r, this means is it not used, "
277 "skipping (this is needed to keep correct "
278 "syncronisation of voxel and layers)");
285 int yBinNum =
h->GetNbinsY();
288 for (
int iy = 1; iy <= yBinNum; ++iy) {
289 for (
int ix = 1; ix <= xBinNum; ++ix) {
290 double energyInVoxel = outputs[
"out_" + std::to_string(vox)];
292 <<
" binx " << ix <<
" biny " << iy);
294 if (energyInVoxel == 0) {
299 simulstate.
add_E(layer, Einit * energyInVoxel);
305 for (
unsigned int ichain =
m_bin_start.back(); ichain <
size(); ++ichain) {
314 for (
const auto& element : binsInLayers) {
315 int layer = element.first;
316 simulstate.
setAuxInfo<
int>(
"GANlayer"_FCShash, layer);
319 const TH2D *
h = &element.second;
320 int xBinNum =
h->GetNbinsX();
325 <<
" has only one bin in r, this means is it not used, "
326 "skipping (this is needed to keep correct "
327 "syncronisation of voxel and layers)");
333 const int bin =
get_bin(simulstate, truth, extrapol);
341 <<
chain()[ichain]->GetName());
342 if (
chain()[ichain]->InheritsFrom(
343 TFCSLateralShapeParametrizationHitBase::Class())) {
346 if (sim->
simulate_hit(hit, simulstate, truth, extrapol) !=
351 <<
chain()[ichain]->GetName());
358 <<
chain()[ichain]->GetName()
359 <<
" does not inherit from "
360 "TFCSLateralShapeParametrizationHitBase");
371 int binResolution = 5;
372 if (layer == 1 || layer == 5) {
376 const double center_eta = hit.center_eta();
377 const double center_phi = hit.center_phi();
378 const double center_r = hit.center_r();
379 const double center_z = hit.center_z();
382 <<
" phi " << center_phi <<
" R " << center_r);
384 const float dist000 =
385 TMath::Sqrt(center_r * center_r + center_z * center_z);
386 const float eta_jakobi = TMath::Abs(2.0 * TMath::Exp(-center_eta) /
387 (1.0 + TMath::Exp(-2 * center_eta)));
392 int yBinNum =
h->GetNbinsY();
395 for (
int iy = 1; iy <= yBinNum; ++iy) {
396 for (
int ix = 1; ix <= xBinNum; ++ix) {
398 double energyInVoxel = outputs[
"out_" + std::to_string(vox)];
400 <<
" binx " << ix <<
" biny " << iy);
402 if (energyInVoxel == 0) {
407 const TAxis *
x =
h->GetXaxis();
408 nHitsR =
x->GetBinUpEdge(ix) -
x->GetBinLowEdge(ix);
411 double r =
x->GetBinUpEdge(ix);
412 nHitsAlpha = ceil(2 * TMath::Pi() *
r / binResolution);
416 const TAxis *
y =
h->GetYaxis();
417 double angle =
y->GetBinUpEdge(iy) -
y->GetBinLowEdge(iy);
418 double r =
x->GetBinUpEdge(ix);
419 double d = 2 *
r * sin(
angle / 2 *
r);
420 nHitsAlpha = ceil(d / binResolution);
423 nHitsAlpha = std::min(10, std::max(1, nHitsAlpha));
424 nHitsR = std::min(10, std::max(1, nHitsR));
426 for (
int ir = 0;
ir < nHitsR; ++
ir) {
427 const TAxis *
x =
h->GetXaxis();
429 x->GetBinLowEdge(ix) +
x->GetBinWidth(ix) / (nHitsR + 1) *
ir;
431 for (
int ialpha = 0; ialpha < nHitsAlpha; ++ialpha) {
437 const TAxis *
y =
h->GetYaxis();
438 alpha =
y->GetBinLowEdge(iy) +
439 y->GetBinWidth(iy) / (nHitsAlpha + 1) * ialpha;
443 hit.E() = Einit * energyInVoxel / (nHitsAlpha * nHitsR);
446 float delta_eta_mm =
r * cos(alpha);
447 float delta_phi_mm =
r * sin(alpha);
457 delta_eta_mm = -delta_eta_mm;
461 if ((
charge < 0. && pdgId!=11) || pdgId==-11)
462 delta_phi_mm = -delta_phi_mm;
464 const float delta_eta = delta_eta_mm / eta_jakobi / dist000;
465 const float delta_phi = delta_phi_mm / center_r;
467 hit.eta() = center_eta + delta_eta;
468 hit.phi() = center_phi + delta_phi;
471 <<
" layer " << layer);
473 const float hit_r =
r * cos(alpha) + center_r;
474 float delta_phi =
r * sin(alpha) / center_r;
479 if ((
charge < 0. && pdgId!=11) || pdgId==-11)
480 delta_phi = -delta_phi;
481 const float hit_phi = delta_phi + center_phi;
482 hit.x() = hit_r * cos(hit_phi);
483 hit.y() = hit_r * sin(hit_phi);
486 <<
" layer " << layer);
490 const int bin =
get_bin(simulstate, truth, extrapol);
492 for (
unsigned int ichain =
498 <<
chain()[ichain]->GetName());
499 if (
chain()[ichain]->InheritsFrom(
500 TFCSLateralShapeParametrizationHitBase::Class())) {
504 if (sim->
simulate_hit(hit, simulstate, truth, extrapol) !=
510 <<
chain()[ichain]->GetName());
517 <<
chain()[ichain]->GetName()
518 <<
" does not inherit from "
519 "TFCSLateralShapeParametrizationHitBase");
543 if (simulstate.
E() > std::numeric_limits<double>::epsilon()) {
545 simulstate.
set_Efrac(ilayer, simulstate.
E(ilayer) / simulstate.
E());
558 for (
unsigned int ichain = 0; ichain <
m_bin_start[0]; ++ichain) {
577 if (!
fillEnergy(simulstate, truth, extrapol, std::move(inputs))) {
589 bool shortprint = opt.Index(
"short") >= 0;
590 bool longprint =
msgLvl(MSG::DEBUG) || (
msgLvl(MSG::INFO) && !shortprint);
591 TString optprint = opt;
592 optprint.ReplaceAll(
"short",
"");
600 <<
"; Binning size=" <<
m_Binning.size());
604 <<
"layer=" << l.first
605 <<
" nR=" << l.second.GetNbinsX()
606 <<
" nalpha=" << l.second.GetNbinsY());
610 TString prefix =
"- ";
611 for (
unsigned int ichain = 0; ichain <
size(); ++ichain) {
612 if (ichain == 0 && ichain !=
m_bin_start.front()) {
622 prefix = Form(
"%-2d", ibin);
632 chain()[ichain]->Print(opt + prefix);
636void TFCSEnergyAndHitGAN::Streamer(TBuffer &R__b) {
639 if (R__b.IsReading()) {
640 R__b.ReadClassBuffer(TFCSEnergyAndHitGAN::Class(),
this);
646 std::stringstream
sin;
648 auto config = lwt::parse_json_graph(sin);
649 m_graph =
new lwt::LightweightGraph(config);
651#ifndef __FastCaloSimStandAlone__
659 R__b.WriteClassBuffer(TFCSEnergyAndHitGAN::Class(),
this);
668#if defined(__FastCaloSimStandAlone__)
676 t->SetPtEtaPhiM(20000, 0.225, 0, 130);
682 e->set_IDCaloBoundary_eta(truth->Eta());
683 for (
int i = 0; i < 24; ++i) {
702 static constexpr int pid = 211;
704 int etaMax = etaMin + 5;
707 "/eos/atlas/atlascerngroupdisk/proj-simul/VoxalisationOutputs/nominal/"
708 "GAN_michele_normE_MaxE/input_for_service_new");
709 for (
int i = 0; i < 24; ++i)
712 Form(
"center%d", i), Form(
"center layer %d", i));
713 c->set_calosample(i);
714 c->setExtrapWeight(0.5);
715 c->setLevel(MSG::VERBOSE);
723 c->set_eta_min(etaMin / 100.0);
724 c->set_eta_max(etaMax / 100.0);
725 c->set_eta_nominal((etaMin + etaMax) / 200.0);
733 TFile *fGAN = TFile::Open(
"FCSGANtest.root",
"recreate");
738 fGAN = TFile::Open(
"FCSGANtest.root");
743 GAN2->
simulate(*simulstate, truth, extrapol);
#define ATH_MSG_VERBOSE(x)
#define ATH_MSG_WARNING(x)
double charge(const T &p)
FCSReturnCode
Base class for all FastCaloSim parametrizations Functionality in derivde classes is provided through ...
double angle(const GeoTrf::Vector2D &a, const GeoTrf::Vector2D &b)
Simple DOM-like node structure to hold the result of XML parsing.
Helper for getting a const version of a pointer.
Header file for AthHistogramAlgorithm.
bool msgLvl(const MSG::Level lvl) const
Check whether the logging system is active at the provided verbosity level.
virtual void setLevel(MSG::Level lvl)
Update outputlevel.
virtual FCSReturnCode simulate(TFCSSimulationState &simulstate, const TFCSTruthState *truth, const TFCSExtrapolationState *extrapol) const override
Method in all derived classes to do some simulation.
unsigned int get_nr_of_init(unsigned int bin) const
bool OnlyScaleEnergy() const
lwt::LightweightGraph * m_graph
void set_nr_of_init(unsigned int bin, unsigned int ninit)
virtual void Print(Option_t *option="") const override
virtual int get_bin(TFCSSimulationState &simulstate, const TFCSTruthState *, const TFCSExtrapolationState *) const override
use the layer to be done as binning of the GAN chain
Binning m_Binning
Do not persistify.
TFCSEnergyAndHitGAN(const char *name=nullptr, const char *title=nullptr)
bool fillEnergy(TFCSSimulationState &simulstate, const TFCSTruthState *truth, const TFCSExtrapolationState *extrapol, NetworkInputs inputs) const
const Binning & get_Binning() const
std::map< std::string, double > NetworkOutputs
virtual ~TFCSEnergyAndHitGAN()
virtual const std::string get_variable_text(TFCSSimulationState &simulstate, const TFCSTruthState *, const TFCSExtrapolationState *) const override
std::map< std::string, std::map< std::string, double > > NetworkInputs
std::map< int, TH2D > Binning
void GetBinning(int pid, int etaMax, const std::string &FastCaloGANInputFolderName)
virtual bool is_match_calosample(int calosample) const override
bool initializeNetwork(int pid, int etaMin, const std::string &FastCaloGANInputFolderName)
std::vector< int > m_bin_ninit
static void unit_test(TFCSSimulationState *simulstate=nullptr, const TFCSTruthState *truth=nullptr, const TFCSExtrapolationState *extrapol=nullptr)
bool fillFastCaloGanNetworkInputs(TFCSSimulationState &simulstate, const TFCSTruthState *truth, NetworkInputs &inputs, double &trueEnergy) const
virtual FCSReturnCode simulate_hit(Hit &hit, TFCSSimulationState &simulstate, const TFCSTruthState *truth, const TFCSExtrapolationState *extrapol)
simulated one hit position with some energy.
virtual void reset_match_all_pdgid()
void Print(Option_t *option="") const
Print object information.
virtual unsigned int get_number_of_bins() const
TFCSParametrizationBinnedChain(const char *name=nullptr, const char *title=nullptr)
std::vector< unsigned int > m_bin_start
Contains the index where the TFCSParametrizationBase* instances to run for a given bin start.
virtual void push_back_in_bin(TFCSParametrizationBase *param, unsigned int bin)
virtual const std::string get_bin_text(int bin) const
print the range of a bin; for bin -1, print the allowed range
FCSReturnCode simulate_and_retry(TFCSParametrizationBase *parametrization, TFCSSimulationState &simulstate, const TFCSTruthState *truth, const TFCSExtrapolationState *extrapol) const
const Chain_t & chain() const
virtual unsigned int size() const override
Some derived classes have daughter instances of TFCSParametrizationBase objects The size() and operat...
virtual void set_eta_max(double max)
virtual void add_pdgid(int id)
virtual void set_eta_nominal(double min)
virtual void set_pdgid(int id)
virtual void set_eta_min(double min)
void Print(Option_t *option="") const
void set_E(int sample, double Esample)
const T getAuxInfo(std::uint32_t index) const
void add_E(int sample, double Esample)
void set_Efrac(int sample, double Efracsample)
void setAuxInfo(std::uint32_t index, const T &val)
CLHEP::HepRandomEngine * randomEngine()
void setRandomEngine(CLHEP::HepRandomEngine *engine)
Simple DOM-like node structure to hold the result of XML parsing.
int ir
counter of the current depth
std::string find(const std::string &s)
return a remapped string
const T * as_const_ptr(const T *p)
Helper for getting a const version of a pointer.