FFFF GitHub - key4hep/k4Opt: Experiment-independent optimization framework for Key4hep · GitHub
[go: up one dir, main page]

Skip to content
key4hepPublic

About

Experiment-independent optimization framework for Key4hep

Resources

Contributing

Stars

1 star

Watchers

1 watching

Forks

Repository files navigation

k4opt

A detector optimization framework for Key4hep.

👉 Open the live dashboard

k4opt is being built to let detector experts define, evaluate, compare and share detector optimization problems for the Key4hep chain (generation, simulation, reconstruction, analysis), starting from the detector descriptions in k4geo. It is in early development: geometry handling, a first end-to-end evaluation (a candidate, simulated with ddsim once and measured by one or more evaluators), a first optimization with Optuna, and publishing its results for a first dashboard exist.

Components

k4opt is organized by component. Each lives in its own subpackage with its own API, command group, documentation and tests.

Component Purpose Status
k4opt.geometry Discover addressable parameters of a DD4hep XML geometry, override them, materialize modified geometries available
k4opt.software Say what candidates run on, by what is there rather than where: the build of the stack (an LCG view's manifests and build time), the system and every environment variable not known to be irrelevant, as one id that a stage's signature and a study hold (k4opt software show) first version
k4opt.problem Declare what can be evaluated and how it is measured: the parameters (type, unit, an optional reference value, what each sets), what each candidate is measured on (named samples, each with its stages, each stage run by an executor or given as a file) and who measures it (evaluators, keyed by binding, each naming its implementation). Problem files compose from fragments (!include, !join) and resolve their paths against one workspace root (.k4opt-root). A problem can be loaded, validated and its geometry targets resolved (k4opt.problem.load_problem, against the active $K4GEO); what to optimize of it is a study's in progress
k4opt.evaluation The contract an evaluator implements (request, result, measurements, what it declares); evaluators read a pipeline stage or combine per-sample measurements and artifacts through declared roles. load_evaluator loads an evaluator from a file in progress
k4opt.execution Evaluate candidates end to end: EvaluationSession (and k4opt evaluate for one candidate) materializes each candidate's geometry, runs each sample's stages once and calls every evaluator, inline or in worker processes, and publishes the candidate's record in progress
k4opt.record What a candidate's evaluation found, as its summary.json holds it: task results, status, measurements, the criteria it was judged by (none for a standalone evaluation) and its assessment against them, read back and checked without the evaluators (Assessment.from_summary) in progress
k4opt.ddsim Run ddsim on a prepared geometry with a particle gun or an event file: command from a sample's stages (the ddsim options written the way ddsim reads them), protected options, logs; run once per candidate and sample as its simulation stage, whatever number of evaluators read it first vertical slice
k4opt.k4run Run a Gaudi reconstruction (k4run, such as CLD's) from a copy of its directory on the candidate's geometry and every simulated event: the stage's options as the job's arguments, checked by the job's own dry run; the geometry, input and output it read verified from its resolved options; run once per candidate and sample as its reconstruction stage reconstruction stage
examples A standalone problem and study beside their evaluator (examples/standalone/), and a workspace (examples/workspace/) of photon-direction, photon/pi0-separation and reconstructed-pi0 (particle flow) problems, each with its studies and evaluators to copy from, run with k4opt evaluate PROBLEM --param NAME=VALUE --output DIR or k4opt optimize STUDY --output DIR. The first asks how fine the CLD ECAL cells should be: finer cells measure a photon's direction better (calo.photon measures it) but fire more readout channels. k4opt ships no evaluators example
k4opt.optimization Run a study: a study file names its problem and says what to optimize of it (the parameters searched and their domains, the objectives and constraints, the strategy and budget, nested levels). k4opt optimize STUDY proposes candidates (Optuna's TPE sampler, a grid, or a strategy of one's own), evaluates each into a trial directory, judges them against the study's criteria, and resumes a study only with what it was made with; k4opt study (load_results) reads a study back, checked and unchanged, to show its trials and Pareto front or export them as CSV or JSON first version
k4opt.publication Publish a study as a portable, read-only snapshot without any local path (k4opt publish STUDY --output DIR) into a directory that can be served as static files or copied anywhere, with a catalog of its studies, and read it back from a directory or an HTTP(S) URL, checked, without Optuna first version
k4opt.visualization Plotly figures of a study from its results alone: trials_figure, the trials on two objectives or parameters as feasible, infeasible or on the Pareto front, with units and uncertainties (k4opt[plot]) first version
dashboard A Streamlit app in dashboard/ that shows the studies of a publication, with its container, CERN OpenShift manifests and a gated deploy workflow; deployed as the live dashboard first version

The planned components are directions, not commitments; their shape depends on what the first ones teach.

Design principles:

  • as easy as possible for the physicist running experiments: small configuration files
  • detector agnostic: CLD is the prototype, nothing in the core is CLD-specific
  • reuse existing open-source tools instead of rebuilding them
  • every experiment reproducible and identifiable
  • stay independent of the executor (local, batch, grid)

Installation

k4opt runs inside the Key4hep stack, which provides Python, lxml, PyYAML and $K4GEO (the installed k4geo tree); strace from the system lets it record what each stage used (docs/software.md). The setup mirrors k4Bench:

git clone https://github.com/key4hep/k4Opt.git && cd k4Opt
source setup.sh      # sources Key4hep (latest nightly unless KEY4HEP_VERSION is set),
                     # creates a CVMFS-aware venv, installs k4opt (editable) and the pre-commit hooks
k4opt --help

setup.sh is idempotent; source it in every new shell. If the default nightly is incomplete (the script warns when $K4GEO is missing) or you need a fixed stack, pin one: KEY4HEP_VERSION=2026-10-20 source setup.sh (a dated Spack nightly) or KEY4HEP_VERSION=2026-04-08 source setup.sh (a release).

Without CVMFS you can still develop and run the unit tests in any Python ≥ 3.13 environment with pip install -e ".[dev]".

A first look

Find the parameter to vary in a geometry from k4geo:

k4opt geometry inspect FCCee/CLD/compact/CLD_o2_v09/CLD_o2_v09.xml --filter ECal_cell_size
FCCee/CLD/compact/CLD_o2_v09/ECalBarrel_o2_v01_03.xml  (4)
     ECal_cell_size.name                            ECal_cell_size
     constants.ECal_cell_size                       5.1*mm
     ...

name it in a problem, here examples/workspace/problems/cld-ecal-granularity.yaml: what can be evaluated and how it is measured.

schema_version: k4opt.problem/v1alpha1
geometry: FCCee/CLD/compact/CLD_o2_v09/CLD_o2_v09.xml   # relative to $K4GEO

parameters:
  ecal_cell_size:            # the name candidates and records use
    type: continuous
    unit: mm
    default: geometry        # its reference value: CLD's, 5.1 mm, as the geometry gives it
    targets:                 # what it varies: here, a constant of the geometry
      geometry: ECal_cell_size

say how the events each candidate is measured on are made, and who measures it:

samples:
  gamma_10gev:
    generation:              # the particle gun, a generation's default executor
      particle: gamma        # 10 GeV photons into the barrel (see the example for the keys)
      # ...
    simulation:              # ddsim, a simulation's default executor
      physics.list: FTFP_BERT

evaluators:
  calo.photon:               # the binding: what objectives, tasks and records call it
    implementation: evaluators/calo_photon.py:CaloPhoton   # relative to the workspace root
    stage: simulation
    collections:
      hits: ECalBarrelCollection
    settings:
      threshold:
        value: 70
        unit: keV

How many events a candidate is evaluated on, and from which seed, is no part of the problem but of a study of it, so the same problem serves a quick search and a careful check. A study that searches nothing evaluates one candidate, examples/workspace/studies/cld-pi0-check.yaml:

schema_version: k4opt.study/v1alpha1
problem: problems/cld-pi0.yaml
fixed: {ecal_cell_size: 8.0}   # the rest at the problem's defaults
seed: 1001                     # every stage's seed derives from it
events: {pi0_50gev: 2000}
k4opt evaluate examples/workspace/studies/cld-pi0-check.yaml --output runs/cld-pi0-8mm

(--dry-run instead of --output shows what the candidate sets, with the events and the seed of each stage, and simulates nothing). The paths inside a problem are relative to its workspace root, the directory of examples/workspace/.k4opt-root, never to the current directory. A parameter can also target a stage option or an evaluator setting, or several of these: cld-ecal-bindings.yaml varies the cell size, a ddsim option and the evaluator's threshold together.

What to optimize of a problem, and how, is a study's, examples/workspace/studies/cld-ecal-granularity.yaml:

schema_version: k4opt.study/v1alpha1
problem: problems/cld-ecal-granularity.yaml
seed: 42                                   # the evaluation seed
events: {gamma_10gev: 1000}                # every candidate on 1000 photons
optimization:
  parameters:
    ecal_cell_size: {range: [2.5, 20.0]}   # the search domain
  objectives:
    - {stage: simulation, metric: ecal_barrel.angular_residual, direction: minimize}
    - {stage: simulation, metric: ecal_barrel.fired_cells, direction: minimize}
  strategy: {name: optuna, seed: 42}
  trials: 30

Let it search the cell size, one evaluation per trial:

k4opt optimize examples/workspace/studies/cld-ecal-granularity.yaml --output runs/cld-ecal-study

(k4opt explain of the study first says what it would do and what it would run at most), and look at the results later, without running anything again:

k4opt study show runs/cld-ecal-study      # what it optimizes, its trials and Pareto front
k4opt study trial runs/cld-ecal-study 12  # one trial, every value as recorded
k4opt study export runs/cld-ecal-study --format csv --output results.csv

publish it, and browse it in the dashboard:

k4opt publish runs/cld-ecal-study --output published/
K4OPT_DASHBOARD_DATA=published/ streamlit run dashboard/app.py   # pip install -r dashboard/requirements.txt

The guides: geometry (target references, include handling, override semantics, manifest, Python API, limitations), software, problem, evaluation, execution, record, example evaluators, optimization, publication, visualization and dashboard. The photon/pi0 example combines two samples through histogram artifacts and weighs the pi0 rejection of finer cells against an approximate channel count.

Development

source setup.sh                       # Key4hep stack + venv + editable install + git hooks
python -m pytest -p xdist -n auto tests/unit          # every core; no stack needed
python -m pytest -p xdist -n auto tests/integration   # needs $K4GEO (or K4GEO_DIR=/path/to/k4geo)
pre-commit run --all-files            # ruff, mypy (strict), codespell, shellcheck, actionlint, ...

The pre-commit hooks run on every git commit once setup.sh has installed them, and CI runs the same hooks plus the tests inside the Key4hep container (.github/workflows/ci.yml). lint, unit and dashboard run on every pull request and are required on main; the integration tests run every night and by hand on any branch (gh workflow run ci.yml --ref <branch>), without holding up a merge. Dependency updates are proposed weekly by dependabot, and merge by themselves once the required checks pass.

Repository layout and conventions for adding a component are described in CONTRIBUTING.md: k4opt/<component>/ for code, tests/{unit,integration}/<component>/, docs/<component>.md, and examples in examples/standalone/ and examples/workspace/.

License

MIT, see LICENSE.

About

Experiment-independent optimization framework for Key4hep

Resources

Contributing

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages

0