Skip to content

Commit

Permalink
Added example scripts to generate & run many macs
Browse files Browse the repository at this point in the history
  • Loading branch information
fzeiser committed Aug 17, 2020
1 parent c7944cb commit 3717dcd
Show file tree
Hide file tree
Showing 24 changed files with 680 additions and 205 deletions.
17 changes: 2 additions & 15 deletions OCL/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -43,19 +43,6 @@ target_link_libraries(OCL ${Geant4_LIBRARIES})
# build Scint. This is so that we can run the executable directly because it
# relies on these scripts being in the current working directory.
#
set(OCLSCRIPTS
PrintSimMacs.cpp
manyruns.sh
)

foreach(_script ${OCLSCRIPTS})
configure_file(
${PROJECT_SOURCE_DIR}/${_script}
${PROJECT_BINARY_DIR}/${_script}
COPYONLY
)
endforeach()

file(GLOB MACROS "${PROJECT_SOURCE_DIR}/*.mac")
file(COPY ${MACROS} DESTINATION ${PROJECT_BINARY_DIR})

Expand All @@ -64,12 +51,12 @@ file(COPY ${MACROS} DESTINATION ${PROJECT_BINARY_DIR})
#--------------------------------------------------------------------------
#
# Checks whether a "data" directory exists at the place GEANT4 wants to save
# the root files.
# the root files.
# If it does not exist, this will lead to errors when you run the simulation
#
IF(EXISTS "../data")
message("-- Data directory exists (needed for the root outputs)")
else()
else()
message(SEND_ERROR " \n WARNING \n \"../data\" directory DOES NOT exists (needed for the root outputs)")
endif()

Expand Down
66 changes: 0 additions & 66 deletions OCL/PrintSimMacs.cpp

This file was deleted.

2 changes: 0 additions & 2 deletions OCL/genAndrunSims.sh

This file was deleted.

5 changes: 0 additions & 5 deletions OCL/manyruns.sh

This file was deleted.

20 changes: 0 additions & 20 deletions OscarBuild/Detectors27112017.txt

This file was deleted.

24 changes: 0 additions & 24 deletions OscarBuild/DetectorsNd_exp.txt

This file was deleted.

66 changes: 0 additions & 66 deletions OscarBuild/PrintSimMacs.cpp

This file was deleted.

8 changes: 8 additions & 0 deletions OscarBuild/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Additional scripts to generate macros / submitt jobs

- `grid_response.py`: Genreates macros to use when simulating
the response for many incident energies
- ` grid_simulations.py` and `grid_inbeam.py` are examples of how the geometry
can be changed by macros, thus that one can optimize some parameters of
the geometry
- `submitt_scripts` contains examples of how to submitt the scripts on the fram HPC using a helper script called [launcher](https://github.com/TACC/launcher)
53 changes: 53 additions & 0 deletions OscarBuild/grid_inbeam.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import numpy as np
from pathlib import Path
import pandas as pd

from grid_simulations import MacroGen

if __name__ == "__main__":
np.random.seed(65432)
macgen = MacroGen()
macgen._base_geometry_cmd = "/control/execute setup_normal_run.mac"
macgen.run_macs = [#"run696keV.mac",
# "run1779keV.mac", "run2838keV.mac",
"runEx4617keV.mac",
"run4440keV.mac"
]
# print(macgen.run())

# nominal thicknesses in cm
dnominal = {'front': 0.2, 'radial': 0.1, 'reflector': 0.1,
'lidhalf': 0.1, 'det': 16}
dthick = {'front': 0.2, 'radial': 0.1, 'reflector': 0.1,
'lidhalf': 0.2, 'det': 16}
dsaintgb = {'front': 0.08, 'radial': 0.08, 'reflector': 0.22,
'lidhalf': 0.1, 'det': 16}

grid = [dnominal, dthick, dsaintgb]
print("Items to calculate: ", len(grid))

fnbase = Path("inbeam_grid_macs")
fnbase.mkdir(exist_ok=True)
for i, pars in enumerate(grid):
# print(f"Simulating gridpoint {i}")
dtmp = pars

macgen.outname_base = f"inbeam_grid_{i}_"
macgen.dgeometry = dtmp
macro = macgen.save(fnbase / f"grid_{i}.mac")

# create summary file with commands to run
# due to concerns on calculation time we may not calculate all values,
# but start with a random selection
indices = np.arange(len(grid))
# np.random.shuffle(indices)

cmds = [f"./OCL inbeam_grid_macs/grid_{i}.mac" for i in indices]
cmd_string = "\n".join(*[cmds])
fn_sum = Path("inbeam_grid_cmd_all.txt")
fn_sum.write_text(cmd_string)

# grid_out = np.column_stack((np.arange(len(grid)), grid))
# grid_out = pd.DataFrame(grid_out, columns=["grid_point", *dnominal.keys()])
# grid_out = grid_out.astype({"grid_point": 'int'}, copy=False)
# grid_out.to_pickle("inbeam_grid_inbeam.pickle")
86 changes: 86 additions & 0 deletions OscarBuild/grid_response.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import numpy as np
from typing import Dict, List, Optional
from pathlib import Path

class MacroGenResponse:
def __init__(self, energy: Optional[float] = None,
nevent: Optional[int] = None):
self.energy = energy
self.nevent = nevent
self.outdir = "../data/"
self.outname_base = "grid_" # optionally: add eg sim_001_

self._base_geometry_cmd = "/control/execute setup_normal_run.mac"

def compose(self):
return '\n'.join(*[self.geometry() + self.run()])

def save(self, fname):
fn = Path(fname)
fn.write_text(self.compose())

def geometry(self,
unit: str = "cm") -> List[str]:
string = [
self._base_geometry_cmd,
"/run/initialize",
""]
return string

def run(self) -> List[str]:
assert np.issubdtype(type(self.nevent), np.integer)

outname_base = Path(self.outdir)
fnout = Path(f"{self.outname_base}{self.energy}keV_n{self.nevent}")
fnout = outname_base / fnout.with_suffix(".root")

def basestring(energykeV, fnout, nevent):
res = ["# Particle type, position, energy...",
"/gps/particle gamma",
"/gps/number 1",
"",
"# Particle source distribution",
"/gps/pos/type Plane",
"/gps/pos/shape Ellipse",
"/gps/pos/centre 0. 0. 0. mm",
"/gps/pos/halfx 0.75 mm",
"/gps/pos/halfy 1.25 mm",
"/gps/ang/type iso",
"",
f"/gps/energy {energykeV} keV",
f"/OCL/setOutName {fnout}",
"",
"# Number of events to run",
f"/run/beamOn {nevent}",
]
return res

string = basestring(self.energy, fnout, self.nevent)
# flat_list = [item for sublist in string for item in sublist]
return string


if __name__ == "__main__":
energy_grid = np.arange(50, 1e4, 10, dtype=int)
nevents = np.linspace(6e5, 3e6, len(energy_grid), dtype=np.int)

energy_grid = np.append(energy_grid, [int(1.2e4), int(1.5e4), int(2e4)])
nevents = np.append(nevents, [int(3e6), int(3e6), int(3e6)])

fnbase = Path("response_grid_macs")
fnbase.mkdir(exist_ok=True)
for i, (energy, nevent) in enumerate(zip(energy_grid, nevents)):
# print(f"Simulating gridpoint {i}")
macgen = MacroGenResponse(energy=energy, nevent=nevent)
macro = macgen.save(fnbase / f"grid_{i}.mac")

# create summary file with commands to run
# sorted by decreasing computation time (highest energies first)
indices = np.arange(len(energy_grid))
# np.random.shuffle(indices)

cmds = [f"./OCL {fnbase}/grid_{i}.mac > $LOGDIR/out.o$LAUNCHER_JID"
for i in indices[::-1]]
cmd_string = "\n".join(*[cmds])
fn_sum = Path("response_grid_cmds.txt")
fn_sum.write_text(cmd_string)
Loading

0 comments on commit 3717dcd

Please sign in to comment.