17#include "CLHEP/Random/RandGauss.h"
18#include "CLHEP/Random/RandFlat.h"
20#if defined(__FastCaloSimStandAlone__)
21#include "CLHEP/Random/TRandomEngine.h"
23#include <CLHEP/Random/RanluxEngine.h>
32#include "lwtnn/LightweightGraph.hh"
33#include "lwtnn/parse_json.hh"
81 int pid,
int etaMin,
const std::string &FastCaloGANInputFolderName) {
87 "Using FastCaloGANInputFolderName: " << FastCaloGANInputFolderName);
89 int etaMax = etaMin + 5;
101 std::string inputFile = std::format(
"{}/neural_net_{}_eta_{}_{}.json",
102 FastCaloGANInputFolderName, pid, etaMin, etaMax);
103 ATH_MSG_INFO(
"For pid: " << pid <<
" and eta " << etaMin <<
"-" << etaMax
104 <<
", loading json file " << inputFile);
105 std::ifstream input(inputFile);
106 if (!input.is_open()) {
107 ATH_MSG_ERROR(std::format(
"Could not open json file: {}", inputFile));
110 std::stringstream sin;
111 sin << input.rdbuf();
114 auto config = lwt::parse_json_graph(sin);
115 m_graph =
new lwt::LightweightGraph(config);
120 m_input =
new std::string(sin.str());
125 GetBinning(pid, (etaMin + etaMax) / 2, FastCaloGANInputFolderName);
136 int pid,
int etaMid,
const std::string &FastCaloGANInputFolderName) {
137 const std::string xmlFullFileName = std::format(
"{}/binning.xml", FastCaloGANInputFolderName);
140 std::vector<Binning> AllBinning;
141 std::vector<int> EtaMaxList;
144 std::unique_ptr<XMLCoreNode> doc = p.parse (xmlFullFileName);
146 int nodePid =
bin->get_int_attrib (
"pid");
147 int nodeEtaMax =
bin->get_int_attrib (
"etaMax");
150 bool correctentry =
true;
152 correctentry =
false;
154 for (
const XMLCoreNode* nodeLayer :
bin->get_children (
"Layer")) {
155 std::vector<double> edges;
156 std::string s = nodeLayer->get_attrib (
"r_edges");
157 std::istringstream
ss(s);
160 while (std::getline(
ss, token,
',')) {
161 edges.push_back(atof(token.c_str()));
164 int binsInAlpha = nodeLayer->get_int_attrib (
"n_bin_alpha");
165 int layer = nodeLayer->get_int_attrib (
"id");
169 << nodeEtaMax <<
" Layer: " << layer
170 <<
" binsInAlpha: " << binsInAlpha
173 std::string name =
"hist_pid_" + std::to_string(nodePid) +
175 std::to_string(EtaMaxList.size()) +
"_layer_" +
176 std::to_string(layer);
177 int xBins = edges.size() - 1;
184 TH2D(name.c_str(), name.c_str(), xBins, &edges[0],
185 binsInAlpha, -TMath::Pi(), TMath::Pi());
186 binsInLayer[layer].SetDirectory(
nullptr);
191 AllBinning.push_back(std::move(binsInLayer));
192 EtaMaxList.push_back(nodeEtaMax);
196 for (
int etaMax : EtaMaxList) {
197 if (etaMid < etaMax) {
211 Form(
"layer=%d", simulstate.
getAuxInfo<
int>(
"GANlayer"_FCShash)));
219 trueEnergy = truth->P();
220 double randUniformZ = 0.;
223 randUniformZ = CLHEP::RandFlat::shoot(simulstate.
randomEngine(), -1., 1.);
224 inputs[
"node_0"].insert(
225 std::pair<std::string, double>(std::to_string(i), randUniformZ));
230 inputs[
"node_1"].insert(
231 std::pair<std::string, double>(
"0", trueEnergy / (std::pow(2, 22))));
240 const int pdgId = truth->
pdgid();
244 const float Ekin = truth->
Ekin();
246 Einit = simulstate.
E();
266 for (
const auto& element : binsInLayers) {
267 int layer = element.first;
269 const TH2D *
h = &element.second;
270 int xBinNum =
h->GetNbinsX();
275 <<
" has only one bin in r, this means is it not used, "
276 "skipping (this is needed to keep correct "
277 "syncronisation of voxel and layers)");
284 int yBinNum =
h->GetNbinsY();
287 for (
int iy = 1; iy <= yBinNum; ++iy) {
288 for (
int ix = 1; ix <= xBinNum; ++ix) {
289 double energyInVoxel = outputs[
"out_" + std::to_string(vox)];
291 <<
" binx " << ix <<
" biny " << iy);
293 if (energyInVoxel == 0) {
298 simulstate.
add_E(layer, Einit * energyInVoxel);
304 for (
unsigned int ichain =
m_bin_start.back(); ichain <
size(); ++ichain) {
313 for (
const auto& element : binsInLayers) {
314 int layer = element.first;
315 simulstate.
setAuxInfo<
int>(
"GANlayer"_FCShash, layer);
318 const TH2D *
h = &element.second;
319 int xBinNum =
h->GetNbinsX();
324 <<
" has only one bin in r, this means is it not used, "
325 "skipping (this is needed to keep correct "
326 "syncronisation of voxel and layers)");
332 const int bin =
get_bin(simulstate, truth, extrapol);
340 <<
chain()[ichain]->GetName());
341 if (
chain()[ichain]->InheritsFrom(
342 TFCSLateralShapeParametrizationHitBase::Class())) {
345 if (sim->
simulate_hit(hit, simulstate, truth, extrapol) !=
350 <<
chain()[ichain]->GetName());
357 <<
chain()[ichain]->GetName()
358 <<
" does not inherit from "
359 "TFCSLateralShapeParametrizationHitBase");
370 int binResolution = 5;
371 if (layer == 1 || layer == 5) {
375 const double center_eta = hit.center_eta();
376 const double center_phi = hit.center_phi();
377 const double center_r = hit.center_r();
378 const double center_z = hit.center_z();
381 <<
" phi " << center_phi <<
" R " << center_r);
383 const float dist000 =
384 TMath::Sqrt(center_r * center_r + center_z * center_z);
385 const float eta_jakobi = TMath::Abs(2.0 * TMath::Exp(-center_eta) /
386 (1.0 + TMath::Exp(-2 * center_eta)));
391 int yBinNum =
h->GetNbinsY();
394 for (
int iy = 1; iy <= yBinNum; ++iy) {
395 for (
int ix = 1; ix <= xBinNum; ++ix) {
397 double energyInVoxel = outputs[
"out_" + std::to_string(vox)];
399 <<
" binx " << ix <<
" biny " << iy);
401 if (energyInVoxel == 0) {
406 const TAxis *
x =
h->GetXaxis();
407 nHitsR =
x->GetBinUpEdge(ix) -
x->GetBinLowEdge(ix);
410 double r =
x->GetBinUpEdge(ix);
411 nHitsAlpha = ceil(2 * TMath::Pi() *
r / binResolution);
415 const TAxis *
y =
h->GetYaxis();
416 double angle =
y->GetBinUpEdge(iy) -
y->GetBinLowEdge(iy);
417 double r =
x->GetBinUpEdge(ix);
418 double d = 2 *
r * sin(
angle / 2 *
r);
419 nHitsAlpha = ceil(d / binResolution);
422 nHitsAlpha = std::min(10, std::max(1, nHitsAlpha));
423 nHitsR = std::min(10, std::max(1, nHitsR));
425 for (
int ir = 0;
ir < nHitsR; ++
ir) {
426 const TAxis *
x =
h->GetXaxis();
428 x->GetBinLowEdge(ix) +
x->GetBinWidth(ix) / (nHitsR + 1) *
ir;
430 for (
int ialpha = 0; ialpha < nHitsAlpha; ++ialpha) {
436 const TAxis *
y =
h->GetYaxis();
437 alpha =
y->GetBinLowEdge(iy) +
438 y->GetBinWidth(iy) / (nHitsAlpha + 1) * ialpha;
442 hit.E() = Einit * energyInVoxel / (nHitsAlpha * nHitsR);
445 float delta_eta_mm =
r * cos(alpha);
446 float delta_phi_mm =
r * sin(alpha);
456 delta_eta_mm = -delta_eta_mm;
460 if ((
charge < 0. && pdgId!=11) || pdgId==-11)
461 delta_phi_mm = -delta_phi_mm;
463 const float delta_eta = delta_eta_mm / eta_jakobi / dist000;
464 const float delta_phi = delta_phi_mm / center_r;
466 hit.eta() = center_eta + delta_eta;
467 hit.phi() = center_phi + delta_phi;
470 <<
" layer " << layer);
472 const float hit_r =
r * cos(alpha) + center_r;
473 float delta_phi =
r * sin(alpha) / center_r;
478 if ((
charge < 0. && pdgId!=11) || pdgId==-11)
479 delta_phi = -delta_phi;
480 const float hit_phi = delta_phi + center_phi;
481 hit.x() = hit_r * cos(hit_phi);
482 hit.y() = hit_r * sin(hit_phi);
485 <<
" layer " << layer);
489 const int bin =
get_bin(simulstate, truth, extrapol);
491 for (
unsigned int ichain =
497 <<
chain()[ichain]->GetName());
498 if (
chain()[ichain]->InheritsFrom(
499 TFCSLateralShapeParametrizationHitBase::Class())) {
503 if (sim->
simulate_hit(hit, simulstate, truth, extrapol) !=
509 <<
chain()[ichain]->GetName());
516 <<
chain()[ichain]->GetName()
517 <<
" does not inherit from "
518 "TFCSLateralShapeParametrizationHitBase");
542 if (simulstate.
E() > std::numeric_limits<double>::epsilon()) {
544 simulstate.
set_Efrac(ilayer, simulstate.
E(ilayer) / simulstate.
E());
557 for (
unsigned int ichain = 0; ichain <
m_bin_start[0]; ++ichain) {
576 if (!
fillEnergy(simulstate, truth, extrapol, std::move(inputs))) {
588 bool shortprint = opt.Index(
"short") >= 0;
589 bool longprint =
msgLvl(MSG::DEBUG) || (
msgLvl(MSG::INFO) && !shortprint);
590 TString optprint = opt;
591 optprint.ReplaceAll(
"short",
"");
599 <<
"; Binning size=" <<
m_Binning.size());
603 <<
"layer=" << l.first
604 <<
" nR=" << l.second.GetNbinsX()
605 <<
" nalpha=" << l.second.GetNbinsY());
609 TString prefix =
"- ";
610 for (
unsigned int ichain = 0; ichain <
size(); ++ichain) {
611 if (ichain == 0 && ichain !=
m_bin_start.front()) {
621 prefix = Form(
"%-2d", ibin);
631 chain()[ichain]->Print(opt + prefix);
635void TFCSEnergyAndHitGAN::Streamer(TBuffer &R__b) {
638 if (R__b.IsReading()) {
639 R__b.ReadClassBuffer(TFCSEnergyAndHitGAN::Class(),
this);
645 std::stringstream
sin;
647 auto config = lwt::parse_json_graph(sin);
648 m_graph =
new lwt::LightweightGraph(config);
650#ifndef __FastCaloSimStandAlone__
658 R__b.WriteClassBuffer(TFCSEnergyAndHitGAN::Class(),
this);
667#if defined(__FastCaloSimStandAlone__)
675 t->SetPtEtaPhiM(20000, 0.225, 0, 130);
681 e->set_IDCaloBoundary_eta(truth->Eta());
682 for (
int i = 0; i < 24; ++i) {
701 static constexpr int pid = 211;
703 int etaMax = etaMin + 5;
706 "/eos/atlas/atlascerngroupdisk/proj-simul/VoxalisationOutputs/nominal/"
707 "GAN_michele_normE_MaxE/input_for_service_new");
708 for (
int i = 0; i < 24; ++i)
711 Form(
"center%d", i), Form(
"center layer %d", i));
712 c->set_calosample(i);
713 c->setExtrapWeight(0.5);
714 c->setLevel(MSG::VERBOSE);
722 c->set_eta_min(etaMin / 100.0);
723 c->set_eta_max(etaMax / 100.0);
724 c->set_eta_nominal((etaMin + etaMax) / 200.0);
732 TFile *fGAN = TFile::Open(
"FCSGANtest.root",
"recreate");
737 fGAN = TFile::Open(
"FCSGANtest.root");
742 GAN2->
simulate(*simulstate, truth, extrapol);
#define ATH_MSG_VERBOSE(x)
#define ATH_MSG_WARNING(x)
double charge(const T &p)
ATLAS-specific HepMC functions.
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.
double charge(const T &p)