From 61a96c9718799aab9f9f08e3356128d1928eff9f Mon Sep 17 00:00:00 2001 From: Ianna Osborne Date: Thu, 8 Oct 2026 11:19:53 +0200 Subject: [PATCH 01/11] Test the Pythia8 event-generation fragments verbatim in CI Tag the Pythia8 shell fences of 2-1-event-generation with invisible ci-fragment markers, run them in page order in one fresh shell, and validate the produced EDM4hep file with key4hep-validate. The runner fails when no tagged fragment is found, so it cannot pass vacuously. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UKgjg6FJ4R6Jbp3pdhqVQD --- .github/scripts/run_fragments.py | 87 +++++++++++++++++++ .github/workflows/test.yml | 10 ++- .../2-1-event-generation/README.md | 3 + CMakeLists.txt | 16 ++++ 4 files changed, 114 insertions(+), 2 deletions(-) create mode 100755 .github/scripts/run_fragments.py diff --git a/.github/scripts/run_fragments.py b/.github/scripts/run_fragments.py new file mode 100755 index 000000000..595adcbe7 --- /dev/null +++ b/.github/scripts/run_fragments.py @@ -0,0 +1,87 @@ +#!/usr/bin/env python3 +"""Run tagged shell fragments of a tutorial page exactly as written, then check outputs. + +Mark each fence to run with an HTML comment on the line before it (invisible in +the rendered page): + + + ```bash + k4run pythia.py -n 500 ... + ``` + +All fragments with the same tag run, in page order, in ONE fresh bash shell inside +an empty directory, so `cd` and variables carry over as they would for a reader. +Afterwards every `--validate FILE:EVENTS` output is checked with key4hep-validate. +""" + +import argparse +import json +import re +import subprocess +import sys +import tempfile +from pathlib import Path + +MARKER = re.compile(r"^\s*\s*$") +FENCE = re.compile(r"^\s*```\s*(bash|sh|shell)?\s*$") + + +def extract(page, tag): + lines = page.read_text().splitlines() + fragments = [] + for number, line in enumerate(lines): + match = MARKER.match(line) + if not match or match.group(1) != tag: + continue + opening = lines[number + 1] if number + 1 < len(lines) else "" + if not FENCE.match(opening) or not FENCE.match(opening).group(1): + sys.exit(f"{page}:{number + 1}: ci-fragment marker must precede a ```bash fence") + body = [] + for inner in lines[number + 2 :]: + if FENCE.match(inner): + break + body.append(inner) + else: + sys.exit(f"{page}:{number + 2}: unterminated fence") + fragments.append((number + 3, "\n".join(body))) + if not fragments: + # Never pass vacuously: a renamed tag or reformatted page must fail loudly. + sys.exit(f"No fragments tagged {tag!r} in {page}") + return fragments + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("page", type=Path) + parser.add_argument("tag") + parser.add_argument("--validate", action="append", default=[], metavar="FILE:EVENTS") + parser.add_argument("--print", action="store_true", help="Print the script and exit") + args = parser.parse_args() + page = args.page.resolve() + script = ["set -euo pipefail"] + for line, body in extract(page, args.tag): + script += [f"echo '+++ {page.name}:{line}' >&2", body] + script = "\n".join(script) + "\n" + if args.print: + print(script, end="") + return 0 + with tempfile.TemporaryDirectory(prefix=f"fragments-{args.tag}-") as work: + work = Path(work) + (work / "fragments.sh").write_text(script) + subprocess.run(["bash", "fragments.sh"], cwd=work, check=True) + failed = False + for item in args.validate: + name, events = item.rsplit(":", 1) + proc = subprocess.run( + [sys.executable, "-m", "mcp_server_key4hep.cli", "validate", + str(work / name), "--events", events], + capture_output=True, text=True, + ) + result = json.loads(proc.stdout) if proc.stdout.strip() else {"error": proc.stderr} + print(f"{name}: {json.dumps(result, sort_keys=True)}") + failed |= proc.returncode != 0 + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 843dece65..3cec12b48 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -7,6 +7,10 @@ on: # Daily run against the Key4hep nightlies - cron: '0 3 * * *' +env: + # Pin the validator (ianna/mcp-server-key4hep, merge of #2); bump deliberately. + KEY4HEP_VALIDATE_REF: bde7af183f57d14cabc809f1d35b281cd4d5dd69 + jobs: test: runs-on: ubuntu-latest @@ -32,11 +36,13 @@ jobs: 'curl -LO https://github.com/jgm/pandoc/releases/download/3.10/pandoc-3.10-linux-amd64.tar.gz;\ tar -xzf pandoc-3.10-linux-amd64.tar.gz;\ cp pandoc-3.10/bin/pandoc /usr/local/bin/;\ + git clone -q https://github.com/ianna/mcp-server-key4hep.git /tmp/key4hep-validate;\ + git -C /tmp/key4hep-validate checkout -q ${{ env.KEY4HEP_VALIDATE_REF }};\ cd ./Package;\ source ${{ matrix.STACK }} ${{ contains(matrix.STACK, 'sw-nightlies') && '--spack' || '' }};\ mkdir build;\ cd build;\ - cmake ..;\ + cmake -DKEY4HEP_VALIDATE_SRC=/tmp/key4hep-validate/src ..;\ make;\ - make test; + ctest --output-on-failure; ' diff --git a/2-gen-and-fastsim/2-1-event-generation/README.md b/2-gen-and-fastsim/2-1-event-generation/README.md index 6eaed8683..65f165f8c 100644 --- a/2-gen-and-fastsim/2-1-event-generation/README.md +++ b/2-gen-and-fastsim/2-1-event-generation/README.md @@ -93,6 +93,7 @@ The Gaudi steering file needs to activate the `GaudiTool` that interfaces An example of steering file can be found at [pythia.py][pythia-example]. The steering file runs the minimal set of algorithms to run Pythia8 and produce an output in `EDM4hep` format: + ```bash wget https://raw.githubusercontent.com/HEP-FCC/k4Gen/main/k4Gen/options/pythia.py k4run --dry-run pythia.py @@ -104,10 +105,12 @@ with expected output ``` For example, to generate 500 $e^{+}e^{-} \rightarrow \mu^{+}\mu^{-}$ at 91.2 GeV, one can do the following, download the configuration file: + ```bash wget https://raw.githubusercontent.com/HEP-FCC/FCC-config/main/FCCee/Generator/Pythia8/p8_ee_Zmumu_ecm91.cmd ``` and run + ```bash k4run pythia.py -n 500 --out.filename p8_mumu_500.e4h.root --Pythia8.PythiaInterface.pythiacard p8_ee_Zmumu_ecm91.cmd ``` diff --git a/CMakeLists.txt b/CMakeLists.txt index 3542cd55f..3a2d517b6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -26,3 +26,19 @@ add_nb_test("2-gen-and-fastsim/2-1-event-generation/README") add_nb_test("2-gen-and-fastsim/2-2-fastsim-delphes/README") add_nb_test("3-analysis/3-1-higgs-analysis/README") add_nb_test("4-full-detector-sim/FccCaloPerformance/CaloFullSimExercise") + +# Shell fragments run verbatim (see .github/scripts/run_fragments.py), followed by +# structural EDM4hep validation of the files the tutorial tells readers to produce. +set(KEY4HEP_VALIDATE_SRC "" CACHE PATH "src/ directory of a mcp-server-key4hep checkout") +function(add_fragment_test page tag) + get_filename_component(_page_dir ${CMAKE_SOURCE_DIR}/${page} DIRECTORY) + add_test(NAME ${page}-fragments-${tag} + COMMAND python3 ${CMAKE_SOURCE_DIR}/.github/scripts/run_fragments.py + ${CMAKE_SOURCE_DIR}/${page}.md ${tag} ${ARGN} + WORKING_DIRECTORY ${_page_dir}) + set_tests_properties(${page}-fragments-${tag} PROPERTIES + ENVIRONMENT "PYTHONPATH=${KEY4HEP_VALIDATE_SRC}:$ENV{PYTHONPATH}") +endfunction() + +add_fragment_test("2-gen-and-fastsim/2-1-event-generation/README" pythia8 + --validate p8_mumu_500.e4h.root:500) From 07d9b2ac54b4f1041a4ed8d2d50be79f15d6fbdf Mon Sep 17 00:00:00 2001 From: Ianna Osborne Date: Thu, 8 Oct 2026 12:21:30 +0200 Subject: [PATCH 02/11] Report a failing fragment without a Python traceback Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UKgjg6FJ4R6Jbp3pdhqVQD --- .github/scripts/run_fragments.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/.github/scripts/run_fragments.py b/.github/scripts/run_fragments.py index 595adcbe7..ccc74d59d 100755 --- a/.github/scripts/run_fragments.py +++ b/.github/scripts/run_fragments.py @@ -68,7 +68,14 @@ def main(): with tempfile.TemporaryDirectory(prefix=f"fragments-{args.tag}-") as work: work = Path(work) (work / "fragments.sh").write_text(script) - subprocess.run(["bash", "fragments.sh"], cwd=work, check=True) + status = subprocess.run(["bash", "fragments.sh"], cwd=work).returncode + if status: + print( + f"FAILED: fragment exited with status {status}; the failing fence is the " + f"last '+++ {page.name}:LINE' marker above", + file=sys.stderr, + ) + return 1 failed = False for item in args.validate: name, events = item.rsplit(":", 1) From 2667a34cbe3933f27584c134b1f9f386b4fc140b Mon Sep 17 00:00:00 2001 From: Ianna Osborne Date: Thu, 8 Oct 2026 12:54:08 +0200 Subject: [PATCH 03/11] Event generation: use --IOSvc.Output and current dry-run output --- 2-gen-and-fastsim/2-1-event-generation/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/2-gen-and-fastsim/2-1-event-generation/README.md b/2-gen-and-fastsim/2-1-event-generation/README.md index 65f165f8c..e2463ea50 100644 --- a/2-gen-and-fastsim/2-1-event-generation/README.md +++ b/2-gen-and-fastsim/2-1-event-generation/README.md @@ -100,7 +100,7 @@ k4run --dry-run pythia.py ``` with expected output ``` -[k4run - INFO] k4run.main: --> Pythia8 --> HepMCToEDMConverter --> StableParticles --> out +[k4run - INFO] k4run.main: --> eventHeaderCreator --> Pythia8 --> HepMCToEDMConverter --> StableParticles [...] ``` For example, to generate 500 $e^{+}e^{-} \rightarrow \mu^{+}\mu^{-}$ at @@ -112,7 +112,7 @@ wget https://raw.githubusercontent.com/HEP-FCC/FCC-config/main/FCCee/Generator/P and run ```bash -k4run pythia.py -n 500 --out.filename p8_mumu_500.e4h.root --Pythia8.PythiaInterface.pythiacard p8_ee_Zmumu_ecm91.cmd +k4run pythia.py -n 500 --IOSvc.Output p8_mumu_500.e4h.root --Pythia8.PythiaInterface.pythiacard p8_ee_Zmumu_ecm91.cmd ``` From 59169f0f9478f7abde24da551f1cd71530e1577d Mon Sep 17 00:00:00 2001 From: Ianna Osborne Date: Thu, 12 Nov 2026 10:59:44 +0100 Subject: [PATCH 04/11] Make Pythia8 tutorial validation self-contained --- .github/scripts/LICENSE.validate_edm4hep | 201 +++++++++++++++++++++++ .github/scripts/run_fragments.py | 18 +- .github/scripts/validate_edm4hep.py | 84 ++++++++++ .github/workflows/test.yml | 14 +- CMakeLists.txt | 3 - 5 files changed, 298 insertions(+), 22 deletions(-) create mode 100644 .github/scripts/LICENSE.validate_edm4hep create mode 100644 .github/scripts/validate_edm4hep.py diff --git a/.github/scripts/LICENSE.validate_edm4hep b/.github/scripts/LICENSE.validate_edm4hep new file mode 100644 index 000000000..261eeb9e9 --- /dev/null +++ b/.github/scripts/LICENSE.validate_edm4hep @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/.github/scripts/run_fragments.py b/.github/scripts/run_fragments.py index ccc74d59d..7a2f63707 100755 --- a/.github/scripts/run_fragments.py +++ b/.github/scripts/run_fragments.py @@ -11,7 +11,7 @@ All fragments with the same tag run, in page order, in ONE fresh bash shell inside an empty directory, so `cd` and variables carry over as they would for a reader. -Afterwards every `--validate FILE:EVENTS` output is checked with key4hep-validate. +Afterwards every `--validate FILE:EVENTS` output is checked with the local EDM4hep validator. """ import argparse @@ -22,6 +22,8 @@ import tempfile from pathlib import Path +from validate_edm4hep import validate + MARKER = re.compile(r"^\s*\s*$") FENCE = re.compile(r"^\s*```\s*(bash|sh|shell)?\s*$") @@ -79,14 +81,12 @@ def main(): failed = False for item in args.validate: name, events = item.rsplit(":", 1) - proc = subprocess.run( - [sys.executable, "-m", "mcp_server_key4hep.cli", "validate", - str(work / name), "--events", events], - capture_output=True, text=True, - ) - result = json.loads(proc.stdout) if proc.stdout.strip() else {"error": proc.stderr} - print(f"{name}: {json.dumps(result, sort_keys=True)}") - failed |= proc.returncode != 0 + try: + result = validate(work / name, int(events)) + except Exception as exc: + result = {"valid": False, "error": f"{type(exc).__name__}: {exc}"} + failed = True + print(f"{name}: {json.dumps(result, sort_keys=True)}", flush=True) return 1 if failed else 0 diff --git a/.github/scripts/validate_edm4hep.py b/.github/scripts/validate_edm4hep.py new file mode 100644 index 000000000..7aa3fa734 --- /dev/null +++ b/.github/scripts/validate_edm4hep.py @@ -0,0 +1,84 @@ +# SPDX-License-Identifier: Apache-2.0 +# Adapted from ianna/mcp-server-key4hep at bde7af183f57d14cabc809f1d35b281cd4d5dd69. +# The standalone CLI was removed. See LICENSE.validate_edm4hep for license terms. +"""Read every event with podio's backend-independent reader. + +This is structural validation, not a physics-reference comparison. Importing +edm4hep loads dictionaries required by podio. Run in the selected stack. +""" + +import math +from pathlib import Path + + +def validate(path, expected): + import edm4hep # noqa: F401 + import ROOT + from podio.reading import get_reader + + if expected <= 0 or not Path(path).is_file() or Path(path).stat().st_size == 0: + raise ValueError("Expected a nonempty output and a positive event count") + reader = get_reader(str(path)) + if "events" not in reader.categories: + raise ValueError("No events category") + frames = reader.get("events") + if len(frames) != expected: + raise ValueError(f"Event count mismatch: {len(frames)} != {expected}") + particles_total = 0 + schema = None + for frame in frames: + names = set(frame.getAvailableCollections()) + if "MCParticles" not in names: + raise ValueError("Missing MCParticles collection") + if schema is None: + schema = sorted(names) + elif sorted(names) != schema: + raise ValueError("Collection names change between events") + # Force deserialization of every collection, not just the tree header. + for name in names: + collection = frame.get(name) + for _ in collection: + pass + particles = frame.get("MCParticles") + # podio returns std::string_view from getTypeName(). Depending on the + # cppyy/ROOT version, str(view) may describe the proxy instead of its + # contents. Check the dictionary-backed C++ class, not its string proxy. + if not isinstance(particles, ROOT.edm4hep.MCParticleCollection): + actual = getattr(type(particles), "__cpp_name__", type(particles).__name__) + raise ValueError( + "MCParticles has the wrong EDM4hep collection type: " + f"expected edm4hep::MCParticleCollection, got {actual}" + ) + identifiers = set() + for particle in particles: + oid = particle.getObjectID() + identifiers.add((oid.collectionID, oid.index)) + momentum = particle.getMomentum() + if not all( + math.isfinite(v) + for v in ( + momentum.x, + momentum.y, + momentum.z, + particle.getMass(), + particle.getCharge(), + ) + ): + raise ValueError("Non-finite MCParticle values") + for particle in particles: + for related in [*particle.getParents(), *particle.getDaughters()]: + if not related.isAvailable(): + raise ValueError("Unresolved MCParticle relation") + oid = related.getObjectID() + if (oid.collectionID, oid.index) not in identifiers: + raise ValueError("MCParticle relation leaves the required collection") + particles_total += len(particles) + if particles_total == 0: + raise ValueError("No MCParticles in generated sample") + return { + "valid": True, + "entries": expected, + "particles": particles_total, + "collections": schema, + "scope": "EDM4hep structure and MCParticle relations", + } diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 3cec12b48..e742a34aa 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -7,10 +7,6 @@ on: # Daily run against the Key4hep nightlies - cron: '0 3 * * *' -env: - # Pin the validator (ianna/mcp-server-key4hep, merge of #2); bump deliberately. - KEY4HEP_VALIDATE_REF: bde7af183f57d14cabc809f1d35b281cd4d5dd69 - jobs: test: runs-on: ubuntu-latest @@ -32,17 +28,15 @@ jobs: -d ghcr.io/key4hep/key4hep-images/alma9:latest /bin/bash - name: Run tests run: | - docker exec CI_container /bin/bash -c \ - 'curl -LO https://github.com/jgm/pandoc/releases/download/3.10/pandoc-3.10-linux-amd64.tar.gz;\ + docker exec CI_container /bin/bash -e -c \ + 'curl -fLO https://github.com/jgm/pandoc/releases/download/3.10/pandoc-3.10-linux-amd64.tar.gz;\ tar -xzf pandoc-3.10-linux-amd64.tar.gz;\ cp pandoc-3.10/bin/pandoc /usr/local/bin/;\ - git clone -q https://github.com/ianna/mcp-server-key4hep.git /tmp/key4hep-validate;\ - git -C /tmp/key4hep-validate checkout -q ${{ env.KEY4HEP_VALIDATE_REF }};\ cd ./Package;\ source ${{ matrix.STACK }} ${{ contains(matrix.STACK, 'sw-nightlies') && '--spack' || '' }};\ mkdir build;\ cd build;\ - cmake -DKEY4HEP_VALIDATE_SRC=/tmp/key4hep-validate/src ..;\ + cmake ..;\ make;\ - ctest --output-on-failure; + ctest --output-on-failure --no-tests=error; ' diff --git a/CMakeLists.txt b/CMakeLists.txt index 3a2d517b6..1cda4583f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -29,15 +29,12 @@ add_nb_test("4-full-detector-sim/FccCaloPerformance/CaloFullSimExercise") # Shell fragments run verbatim (see .github/scripts/run_fragments.py), followed by # structural EDM4hep validation of the files the tutorial tells readers to produce. -set(KEY4HEP_VALIDATE_SRC "" CACHE PATH "src/ directory of a mcp-server-key4hep checkout") function(add_fragment_test page tag) get_filename_component(_page_dir ${CMAKE_SOURCE_DIR}/${page} DIRECTORY) add_test(NAME ${page}-fragments-${tag} COMMAND python3 ${CMAKE_SOURCE_DIR}/.github/scripts/run_fragments.py ${CMAKE_SOURCE_DIR}/${page}.md ${tag} ${ARGN} WORKING_DIRECTORY ${_page_dir}) - set_tests_properties(${page}-fragments-${tag} PROPERTIES - ENVIRONMENT "PYTHONPATH=${KEY4HEP_VALIDATE_SRC}:$ENV{PYTHONPATH}") endfunction() add_fragment_test("2-gen-and-fastsim/2-1-event-generation/README" pythia8 From fee763dd91be5b6c53b0aa851c8cd4026fda16f0 Mon Sep 17 00:00:00 2001 From: Ianna Osborne Date: Thu, 12 Nov 2026 11:04:10 +0100 Subject: [PATCH 05/11] Use the FCC tutorials license for the validator --- .github/scripts/LICENSE.validate_edm4hep | 201 ----------------------- .github/scripts/validate_edm4hep.py | 2 - 2 files changed, 203 deletions(-) delete mode 100644 .github/scripts/LICENSE.validate_edm4hep diff --git a/.github/scripts/LICENSE.validate_edm4hep b/.github/scripts/LICENSE.validate_edm4hep deleted file mode 100644 index 261eeb9e9..000000000 --- a/.github/scripts/LICENSE.validate_edm4hep +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/.github/scripts/validate_edm4hep.py b/.github/scripts/validate_edm4hep.py index 7aa3fa734..605c1d714 100644 --- a/.github/scripts/validate_edm4hep.py +++ b/.github/scripts/validate_edm4hep.py @@ -1,6 +1,4 @@ -# SPDX-License-Identifier: Apache-2.0 # Adapted from ianna/mcp-server-key4hep at bde7af183f57d14cabc809f1d35b281cd4d5dd69. -# The standalone CLI was removed. See LICENSE.validate_edm4hep for license terms. """Read every event with podio's backend-independent reader. This is structural validation, not a physics-reference comparison. Importing From 1932abe1188541bda8613a46eee8c48936808655 Mon Sep 17 00:00:00 2001 From: Ianna Osborne Date: Thu, 12 Nov 2026 13:14:40 +0100 Subject: [PATCH 06/11] Validate the Whizard ditau tutorial in CI --- .../2-1-event-generation/README.md | 27 ++++++++++++------- CMakeLists.txt | 3 +++ 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/2-gen-and-fastsim/2-1-event-generation/README.md b/2-gen-and-fastsim/2-1-event-generation/README.md index e2463ea50..848581046 100644 --- a/2-gen-and-fastsim/2-1-event-generation/README.md +++ b/2-gen-and-fastsim/2-1-event-generation/README.md @@ -766,7 +766,7 @@ which mg5_aMC ## Hands-on case study: ditau events with Pythia8, Whizard and KKMCee In this section we describe, with exercises, the generation of an equivalent sample of Monte Carlo events with three diffent generators: `Pythia8`, `Whizard` and `KKMCee`. The process chosen is $e^{-}e^{+} \rightarrow \tau^{-}\tau^{+}$ - (hereafter referred to as _ditaus_), with both _taus_ decaying leptonically with a _muon_ in the final state. The centre of mass energy of 91.2 GeV. In the three cases 10000 will be generated and saved in `ROOT` files in `EDM4hep` format: the steps to arrive at this results are however different. + (hereafter referred to as _ditaus_), with both _taus_ decaying leptonically with a _muon_ in the final state. The centre of mass energy of 91.2 GeV. Each workflow produces an EDM4hep ROOT file. The Pythia8 and KKMCee examples use 10,000 events, and the Whizard example uses a 10-event sample. ### Generating ditaus with Pythia8 @@ -824,13 +824,18 @@ i.e. 1458.0 +- 7.7 pb. As explained in the dedicated [Whizard section](#whizard), to use `whizard` we need a `Sindarin` configuration file. To generate ditau events we will use the file [Z_tautau.sin](https://fccsw.web.cern.ch/tutorials/apr2023/tutorial1/Z_tautau.sin): + + ```bash wget https://fccsw.web.cern.ch/tutorials/apr2023/tutorial1/Z_tautau.sin ``` -and run it in a dedicate directory to not pollute the working one with the many files produced: +Run it in a dedicated directory to keep the generated files together. The downloaded +card generates 10 events, which is enough to exercise the conversion. + + ```bash -mkdir -p whizard; cd whizard; -whizard ../Z_tautau.sin +mkdir -p whizard +(cd whizard && whizard ../Z_tautau.sin) ``` The output created by `whizard` is `LHEf` (Les Houches Event format); this is because the current build does not support writing `HepMC`; this may change in the future. @@ -851,10 +856,13 @@ In order to get the events in `EDM4hep` format, we exploit the fact that `Pythia` provides `LHEf` reader functionality. To activate that we will use `Gaudi` and a special `.cmd` file which considers the input `LHEf` input file as a `Beam`. This special `.cmd` is called `p8_lhereader.cmd` and it is available -on the web: +on the web. Download the card and the same Pythia8 steering used above: + + ```bash -cd ../cards -wget https://fccsw.web.cern.ch/tutorials/apr2023/tutorial1/p8_lhereader.cmd +mkdir -p cards config gen/wz_tautau_ecm91 +wget -O cards/p8_lhereader.cmd https://fccsw.web.cern.ch/tutorials/apr2023/tutorial1/p8_lhereader.cmd +wget -O config/pythia.py https://raw.githubusercontent.com/HEP-FCC/k4Gen/main/k4Gen/options/pythia.py ``` Please note the lines ``` @@ -862,7 +870,7 @@ Please note the lines Beams:frameType = 4 ! read info from a LHEF Beams:LHEF = z_tautau.lhe ! the LHEF to read from ``` -This file needs to be edited to enter the exact locaton of the input file (it could also be a symlink to avoid always editng the file. +Run the conversion from the `whizard` directory so Pythia8 finds `z_tautau.lhe` at the relative path in the card. Also note the lines: ``` @@ -879,9 +887,10 @@ As steering we will use the file `pythia.py`. :::{admonition} Answer :class: solution toggle + ```bash cd whizard -k4run ../config/pythia.py -n 10000 --out.filename ../gen/wz_tautau_ecm91/events_1.root --Pythia8.PythiaInterface.pythiacard ../cards/p8_lhereader.cmd | tee wz_ee_Ztautau_mumu_ecm91.log +k4run ../config/pythia.py -n 10 --IOSvc.Output ../gen/wz_tautau_ecm91/events_1.root --Pythia8.PythiaInterface.pythiacard ../cards/p8_lhereader.cmd | tee wz_ee_Ztautau_mumu_ecm91.log ``` ::: diff --git a/CMakeLists.txt b/CMakeLists.txt index 1cda4583f..919379ca2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -39,3 +39,6 @@ endfunction() add_fragment_test("2-gen-and-fastsim/2-1-event-generation/README" pythia8 --validate p8_mumu_500.e4h.root:500) + +add_fragment_test("2-gen-and-fastsim/2-1-event-generation/README" whizard-ditau + --validate gen/wz_tautau_ecm91/events_1.root:10) From 19a4cd37d262f13c526527cadb00531d80ca9b87 Mon Sep 17 00:00:00 2001 From: Ianna Osborne Date: Thu, 12 Nov 2026 13:26:56 +0100 Subject: [PATCH 07/11] Validate the KKMCee ditau tutorial in CI --- .../2-1-event-generation/README.md | 134 ++++++------------ CMakeLists.txt | 3 + 2 files changed, 45 insertions(+), 92 deletions(-) diff --git a/2-gen-and-fastsim/2-1-event-generation/README.md b/2-gen-and-fastsim/2-1-event-generation/README.md index 848581046..da7372cbe 100644 --- a/2-gen-and-fastsim/2-1-event-generation/README.md +++ b/2-gen-and-fastsim/2-1-event-generation/README.md @@ -903,16 +903,13 @@ Currently, `KKMCee` does not have the option to save directly the events in `EDM #### Generating `HepMC` events -**Q:** What are the commands (options) to generate 10000 ditau events and save -them into the file `gen/kk_ee_Ztautau_mumu_ecm91_10000.hepmc`? - -:::{admonition} Suggested answer -:class: callout toggle +From the ditau exercise directory, generate 10,000 events with one tau forced +to decay to a muon: + ```bash -KKMCee -f Tau -e 91.2 -n 10000 -o kk_ee_Zautau_mumu_10000.hepmc -t 2002 +KKMCee -f Tau -e 91.2 -n 10000 -o kk_tautau_10000.hepmc -t 2002 ``` -::: :::{admonition} Expand to see the example of the produced `HepMC` output :class: callout toggle @@ -920,7 +917,7 @@ KKMCee -f Tau -e 91.2 -n 10000 -o kk_ee_Zautau_mumu_10000.hepmc -t 2002 The `HepMC` output is an ASCII format and can browsed with for example `more`: ```bash -more kk_ee_Ztautau_mumu_10000.hepmc +more kk_tautau_10000.hepmc ``` ``` HepMC::Version 3.02.05 @@ -1045,102 +1042,55 @@ $1485.5 \pm 0.007~\mathrm{pb}$. #### `HepMC` to `EDM4hep` conversion -In order to get the events in `EDM4hep` format, we will use `Gaudi` and the -tools available in [k4FWCore](https://github.com/key4hep/k4FWCore) and -[k4Gen](https://github.com/key4hep/k4Gen/). We need a Gaudi steering file that -reads the `HepMC` file and writes out the `EDM4hep` file. -A minimal version of such a steering code is available on the tutorial reference -page: -```bash -wget https://fccsw.web.cern.ch/tutorials/apr2023/tutorial1/hepmc2edm.py -``` -Let's see what it does: that is shown by the first line of the help function -```bash -k4run hepmc2edm.py -h -``` -``` - --> GenAlg --> HepMCToEDMConverter --> out -... -``` - -##### Dissection of `hepmc2edm.py` - -:::{admonition} Expand -:class: discussion toggle +`HepMCFileReader` supplies events to `GenAlg`. The converter writes +`MCParticles`, keeping all HepMC statuses so the analysis can access both +the original taus and their decay products. `IOSvc` writes the EDM4hep file. -The tool that we need is [HepMCFileReader](https://github.com/HEP-FCC/k4Gen/blob/main/k4Gen/src/components/HepMCFileReader.h), which is a `GaudiTool`, not a `GaudiAlgorithm`, which is used as a signal provider (such as a Monte Carlo generator) within the [Generator Algorithm (GenAlg)](https://github.com/HEP-FCC/k4Gen/blob/main/k4Gen/src/components/GenAlg.h). This is done in this part of the code: -```python -from Configurables import HepMCFileReader -hepmcreader = HepMCFileReader() + +```bash +mkdir -p config gen/kk_tautau_ecm91 +cat > config/hepmc2edm.py <<'PYTHON' +from Configurables import EventDataSvc, GenAlg, GenParticleFilter, HepMCFileReader +from Configurables import HepMCToEDMConverter +from k4FWCore import ApplicationMgr, IOSvc -from Configurables import GenAlg -reader = GenAlg() -reader.SignalProvider = hepmcreader +reader = GenAlg("GenAlg") +reader.SignalProvider = HepMCFileReader("HepMCFileReader") reader.hepmc.Path = "hepmc" -ApplicationMgr().TopAlg += [reader] -``` -Then we convert the event from `HepMC` to `EDM4hep` with the [HepMCToEDMConverter](https://github.com/HEP-FCC/k4Gen/blob/main/k4Gen/src/components/HepMCToEDMConverter.h): -```python -from Configurables import HepMCToEDMConverter -hepmc_converter = HepMCToEDMConverter() -hepmc_converter.hepmc.Path="hepmc" -hepmc_converter.GenParticles.Path = "GenParticles" -ApplicationMgr().TopAlg += [hepmc_converter] -``` +converter = HepMCToEDMConverter() +converter.hepmc.Path = "hepmc" +converter.hepmcStatusList = [] +converter.GenParticles.Path = "MCParticles" -Finally we write out the converted events into a file with the [PodioOutput](https://github.com/key4hep/k4FWCore/blob/master/k4FWCore/components/PodioOutput.h) algorithm: -```python -from Configurables import PodioOutput -out = PodioOutput("out", filename = "hepmc2edm_output.root") -out.outputCommands = ["keep *"] -ApplicationMgr().TopAlg += [out] -``` -::: +stable_particles = GenParticleFilter("StableParticles") +stable_particles.accept = [1] +stable_particles.GenParticles.Path = "MCParticles" +stable_particles.GenParticlesFiltered.Path = "MCParticlesStable" -##### Running `hepmc2edm.py` +io = IOSvc() +io.Output = "hepmc2edm_output.root" +io.outputCommands = ["keep *"] -Among the `hepmc2edm` switches relevant for the purpose are those controlling -input an output files: -```bash -k4run hepmc2edm.py -h -``` -``` -... - --GenAlg.HepMCFileReader.Filename [GENALG.HEPMCFILEREADER.FILENAME], --Filename.GenAlg.HepMCFileReader [GENALG.HEPMCFILEREADER.FILENAME] - Name of the HepMC file to read [HepMCFileReader] -... - --out.filename [OUT.FILENAME], --filename.out [OUT.FILENAME] - Name of the file to create [PodioOutput] -... +ApplicationMgr( + EvtSel="NONE", + EvtMax=1, + ExtSvc=[EventDataSvc("EventDataSvc"), io], + TopAlg=[reader, converter, stable_particles], +) +PYTHON ``` -**Q:** We would like the output file to be called -`kk_Ztautau_mumu_10000.e4h.root` . Which command should we use for that? -:::{admonition} Answer -:class: solution toggle +Use `-n` to override the steering file's one-event default. The +`--GenAlg.HepMCFileReader.Filename` and `--IOSvc.Output` options select the +input and output files: + ```bash -k4run config/hepmc2edm.py -n 10000 --GenAlg.HepMCFileReader.Filename kk/kk_tautau_10000.hepmc --out.filename gen/kk_tautau_ecm91/events_1.root -``` -::: - -**Q:** Can you explain why we need to pass the `-n 10000` switch and how you -could modify `hepmc2edm.py` to avoid that? - -:::{admonition} Check answer -:class: solution toggle - -Because `hepmc2edm.py` contains this piece of code: -```python -from Configurables import ApplicationMgr -ApplicationMgr( - EvtSel='NONE', - EvtMax=1, - OutputLevel=INFO, +k4run config/hepmc2edm.py -n 10000 \ + --GenAlg.HepMCFileReader.Filename kk_tautau_10000.hepmc \ + --IOSvc.Output gen/kk_tautau_ecm91/events_1.root ``` -The setting `EvtMax=1` is overwritten by `-n `. To avoid this one could set `EvtMax=10000` inside `hepmc2edm.py` (try!) -::: Note _en passant_ that the `EDM4hep` file is much smaller than the `HepMC` one: ```bash diff --git a/CMakeLists.txt b/CMakeLists.txt index 919379ca2..5b08b4ff9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -42,3 +42,6 @@ add_fragment_test("2-gen-and-fastsim/2-1-event-generation/README" pythia8 add_fragment_test("2-gen-and-fastsim/2-1-event-generation/README" whizard-ditau --validate gen/wz_tautau_ecm91/events_1.root:10) + +add_fragment_test("2-gen-and-fastsim/2-1-event-generation/README" kkmcee-ditau + --validate gen/kk_tautau_ecm91/events_1.root:10000) From 0b77db11e469d3536bd647e2d5661ed881284238 Mon Sep 17 00:00:00 2001 From: Ianna Osborne Date: Thu, 12 Nov 2026 14:37:17 +0100 Subject: [PATCH 08/11] Validate BHLUMI and BabaYaga LHE output in CI --- .github/scripts/run_fragments.py | 25 ++++++++----- .github/scripts/validate_lhe.py | 37 +++++++++++++++++++ .../2-1-event-generation/README.md | 14 +++++++ CMakeLists.txt | 8 +++- 4 files changed, 73 insertions(+), 11 deletions(-) create mode 100644 .github/scripts/validate_lhe.py diff --git a/.github/scripts/run_fragments.py b/.github/scripts/run_fragments.py index 7a2f63707..23a0fab82 100755 --- a/.github/scripts/run_fragments.py +++ b/.github/scripts/run_fragments.py @@ -11,7 +11,8 @@ All fragments with the same tag run, in page order, in ONE fresh bash shell inside an empty directory, so `cd` and variables carry over as they would for a reader. -Afterwards every `--validate FILE:EVENTS` output is checked with the local EDM4hep validator. +Afterwards, check EDM4hep outputs with `--validate FILE:EVENTS` and LHE outputs +with `--validate-lhe FILE:EVENTS`. """ import argparse @@ -22,7 +23,8 @@ import tempfile from pathlib import Path -from validate_edm4hep import validate +from validate_edm4hep import validate as validate_edm4hep +from validate_lhe import validate as validate_lhe MARKER = re.compile(r"^\s*\s*$") FENCE = re.compile(r"^\s*```\s*(bash|sh|shell)?\s*$") @@ -57,6 +59,7 @@ def main(): parser.add_argument("page", type=Path) parser.add_argument("tag") parser.add_argument("--validate", action="append", default=[], metavar="FILE:EVENTS") + parser.add_argument("--validate-lhe", action="append", default=[], metavar="FILE:EVENTS") parser.add_argument("--print", action="store_true", help="Print the script and exit") args = parser.parse_args() page = args.page.resolve() @@ -79,14 +82,16 @@ def main(): ) return 1 failed = False - for item in args.validate: - name, events = item.rsplit(":", 1) - try: - result = validate(work / name, int(events)) - except Exception as exc: - result = {"valid": False, "error": f"{type(exc).__name__}: {exc}"} - failed = True - print(f"{name}: {json.dumps(result, sort_keys=True)}", flush=True) + checks = [(args.validate, validate_edm4hep), (args.validate_lhe, validate_lhe)] + for items, validate in checks: + for item in items: + name, events = item.rsplit(":", 1) + try: + result = validate(work / name, int(events)) + except Exception as exc: + result = {"valid": False, "error": f"{type(exc).__name__}: {exc}"} + failed = True + print(f"{name}: {json.dumps(result, sort_keys=True)}", flush=True) return 1 if failed else 0 diff --git a/.github/scripts/validate_lhe.py b/.github/scripts/validate_lhe.py new file mode 100644 index 000000000..ffab3c1d6 --- /dev/null +++ b/.github/scripts/validate_lhe.py @@ -0,0 +1,37 @@ +"""Check the structure and event count of a Les Houches Event file.""" + +from xml.etree import ElementTree + + +def validate(path, expected): + if expected <= 0: + raise ValueError("Expected a positive event count") + + with path.open("rb") as stream: + elements = ElementTree.iterparse(stream, events=("start", "end")) + _, root = next(elements) + if root.tag != "LesHouchesEvents": + raise ValueError("Expected a LesHouchesEvents document") + + depth = 1 + initialized = False + count = 0 + for action, element in elements: + if action == "start": + depth += 1 + continue + if depth == 2: + if element.tag == "init": + initialized = bool(element.text and element.text.strip()) + elif element.tag == "event": + if not initialized: + raise ValueError("Missing LHE initialization before events") + count += 1 + if not element.text or not element.text.strip(): + raise ValueError(f"Empty LHE event {count}") + root.remove(element) + depth -= 1 + + if count != expected: + raise ValueError(f"Event count mismatch: {count} != {expected}") + return {"valid": True, "entries": count, "scope": "LHE structure and event count"} diff --git a/2-gen-and-fastsim/2-1-event-generation/README.md b/2-gen-and-fastsim/2-1-event-generation/README.md index da7372cbe..37bfcd63c 100644 --- a/2-gen-and-fastsim/2-1-event-generation/README.md +++ b/2-gen-and-fastsim/2-1-event-generation/README.md @@ -687,6 +687,13 @@ Additional switches (for experts only): ::: +A short run at 91.2 GeV produces a 100-event LHE sample: + + +```bash +BHLUMI -f 0.022 -t 0.082 -x 0.001 -e 91.2 -n 100 -o bhlumi_100.LHE +``` + ### BabaYaga `BabaYaga` is a Monte Carlo generator of two-photons events used at LEP. @@ -738,6 +745,13 @@ babayaga -c babayaga.input -o bbyg.LHE ::: +A short run at 91.2 GeV produces a 100-event LHE sample: + + +```bash +babayaga -f 15. -t 165. -e 91.2 -n 100 -o bbyg_100.LHE +``` + ### Herwig diff --git a/CMakeLists.txt b/CMakeLists.txt index 5b08b4ff9..db77f742c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -28,7 +28,7 @@ add_nb_test("3-analysis/3-1-higgs-analysis/README") add_nb_test("4-full-detector-sim/FccCaloPerformance/CaloFullSimExercise") # Shell fragments run verbatim (see .github/scripts/run_fragments.py), followed by -# structural EDM4hep validation of the files the tutorial tells readers to produce. +# structural validation of the files the tutorial tells readers to produce. function(add_fragment_test page tag) get_filename_component(_page_dir ${CMAKE_SOURCE_DIR}/${page} DIRECTORY) add_test(NAME ${page}-fragments-${tag} @@ -45,3 +45,9 @@ add_fragment_test("2-gen-and-fastsim/2-1-event-generation/README" whizard-ditau add_fragment_test("2-gen-and-fastsim/2-1-event-generation/README" kkmcee-ditau --validate gen/kk_tautau_ecm91/events_1.root:10000) + +add_fragment_test("2-gen-and-fastsim/2-1-event-generation/README" bhlumi + --validate-lhe bhlumi_100.LHE:100) + +add_fragment_test("2-gen-and-fastsim/2-1-event-generation/README" babayaga + --validate-lhe bbyg_100.LHE:100) From 4337e1080266a819f80c02a7acbb24812459a0ff Mon Sep 17 00:00:00 2001 From: Ianna Osborne Date: Thu, 12 Nov 2026 14:44:30 +0100 Subject: [PATCH 09/11] Validate Herwig and MadGraph5 tutorial output in CI --- .github/scripts/run_fragments.py | 11 ++++- .github/scripts/validate_hepmc.py | 40 ++++++++++++++++ .../2-1-event-generation/README.md | 46 +++++++++++++++++++ CMakeLists.txt | 6 +++ 4 files changed, 101 insertions(+), 2 deletions(-) create mode 100644 .github/scripts/validate_hepmc.py diff --git a/.github/scripts/run_fragments.py b/.github/scripts/run_fragments.py index 23a0fab82..abe5504f5 100755 --- a/.github/scripts/run_fragments.py +++ b/.github/scripts/run_fragments.py @@ -12,7 +12,8 @@ All fragments with the same tag run, in page order, in ONE fresh bash shell inside an empty directory, so `cd` and variables carry over as they would for a reader. Afterwards, check EDM4hep outputs with `--validate FILE:EVENTS` and LHE outputs -with `--validate-lhe FILE:EVENTS`. +with `--validate-lhe FILE:EVENTS`, or HepMC3 ASCII outputs with +`--validate-hepmc FILE:EVENTS`. """ import argparse @@ -24,6 +25,7 @@ from pathlib import Path from validate_edm4hep import validate as validate_edm4hep +from validate_hepmc import validate as validate_hepmc from validate_lhe import validate as validate_lhe MARKER = re.compile(r"^\s*\s*$") @@ -60,6 +62,7 @@ def main(): parser.add_argument("tag") parser.add_argument("--validate", action="append", default=[], metavar="FILE:EVENTS") parser.add_argument("--validate-lhe", action="append", default=[], metavar="FILE:EVENTS") + parser.add_argument("--validate-hepmc", action="append", default=[], metavar="FILE:EVENTS") parser.add_argument("--print", action="store_true", help="Print the script and exit") args = parser.parse_args() page = args.page.resolve() @@ -82,7 +85,11 @@ def main(): ) return 1 failed = False - checks = [(args.validate, validate_edm4hep), (args.validate_lhe, validate_lhe)] + checks = [ + (args.validate, validate_edm4hep), + (args.validate_lhe, validate_lhe), + (args.validate_hepmc, validate_hepmc), + ] for items, validate in checks: for item in items: name, events = item.rsplit(":", 1) diff --git a/.github/scripts/validate_hepmc.py b/.github/scripts/validate_hepmc.py new file mode 100644 index 000000000..c3a592795 --- /dev/null +++ b/.github/scripts/validate_hepmc.py @@ -0,0 +1,40 @@ +"""Check the framing and event count of a HepMC3 ASCII file.""" + +START = "HepMC::Asciiv3-START_EVENT_LISTING" +END = "HepMC::Asciiv3-END_EVENT_LISTING" + + +def validate(path, expected): + if expected <= 0: + raise ValueError("Expected a positive event count") + + count = 0 + with path.open() as stream: + if not next(stream, "").startswith("HepMC::Version ") or next(stream, "").strip() != START: + raise ValueError("Expected a HepMC3 ASCII header") + + declared_particles = particles = 0 + for line in stream: + record = line.split() + if not record: + continue + if record[0] in ("E", END): + if particles != declared_particles: + raise ValueError(f"Particle count mismatch in HepMC event {count}") + if record[0] == END: + break + count += 1 + declared_particles = int(record[3]) + if declared_particles <= 0: + raise ValueError(f"Empty HepMC event {count}") + particles = 0 + elif record[0] == "P": + particles += 1 + else: + raise ValueError("Missing HepMC3 end marker") + if any(line.strip() for line in stream): + raise ValueError("Unexpected data after the HepMC3 end marker") + + if count != expected: + raise ValueError(f"Event count mismatch: {count} != {expected}") + return {"valid": True, "entries": count, "scope": "HepMC3 ASCII framing and event count"} diff --git a/2-gen-and-fastsim/2-1-event-generation/README.md b/2-gen-and-fastsim/2-1-event-generation/README.md index 37bfcd63c..3b2bc01dc 100644 --- a/2-gen-and-fastsim/2-1-event-generation/README.md +++ b/2-gen-and-fastsim/2-1-event-generation/README.md @@ -764,6 +764,27 @@ which Herwig /cvmfs/sw.hsf.org/spackages7/herwig3/7.2.3/x86_64-centos7-gcc11.2.0-opt/q3pxd/bin/Herwig ``` +This example runs Herwig's built-in electron–positron setup at 91.2 GeV. +It generates 100 quark–antiquark events and writes the showered and hadronized +events in HepMC3 ASCII format. + + +```bash +cat > fcc-lep.in <<'HERWIG' +read snippets/EECollider.in +cd /Herwig/MatrixElements +insert SubProcess:MatrixElements 0 MEee2gZ2qq +cd /Herwig/Generators +set EventGenerator:EventHandler:LuminosityFunction:Energy 91.2 +read snippets/HepMC.in +set /Herwig/Analysis/HepMC:Format GenEventHepMC3 +set /Herwig/Analysis/HepMC:Filename herwig_100.hepmc +saverun fcc-lep EventGenerator +HERWIG +Herwig read fcc-lep.in +Herwig run fcc-lep.run -N 100 +``` + ### MadGraph5 @@ -776,6 +797,31 @@ which mg5_aMC /cvmfs/sw.hsf.org/spackages7/madgraph5amc/2.8.1/x86_64-centos7-gcc11.2.0-opt/nlauf/bin/mg5_aMC ``` +This example generates 100 electron–positron dimuon events at 91.2 GeV. +MadGraph writes the unweighted hard-process events in LHE format. + + +```bash +cat > fcc-mumu.mg5 <<'MADGRAPH' +set run_mode 0 +set automatic_html_opening False +generate e+ e- > mu+ mu- +output fcc_mumu -f +launch fcc_mumu +shower=OFF +done +set lpp1 0 +set lpp2 0 +set ebeam1 45.6 +set ebeam2 45.6 +set nevents 100 +set use_syst False +done +MADGRAPH +mg5_aMC fcc-mumu.mg5 +gzip -dc fcc_mumu/Events/run_01/unweighted_events.lhe.gz > madgraph5_100.lhe +``` + ## Hands-on case study: ditau events with Pythia8, Whizard and KKMCee diff --git a/CMakeLists.txt b/CMakeLists.txt index db77f742c..ca014e91c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -51,3 +51,9 @@ add_fragment_test("2-gen-and-fastsim/2-1-event-generation/README" bhlumi add_fragment_test("2-gen-and-fastsim/2-1-event-generation/README" babayaga --validate-lhe bbyg_100.LHE:100) + +add_fragment_test("2-gen-and-fastsim/2-1-event-generation/README" herwig + --validate-hepmc herwig_100.hepmc:100) + +add_fragment_test("2-gen-and-fastsim/2-1-event-generation/README" madgraph5 + --validate-lhe madgraph5_100.lhe:100) From d836ac6895dd5d7d7e115b072816c20a2f569878 Mon Sep 17 00:00:00 2001 From: Ianna Osborne Date: Thu, 12 Nov 2026 15:27:03 +0100 Subject: [PATCH 10/11] Validate the accepted BabaYaga event count --- .github/scripts/run_fragments.py | 7 ++++--- .github/scripts/validate_lhe.py | 11 +++++++---- 2-gen-and-fastsim/2-1-event-generation/README.md | 3 ++- CMakeLists.txt | 2 +- 4 files changed, 14 insertions(+), 9 deletions(-) diff --git a/.github/scripts/run_fragments.py b/.github/scripts/run_fragments.py index 23a0fab82..0d66288a5 100755 --- a/.github/scripts/run_fragments.py +++ b/.github/scripts/run_fragments.py @@ -12,7 +12,7 @@ All fragments with the same tag run, in page order, in ONE fresh bash shell inside an empty directory, so `cd` and variables carry over as they would for a reader. Afterwards, check EDM4hep outputs with `--validate FILE:EVENTS` and LHE outputs -with `--validate-lhe FILE:EVENTS`. +with `--validate-lhe FILE:EVENTS`. LHE counts can also be a MIN-MAX range. """ import argparse @@ -59,7 +59,7 @@ def main(): parser.add_argument("page", type=Path) parser.add_argument("tag") parser.add_argument("--validate", action="append", default=[], metavar="FILE:EVENTS") - parser.add_argument("--validate-lhe", action="append", default=[], metavar="FILE:EVENTS") + parser.add_argument("--validate-lhe", action="append", default=[], metavar="FILE:COUNT_OR_RANGE") parser.add_argument("--print", action="store_true", help="Print the script and exit") args = parser.parse_args() page = args.page.resolve() @@ -87,7 +87,8 @@ def main(): for item in items: name, events = item.rsplit(":", 1) try: - result = validate(work / name, int(events)) + count = events if validate is validate_lhe else int(events) + result = validate(work / name, count) except Exception as exc: result = {"valid": False, "error": f"{type(exc).__name__}: {exc}"} failed = True diff --git a/.github/scripts/validate_lhe.py b/.github/scripts/validate_lhe.py index ffab3c1d6..9368d0acd 100644 --- a/.github/scripts/validate_lhe.py +++ b/.github/scripts/validate_lhe.py @@ -4,8 +4,11 @@ def validate(path, expected): - if expected <= 0: - raise ValueError("Expected a positive event count") + minimum, separator, maximum = str(expected).partition("-") + minimum = int(minimum) + maximum = int(maximum) if separator else minimum + if not 0 < minimum <= maximum: + raise ValueError("Expected a positive event count or an increasing range") with path.open("rb") as stream: elements = ElementTree.iterparse(stream, events=("start", "end")) @@ -32,6 +35,6 @@ def validate(path, expected): root.remove(element) depth -= 1 - if count != expected: - raise ValueError(f"Event count mismatch: {count} != {expected}") + if not minimum <= count <= maximum: + raise ValueError(f"Event count mismatch: got {count}, expected {expected}") return {"valid": True, "entries": count, "scope": "LHE structure and event count"} diff --git a/2-gen-and-fastsim/2-1-event-generation/README.md b/2-gen-and-fastsim/2-1-event-generation/README.md index 37bfcd63c..5d511e98b 100644 --- a/2-gen-and-fastsim/2-1-event-generation/README.md +++ b/2-gen-and-fastsim/2-1-event-generation/README.md @@ -745,7 +745,8 @@ babayaga -c babayaga.input -o bbyg.LHE ::: -A short run at 91.2 GeV produces a 100-event LHE sample: +This short run at 91.2 GeV requests 100 trials. BabaYaga writes the events +that pass its cuts, so the LHE file can contain fewer than 100 events. ```bash diff --git a/CMakeLists.txt b/CMakeLists.txt index db77f742c..88054b349 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -50,4 +50,4 @@ add_fragment_test("2-gen-and-fastsim/2-1-event-generation/README" bhlumi --validate-lhe bhlumi_100.LHE:100) add_fragment_test("2-gen-and-fastsim/2-1-event-generation/README" babayaga - --validate-lhe bbyg_100.LHE:100) + --validate-lhe bbyg_100.LHE:1-100) From 3846d8ae58cb89b133eec288074d743c697ad6ae Mon Sep 17 00:00:00 2001 From: Ianna Osborne Date: Thu, 12 Nov 2026 15:27:40 +0100 Subject: [PATCH 11/11] Set up Herwig runtime dependencies in CI --- .github/scripts/setup_herwig_ci.sh | 36 ++++++++++++++++++++++++++++++ .github/workflows/test.yml | 1 + 2 files changed, 37 insertions(+) create mode 100644 .github/scripts/setup_herwig_ci.sh diff --git a/.github/scripts/setup_herwig_ci.sh b/.github/scripts/setup_herwig_ci.sh new file mode 100644 index 000000000..2a50e0eef --- /dev/null +++ b/.github/scripts/setup_herwig_ci.sh @@ -0,0 +1,36 @@ +# Source after the Key4hep setup, from the CTest build directory. +# Some Key4hep builds omit ThePEG's nested lib directory from Herwig's search path. +herwig_binary=$(command -v Herwig) +herwig_links=$(ldd "$herwig_binary") +thepeg_soname=$(awk '$1 ~ /^libThePEG\.so\./ && $3 == "not" {print $1; exit}' <<< "$herwig_links") +if [[ -n "$thepeg_soname" ]]; then + # Look alongside the selected Herwig package in the active CVMFS stack. + herwig_package=$(dirname "$(dirname "$(realpath "$herwig_binary")")") + packages_dir=$(dirname "$herwig_package") + stack_dir=$(dirname "$packages_dir") + thepeg_libraries=() + for candidate in "$stack_dir"/thepeg/*/lib/ThePEG/"$thepeg_soname" \ + "$packages_dir"/thepeg-*/lib/ThePEG/"$thepeg_soname"; do + if [[ -f "$candidate" ]]; then + thepeg_libraries+=("$candidate") + fi + done + if [[ ${#thepeg_libraries[@]} -ne 1 ]]; then + printf 'Expected one %s alongside Herwig in %s, found %s\n' \ + "$thepeg_soname" "$herwig_package" "${#thepeg_libraries[@]}" >&2 + return 1 + fi + thepeg_libdir=$(dirname "${thepeg_libraries[0]}") + export LD_LIBRARY_PATH="$thepeg_libdir${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" +fi + +# Herwig loads these defaults even for the electron–positron steering. +pdf_dir="$PWD/herwig-pdf" +for pdf_set in CT14lo CT14nlo; do + mkdir -p "$pdf_dir/$pdf_set" + for pdf_file in "$pdf_set.info" "${pdf_set}_0000.dat"; do + curl -fsSL --retry 3 "https://lhapdfsets.web.cern.ch/current/$pdf_set/$pdf_file" \ + -o "$pdf_dir/$pdf_set/$pdf_file" + done +done +export LHAPDF_DATA_PATH="$pdf_dir${LHAPDF_DATA_PATH:+:$LHAPDF_DATA_PATH}" diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index e742a34aa..de42595b9 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -36,6 +36,7 @@ jobs: source ${{ matrix.STACK }} ${{ contains(matrix.STACK, 'sw-nightlies') && '--spack' || '' }};\ mkdir build;\ cd build;\ + source ../.github/scripts/setup_herwig_ci.sh;\ cmake ..;\ make;\ ctest --output-on-failure --no-tests=error;