/cms:awkward-arrayfrom cms
Manipulates jagged or variable-length arrays in Python with Awkward Array 2 (import awkward as ak).
Ships in cms. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Awkward Array handles nested, variable-length data such as "a list of muons per
event" with NumPy-style vectorized operations, so no Python loops over events
are needed. CMS NanoAOD stores each collection as flat branches (Muon_pt,
Muon_eta, …) plus a counter (nMuon). uproot reads them as jagged arrays
(N * var * float32), and you zip them into records.
Workflow (from the IRIS-HEP skill this one is adapted from):
ak.zip the branches of each collection.CMS NanoAOD kinematics are in GeV.
*Idx*)cannot slice, index out of range), unexpected NonesFor physics vectors (Momentum4D, .deltaR, .mass) use the vector
library with vector.register_awkward(). A short example is in the asset
script.
| Concept | Meaning |
|---|---|
axis=0 | Events. axis=1 (or -1 for the innermost) is objects within an event |
| Type string | 20000 * var * float32 means 20000 events, variable number of floats each. Print with ak.type(x) |
| Record | ak.zip({"pt": ..., "eta": ...}) gives var * {pt, eta}; access fields as mu.pt or mu["pt"] |
ak.num(x, 1) | Number of entries per event (equals NanoAOD nMuon) |
ak.count(x, 1) | Number of non-None entries per event |
| Option type | ?float32: values may be None, produced by ak.firsts, ak.mask, ak.pad_none, argmax |
| Masks | Boolean arrays with the same jagged structure select objects; 1D per-event booleans select events |
import awkward as ak, numpy as np, uproot
url = "root://eospublic.cern.ch//eos/opendata/cms/.../NANOAODSIM/.../0082C29D-....root"
f = uproot.open(url) # pip env with fsspec-xrootd
# f = uproot.open(url, handler=uproot.source.xrootd.XRootDSource) # inside CMSSW
arr = f["Events"].arrays(["Muon_pt", "Muon_eta", "Muon_phi", "Muon_mass", "Muon_charge",
"Jet_pt", "Jet_eta", "Jet_phi", "genWeight"],
entry_stop=20000) # read only needed branches
mu_all = f["Events"].arrays(filter_name="Muon_*", how="zip", entry_stop=5).Muon # auto-zip by prefix
See io-and-environments.md for XRootD
backends, cut=, Parquet and JSON.
muons = ak.zip({"pt": arr.Muon_pt, "eta": arr.Muon_eta, "phi": arr.Muon_phi,
"mass": arr.Muon_mass, "charge": arr.Muon_charge})
jets = ak.zip({"pt": arr.Jet_pt, "eta": arr.Jet_eta, "phi": arr.Jet_phi})
good = muons[(muons.pt > 20) & (abs(muons.eta) < 2.4)] # object mask: jagged booleans
sel = ak.num(good, axis=1) >= 2 # event mask: one bool per event
good, jets, weights = good[sel], jets[sel], arr.genWeight[sel] # SAME mask on every per-event array
pairs = ak.combinations(good, 2, fields=["m1", "m2"]) # unique pairs within a collection
pairs = pairs[pairs.m1.charge != pairs.m2.charge] # opposite sign
mll = np.sqrt(2 * pairs.m1.pt * pairs.m2.pt *
(np.cosh(pairs.m1.eta - pairs.m2.eta) - np.cos(pairs.m1.phi - pairs.m2.phi)))
j, m = ak.unzip(ak.cartesian([jets, good], axis=1, nested=True)) # per jet: all muons
dphi = (j.phi - m.phi + np.pi) % (2 * np.pi) - np.pi
clean_jets = jets[ak.all(np.sqrt((j.eta - m.eta) ** 2 + dphi**2) > 0.4, axis=-1)]
nested=True keeps one list per jet, so reducing with axis=-1 gives one
boolean per jet.
lead_pt = ak.firsts(good.pt) # None where no muon; good.pt[:, 0] would raise
i = ak.argmax(good.pt, axis=1, keepdims=True) # keepdims keeps [[i], [None], ...] for slicing
lead = ak.firsts(good[i]) # general "best candidate" pattern
NanoAOD collections are already pt-ordered, so ak.firsts(good.pt) is the
leading one. Use argmax for other criteria (e.g. best b-tag score).
Jet_muonIdx1, Electron_jetIdx, …)idx = ak.mask(jets.muonIdx1, jets.muonIdx1 >= 0) # -1 -> None
matched_mu_pt = muons.pt[idx] # None where no match
Index into the unfiltered collection: the indices refer to positions in
the original Muon_* arrays.
good["pt_x2"] = good.pt * 2 # top-level field (ak.with_field under the hood)
ev = ak.zip({"mu": good}, depth_limit=1)
ev["mu", "is_hard"] = ev.mu.pt > 50 # nested field
values = ak.to_numpy(ak.flatten(mll, axis=1)) # one entry per pair -> np.histogram / hist
sumw = float(ak.sum(ak.values_astype(weights, np.float64)))
The full tested example is assets/nanoaod_dimuon.py: a Z→μμ selection, cleaning, index branches and weights, identical results in CMSSW and pip environments.
-1 index branches silently pick the wrong object. Awkward treats -1
as "last element", so muons.pt[jets.muonIdx1] returns the last muon for
unmatched jets, and only raises when the event has no muons at all. Use
ak.mask(idx, idx >= 0) first.keepdims=True indexes events. a[ak.argmax(a, axis=1)]
silently returns whole events. Use keepdims=True then ak.firsts.x[:, 0] raises index out of range if any event's list is empty. Use
ak.firsts(x), or ak.pad_none(x, 1, axis=1)[:, 0].cannot broadcast RegularArray of size N with RegularArray of size M.ak.num vs ak.count: num counts slots, count skips None
([[1, None, 3]] gives 3 vs 2).float32. Summing millions of
them is visibly off, so cast with ak.values_astype(w, np.float64) first.root:// needs an XRootD backend. Plain pip uproot fails with "Install
fsspec-xrootd". In CMSSW pass handler=uproot.source.xrootd.XRootDSource.step_size over root://: use an event count. With fsspec-xrootd,
iterate(..., step_size="100 MB") raises
TypeError: integer argument expected for offset. step_size=200_000 works.
With handler=XRootDSource, call f.close() or the script can hang at exit.ak.abs (use abs() / np.abs),
ak.take, ak.expand_dims, ak.stack (np.stack works only on
rectangular data), ak.fill_like (use ak.full_like / ak.zeros_like).
ak.max and ak.min do exist.ak.from_json("file.json") parses the string itself as JSON. Pass
pathlib.Path("file.json") to read a file.ak.with_field / arr["f"] = ... rebind the
variable, and attribute assignment (arr.f = ...) raises.export PYTHONNOUSERSITE=1 so
~/.local packages don't shadow the release's.num/count/sum/max), axis rules, sorting,
argmin/argmax, flattening, option types, records and NumPy interop.root:// files, choosing branches/cuts in uproot, writing
Parquet/JSON, or setting up awkward in CMSSW vs a pip environment.--url, --entries).awkward-array skill
(BSD 3-Clause; see plugins/cms/VENDORED-LICENSES.md):
https://github.com/iris-hep/marketplace/tree/main/iris-hep/skills/awkward-arrayWhat SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
npx claudepluginhub cms-ml/marketplace --plugin cms10 skills in this plugin
/analysis-spec-builderUse when a user wants to plan, scope or write down a CMS physics analysis or plotting task before coding it: creating or updating an analysis specification, turning a quick request ("plot the dimuon mass in 2016 data vs DY", "find the best trijet in ttbar") into a structured document, listing datasets, triggers, selections, histograms, corrections and statistical treatment, or producing a specification.md for later implementation./cmsswUse when setting up or working inside a CMSSW release area (cmsrel, cmsenv, scram), choosing a CMSSW release or SCRAM_ARCH for a dataset, running an old release inside a cmssw-el7/el8 container, checking out or patching CMSSW packages with git cms-addpkg or git cms-merge-topic, writing or building an EDAnalyzer, EDProducer or EDFilter, writing or debugging a cmsRun Python configuration (_cfg.py, _cfi.py, _cff.py), inspecting EDM ROOT files (MiniAOD, AOD, RECO) with edm* tools, or installing extra Python packages on top of a CMSSW release./combineUse when working with CMS Combine (HiggsAnalysis-CombinedLimit): writing or debugging a datacard or physics model, choosing or running a Combine method (AsymptoticLimits, FitDiagnostics, MultiDimFit, HybridNew, Significance, GoodnessOfFit, ChannelCompatibilityCheck, Impacts), interpreting Combine output, explaining a Combine error message or warning, asking how or why Combine does something, or running a Combine command (combine, text2workspace.py, combineCards.py, combineTool.py) to reproduce, diagnose or confirm a result./hepdataUse when preparing, writing, validating or reviewing a HEPData record for a CMS paper, PAS, or an Open Data study: converting spectra, efficiencies, cutflows, fit results, limits or hist/ROOT histograms into HEPData YAML with hepdata_lib, filling keywords, qualifiers and asymmetric uncertainties, running hepdata-validate, uploading to the HEPData sandbox, following the CMS (EXO, B2G) HEPData and reinterpretation requirements, or debugging errors such as "Got unexpected extra argument", "takes 2 positional arguments", "The tar ball is not valid", "Inconsistent length of 'values' list" or .nan values in the YAML./histUse when creating, filling, slicing, rebinning, normalising or plotting histograms in Python with scikit-hep hist / boost-histogram and mplhep, especially from CMS NanoAOD arrays: choosing axes and binning for GeV quantities, weighted fills with genWeight (including negative weights), normalising MC to cross section times luminosity, categorical axes for regions, processes or systematics, UHI indexing, CMS-style plots with hep.cms.label, ratio panels, or errors such as "has no attribute 'Weight'", "Select 'histtype' from" or "cannot convert to RegularArray" when filling./muon-tag-and-probeUse when measuring muon efficiencies or data/MC scale factors with tag and probe on Z → μμ in CMS NanoAOD: muon ID (tight, medium, high-pT), isolation or single-muon trigger (IsoMu24, Mu50) efficiencies in bins of pT and |η|; choosing tag and probe definitions; matching muons to trigger objects with TrigObj_filterBits; fitting pass and fail m_μμ spectra with signal plus background; comparing with or applying the Muon POG correctionlib JSON (muon_Z.json.gz, muon_HighPt.json.gz); or debugging scale factors that are above 1, differ from the POG by a few percent, or fits that fail in the fail category.Other plugins' skills for the same job