ATLAS Offline Software
TFCSEnergyAndHitGAN.cxx
Go to the documentation of this file.
1 /*
2  Copyright (C) 2002-2023 CERN for the benefit of the ATLAS collaboration
3 */
4 
11 #include "CxxUtils/as_const_ptr.h"
12 
13 #include "TFile.h"
14 
15 #include "HepPDT/ParticleData.hh"
16 #include "HepPDT/ParticleDataTable.hh"
17 
18 #include "CLHEP/Random/RandGauss.h"
19 #include "CLHEP/Random/RandFlat.h"
20 
21 #if defined(__FastCaloSimStandAlone__)
22 #include "CLHEP/Random/TRandomEngine.h"
23 #else
24 #include <CLHEP/Random/RanluxEngine.h>
25 #endif
26 
27 #include <iostream>
28 #include <fstream>
29 #include <limits>
30 
31 // LWTNN
32 #include "lwtnn/LightweightGraph.hh"
33 #include "lwtnn/parse_json.hh"
34 
35 // XML reader
36 #include <libxml/xmlmemory.h>
37 #include <libxml/parser.h>
38 #include <libxml/tree.h>
39 #include <libxml/xmlreader.h>
40 #include <libxml/xpath.h>
41 #include <libxml/xpathInternals.h>
42 
43 //=============================================
44 //======= TFCSEnergyAndHitGAN =========
45 //=============================================
46 
50 }
51 
53  if (m_input != nullptr) {
54  delete m_input;
55  }
56  if (m_graph != nullptr) {
57  delete m_graph;
58  }
59 }
60 
61 bool TFCSEnergyAndHitGAN::is_match_calosample(int calosample) const {
62  if (get_Binning().find(calosample) == get_Binning().cend())
63  return false;
64  if (get_Binning().at(calosample).GetNbinsX() == 1)
65  return false;
66  return true;
67 }
68 
69 unsigned int TFCSEnergyAndHitGAN::get_nr_of_init(unsigned int bin) const {
70  if (bin >= m_bin_ninit.size())
71  return 0;
72  return m_bin_ninit[bin];
73 }
74 
75 void TFCSEnergyAndHitGAN::set_nr_of_init(unsigned int bin, unsigned int ninit) {
76  if (bin >= m_bin_ninit.size()) {
77  m_bin_ninit.resize(bin + 1, 0);
78  m_bin_ninit.shrink_to_fit();
79  }
80  m_bin_ninit[bin] = ninit;
81 }
82 
83 // initialize lwtnn network
85  int pid, int etaMin, const std::string &FastCaloGANInputFolderName) {
86 
87  // initialize all necessary constants
88  // FIXME eventually all these could be stored in the .json file
89 
91  "Using FastCaloGANInputFolderName: " << FastCaloGANInputFolderName);
92  // get neural net JSON file as an std::istream object
93  int etaMax = etaMin + 5;
94 
96  set_pdgid(pid);
97  if (pid == 11)
98  add_pdgid(-pid);
99  if (pid == 211)
100  add_pdgid(-pid);
101  set_eta_min(etaMin / 100.0);
102  set_eta_max(etaMax / 100.0);
103  set_eta_nominal((etaMin + etaMax) / 200.0);
104 
105  std::string inputFile =
106  FastCaloGANInputFolderName + "/neural_net_" + std::to_string(pid) +
107  "_eta_" + std::to_string(etaMin) + "_" + std::to_string(etaMax) + ".json";
108  if (inputFile.empty()) {
109  ATH_MSG_ERROR("Could not find json file " << inputFile);
110  return false;
111  } else {
112  ATH_MSG_INFO("For pid: " << pid << " and eta " << etaMin << "-" << etaMax
113  << ", loading json file " << inputFile);
114  std::ifstream input(inputFile);
115  std::stringstream sin;
116  sin << input.rdbuf();
117  input.close();
118  // build the graph
120  m_graph = new lwt::LightweightGraph(config);
121  if (m_graph == nullptr) {
122  ATH_MSG_ERROR("Could not create LightWeightGraph from " << inputFile);
123  return false;
124  }
125  if (m_input != nullptr) {
126  delete m_input;
127  }
128  m_input = new std::string(sin.str());
129  }
130  m_GANLatentSize = 50;
131 
132  // Get all Binning histograms to store in memory
133  GetBinning(pid, (etaMin + etaMax) / 2, FastCaloGANInputFolderName);
134 
135  if (m_GANLatentSize == 0) {
136  ATH_MSG_ERROR("m_GANLatentSize uninitialized!");
137  return false;
138  }
139 
140  return true;
141 }
142 
144  int pid, int etaMid, const std::string &FastCaloGANInputFolderName) {
145  std::string xmlFullFileName = FastCaloGANInputFolderName + "/binning.xml";
146  ATH_MSG_DEBUG("Opening XML file in " << xmlFullFileName);
147 
148  std::vector<Binning> AllBinning;
149  std::vector<int> EtaMaxList;
150 
151  xmlDocPtr doc = xmlParseFile(xmlFullFileName.c_str());
152  for (xmlNodePtr nodeRoot = doc->children; nodeRoot != nullptr;
153  nodeRoot = nodeRoot->next) {
154  if (xmlStrEqual(nodeRoot->name, BAD_CAST "Bins")) {
155  for (xmlNodePtr nodeBin = nodeRoot->children; nodeBin != nullptr;
156  nodeBin = nodeBin->next) {
157  if (xmlStrEqual(nodeBin->name, BAD_CAST "Bin")) {
158  int nodePid = atof((const char *)xmlGetProp(nodeBin, BAD_CAST "pid"));
159  // int nodeEtaMin = atof( (const char*) xmlGetProp( nodeBin, BAD_CAST
160  // "etaMin" ) );
161  int nodeEtaMax =
162  atof((const char *)xmlGetProp(nodeBin, BAD_CAST "etaMax"));
163 
164  Binning binsInLayer;
165  bool correctentry = true;
166  if (nodePid != pid)
167  correctentry = false;
168 
169  for (xmlNodePtr nodeLayer = nodeBin->children; nodeLayer != nullptr;
170  nodeLayer = nodeLayer->next) {
171  if (xmlStrEqual(nodeLayer->name, BAD_CAST "Layer")) {
172  std::vector<double> edges;
173  std::string s(
174  (const char *)xmlGetProp(nodeLayer, BAD_CAST "r_edges"));
175 
176  std::istringstream ss(s);
177  std::string token;
178 
179  while (std::getline(ss, token, ',')) {
180  edges.push_back(atof(token.c_str()));
181  }
182 
183  int binsInAlpha = atof(
184  (const char *)xmlGetProp(nodeLayer, BAD_CAST "n_bin_alpha"));
185  int layer =
186  atof((const char *)xmlGetProp(nodeLayer, BAD_CAST "id"));
187 
188  if (correctentry)
189  ATH_MSG_DEBUG("nodepid=" << nodePid << " nodeEtaMax="
190  << nodeEtaMax << " Layer: " << layer
191  << " binsInAlpha: " << binsInAlpha
192  << " edges: " << s);
193 
194  std::string name = "hist_pid_" + std::to_string(nodePid) +
195  "_etaSliceNumber_" +
196  std::to_string(EtaMaxList.size()) + "_layer_" +
198  int xBins = edges.size() - 1;
199  if (xBins == 0) {
200  xBins = 1; // remove warning
201  edges.push_back(0);
202  edges.push_back(1);
203  }
204  binsInLayer[layer] =
205  TH2D(name.c_str(), name.c_str(), xBins, &edges[0],
206  binsInAlpha, -TMath::Pi(), TMath::Pi());
207  binsInLayer[layer].SetDirectory(nullptr);
208  }
209  }
210 
211  if (!correctentry)
212  continue;
213  AllBinning.push_back(binsInLayer);
214  EtaMaxList.push_back(nodeEtaMax);
215  }
216  }
217  }
218  }
219 
220  int index = 0;
221  for (int etaMax : EtaMaxList) {
222  if (etaMid < etaMax) {
223  m_Binning = AllBinning[index];
224  break;
225  }
226  index++;
227  }
228 
229  ATH_MSG_DEBUG("Done XML file");
230 }
231 
232 const std::string
234  const TFCSTruthState *,
235  const TFCSExtrapolationState *) const {
236  return std::string(
237  Form("layer=%d", simulstate.getAuxInfo<int>("GANlayer"_FCShash)));
238 }
239 
241  TFCSSimulationState &simulstate, const TFCSTruthState *truth,
242  NetworkInputs &inputs, double &trueEnergy) const {
243  // fill randomize latent space
244  // FIXME: should this really be momentum
245  trueEnergy = truth->P();
246  double randUniformZ = 0.;
247  // FIXME: make dependency on input particle eta, pdgid and energy
248  for (int i = 0; i < m_GANLatentSize; i++) {
249  randUniformZ = CLHEP::RandFlat::shoot(simulstate.randomEngine(), -1., 1.);
250  inputs["node_0"].insert(
251  std::pair<std::string, double>(std::to_string(i), randUniformZ));
252  }
253 
254  // ATH_MSG_INFO( "Check label: " <<trueEnergy <<" "<<std::pow(2,22)<<"
255  // "<<trueEnergy/std::pow(2,22));
256  inputs["node_1"].insert(
257  std::pair<std::string, double>("0", trueEnergy / (std::pow(2, 22))));
258 
259  return true;
260 }
261 
263  const TFCSTruthState *truth,
265  NetworkInputs inputs) const {
266  const int pdgId = truth->pdgid();
267  const float charge = HepPDT::ParticleID(pdgId).charge();
268 
269  float Einit;
270  const float Ekin = truth->Ekin();
271  if (OnlyScaleEnergy())
272  Einit = simulstate.E();
273  else
274  Einit = Ekin;
275 
276  ATH_MSG_VERBOSE("Momentum " << truth->P() << " pdgId " << truth->pdgid());
277 
278  // compute the network output values
279  // ATH_MSG_VERBOSE("neural network input = "<<inputs);
280  ATH_MSG_VERBOSE("input size " << inputs["node_0"].size());
281  NetworkOutputs outputs = m_graph->compute(inputs);
282  // ATH_MSG_VERBOSE("neural network output = "<<outputs);
283 
284  ATH_MSG_VERBOSE("neural network output size = " << outputs.size());
285 
286  const Binning &binsInLayers = m_Binning;
287  ATH_MSG_VERBOSE("Get binning");
288 
289  simulstate.set_E(0);
290 
291  int vox = 0;
292  for (const auto& element : binsInLayers) {
293  int layer = element.first;
294 
295  const TH2D *h = &element.second;
296  int xBinNum = h->GetNbinsX();
297  // If only one bin in r means layer is empty, no value should be added
298  if (xBinNum == 1) {
299  ATH_MSG_VERBOSE(" Layer "
300  << layer
301  << " has only one bin in r, this means is it not used, "
302  "skipping (this is needed to keep correct "
303  "syncronisation of voxel and layers)");
304  // delete h;
305  continue;
306  }
307 
308  ATH_MSG_VERBOSE(" Getting energy for Layer " << layer);
309 
310  int yBinNum = h->GetNbinsY();
311 
312  // First fill energies
313  for (int iy = 1; iy <= yBinNum; ++iy) {
314  for (int ix = 1; ix <= xBinNum; ++ix) {
315  double energyInVoxel = outputs["out_" + std::to_string(vox)];
316  ATH_MSG_VERBOSE(" Vox " << vox << " energy " << energyInVoxel
317  << " binx " << ix << " biny " << iy);
318 
319  if (energyInVoxel == 0) {
320  vox++;
321  continue;
322  }
323 
324  simulstate.add_E(layer, Einit * energyInVoxel);
325  vox++;
326  }
327  }
328  }
329 
330  for (unsigned int ichain = m_bin_start.back(); ichain < size(); ++ichain) {
331  ATH_MSG_DEBUG("now run for all bins: " << chain()[ichain]->GetName());
332  if (simulate_and_retry(chain()[ichain], simulstate, truth, extrapol) !=
333  FCSSuccess) {
334  return FCSFatal;
335  }
336  }
337 
338  vox = 0;
339  for (const auto& element : binsInLayers) {
340  int layer = element.first;
341  simulstate.setAuxInfo<int>("GANlayer"_FCShash, layer);
343 
344  const TH2D *h = &element.second;
345  int xBinNum = h->GetNbinsX();
346  // If only one bin in r means layer is empty, no value should be added
347  if (xBinNum == 1) {
348  ATH_MSG_VERBOSE(" Layer "
349  << layer
350  << " has only one bin in r, this means is it not used, "
351  "skipping (this is needed to keep correct "
352  "syncronisation of voxel and layers)");
353  // delete h;
354  continue;
355  }
356 
357  if (get_number_of_bins() > 0) {
358  const int bin = get_bin(simulstate, truth, extrapol);
359  if (bin >= 0 && bin < (int)get_number_of_bins()) {
360  for (unsigned int ichain = m_bin_start[bin];
361  ichain < TMath::Min(m_bin_start[bin] + get_nr_of_init(bin),
362  m_bin_start[bin + 1]);
363  ++ichain) {
364  ATH_MSG_DEBUG("for " << get_variable_text(simulstate, truth, extrapol)
365  << " run init " << get_bin_text(bin) << ": "
366  << chain()[ichain]->GetName());
367  if (chain()[ichain]->InheritsFrom(
368  TFCSLateralShapeParametrizationHitBase::Class())) {
371  if (sim->simulate_hit(hit, simulstate, truth, extrapol) !=
372  FCSSuccess) {
373  ATH_MSG_ERROR("error for "
374  << get_variable_text(simulstate, truth, extrapol)
375  << " run init " << get_bin_text(bin) << ": "
376  << chain()[ichain]->GetName());
377  return false;
378  }
379  } else {
380  ATH_MSG_ERROR("for "
381  << get_variable_text(simulstate, truth, extrapol)
382  << " run init " << get_bin_text(bin) << ": "
383  << chain()[ichain]->GetName()
384  << " does not inherit from "
385  "TFCSLateralShapeParametrizationHitBase");
386  return false;
387  }
388  }
389  } else {
390  ATH_MSG_WARNING("nothing to init for "
391  << get_variable_text(simulstate, truth, extrapol)
392  << ": " << get_bin_text(bin));
393  }
394  }
395 
396  int binResolution = 5;
397  if (layer == 1 || layer == 5) {
398  binResolution = 1;
399  }
400 
401  const double center_eta = hit.center_eta();
402  const double center_phi = hit.center_phi();
403  const double center_r = hit.center_r();
404  const double center_z = hit.center_z();
405 
406  ATH_MSG_VERBOSE(" Layer " << layer << " Extrap eta " << center_eta
407  << " phi " << center_phi << " R " << center_r);
408 
409  const float dist000 =
410  TMath::Sqrt(center_r * center_r + center_z * center_z);
411  const float eta_jakobi = TMath::Abs(2.0 * TMath::Exp(-center_eta) /
412  (1.0 + TMath::Exp(-2 * center_eta)));
413 
414  int nHitsAlpha;
415  int nHitsR;
416 
417  int yBinNum = h->GetNbinsY();
418 
419  // Now create hits
420  for (int iy = 1; iy <= yBinNum; ++iy) {
421  for (int ix = 1; ix <= xBinNum; ++ix) {
422 
423  double energyInVoxel = outputs["out_" + std::to_string(vox)];
424  ATH_MSG_VERBOSE(" Vox " << vox << " energy " << energyInVoxel
425  << " binx " << ix << " biny " << iy);
426 
427  if (energyInVoxel == 0) {
428  vox++;
429  continue;
430  }
431 
432  const TAxis *x = h->GetXaxis();
433  nHitsR = x->GetBinUpEdge(ix) - x->GetBinLowEdge(ix);
434  if (yBinNum == 1) {
435  // nbins in alpha depend on circumference lenght
436  double r = x->GetBinUpEdge(ix);
437  nHitsAlpha = ceil(2 * TMath::Pi() * r / binResolution);
438  } else {
439  // d = 2*r*sin (a/2r) this distance at the upper r must be 1mm for
440  // layer 1 or 5, 5mm otherwise.
441  const TAxis *y = h->GetYaxis();
442  double angle = y->GetBinUpEdge(iy) - y->GetBinLowEdge(iy);
443  double r = x->GetBinUpEdge(ix);
444  double d = 2 * r * sin(angle / 2 * r);
445  nHitsAlpha = ceil(d / binResolution);
446  }
447 
448  nHitsAlpha = std::min(10, std::max(1, nHitsAlpha));
449  nHitsR = std::min(10, std::max(1, nHitsR));
450 
451  for (int ir = 0; ir < nHitsR; ++ir) {
452  const TAxis *x = h->GetXaxis();
453  double r =
454  x->GetBinLowEdge(ix) + x->GetBinWidth(ix) / (nHitsR + 1) * ir;
455 
456  for (int ialpha = 0; ialpha < nHitsAlpha; ++ialpha) {
457  double alpha;
458  if (yBinNum == 1) {
459  alpha = CLHEP::RandFlat::shoot(simulstate.randomEngine(), -M_PI,
460  M_PI);
461  } else {
462  const TAxis *y = h->GetYaxis();
463  alpha = y->GetBinLowEdge(iy) +
464  y->GetBinWidth(iy) / (nHitsAlpha + 1) * ialpha;
465  }
466 
467  hit.reset();
468  hit.E() = Einit * energyInVoxel / (nHitsAlpha * nHitsR);
469 
470  if (layer <= 20) {
471  float delta_eta_mm = r * cos(alpha);
472  float delta_phi_mm = r * sin(alpha);
473 
474  ATH_MSG_VERBOSE("delta_eta_mm " << delta_eta_mm
475  << " delta_phi_mm "
476  << delta_phi_mm);
477 
478  // Particles with negative eta are expected to have the same shape
479  // as those with positive eta after transformation: delta_eta -->
480  // -delta_eta
481  if (center_eta < 0.)
482  delta_eta_mm = -delta_eta_mm;
483  // We derive the shower shapes for electrons and positively charged hadrons.
484  // Particle with the opposite charge are expected to have the same shower shape
485  // after the transformation: delta_phi --> -delta_phi
486  if ((charge < 0. && pdgId!=11) || pdgId==-11)
487  delta_phi_mm = -delta_phi_mm;
488 
489  const float delta_eta = delta_eta_mm / eta_jakobi / dist000;
490  const float delta_phi = delta_phi_mm / center_r;
491 
492  hit.eta() = center_eta + delta_eta;
493  hit.phi() = center_phi + delta_phi;
494 
495  ATH_MSG_VERBOSE(" Hit eta " << hit.eta() << " phi " << hit.phi()
496  << " layer " << layer);
497  } else { // FCAL is in (x,y,z)
498  const float hit_r = r * cos(alpha) + center_r;
499  float delta_phi = r * sin(alpha) / center_r;
500 
501  // We derive the shower shapes for electrons and positively charged hadrons.
502  // Particle with the opposite charge are expected to have the same shower shape
503  // after the transformation: delta_phi --> -delta_phi
504  if ((charge < 0. && pdgId!=11) || pdgId==-11)
505  delta_phi = -delta_phi;
506  const float hit_phi = delta_phi + center_phi;
507  hit.x() = hit_r * cos(hit_phi);
508  hit.y() = hit_r * sin(hit_phi);
509  hit.z() = center_z;
510  ATH_MSG_VERBOSE(" Hit x " << hit.x() << " y " << hit.y()
511  << " layer " << layer);
512  }
513 
514  if (get_number_of_bins() > 0) {
515  const int bin = get_bin(simulstate, truth, extrapol);
516  if (bin >= 0 && bin < (int)get_number_of_bins()) {
517  for (unsigned int ichain =
519  ichain < m_bin_start[bin + 1]; ++ichain) {
521  "for " << get_variable_text(simulstate, truth, extrapol)
522  << " run " << get_bin_text(bin) << ": "
523  << chain()[ichain]->GetName());
524  if (chain()[ichain]->InheritsFrom(
525  TFCSLateralShapeParametrizationHitBase::Class())) {
528  *)(chain()[ichain]);
529  if (sim->simulate_hit(hit, simulstate, truth, extrapol) !=
530  FCSSuccess) {
532  "error for "
533  << get_variable_text(simulstate, truth, extrapol)
534  << " run init " << get_bin_text(bin) << ": "
535  << chain()[ichain]->GetName());
536  return false;
537  }
538  } else {
540  "for " << get_variable_text(simulstate, truth, extrapol)
541  << " run init " << get_bin_text(bin) << ": "
542  << chain()[ichain]->GetName()
543  << " does not inherit from "
544  "TFCSLateralShapeParametrizationHitBase");
545  return false;
546  }
547  }
548  } else {
550  "nothing to do for "
551  << get_variable_text(simulstate, truth, extrapol) << ": "
552  << get_bin_text(bin));
553  }
554  } else {
555  ATH_MSG_WARNING("no bins defined, is this intended?");
556  }
557  }
558  }
559  vox++;
560  }
561  }
562 
563  ATH_MSG_VERBOSE("Number of voxels " << vox);
564 
565  // delete h;
566  ATH_MSG_VERBOSE("Done layer " << layer);
567  }
568  if (simulstate.E() > std::numeric_limits<double>::epsilon()) {
569  for (int ilayer = 0; ilayer < CaloCell_ID_FCS::MaxSample; ++ilayer) {
570  simulstate.set_Efrac(ilayer, simulstate.E(ilayer) / simulstate.E());
571  }
572  }
573 
574  ATH_MSG_VERBOSE("Done particle");
575 
576  return true;
577 }
578 
581  const TFCSTruthState *truth,
582  const TFCSExtrapolationState *extrapol) const {
583  for (unsigned int ichain = 0; ichain < m_bin_start[0]; ++ichain) {
584  ATH_MSG_DEBUG("now run for all bins: " << chain()[ichain]->GetName());
585  if (simulate_and_retry(chain()[ichain], simulstate, truth, extrapol) !=
586  FCSSuccess) {
587  return FCSFatal;
588  }
589  }
590 
591  // Compute all inputs to the network
593  double trueEnergy;
594  ATH_MSG_VERBOSE("Get Inputs");
595  if (!fillFastCaloGanNetworkInputs(simulstate, truth, inputs, trueEnergy)) {
596  ATH_MSG_WARNING("Could not initialize network ");
597  // bail out but do not stop the job
598  return FCSSuccess;
599  }
600 
601  ATH_MSG_VERBOSE("Fill Energies");
602  if (!fillEnergy(simulstate, truth, extrapol, inputs)) {
603  ATH_MSG_WARNING("Could not fill energies ");
604  // bail out but do not stop the job
605  return FCSSuccess;
606  }
607 
608  return FCSSuccess;
609 }
610 
611 void TFCSEnergyAndHitGAN::Print(Option_t *option) const {
613  TString opt(option);
614  bool shortprint = opt.Index("short") >= 0;
615  bool longprint = msgLvl(MSG::DEBUG) || (msgLvl(MSG::INFO) && !shortprint);
616  TString optprint = opt;
617  optprint.ReplaceAll("short", "");
618 
619  if (longprint) {
620  ATH_MSG_INFO(optprint << " "
621  << "Graph=" << CxxUtils::as_const_ptr(m_graph)
622  << "; json input=" << CxxUtils::as_const_ptr(m_input)
623  << "; free mem=" << GANfreemem()
624  << "; latent space=" << m_GANLatentSize
625  << "; Binning size=" << m_Binning.size());
626  for (const auto &l : m_Binning)
627  if (is_match_calosample(l.first)) {
628  ATH_MSG_INFO(optprint << " "
629  << "layer=" << l.first
630  << " nR=" << l.second.GetNbinsX()
631  << " nalpha=" << l.second.GetNbinsY());
632  }
633  }
634 
635  TString prefix = "- ";
636  for (unsigned int ichain = 0; ichain < size(); ++ichain) {
637  if (ichain == 0 && ichain != m_bin_start.front()) {
638  prefix = "> ";
639  if (longprint)
640  ATH_MSG_INFO(optprint << prefix << "Run for all bins");
641  }
642  for (unsigned int ibin = 0; ibin < get_number_of_bins(); ++ibin) {
643  if (ichain == m_bin_start[ibin]) {
644  if (ibin < get_number_of_bins() - 1)
645  if (ichain == m_bin_start[ibin + 1])
646  continue;
647  prefix = Form("%-2d", ibin);
648  if (longprint)
649  ATH_MSG_INFO(optprint << prefix << "Run for " << get_bin_text(ibin));
650  }
651  }
652  if (ichain == m_bin_start.back()) {
653  prefix = "< ";
654  if (longprint)
655  ATH_MSG_INFO(optprint << prefix << "Run for all bins");
656  }
657  chain()[ichain]->Print(opt + prefix);
658  }
659 }
660 
661 void TFCSEnergyAndHitGAN::Streamer(TBuffer &R__b) {
662  // Stream an object of class TFCSEnergyAndHitGAN
663 
664  if (R__b.IsReading()) {
665  R__b.ReadClassBuffer(TFCSEnergyAndHitGAN::Class(), this);
666  if (m_graph != nullptr) {
667  delete m_graph;
668  m_graph = nullptr;
669  }
670  if (m_input) {
671  std::stringstream sin;
672  sin.str(*m_input);
674  m_graph = new lwt::LightweightGraph(config);
675  }
676 #ifndef __FastCaloSimStandAlone__
677  // When running inside Athena, delete config to free the memory
678  if (GANfreemem()) {
679  delete m_input;
680  m_input = nullptr;
681  }
682 #endif
683  } else {
684  R__b.WriteClassBuffer(TFCSEnergyAndHitGAN::Class(), this);
685  }
686 }
687 
689  const TFCSTruthState *truth,
691  if (!simulstate) {
692  simulstate = new TFCSSimulationState();
693 #if defined(__FastCaloSimStandAlone__)
694  simulstate->setRandomEngine(new CLHEP::TRandomEngine());
695 #else
696  simulstate->setRandomEngine(new CLHEP::RanluxEngine());
697 #endif
698  }
699  if (!truth) {
701  t->SetPtEtaPhiM(20000, 0.225, 0, 130);
702  t->set_pdgid(211);
703  truth = t;
704  }
705  if (!extrapol) {
707  e->set_IDCaloBoundary_eta(truth->Eta());
708  for (int i = 0; i < 24; ++i) {
709  e->set_eta(i, TFCSExtrapolationState::SUBPOS_ENT, truth->Eta());
710  e->set_eta(i, TFCSExtrapolationState::SUBPOS_EXT, truth->Eta());
711  e->set_eta(i, TFCSExtrapolationState::SUBPOS_MID, truth->Eta());
712  e->set_phi(i, TFCSExtrapolationState::SUBPOS_ENT, 0);
713  e->set_phi(i, TFCSExtrapolationState::SUBPOS_EXT, 0);
714  e->set_phi(i, TFCSExtrapolationState::SUBPOS_MID, 0);
715  e->set_r(i, TFCSExtrapolationState::SUBPOS_ENT, 1500 + i * 10);
716  e->set_r(i, TFCSExtrapolationState::SUBPOS_EXT, 1510 + i * 10);
717  e->set_r(i, TFCSExtrapolationState::SUBPOS_MID, 1505 + i * 10);
718  e->set_z(i, TFCSExtrapolationState::SUBPOS_ENT, 3500 + i * 10);
719  e->set_z(i, TFCSExtrapolationState::SUBPOS_EXT, 3510 + i * 10);
720  e->set_z(i, TFCSExtrapolationState::SUBPOS_MID, 3505 + i * 10);
721  }
722  extrapol = e;
723  }
724 
725  TFCSEnergyAndHitGAN GAN("GAN", "GAN");
726  GAN.setLevel(MSG::VERBOSE);
727  int pid = 211;
728  int etaMin = 20;
729  int etaMax = etaMin + 5;
730  GAN.initializeNetwork(
731  pid, etaMin,
732  "/eos/atlas/atlascerngroupdisk/proj-simul/VoxalisationOutputs/nominal/"
733  "GAN_michele_normE_MaxE/input_for_service_new");
734  for (int i = 0; i < 24; ++i)
735  if (GAN.is_match_calosample(i)) {
737  Form("center%d", i), Form("center layer %d", i));
738  c->set_calosample(i);
739  c->setExtrapWeight(0.5);
740  c->setLevel(MSG::VERBOSE);
741  c->set_pdgid(pid);
742  if (pid == 11)
743  c->add_pdgid(-pid);
744  if (pid == 211)
745  c->add_pdgid(-pid);
746  c->set_eta_min(etaMin / 100.0);
747  c->set_eta_max(etaMax / 100.0);
748  c->set_eta_nominal((etaMin + etaMax) / 200.0);
749 
750  GAN.push_back_in_bin(c, i);
751  GAN.set_nr_of_init(i, 1);
752  }
753 
754  GAN.Print();
755 
756  TFile *fGAN = TFile::Open("FCSGANtest.root", "recreate");
757  GAN.Write();
758  fGAN->ls();
759  fGAN->Close();
760 
761  fGAN = TFile::Open("FCSGANtest.root");
762  TFCSEnergyAndHitGAN *GAN2 = (TFCSEnergyAndHitGAN *)(fGAN->Get("GAN"));
763  GAN2->Print();
764 
765  GAN2->setLevel(MSG::DEBUG);
766  GAN2->simulate(*simulstate, truth, extrapol);
767  simulstate->Print();
768 }
TFCSCenterPositionCalculation.h
beamspotman.r
def r
Definition: beamspotman.py:676
FCSReturnCode
FCSReturnCode
Base class for all FastCaloSim parametrizations Functionality in derivde classes is provided through ...
Definition: TFCSParametrizationBase.h:41
TFCSEnergyAndHitGAN::NetworkInputs
std::map< std::string, std::map< std::string, double > > NetworkInputs
Definition: TFCSEnergyAndHitGAN.h:21
TFCSLateralShapeParametrizationHitBase::simulate_hit
virtual FCSReturnCode simulate_hit(Hit &hit, TFCSSimulationState &simulstate, const TFCSTruthState *truth, const TFCSExtrapolationState *extrapol)
simulated one hit position with some energy.
Definition: TFCSLateralShapeParametrizationHitBase.cxx:50
TFCSSimulationState::getAuxInfo
const T getAuxInfo(std::uint32_t index) const
Definition: TFCSSimulationState.h:161
TFCSParametrizationBinnedChain::get_bin_text
virtual const std::string get_bin_text(int bin) const
print the range of a bin; for bin -1, print the allowed range
Definition: TFCSParametrizationBinnedChain.cxx:60
python.SystemOfUnits.s
int s
Definition: SystemOfUnits.py:131
max
#define max(a, b)
Definition: cfImp.cxx:41
TFCSEnergyAndHitGAN::fillFastCaloGanNetworkInputs
bool fillFastCaloGanNetworkInputs(TFCSSimulationState &simulstate, const TFCSTruthState *truth, NetworkInputs &inputs, double &trueEnergy) const
Definition: TFCSEnergyAndHitGAN.cxx:240
PowhegControl_ttHplus_NLO.ss
ss
Definition: PowhegControl_ttHplus_NLO.py:83
ATH_MSG_INFO
#define ATH_MSG_INFO(x)
Definition: AthMsgStreamMacros.h:31
find
std::string find(const std::string &s)
return a remapped string
Definition: hcg.cxx:135
TFCSEnergyAndHitGAN::initializeNetwork
bool initializeNetwork(int pid, int etaMin, const std::string &FastCaloGANInputFolderName)
Definition: TFCSEnergyAndHitGAN.cxx:84
index
Definition: index.py:1
hist_file_dump.d
d
Definition: hist_file_dump.py:137
TFCSEnergyAndHitGAN::Binning
std::map< int, TH2D > Binning
Definition: TFCSEnergyAndHitGAN.h:23
TFCSParametrization::add_pdgid
virtual void add_pdgid(int id)
Definition: TFCSParametrization.cxx:35
conifer::pow
constexpr int pow(int x)
Definition: conifer.h:20
as_const_ptr.h
Helper for getting a const version of a pointer.
TFCSCenterPositionCalculation
Definition: TFCSCenterPositionCalculation.h:11
TFCSEnergyAndHitGAN::GetBinning
void GetBinning(int pid, int etaMax, const std::string &FastCaloGANInputFolderName)
Definition: TFCSEnergyAndHitGAN.cxx:143
M_PI
#define M_PI
Definition: ActiveFraction.h:11
TFCSParametrizationBinnedChain::push_back_in_bin
virtual void push_back_in_bin(TFCSParametrizationBase *param, unsigned int bin)
Definition: TFCSParametrizationBinnedChain.cxx:31
bin
Definition: BinsDiffFromStripMedian.h:43
TFCSEnergyAndHitGAN::get_variable_text
virtual const std::string get_variable_text(TFCSSimulationState &simulstate, const TFCSTruthState *, const TFCSExtrapolationState *) const override
Definition: TFCSEnergyAndHitGAN.cxx:233
TFCSEnergyAndHitGAN::NetworkOutputs
std::map< std::string, double > NetworkOutputs
Definition: TFCSEnergyAndHitGAN.h:22
xAOD::etaMax
etaMax
Definition: HIEventShape_v2.cxx:46
TFCSEnergyAndHitGAN::set_nr_of_init
void set_nr_of_init(unsigned int bin, unsigned int ninit)
Definition: TFCSEnergyAndHitGAN.cxx:75
TFCSExtrapolationState::SUBPOS_ENT
@ SUBPOS_ENT
Definition: TFCSExtrapolationState.h:21
UploadAMITag.l
list l
Definition: UploadAMITag.larcaf.py:158
TFCSExtrapolationState
Definition: TFCSExtrapolationState.h:13
TFCSSimulationState::randomEngine
CLHEP::HepRandomEngine * randomEngine()
Definition: TFCSSimulationState.h:36
TFCSLateralShapeParametrizationHitBase::Hit
Definition: TFCSLateralShapeParametrizationHitBase.h:42
TFCSEnergyAndHitGAN::~TFCSEnergyAndHitGAN
virtual ~TFCSEnergyAndHitGAN()
Definition: TFCSEnergyAndHitGAN.cxx:52
read_hist_ntuple.t
t
Definition: read_hist_ntuple.py:5
drawFromPickle.cos
cos
Definition: drawFromPickle.py:36
TFCSExtrapolationState::SUBPOS_MID
@ SUBPOS_MID
Definition: TFCSExtrapolationState.h:20
RunActsMaterialValidation.extrapol
extrapol
Definition: RunActsMaterialValidation.py:90
ATH_MSG_VERBOSE
#define ATH_MSG_VERBOSE(x)
Definition: AthMsgStreamMacros.h:28
TFCSEnergyAndHitGAN::get_Binning
const Binning & get_Binning() const
Definition: TFCSEnergyAndHitGAN.h:68
TFCSEnergyAndHitGAN
Definition: TFCSEnergyAndHitGAN.h:18
x
#define x
TFCSExtrapolationState::SUBPOS_EXT
@ SUBPOS_EXT
Definition: TFCSExtrapolationState.h:22
postInclude.inputs
inputs
Definition: postInclude.SortInput.py:15
PowhegPy8EG_H2a.pdgId
dictionary pdgId
Definition: PowhegPy8EG_H2a.py:128
TFCSParametrization::set_eta_max
virtual void set_eta_max(double max)
Definition: TFCSParametrization.cxx:53
TFCSEnergyAndHitGAN::m_GANLatentSize
int m_GANLatentSize
Definition: TFCSEnergyAndHitGAN.h:110
TFCSEnergyAndHitGAN::set_GANfreemem
void set_GANfreemem()
Definition: TFCSEnergyAndHitGAN.h:42
config
Definition: PhysicsAnalysis/AnalysisCommon/AssociationUtils/python/config.py:1
TFCSLateralShapeParametrizationHitBase
Definition: TFCSLateralShapeParametrizationHitBase.h:13
TFCSParametrization::set_pdgid
virtual void set_pdgid(int id)
Definition: TFCSParametrization.cxx:28
TFCSParametrizationBinnedChain::get_number_of_bins
virtual unsigned int get_number_of_bins() const
Definition: TFCSParametrizationBinnedChain.h:22
TFCSParametrizationBinnedChain
Definition: TFCSParametrizationBinnedChain.h:10
TFCSSimulationState::add_E
void add_E(int sample, double Esample)
Definition: TFCSSimulationState.h:53
TFCSLateralShapeParametrizationHitBase.h
CaloCell_ID_FCS::MaxSample
@ MaxSample
Definition: FastCaloSim_CaloCell_ID.h:47
ATH_MSG_ERROR
#define ATH_MSG_ERROR(x)
Definition: AthMsgStreamMacros.h:33
TFCSEnergyAndHitGAN::get_nr_of_init
unsigned int get_nr_of_init(unsigned int bin) const
Definition: TFCSEnergyAndHitGAN.cxx:69
CaloCondBlobAlgs_fillNoiseFromASCII.inputFile
string inputFile
Definition: CaloCondBlobAlgs_fillNoiseFromASCII.py:17
TFCSEnergyAndHitGAN::simulate
virtual FCSReturnCode simulate(TFCSSimulationState &simulstate, const TFCSTruthState *truth, const TFCSExtrapolationState *extrapol) const override
Method in all derived classes to do some simulation.
Definition: TFCSEnergyAndHitGAN.cxx:580
lumiFormat.i
int i
Definition: lumiFormat.py:92
TFCSParametrizationChain::chain
const Chain_t & chain() const
Definition: TFCSParametrizationChain.h:53
ATH_MSG_DEBUG
#define ATH_MSG_DEBUG(x)
Definition: AthMsgStreamMacros.h:29
angle
double angle(const GeoTrf::Vector2D &a, const GeoTrf::Vector2D &b)
Definition: TRTDetectorFactory_Full.cxx:73
TFCSTruthState::Ekin
double Ekin() const
Definition: TFCSTruthState.h:26
TRT::Hit::layer
@ layer
Definition: HitInfo.h:79
covarianceTool.title
title
Definition: covarianceTool.py:542
PlotPulseshapeFromCool.input
input
Definition: PlotPulseshapeFromCool.py:106
TFCSEnergyAndHitGAN::get_bin
virtual int get_bin(TFCSSimulationState &simulstate, const TFCSTruthState *, const TFCSExtrapolationState *) const override
use the layer to be done as binning of the GAN chain
Definition: TFCSEnergyAndHitGAN.h:57
ParticleGun_EoverP_Config.pid
pid
Definition: ParticleGun_EoverP_Config.py:62
checkCorrelInHIST.prefix
dictionary prefix
Definition: checkCorrelInHIST.py:391
TFCSEnergyAndHitGAN.h
jobOptions.ParticleID
ParticleID
Definition: jobOptions.decayer.py:85
TFCSParametrizationBase::Print
void Print(Option_t *option="") const
Print object information.
Definition: TFCSParametrizationBase.cxx:52
TH2D
Definition: rootspy.cxx:430
TFCSSimulationState::Print
void Print(Option_t *option="") const
Definition: TFCSSimulationState.cxx:40
FCSFatal
@ FCSFatal
Definition: TFCSParametrizationBase.h:41
FCSSuccess
@ FCSSuccess
Definition: TFCSParametrizationBase.h:41
TFCSEnergyAndHitGAN::is_match_calosample
virtual bool is_match_calosample(int calosample) const override
Definition: TFCSEnergyAndHitGAN.cxx:61
TFCSEnergyAndHitGAN::fillEnergy
bool fillEnergy(TFCSSimulationState &simulstate, const TFCSTruthState *truth, const TFCSExtrapolationState *extrapol, NetworkInputs inputs) const
Definition: TFCSEnergyAndHitGAN.cxx:262
python.CreateTierZeroArgdict.outputs
outputs
Definition: CreateTierZeroArgdict.py:189
TFCSEnergyAndHitGAN::m_Binning
Binning m_Binning
Do not persistify.
Definition: TFCSEnergyAndHitGAN.h:106
CxxUtils::atof
double atof(std::string_view str)
Converts a string into a double / float.
Definition: Control/CxxUtils/Root/StringUtils.cxx:91
min
#define min(a, b)
Definition: cfImp.cxx:40
merge_scale_histograms.doc
string doc
Definition: merge_scale_histograms.py:9
TFCSParametrizationBase::reset_match_all_pdgid
virtual void reset_match_all_pdgid()
Definition: TFCSParametrizationBase.h:84
name
std::string name
Definition: Control/AthContainers/Root/debug.cxx:195
pmontree.opt
opt
Definition: pmontree.py:16
TFCSParametrization::set_eta_nominal
virtual void set_eta_nominal(double min)
Definition: TFCSParametrization.cxx:47
ActsTrk::to_string
std::string to_string(const DetectorType &type)
Definition: GeometryDefs.h:34
ISF_FCS::MLogging::setLevel
virtual void setLevel(MSG::Level lvl)
Update outputlevel.
Definition: MLogging.cxx:105
TFCSSimulationState::setAuxInfo
void setAuxInfo(std::uint32_t index, const T &val)
Definition: TFCSSimulationState.h:168
CxxUtils::as_const_ptr
const T * as_const_ptr(const T *p)
Helper for getting a const version of a pointer.
Definition: as_const_ptr.h:32
TFCSEnergyAndHitGAN::unit_test
static void unit_test(TFCSSimulationState *simulstate=nullptr, const TFCSTruthState *truth=nullptr, const TFCSExtrapolationState *extrapol=nullptr)
Definition: TFCSEnergyAndHitGAN.cxx:688
plotBeamSpotVxVal.bin
int bin
Definition: plotBeamSpotVxVal.py:83
TFCSSimulationState::set_E
void set_E(int sample, double Esample)
Definition: TFCSSimulationState.h:48
charge
double charge(const T &p)
Definition: AtlasPID.h:494
TFCSTruthState::pdgid
int pdgid() const
Definition: TFCSTruthState.h:25
TFCSEnergyAndHitGAN::Print
virtual void Print(Option_t *option="") const override
Definition: TFCSEnergyAndHitGAN.cxx:611
TFCSSimulationState::setRandomEngine
void setRandomEngine(CLHEP::HepRandomEngine *engine)
Definition: TFCSSimulationState.h:37
ir
int ir
counter of the current depth
Definition: fastadd.cxx:49
lwtDev::parse_json_graph
GraphConfig parse_json_graph(std::istream &json)
Definition: parse_json.cxx:71
DeMoScan.index
string index
Definition: DeMoScan.py:362
TFCSEnergyAndHitGAN::OnlyScaleEnergy
bool OnlyScaleEnergy() const
Definition: TFCSEnergyAndHitGAN.h:52
DiTauMassTools::MaxHistStrategyV2::e
e
Definition: PhysicsAnalysis/TauID/DiTauMassTools/DiTauMassTools/HelperFunctions.h:26
LArCellBinning.etaMin
etaMin
Definition: LArCellBinning.py:84
TFCSTruthState.h
y
#define y
h
ATH_MSG_WARNING
#define ATH_MSG_WARNING(x)
Definition: AthMsgStreamMacros.h:32
TFCSExtrapolationState.h
TFCSEnergyAndHitGAN::m_input
std::string * m_input
Definition: TFCSEnergyAndHitGAN.h:103
eFEXNTuple.delta_phi
def delta_phi(phi1, phi2)
Definition: eFEXNTuple.py:15
TFCSEnergyAndHitGAN::TFCSEnergyAndHitGAN
TFCSEnergyAndHitGAN(const char *name=nullptr, const char *title=nullptr)
Definition: TFCSEnergyAndHitGAN.cxx:47
DEBUG
#define DEBUG
Definition: page_access.h:11
TFCSParametrizationChain::simulate_and_retry
FCSReturnCode simulate_and_retry(TFCSParametrizationBase *parametrization, TFCSSimulationState &simulstate, const TFCSTruthState *truth, const TFCSExtrapolationState *extrapol) const
TFCSEnergyAndHitGAN::GANfreemem
bool GANfreemem() const
Definition: TFCSEnergyAndHitGAN.h:41
TFCSParametrization::set_eta_min
virtual void set_eta_min(double min)
Definition: TFCSParametrization.cxx:51
TFCSSimulationState::E
double E() const
Definition: TFCSSimulationState.h:42
TFCSSimulationState.h
python.Constants.VERBOSE
int VERBOSE
Definition: Control/AthenaCommon/python/Constants.py:14
drawFromPickle.sin
sin
Definition: drawFromPickle.py:36
TFCSEnergyAndHitGAN::m_bin_ninit
std::vector< int > m_bin_ninit
Definition: TFCSEnergyAndHitGAN.h:97
TFCSTruthState
Definition: TFCSTruthState.h:13
python.compressB64.c
def c
Definition: compressB64.py:93
TFCSSimulationState
Definition: TFCSSimulationState.h:32
TFCSEnergyAndHitGAN::m_graph
lwt::LightweightGraph * m_graph
Definition: TFCSEnergyAndHitGAN.h:104
MakeTH3DFromTH2Ds.xBins
list xBins
Definition: MakeTH3DFromTH2Ds.py:76
ISF_FCS::MLogging::msgLvl
bool msgLvl(const MSG::Level lvl) const
Check whether the logging system is active at the provided verbosity level.
Definition: MLogging.h:222
TFCSParametrizationBinnedChain::m_bin_start
std::vector< unsigned int > m_bin_start
Contains the index where the TFCSParametrizationBase* instances to run for a given bin start.
Definition: TFCSParametrizationBinnedChain.h:53
TFCSSimulationState::set_Efrac
void set_Efrac(int sample, double Efracsample)
Definition: TFCSSimulationState.h:49
TFCSParametrizationChain::size
virtual unsigned int size() const override
Some derived classes have daughter instances of TFCSParametrizationBase objects The size() and operat...
Definition: TFCSParametrizationChain.h:41