Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
189 changes: 189 additions & 0 deletions Detectors/Align/CLAUDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## What this is

A module of ALICE O2 (`Detectors/Align`), producing `libO2Align` plus one DPL workflow
executable, `o2-barrel-alignment-workflow` ([src/alignment-workflow.cxx](src/alignment-workflow.cxx)), and the
stand-alone `o2-barrel-mille-replay` ([src/milleReplay.cxx](src/milleReplay.cxx), standard library only): it replays the
Mille binaries with a `millepede.res` applied, emulating pede's local fit and rejections, and reports per input file the
rejection and the residual pressure on every free or fixed parameter — the fast way to validate a solution without
regenerating the debug trees ([doc/MilleReplay.md](doc/MilleReplay.md)).
It aligns ALICE barrel detectors by refitting tracks with GBL (General Broken Lines) and writing
Millepede-II input. Originally cloned from `O2/Detectors/Upgrades/ITS3/alignment`, so ITS/ITS3 is
still the most developed part.

## Build and run

Built as the `Detectors/Align` module of O2 (needs Millepede-II): configure/build/install O2 as usual, e.g.
`ninja -C <O2build> -j 3 install` (lower `-j` if the job gets OOM-killed), then load the O2 environment so that
`o2-barrel-alignment-workflow` is on the PATH.

There is no test suite and no linter config. Verification means running the workflow — see the
closure test in [README.md](README.md), which injects a known misalignment (`misAlgJson`) and checks
that the fit recovers it.

`Params` is an O2 `ConfigurableParam` whose prefix is **`AlignParams`** (`O2ParamDef(Params,
"AlignParams")` in [Params.h](include/O2Align/Params.h)).

Three-stage workflow, the same executable each time:
1. `--output MilleData,MilleSteer` over reconstructed data — writes `mp2data.bin` and the steering
files `mp2tree.txt` / `mp2con.txt` / `mp2param.txt`. The `gbl::MilleBinary` is opened at the 1st
TF and kept open until `endOfStream`, the trajectories of every TF being appended. The steering
files are likewise always written from `endOfStream` (not at `init()`), after this lane's
per-volume track counts (`Volume::getDataCounter()`) are final, so `AlignParams.useStatWeightedMeanConstraints=true`
(see [doc/DOFConfig_rules.md](doc/DOFConfig_rules.md#weighting-the-mean-by-statistics)) can weight
`mp2con.txt`'s hierarchical mean constraints by them instead of splitting equally. The common
pattern of recording `mp2data.bin` once with a wide-open `dofConfigJson` and then regenerating just
the steering files (`--output MilleSteer`, no data — reached via `endOfStream` just the same, after
the single `run()` call of the `NoInpDummyOutSpec` companion) against a more restricted one still
works with stat-weighting on, via `AlignParams.statInFile` pointing at a previous run's saved
`ProcessingStats` (`AlignParams.statFile`).
2. `pede` (external, from Millepede-II) → `millepede.res`.
3. `--output MilleRes` — reads no data at all (the workflow inserts `NoInpDummyOutSpec`), only
rebuilds the hierarchy and translates `millepede.res` into `result.json`, subtracting the
injected misalignment if `misAlgJson` is given (and writing `closure.json`).

With `MilleRes`, `WeakModesDiag` also runs `diagnoseWeakModes` ([WeakModes.h](include/O2Align/WeakModes.h)):
per detector branch it writes `weakModes.json/.root` (prefix `AlignParams.weakModesOutBase`) with the amplitude of every
global mode, from the constraint projection (A) and from a fit of the sensor displacement field (B);
`scripts/drawWeakModes.C` plots them.

`--output` is a comma-separated `EnumFlags` list: `VerboseGBL, MilleData, MilleSteer, MilleRes,
MisRes, WeakModesDiag, WeakModesDiagIni, Regularize` ([AlignmentSpec.h](include/O2Align/AlignmentSpec.h)).
`AlignParams.debugTracksFraction>0` writes a random fraction of the tracks, with their GBL points, residuals and kinks, to the `gbltrack` tree of
`debug_alg[_<lane>].root` (see [doc/DebugInfo.md](doc/DebugInfo.md)); the file is created only if something is to be written into it.
`WeakModesDiagIni` is a standalone pass, independent of `MilleRes`: it diagnoses the weak modes
already present in the initial (CCDB) alignment baked into the loaded geometry, relative to the
ideal geometry, with no millepede.res involved (see [doc/WeakModes.md](doc/WeakModes.md)).
`Regularize` (any combination not processing data) rewrites `<DET>_<algParamsOutFile>` — of the
`MilleRes` result, or else of the initial alignment — transferring to each TGeo alignable parent
(`AlignParams.regularizeParents` regex, all if empty; deepest first) the rigid motion robustly (L1/IRLS)
fitted to the displacements of its children's bounding-box corners, sensors kept in place
(`geomutils::transferChildrenCommonMotion`, see [doc/Regularization.md](doc/Regularization.md)). The aligned geometry loaded must be the one of the
initial alignment, otherwise the ideal matrices derived from it are wrong.

If DPL workflow should be piped to a chain of shell comands, it has to have `--run` option before the 1st element not being a workflow, i.e. `... | o2-barrel-alignment-workflow --run | tee my.log`.

## Documentation conventions

- [doc/history.md](doc/history.md) records *why* developments happened (observations, found problems, fixes), in
chronological order. Feature docs and code comments describe only what the code does and how to use it. Whoever
motivates a change by an observation adds the entry to `history.md`, not a narrative to a comment or feature doc.
- Handovers go to `doc/handovers/` (create it when needed), each with a `Date:` line; superseded notes are moved to `doc/obsoleteNotes/`.

## Coding preferences

Prefer readability over efficiency, except in code marked as performance-critical
(e.g. per-hit / per-track loops), where avoiding allocations and virtual calls matters more.
Prefer splitting large functions to logically self-consistent helper methods.

## Architecture

### The volume hierarchy is the central abstraction

All detectors live in **one** tree ([Volume](include/O2Align/Volume.h)), rooted in a fictitious
volume from `Volume::makeRoot()` whose children are the detector top volumes. The root owns no
rigid-body DOFs, so unrelated detector branches are never mutually constrained. Every operation —
`applyDOFConfig`, `finalise`, `writeTree`/`writeRigidBodyConstraints`/`writeParameters`,
`writeMillepedeResults` — is applied once, to the root.

`Volume::finalise()` is the ordering-sensitive heart of the class: it assigns levels, makes sensors
and fictitious volumes define their own `L2G`/`T2L`, derives each volume's local-to-parent matrix
`mL2P` and the jacobians `mJL2P`/`mJP2L` from the (possibly pre-aligned) geometry. It fixes no DOFs:
a free parent DOF with nothing free below it is legitimate (the subtree is aligned as one rigid
body). Call it only on the root, after the DOF configuration.

Conventions that are easy to violate:
- **`isLeaf()` is used as the proxy for "is a sensor"** in the matrix code: a leaf defines its own
matrices, a non-leaf takes them from `TGeoPhysicalNode`. A childless volume that is neither a
sensor nor virtual would therefore silently get an identity `L2G`; `finalise` makes that fatal.
- **`virt = true`** means no alignable entry in the geometry (envelopes, TPC sectors, the mean
vertex). Such a volume must define `L2G` itself, or leave it at the identity deliberately.
- **`setRigidBodyAllowed(false)`** marks volumes that cannot be shifted (the root, the TPC envelope, the mean
vertex): a matching `rigidBody` rule is ignored and no constraint over their
children is generated. Calibration DOFs are unaffected. The TRD/TOF envelopes are allowed: with their
identity `L2G` their DOFs are a global lab-frame motion of the detector, transported to the supermodules on output.
- **Millepede labels** ([Label.h](include/O2Align/Label.h)) are bit-packed
`DOF|CALIB|ID|SENS|DET`. Uniqueness across detectors relies purely on the `DET` field, since every
detector restarts its own volume counter from 0. `Label::DET_GLOBAL` is reserved for the root.

### Detector plugins

Each detector is a [Detector](include/O2Align/Detector.h) subclass with three jobs: `prepareData`
(once per TF, e.g. transforming clusters/tracklets that do not depend on the track), `prepareTrack`
(per track, appending `FrameInfoExt` + `Measurement` to the `Track`), and the protected
`buildHierarchy` (its own stand-alone branch). `Detector::attachTo` grafts that branch under the
common root, discards a branch containing no sensor, and remembers the top as `getTopVolume()`.

`Sensor*` classes (`SensorITS`, `SensorIT3`, `SensorTPC`, `SensorTRD`, `SensorTOF`) exist only to
override `defineMatrixL2G` / `defineMatrixT2L` for volumes whose measurement plane differs from the
geometry volume or has no geometry at all. T2L is always L2G^-1 * RotZ(alpha), see
`Volume::setT2LFromAlpha`. An ITS3 tile has no fixed tracking frame (`hasFixedTrackingFrame()` is
false): its derivatives use the per-cluster frame, `computeT2L(frame.alpha)`.

`DetectorPVT` is a virtual detector with a single sensor-like volume, the mean interaction vertex.
It provides no measurement: frames with `isVertex()` bypass the hierarchy derivative chain, and the
vertex position enters the fit through `DetectorPVT::getPositionLabels()`. The position is a calibration DOF set
(`MeanVertexDOFSet`, X/Y/Z, calib type `meanvertex`), not a rigid body: rigid-body DOFs are never
time-sliced, while calibration DOFs get one label per time slot ([TimeSlotsSet](include/O2Align/TimeSlotsSet.h),
`Volume::setCalibSlots` / `setActiveCalibSlot`), so each mean-vertex slot is aligned independently,
like the TPC drift.

Consequence for any fit of `mp2data.bin` outside pede (e.g. the fit described in [doc/milleSplit.md](doc/milleSplit.md)): the vertex records
measure the mean vertex relative to its reference (typically (0,0)), which can be far from the real beam
(~1.8 mm in Y for the 2025 runs). The mean-vertex calibration labels must then be free parameters of
such a fit; keeping them fixed injects a large transverse vertex pull that fakes rphi-only chip terms.

### From a measurement to global derivatives

In [AlignmentSpec.cxx](src/AlignmentSpec.cxx) the per-point globals are built by walking from the
measurement leaf up to the root: the base derivative in the tracking frame is converted to the
sensor's local frame via `computeJacobianL2T`, then transported level by level with each child's
`getJL2P()`, each volume with a `RigidBodyDOFSet` contributing its columns. The top volume of the
detector participates; the root, having no DOFs, ends the chain.

The chain is implemented once, in `buildPointGlobals()`, called once per point in `fillGBLPoints`; its result
is both added to the GBL point and used by `applyMisalignment()` to inject the misalignment. The derivatives are those of the prediction (= minus those of
the residual), as Millepede expects; where the *measurement* depends on a parameter (the mean-vertex
prior) the sign is flipped accordingly. Calibration derivatives are collected from one volume only,
the direct parent of the measurement leaf (for ITS3 that is the half-barrel sensor above the pseudo
tiles), so a calibration DOF set placed on a leaf or on an envelope is written to the parameter file
but does not yet enter the fit.

`writeRigidBodyConstraints` implements the hierarchical constraint: for each free DOF of a parent,
the weighted mean of the corresponding DOFs of its nearest descendants having a free rigid-body DOF
(children without one are looked through, their jacobians chained with `getJP2L()`) is required to
vanish. The same constraint is also written for a fixed parent DOF flagged by the `pinChildrenMean`
clause of the DOF config ([doc/DOFConfig_rules.md](doc/DOFConfig_rules.md)).

### DOF sets and JSON configuration

[DOFSet](include/O2Align/DOFSet.h) is the DOF-block interface (`nDOFs`, free/fixed mask,
`fillDerivatives` from a `DerivativeContext`): `RigidBodyDOFSet` (TX,TY,TZ,RX,RY,RZ in the local
frame), `LegendreDOFSet` and `InextensionalDOFSet` (deformation modes of ITS3 half-cylinders).

Two JSON files drive a run, both documented by example in the README:
- `dofConfigJson` — `defaults` plus `rules`, each with an fnmatch `match` pattern (also retried with
an implicit leading `*`), a `rigidBody` and/or `calib` clause. Rules are applied in order, a later
match replaces an earlier DOF set. This is the only place where DOFs are freed or fixed; the
hierarchy construction itself fixes nothing.
- `misAlgJson` — misalignment to inject (closure test), empty = none; there are no other switches. A rule file in the
style of `dofConfigJson` ([MisalignmentUtils](include/O2Align/MisalignmentUtils.h) `MisalignmentConfig`, documented in
[doc/MisalignmentTest.md](doc/MisalignmentTest.md)): `match` regex, `rigidBody` DOF values, `calib` values. It is
validated in `buildHierarchy` against the final DOF configuration (a DOF which is not free is `LOGP(fatal)`). The values
are injected linearly with the derivatives of `buildPointGlobals` in `applyMisalignment`, only
`"model": "exact"` ITS3 Legendre/inextensional use the non-linear evaluators. At stage 3 the injected values (and the
`misAlgRefMilleRes` control run) are subtracted label by label from the fit before `result.json` is written, and the sensor-level
`closure.json` is produced. It is applied when the GBL points are filled, which is serial; only the detector
`prepareTrack` + KF refit run under OpenMP (`nthreads`).

## Repository notes

- `scripts/` holds the shell/Python/ROOT helpers of the workflow (`setenv_align.sh`, `o2data2mille.sh`, `solPede.sh`,
`makeCDB.sh`, `drawWeakModes.C`, …) installed to `$O2_ROOT/share/Detectors/Align/scripts`, e.g. `CreateTimeSlots.C`,
which produces the mean-vertex time-slot JSON consumed by `AlignParams.MVTimeSlotsJson`.
- `varia/` holds one-off study scripts and ROOT macros, not installed. Every ROOT macro of `scripts/` and `varia/` is
registered in `CMakeLists.txt` with `o2_add_test_root_macro`: add a new macro there too.
- Stray `core_dump_*` and `*.json` run products in the working tree are not git-ignored, so do not `git add -A`.
Loading