# Tutorial on CEPCSW simulation
Tao Lin
IHEP
17 Sept. 2020
[CEPCSW Tutorial, 2020, IHEP](https://indico.ihep.ac.cn/event/12341/other-view?view=standard)
---
## What will learn in this Tutorial?
* As Users
* Run a simple simulation job in CEPCSW
* Understand and Customize the simulation
* Analyze the simulation output
* As Developers
* Understand the simulation framework
* Learn basics on Geant4 simulation
* Simulate with different detector options
* Note: the emoji :writing_hand: means exercises
---
### CEPCSW Simulation Framework

* The simulation chain is driven by Gaudi.
* Detector description is from DD4hep.
* Event Data Model is in EDM4hep format.
* Detector response is done by Geant4.
----
#### Code is on GitHub
* Detector description: [See Detector](https://github.com/cepc/CEPCSW/tree/master/Detector)
* Event generator interface: [See Generator](https://github.com/cepc/CEPCSW/tree/master/Generator)
* Detector simulation: [See Simulation](https://github.com/cepc/CEPCSW/tree/master/Simulation)
* [DetSimInterface: Gaudi Tool interface](https://github.com/cepc/CEPCSW/tree/master/Simulation/DetSimInterface)
* [DetSimCore: integrate Gaudi and Geant4](https://github.com/cepc/CEPCSW/tree/master/Simulation/DetSimCore)
* [DetSimGeom: integrate with DD4hep](https://github.com/cepc/CEPCSW/tree/master/Simulation/DetSimGeom)
* [DetSimAna: collect data from Geant4](https://github.com/cepc/CEPCSW/tree/master/Simulation/DetSimAna)
* [DetSimSD: detector response](https://github.com/cepc/CEPCSW/tree/master/Simulation/DetSimSD)
* Job options: [See Examples/options](https://github.com/cepc/CEPCSW/tree/master/Examples/options)
---
### Run simulation in CEPCSW
* The simulation is run by following command:
```bash
$ ./run.sh Examples/options/tut_detsim.py
```
* The job option: `Examples/options/tut_detsim.py`. <!-- .element: style="color:yellow; " -->
* :writing_hand: copy the job option into your current directory. Edit your job option in the later exercises.
```bash
$ cp Examples/options/tut_detsim.py my_detsim.py
```
---
### What's inside the job option?
* Random Number Service
* Use `Seeds` option to control the random number sequences.
* Event Data Service and PODIO writer
* Geometry Service
* Different detector options could be loaded here via `compact` option.
* Physics generator algorithm
* Detector simulation algorithm
---
#### Save detector response into ROOT file
```python
from Configurables import PodioOutput
out = PodioOutput("outputalg")
out.filename = "test-detsim10-seed42.root"
out.outputCommands = ["keep *"]
```
* The EDM4hep format is used in the detector response.
* All the collections created in simulation will be saved.
* :writing_hand: modify the output file name.
---
#### Control how many events to be simulated
```python
from Configurables import ApplicationMgr
ApplicationMgr( TopAlg = [genalg, detsimalg, out],
EvtSel = 'NONE',
EvtMax = 10,
ExtSvc = [rndmengine, dsvc, geosvc],
)
```
* :writing_hand: modify the `EvtMax` property and check the entries in the output.
---
#### Random Number
```python
from Configurables import RndmGenSvc, HepRndm__Engine_CLHEP__RanluxEngine_
# rndmengine = HepRndm__Engine_CLHEP__RanluxEngine_() # The default engine in Gaudi
rndmengine = HepRndm__Engine_CLHEP__HepJamesRandom_() # The default engine in Geant4
rndmengine.SetSingleton = True
rndmengine.Seeds = [42]
```
* Seed is used to initialize the state of the random number engine.
* If two job set the same seed, the outputs will be same.
* :writing_hand: modify the seed and see the difference.
---
#### Geometry / Detector Description
```python
geometry_option = "CepC_v4-onlyVXD.xml"
geometry_path = os.path.join(os.getenv("DETCEPCV4ROOT"),
"compact", geometry_option)
from Configurables import GeoSvc
geosvc = GeoSvc("GeoSvc")
geosvc.compact = geometry_path
```
* The compact file is in XML format, which describes the detector.
* :writing_hand: change the geometry path and run simulation again.
```
geometry_path = "Detector/DetEcalMatrix/compact/det.xml"
```
---
#### Customize primary particles
##### Particle Gun
```python
gun = GtGunTool("GtGunTool")
gun.Particles = ["pi+", "pi-"]
gun.EnergyMins = [100., 100] # GeV
gun.EnergyMaxs = [100., 100] # GeV
gun.ThetaMins = [0, 0] # deg
gun.ThetaMaxs = [180., 180] # deg
gun.PhiMins = [0., 0.] # deg
gun.PhiMaxs = [360., 360.] # deg
```
* Particle name can be found in [`$ROOTSYS/etc/pdg_table.txt`](https://github.com/root-project/root/blob/master/etc/pdg_table.txt)
* :writing_hand: change the particles, energies and directions.
----
##### Event Generators
```python
stdheprdr = StdHepRdr("StdHepRdr")
stdheprdr.Input = "/cefs/data/stdhep/CEPC250/2fermions/E250.Pbhabha.e0.p0.whizard195/bhabha.e0.p0.00001.stdhep"
genalg = GenAlgo("GenAlgo")
genalg.GenTools = ["StdHepRdr"]
```
* There are several readers to read the output of event generators in different formats
* StdHep: `StdHepRdr`, lcio: `SLCIORdr`, HepMC: `HepMCRdr`.
* :writing_hand: use the different readers to load different samples.
* [The existing samples could be found here.](http://cepcsoft.ihep.ac.cn/guides/Generation/docs/ExistingSamples/)
---
#### Customize Geant4 using [built-in commands](http://geant4-userdoc.web.cern.ch/geant4-userdoc/UsersGuides/ForApplicationDeveloper/html/Control/AllResources/Control/UIcommands/_.html)
##### :writing_hand: Turn on the verbose during tracking
```python
detsimalg.RunCmds = [
"/tracking/verbose 1",
]
# Or
detsimalg.RunMacs = [
"run.mac",
]
```
```bash
# Below is the content of run.mac
/tracking/verbose 1
```
* Each step will be print out. Remeber to redirect the output to a file.
```bash
$ ./run.sh my_detsim.py >& mylog
```
----
##### Geant4 tracking output
```
*********************************************************************************************************
* G4Track Information: Particle = gamma, Track ID = 1, Parent ID = 0
*********************************************************************************************************
Step# X(mm) Y(mm) Z(mm) KinE(MeV) dE(MeV) StepLeng TrackLeng NextVolume ProcName
0 0 0 0 1e+05 0 0 0 pWorld initStep
1 1.03e+03 1.8e+04 1.1e-12 0 0 1.8e+04 1.8e+04 pWorld conv
*********************************************************************************************************
* G4Track Information: Particle = e+, Track ID = 4, Parent ID = 1
*********************************************************************************************************
Step# X(mm) Y(mm) Z(mm) KinE(MeV) dE(MeV) StepLeng TrackLeng NextVolume ProcName
0 1.03e+03 1.8e+04 1.1e-12 2.91e+04 0 0 0 pWorld initStep
1 1.04e+03 1.8e+04 -0.00523 2.91e+04 0.0117 54.9 54.9 pWorld eIoni
2 1.04e+03 1.81e+04 -0.00912 2.91e+04 0.00604 38.7 93.6 pWorld eIoni
3 1.06e+03 1.84e+04 -0.0404 2.91e+04 0.0634 321 415 pWorld eIoni
4 1.06e+03 1.84e+04 -0.0416 2.91e+04 0.00234 13.1 428 pWorld eIoni
```
<!-- .element: style="color:yellow; font-size:small" -->
* From this output, you can see the current track and its stepping information.
* Particle name, current track ID, parent track ID
* Step position, deposit energy
----
##### :writing_hand: Visualize using Geant4
* Enable following command in your job option:
```python
detsimalg.VisMacs = ["Examples/options/vis.mac"]
```
* :warning: If your X Server supports the G4 OpenGL, the detector will be shown.
* Try [Xming X Server](https://sourceforge.net/projects/xming/) in Windows.
* :notebook: [Visualization in Geant4 Documentation](http://geant4-userdoc.web.cern.ch/geant4-userdoc/UsersGuides/ForApplicationDeveloper/html/Visualization/visualization.html)
* G4 UI commands during visualization
```
/vis/scene/add/axes 0 0 0 3 m
/vis/scene/add/magneticField
```
----
##### Snapshot: The Qt based Geant4 visualization

:writing_hand: Play with Geant4 Visualization
<!-- .element: style="color:yellow" -->
---
### Analyze the simulation output
* :writing_hand: Modify the geometry option and run the simulation
```python
geometry_option = "CepC_v4-onlyECAL.xml"
```
* :writing_hand: Plot the `EcalBarrelCollection` in ROOT
```
root [] events->Draw("EcalBarrelCollection.position.y:EcalBarrelCollection.position.x")
root [] events->Draw("EcalBarrelCollection.position.y:EcalBarrelCollection.position.x", "Entry$==0")
```
<!-- .element: style="color:yellow; font-size:small" -->
----
#### See the branches in the `events` tree
```
root [] events->Print()
*............................................................................*
*Br 146 :EcalBarrelCollection.cellID : *
* | ULong64_t cellID[EcalBarrelCollection_] *
*Entries : 10 : Total Size= 1398779 bytes File Size = 420214 *
*Baskets : 4 : Basket Size= 32000 bytes Compression= 3.33 *
*............................................................................*
*Br 147 :EcalBarrelCollection.energy : Float_t energy[EcalBarrelCollection_]*
*Entries : 10 : Total Size= 699855 bytes File Size = 163107 *
*Baskets : 3 : Basket Size= 32000 bytes Compression= 4.29 *
*............................................................................*
*Br 148 :EcalBarrelCollection.position.x : Float_t x[EcalBarrelCollection_] *
*Entries : 10 : Total Size= 699865 bytes File Size = 466951 *
*Baskets : 3 : Basket Size= 32000 bytes Compression= 1.50 *
*............................................................................*
*Br 149 :EcalBarrelCollection.position.y : Float_t y[EcalBarrelCollection_] *
*Entries : 10 : Total Size= 699865 bytes File Size = 469393 *
*Baskets : 3 : Basket Size= 32000 bytes Compression= 1.49 *
*............................................................................*
*Br 150 :EcalBarrelCollection.position.z : Float_t z[EcalBarrelCollection_] *
*Entries : 10 : Total Size= 699865 bytes File Size = 560229 *
*Baskets : 3 : Basket Size= 32000 bytes Compression= 1.25 *
*............................................................................*
```
<!-- .element: style="color:yellow; font-size:small" -->
---
# Thank you for your attention
* [Create issue](https://github.com/cepc/CEPCSW/issues): Report a bug
* [Pull Request](https://github.com/cepc/CEPCSW/pulls): Fix a bug or Implement a feature
Your contributions are welcome!
{"type":"slide","slideOptions":{"transition":"slide","controls":true,"showSlideNumber":"all","navigationMode":"linear","center":false}}