Skip to content
HEP-FCCPublic

About

Decay Tree Fitter

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

k4DTF — Decay Tree Fitter for Key4hep

k4DTF fits a complete decay chain, such as B- → (D0 → K- π+) K-, in one go: every vertex position, flight length and momentum in the tree, together with all their correlations. Its inputs and outputs use EDM4hep. It is a port of the BaBar/LHCb DecayTreeFitter (W. D. Hulsbergen, NIM A 552 (2005) 566) to the FCC software. It comes as:

  • a C++ library (k4DTF), independent of any framework;
  • FCCAnalyses / RDataFrame functions (k4DTFFCCAnalyses): candidate building from a decay descriptor, MC-truth matching, and the fit with the tracks, photon clusters and primary vertex of each candidate;
  • a Gaudi algorithm (k4DTFGaudi, k4FWCore MultiTransformer);
  • validation tools: test samples for FCC-ee (Delphes IDEA), a stand-alone fit and pull program, and a pull-check script.

Contents


Idea

A vertex-by-vertex approach fits the D0 vertex from its tracks, builds a D0, then fits the B vertex from the D0 and the bachelor. Each step uses only part of the information. The decay-tree fit instead treats the whole chain as one least-squares problem:

  • parameters: the decay vertex and flight length of every composite that lives long enough to fly (B, D0, KS, ...), and the momenta of all particles;
  • measurements: the track helices, the photon clusters, and optionally the primary vertex;
  • constraints: momentum conservation at each decay; each daughter comes from its mother's decay vertex; each mother flies along its momentum from where it was produced; optional mass constraints on any node.

The fit returns the χ² of the whole tree and, for every node, the fitted 4-momentum, mass, decay vertex, flight length and proper decay length c·τ, with errors and correlations.

This matters most where a vertex has few or no tracks of its own. In B0 → D0 π0, for example, no charged track comes from the B0 vertex. The fit finds it where the D0 flight line meets the line from the primary vertex along the B0 momentum, and still measures the B0 decay time to about 45 fs (toy, 3 µm track impact-parameter resolution).

What it can do

  • Nested decay chains of any depth from a decay descriptor in LHCb notation, e.g. B0 -> (D*(2010)- -> (D~0 -> K+ pi-) pi-) pi+. LHCb, EvtGen and ROOT particle names are understood; charge conjugates are built automatically.
  • Charged tracks as helix measurements (edm4hep::TrackState), with the mass hypothesis of the descriptor.
  • Photons as calorimeter clusters (position, energy and their errors). The photon flies from its mother's vertex to the cluster.
  • Resolved π0 → γγ (and other resonances): resonances such as D*, J/ψ or π0 decay where they are made; they get no vertex of their own.
  • Mass constraints on any node; the primary-vertex constraint (the head is produced at the primary vertex).
  • Long-lived particles (KS decaying tens of cm away): vertices are seeded from the intersection of the daughters' helices.
  • For FCCAnalyses: candidate building with mass windows, MC-truth matching of every node, the primary vertex refitted for each candidate without its own tracks, and an option to keep only truth-matched candidates for fast resolution studies.

How it has been validated

  • Toy Monte Carlo (test/test_toy.cpp): exact decays, track helices smeared with their covariance, photons as Delphes makes them. Pulls of all fitted momenta, vertices and c·τ are unit Gaussians and ⟨χ²⟩ = ndf, for B- → D0 K-, B0 → D*- π+, B0 → K*0 γ, B0 → J/ψ KS (KS up to 60 cm) and B- → D0(→ K- π+ π0) π-.
  • Independent cross-check (test/test_crosscheck.cpp): a separately written global χ² fit (its own helix model, photons compared at the calorimeter, mass constraints as Lagrange multipliers) reaches the same χ², values and errors as k4DTF (errors agree to 0.05%), and k4DTF's errors equal the Cramér–Rao bound, the best precision any unbiased fit can reach. This is checked for B- → D0 K- and B0 → D0 π0.
  • Delphes IDEA samples (examples/dtf_test_samples): with full FCC-ee events, the input-track pulls are standard normal. The pulls of the fitted quantities are too when the primary vertex is fitted from MC-truth prompt tracks only and decays that radiated photons are left out. Without these selections the tails come from the reconstructed primary vertex (tracks from heavy-flavour decays pull it) and from the truth reference (radiated photons), not from the fitter; the samples README shows how to see each.

Getting started

All dependencies come with the Key4hep stack: ROOT ≥ 6.28, EDM4hep, podio, Gaudi, k4FWCore, Eigen, and Catch2 for the tests. FCCAnalyses is needed only to run the RDataFrame examples.

# 1. Key4hep: a release, or the nightlies (needed for photon cluster positions
#    and errors from Delphes; see the samples README)
source /cvmfs/sw.hsf.org/key4hep/setup.sh
# source /cvmfs/sw-nightlies.hsf.org/key4hep/setup.sh

# 2. build and install
git clone https://github.com/HEP-FCC/k4DTF.git
cd k4DTF
cmake -B build -DCMAKE_INSTALL_PREFIX=$PWD/install
cmake --build build -j$(nproc)
cmake --install build

# 3. put the installation in the environment (PATH, LD_LIBRARY_PATH,
#    ROOT_INCLUDE_PATH, ...); run from the repository root
k4_local_repo

# 4. tests
ctest --test-dir build --output-on-failure

After changing the code, rebuild and install (cmake --build build && cmake --install build): FCCAnalyses and the tools use the installed library and headers. If ROOT complains that a k4DTF type or function does not exist, it is usually loading an older installation.

-DBUILD_TESTING=OFF skips the tests. The test suite contains:

Test Checks
test_k4DTF (Catch2) descriptor parser, particle table, EDM4hep conversions, helix conventions, toy-MC pulls, candidate building and truth matching on synthetic events, the cross-check against the global fit
test_pulls the statistics of k4dtf_pulls.py

./build/test/test_k4DTF "[crosscheck]" prints the cross-check summary; K4DTF_CROSSCHECK_EVENTS=5000 runs more events.

Usage

FCCAnalyses / RDataFrame

The complete, maintained example is the stage-1 script of the test samples, examples/dtf_test_samples/analysis/stage1_dtf_inputs.py: it does everything below for several decay modes and writes the fit results and the MC truth to an ntuple. The building blocks, for Delphes EDM4hep files:

import ROOT
ROOT.gSystem.Load("libk4DTFFCCAnalyses")
ROOT.gInterpreter.Declare('''
#include "k4DTFFCCAnalyses/DTFFunctions.h"
namespace myana {
// candidates within mass windows [GeV]; charge conjugate included
const k4DTF::CandidateBuilder builder("B- -> (D0 -> K- pi+) K-",
                                      {{521, {4.9, 5.7}}, {421, {1.80, 1.93}}});
const k4DTF::TruthMatcher matcher(builder);
// D0 mass constraint, primary-vertex constraint
const k4DTF::DTFRunner fit(builder, {421}, true);
}
''')

df = (df
  # EDM4hep relations
  .Alias("rpTracks",    "_ReconstructedParticles_tracks.index")
  .Alias("trackStates", "_EFlowTrack_trackStates")
  .Alias("linkFrom",    "_RecoMCLink_from.index")
  .Alias("linkTo",      "_RecoMCLink_to.index")
  .Alias("mcParents",   "_Particle_parents.index")
  .Alias("mcDaughters", "_Particle_daughters.index")
  .Define("Bz",       "2.0f")
  # per reconstructed particle: MC link, PID (here: MC truth), track state
  .Define("RP_mcIdx", "k4DTF::recoToMC(ReconstructedParticles, linkFrom, linkTo)")
  .Define("RP_pid",   "k4DTF::truthPDG(RP_mcIdx, Particle)")
  .Define("RP_ts",    "k4DTF::trackStatePerReco(ReconstructedParticles, rpTracks, EFlowTrack, trackStates)")
  # candidates and their MC truth
  .Define("cands",    "myana::builder(ReconstructedParticles, RP_pid)")
  .Filter("k4DTF::nCandidates(cands) > 0")
  .Define("truth",    "myana::matcher(cands, RP_mcIdx, Particle, mcParents, mcDaughters)")
  .Define("isSignal", "truth.isSignal")
  # primary vertex (one per event here; the stage-1 script refits it per candidate)
  .Define("PV_tracks", "FCCAnalyses::VertexFitterSimple::get_PrimaryTracks(trackStates, true, 4.5, 0.02, 300., 0., 0., 0.)")
  .Define("PV",        "FCCAnalyses::VertexingUtils::get_VertexData("
                       "FCCAnalyses::VertexFitterSimple::VertexFitter_Tk(1, PV_tracks, true, 4.5, 0.02, 300., 0., 0., 0.))")
  # the fit, and per-candidate columns; nodes are numbered in descriptor
  # pre-order: 0 B-, 1 D0, 2 K-, 3 pi+, 4 K-
  .Define("fits",     "myana::fit(cands, ReconstructedParticles, RP_ts, Bz, PV)")
  .Define("chi2",     "k4DTF::fitChi2(fits)")
  .Define("prob",     "k4DTF::fitProb(fits)")
  .Define("B_M",      "k4DTF::fitNodeMass(fits, 0)")
  .Define("B_ctau",   "k4DTF::fitNodeCtau(fits, 0)")
  .Define("D0_ctau",  "k4DTF::fitNodeCtau(fits, 1)")
)

Things to know:

  • RP_pid decides which reconstructed particle can be which leaf. Here it is MC truth (perfect PID); for a realistic analysis replace it with your own PID.
  • Photons need their clusters: k4DTF::photonClusterPerReco(...) and the DTFRunner overloads that take them (see the stage-1 script).
  • The primary vertex should not contain the candidate's own tracks; the stage-1 script refits it for each candidate (pvTracksWithoutCandidate).
  • Fit columns are -999 for fits that did not converge.
  • Per node: fitNodeMass, fitNodeMassErr, fitNodeP, fitNodeMomentum, fitNodeDecayVertex, fitNodeDecayVertexErr, fitNodeCtau, fitNodeCtauErr, fitNodeDecayLength, fitNodeDecayLengthErr; per candidate: fitStatus, fitChi2, fitNdf, fitNIter, fitProb.

C++ library

#include "k4DTF/DecayDescriptor.h"
#include "k4DTF/DecayTreeFitter.h"
#include "k4DTF/TreeInput.h"

const auto desc = k4DTF::DecayDescriptor::fromString("B- -> (D0 -> K- pi+) K-");

// one DTFParticle per leaf, in depth-first order (K-, pi+, K-):
//   charged: k4DTF::DTFParticle::fromEDM4hep(recoParticle, trackState, Bz, mass)
//   photon:  k4DTF::DTFParticle::fromEDM4hep(recoParticle, clusterData)
std::vector<k4DTF::DTFParticle> leaves = {kaon, pion, bachelor};

const auto input = k4DTF::makeDecayNodeInput(desc, leaves, /*mass constraints*/ {421});
const auto pv = k4DTF::makeInteractionPoint(k4DTF::DTFVertex::fromEDM4hep(primaryVertex));

const k4DTF::DecayTreeFitter dtf;  // Configuration: maxIter, convergence, ...
const k4DTF::FitResult r = dtf.fit(input, pv);

if (r.converged()) {
  // r.chi2, r.ndf, r.prob(); r.nodes in descriptor pre-order: B-, D0, K-, pi+, K-
  const auto& B = r.nodes[0];
  std::cout << "B ctau = " << B.ctau << " +- " << B.ctauErr << " mm\n";
}

The fitter itself only needs a k4DTF::DecayNodeInput (a tree of nodes with measurements on the leaves, k4DTF/core/DecayNodeInput.h); the descriptor and DTFParticle are a convenient way to build one from EDM4hep.

Gaudi / k4FWCore

DTFAlgorithm reads a ReconstructedParticleCollection with the final-state particles of one candidate, in the depth-first leaf order of the descriptor (charged particles with their track, photons with their cluster), and writes every fitted node (head first, with daughter relations) and one Vertex per decay vertex.

from Configurables import DTFAlgorithm

dtf = DTFAlgorithm("BDTF",
    InputParticles  = ["BDaughters"],
    OutputParticles = ["BFitted"],
    OutputVertices  = ["BFittedVertices"],
    DecayDescriptor = "B- -> (D0 -> K- pi+) K-",
    MassConstraints = {"421": 0.0},   # PDG code (str) -> mass [GeV]; <= 0: nominal
    Bz              = 2.0,
)

The algorithm has no primary-vertex input yet, and it has not been tested with a full Gaudi job.

Tools

  • k4dtf-validate re-runs the fit on a stage-1 ntuple and writes one row per candidate with fitted and true values and pulls. Use it after every change to the fitter; no FCCAnalyses needed.
  • k4dtf_pulls.py summarises the pulls in that output: a Gaussian fit to the core, tail fractions beyond 3 and 5 against expectation, the χ² probability, side by side for several files and selections, with optional plots.

Both are described in the samples README.

Conventions

  • Units: mm, GeV, T; c·τ in mm.
  • Nodes are numbered in pre-order of the descriptor (head first, then each daughter followed by its own daughters), in the fit results and in the per-node functions.
  • Tracks follow edm4hep::TrackState as written by k4SimDelphes: (D0, φ, ω, Z0, tanλ) at reference point (0,0,0), sign(ω) = sign(q·Bz). See k4DTF/core/Helix.h.
  • Masses of leaves and constraints come from k4DTF::ParticleTable (EvtGen evt.pdl values).
  • Photon errors: clusters without errors get them from k4DTF::CalorimeterResolution (Delphes IDEA defaults).

Algorithm

All parameters of the tree are fitted at once. The constraints are applied one after another as Kalman-filter steps, and the whole pass is iterated until the χ² is stable (Hulsbergen 2005).

Node Parameters Constraints
Primary vertex (optional) position measured position
Composite with lifetime decay vertex, flight length, (px, py, pz, E) 4-momentum conservation; flight along p from the production vertex; optional mass
Resonance (px, py, pz, E) 4-momentum conservation; optional mass
Track (px, py, pz) helix at the mother's vertex = measured helix (5)
Photon (px, py, pz) points from the mother's vertex to the cluster (2); |p| = cluster energy (1)
  • Each iteration linearises all constraints at the result of the previous one and starts from that result with a weak prior: its covariance diagonal scaled by Configuration::priorScale (1e4). The covariance update uses the Joseph form.
  • Vertices with two or more tracks start at the crossing of two helices; track momenta start at the point of the helix nearest that vertex.
  • If the χ² oscillates (which can happen with a π0 mass constraint, which is strongly non-linear on the scale of the photon errors), the step is halved.

Repository structure

k4DTF/
├── k4DTF/                         core library
│   ├── include/k4DTF/
│   │   ├── DecayTreeFitter.h      the fitter and its configuration
│   │   ├── FitResult.h            chi2, status, per-node results
│   │   ├── DecayDescriptor.h      descriptor parser
│   │   ├── ParticleTable.h        names, PDG codes, masses, resonances
│   │   ├── DTFParticle.h          particle with track/cluster; EDM4hep conversions
│   │   ├── TreeInput.h            descriptor + particles -> fitter input
│   │   ├── CalorimeterResolution.h  photon errors when the file has none
│   │   └── core/                  fitter input, measurements, helix conventions
│   └── src/core/                  nodes, Kalman filter, parameters
├── k4DTFFCCAnalyses/              RDataFrame functions
│   ├── DTFInput.h                 candidates, truth matching, PV and photon helpers
│   └── DTFFunctions.h             DTFRunner, fit* extractors
├── k4DTFGaudi/                    DTFAlgorithm
├── tools/                         k4dtf-validate, k4dtf_pulls.py
├── examples/
│   ├── dtf_test_samples/          generation, stage-1 script, validation guide
└── test/                          Catch2 tests, toy MC, global-fit cross-check

Limitations and open points

  • Merged π0 (both photons in one calorimeter cluster) cannot be fitted from FCCAnalyses inputs yet: the core has a merged-π0 node, but nothing builds its input.
  • Photon pointing (the flight direction measured by the calorimeter) is not used. For photons from vertices located to better than a mm, as in B decays with a primary-vertex constraint, it would add almost nothing.
  • PID in the examples is MC truth.
  • Gaudi: no primary-vertex input; not tested in a Gaudi job.
  • The core's composite and merged-π0 measurement nodes have no tests.

References

License

Apache License 2.0, as the rest of Key4hep. Source files carry

// SPDX-FileCopyrightText: Copyright (c) 2026 CERN
// SPDX-License-Identifier: Apache-2.0

Contributing

Issues and pull requests are welcome on GitHub. Code follows the Key4hep conventions and is formatted with clang-format.

Acknowledgements

Parts of this project were developed with the assistance of Claude (Anthropic).

About

Decay Tree Fitter

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages