Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-12-02 09:11:07

0001 """dRICH and BIC example workflow payloads and objective calculations."""
0002 
0003 from pathlib import Path
0004 from itertools import product
0005 import json
0006 import shlex
0007 
0008 import numpy as np
0009 
0010 
0011 # dRICH payloads
0012 
0013 # sim
0014 
0015 
0016 def drich_sim_payloads(*, problem_config, workflow_context, **_):
0017     """Return dRICH particle simulation payloads."""
0018     eval_config = problem_config.evaluation_config
0019     trial_tag = str(workflow_context["trial_index"])
0020     output_dir = Path(workflow_context["output_dir"]) / "drich" / "sim"
0021     output_dir.mkdir(parents=True, exist_ok=True)
0022     records = []
0023     for scan_index, point in enumerate(eval_config["drich_scan_points"]):
0024         for particle in eval_config["drich_particles"]:
0025             tag = (
0026                 f"{trial_tag}_{particle}_p_{point['p']}_"
0027                 f"eta_{point['eta_min']}_{point['eta_max']}"
0028             )
0029             records.append(
0030                 {
0031                     "scan_index": scan_index,
0032                     "particle": particle,
0033                     "sim_file": str(output_dir / f"scan_{tag}.root"),
0034                     "sim_arguments": shlex.join([
0035                         "-G",
0036                         "--gun.etaMax", str(point["eta_max"]),
0037                         "--gun.etaMin", str(point["eta_min"]),
0038                         "--gun.momentumMax", f"{point['p']}*GeV",
0039                         "--gun.momentumMin", f"{point['p']}*GeV",
0040                         "--gun.particle", particle,
0041                         "--gun.multiplicity", "1",
0042                         "--gun.position", "0.0 0.0 0.0",
0043                         "--gun.direction", "0.0 0.0 1.0",
0044                         "--gun.distribution", "eta",
0045                         "--gun.phiMin", "0",
0046                         "--gun.phiMax", "6.2831853",
0047                     ]),
0048                 }
0049             )
0050     return records
0051 
0052 
0053 # rec
0054 
0055 
0056 def drich_rec_payloads(*, problem_config, workflow_context, **_):
0057     """Return dRICH reconstruction payloads."""
0058     output_dir = Path(workflow_context["output_dir"]) / "drich" / "rec"
0059     output_dir.mkdir(parents=True, exist_ok=True)
0060     sim_records = drich_sim_payloads(
0061         problem_config=problem_config, workflow_context=workflow_context
0062     )
0063     records = []
0064     for record in sim_records:
0065         records.append(
0066             {
0067                 **record,
0068                 "reco_file": str(output_dir / f"recon_{Path(record['sim_file']).name}"),
0069                 "rec_arguments": "-Pnthreads=1 -Ppodio:output_include_collections=DRICHHits,MCParticles,DRICHRawHits,DRICHRawHitsAssociations,DRICHAerogelTracks,DRICHGasTracks,DRICHAerogelIrtCherenkovParticleID,DRICHGasIrtCherenkovParticleID,DRICHMergedIrtCherenkovParticleID",
0070             }
0071         )
0072     return records
0073 
0074 
0075 # ana
0076 
0077 
0078 def drich_ana_payloads(*, problem_config, workflow_context, **_):
0079     """Return payload records for dRICH analysis jobs."""
0080     eval_config = problem_config.evaluation_config
0081     trial_tag = str(workflow_context["trial_index"])
0082     output_dir = Path(workflow_context["output_dir"]) / "drich" / "ana"
0083     output_dir.mkdir(parents=True, exist_ok=True)
0084     if sorted(eval_config["drich_particles"]) != ["kaon+", "pi+"]:
0085         raise ValueError("dRICH analysis requires particles pi+ and kaon+")
0086     rec_records = drich_rec_payloads(
0087         problem_config=problem_config, workflow_context=workflow_context
0088     )
0089 
0090     records = []
0091     for scan_index, point in enumerate(eval_config["drich_scan_points"]):
0092         reco_files = [
0093             record["reco_file"]
0094             for particle in ("pi+", "kaon+")
0095             for record in rec_records
0096             if record["scan_index"] == scan_index and record["particle"] == particle
0097         ]
0098         records.append(
0099             {
0100                 "radiator": point["radiator"],
0101                 "ana_inputs": shlex.join(reco_files),
0102                 "analysis_output": str(
0103                     output_dir / f"recon_scan_{trial_tag}_p_{point['p']}_"
0104                     f"eta_{point['eta_min']}_{point['eta_max']}.txt"
0105                 ),
0106             }
0107         )
0108     return records
0109 
0110 
0111 # BIC payloads
0112 
0113 # sim
0114 
0115 
0116 def bic_sim_payloads(*, problem_config, workflow_context, **_):
0117     """Return BIC photon simulation payloads."""
0118     eval_config = problem_config.evaluation_config
0119     output_dir = Path(workflow_context["output_dir"]) / "bic" / "sim"
0120     output_dir.mkdir(parents=True, exist_ok=True)
0121     records = []
0122     for index, (particle, energy) in enumerate(product(
0123         eval_config["bic_particles"], eval_config["bic_energies"]
0124     )):
0125         records.append(
0126             {
0127                 "particle": particle,
0128                 "sim_file": str(output_dir / f"central_photons_bin{index}.edm4hep.root"),
0129                 "sim_arguments": shlex.join([
0130                     "-G",
0131                     "--gun.energy", f"{energy}*GeV",
0132                     "--gun.multiplicity", "1",
0133                     "--gun.position", "0.0 0.0 0.0",
0134                     "--gun.direction", "0.0 0.0 1.0",
0135                     "--gun.particle", particle,
0136                     "--gun.distribution", "cos(theta)",
0137                     "--gun.thetaMin", "45*degree",
0138                     "--gun.thetaMax", "135*degree",
0139                 ]),
0140             }
0141         )
0142     return records
0143 
0144 
0145 # rec
0146 
0147 
0148 def bic_rec_payloads(*, problem_config, workflow_context, **_):
0149     """Return BIC reconstruction payloads, merging simulation files first."""
0150     output_dir = Path(workflow_context["output_dir"]) / "bic" / "rec"
0151     output_dir.mkdir(parents=True, exist_ok=True)
0152     sim_file = output_dir.parent / "sim" / "central_photons.edm4hep.root"
0153     sim_records = bic_sim_payloads(
0154         problem_config=problem_config, workflow_context=workflow_context
0155     )
0156     bic_files = [record["sim_file"] for record in sim_records]
0157     records = [
0158         {
0159             "sim_file": str(sim_file),
0160             "reco_file": str(output_dir / "central_photons.edm4eic.root"),
0161             "rec_arguments": "-Pnthreads=1 -Peicrecon:LogLevel=debug",
0162             "merge_command": shlex.join(["hadd", "-f", str(sim_file), *bic_files]),
0163         }
0164     ]
0165     return records
0166 
0167 
0168 # ana
0169 
0170 
0171 def bic_ana_payloads(*, workflow_context, **_):
0172     """Return BIC analysis payloads."""
0173     output_dir = Path(workflow_context["output_dir"]) / "bic" / "ana"
0174     output_dir.mkdir(parents=True, exist_ok=True)
0175     records = [
0176         {
0177             "job_name": "bic_ana",
0178             "analysis_output": str(output_dir / "central_photons.hist.root"),
0179             "analysis_arguments": "-c phi -s 22",
0180         }
0181     ]
0182     return records
0183 
0184 
0185 # Collect objectives
0186 
0187 
0188 def collect_objectives(*, problem_config, workflow_context, extra_args, **_):
0189     """Return objectives for a framework objective-plan step."""
0190     # dRICH separation, acceptance, and uncertainties.
0191     eval_config = problem_config.evaluation_config
0192     trial_index = workflow_context["trial_index"]
0193     scan_points = eval_config["drich_scan_points"]
0194     ana_records = drich_ana_payloads(
0195         problem_config=problem_config, workflow_context=workflow_context
0196     )
0197     results = np.array([np.loadtxt(record["analysis_output"]) for record in ana_records])
0198     momenta = np.array([point["p"] for point in scan_points])
0199     metric_values = (
0200         ("piKsep_etalow", results[momenta == 15, 2], results[momenta == 15, 3]),
0201         ("piKsep_etahigh", results[momenta == 45, 2], results[momenta == 45, 3]),
0202         ("acceptance", results[1:, 0], results[1:, 1]),
0203     )
0204     metrics = {}
0205     for name, values, errors in metric_values:
0206         metrics[name] = float(np.mean(values))
0207         metrics[f"{name}_err"] = float(np.linalg.norm(errors) / len(errors))
0208 
0209     if any(np.isnan(value) for value in metrics.values()):
0210         raise RuntimeError(f"NaN objective for trial {trial_index}")
0211 
0212     # BIC photon phi resolution.
0213     with open(extra_args["file"].replace(".root", ".json"), "r") as f:
0214         metrics[extra_args["key"]] = json.load(f)[extra_args["key"]]
0215     return metrics