From c90f21f5c12dd0428bb9a91f7a0d8ea6a91d0e99 Mon Sep 17 00:00:00 2001 From: Remco de Boer <29308176+redeboer@users.noreply.github.com> Date: Sun, 8 Nov 2026 10:31:20 +0100 Subject: [PATCH 1/5] DOC: compare phase space backends for four-body decays and in a benchmark --- docs/usage/phase-space.ipynb | 214 ++++++++++++++++++++++++++++++++++- pyproject.toml | 1 + 2 files changed, 213 insertions(+), 2 deletions(-) diff --git a/docs/usage/phase-space.ipynb b/docs/usage/phase-space.ipynb index 57373638..2d859b4a 100644 --- a/docs/usage/phase-space.ipynb +++ b/docs/usage/phase-space.ipynb @@ -4,7 +4,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "\n", + "\n", "\n", "# Phase space generators\n", "\n", @@ -227,13 +227,223 @@ "plt.show()" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Four-body decays\n", + "\n", + "A three-body decay has two independent kinematic variables, so its phase space fits in a single Dalitz plot. A four-body decay has five, and no single plot shows them all. A common choice is the set of [Cabibbo–Maksymowicz variables](https://doi.org/10.1103/PhysRev.137.B438), which split the decay into two pairs of particles:\n", + "\n", + "- the invariant masses $m_{01}$ and $m_{23}$ of the two pairs,\n", + "- the helicity angles $\\theta_{01}$ and $\\theta_{23}$ of particles $0$ and $2$ in the rest frames of their pairs,\n", + "- the angle $\\phi$ between the two decay planes.\n", + "\n", + "For a uniform phase space sample, $\\cos\\theta_{01}$, $\\cos\\theta_{23}$ and $\\phi$ are distributed uniformly, while the two masses are not. As an example, we generate $D^0 \\to K^-\\pi^+\\pi^+\\pi^-$ with each backend." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "four_body_masses = {0: 0.4937, 1: 0.1396, 2: 0.1396, 3: 0.1396}\n", + "four_body_samples = {}\n", + "for name, (_, rng) in generators.items():\n", + " generator = TFPhaseSpaceGenerator(1.8648, four_body_masses, backend=name)\n", + " generator.show_progress = False\n", + " four_body_samples[name] = generator.generate(n_events, rng)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "jupyter": { + "source_hidden": true + }, + "mystnb": { + "code_prompt_show": "Plot Cabibbo–Maksymowicz variables" + }, + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "def boost_to_rest_frame(p: np.ndarray, frame: np.ndarray) -> np.ndarray:\n", + " beta = frame[:, 1:] / frame[:, :1]\n", + " beta_squared = np.sum(beta**2, axis=1, keepdims=True)\n", + " gamma = 1 / np.sqrt(1 - beta_squared)\n", + " beta_dot_p = np.sum(beta * p[:, 1:], axis=1, keepdims=True)\n", + " energy = gamma * (p[:, :1] - beta_dot_p)\n", + " momentum = (\n", + " p[:, 1:] + ((gamma - 1) * beta_dot_p / beta_squared - gamma * p[:, :1]) * beta\n", + " )\n", + " return np.concatenate([energy, momentum], axis=1)\n", + "\n", + "\n", + "def unit(v: np.ndarray) -> np.ndarray:\n", + " return v / np.linalg.norm(v, axis=1, keepdims=True)\n", + "\n", + "\n", + "def cabibbo_maksymowicz(sample: dict[str, np.ndarray]) -> dict[str, np.ndarray]:\n", + " p0, p1, p2, p3 = (sample[f\"p{i}\"] for i in range(4))\n", + " p01 = p0 + p1\n", + " p23 = p2 + p3\n", + " z = unit(p01[:, 1:])\n", + " n01 = unit(np.cross(p0[:, 1:], p1[:, 1:]))\n", + " n23 = unit(np.cross(p2[:, 1:], p3[:, 1:]))\n", + " sin_phi = np.sum(np.cross(n01, n23) * z, axis=1)\n", + " cos_phi = np.sum(n01 * n23, axis=1)\n", + " return {\n", + " \"$m_{01}$ [GeV]\": np.sqrt(invariant_mass_squared(p01)),\n", + " \"$m_{23}$ [GeV]\": np.sqrt(invariant_mass_squared(p23)),\n", + " R\"$\\cos\\theta_{01}$\": np.sum(\n", + " unit(boost_to_rest_frame(p0, p01)[:, 1:]) * z, axis=1\n", + " ),\n", + " R\"$\\cos\\theta_{23}$\": np.sum(\n", + " unit(boost_to_rest_frame(p2, p23)[:, 1:]) * -z, axis=1\n", + " ),\n", + " R\"$\\phi$\": np.arctan2(sin_phi, cos_phi),\n", + " }\n", + "\n", + "\n", + "variables = {name: cabibbo_maksymowicz(s) for name, s in four_body_samples.items()}\n", + "labels = list(next(iter(variables.values())))\n", + "fig, axes = plt.subplots(ncols=len(labels), figsize=(3 * len(labels), 3), sharey=True)\n", + "for ax, label in zip(axes, labels, strict=True):\n", + " for name, values in variables.items():\n", + " ax.hist(values[label], bins=50, histtype=\"step\", label=name)\n", + " ax.set_xlabel(label)\n", + "axes[0].set_ylabel(\"Events\")\n", + "axes[-1].legend()\n", + "fig.tight_layout()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The variables are not independent in their ranges: the sum of the two pair masses cannot exceed the mass of the decaying particle. A two-dimensional histogram of $m_{01}$ against $m_{23}$ shows this kinematic boundary, which plays a role similar to the boundary of the Dalitz plot." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "jupyter": { + "source_hidden": true + }, + "mystnb": { + "code_prompt_show": "Plot pair masses" + }, + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "fig, axes = plt.subplots(\n", + " ncols=len(variables), figsize=(4 * len(variables), 3.5), sharex=True, sharey=True\n", + ")\n", + "for ax, (name, values) in zip(np.atleast_1d(axes), variables.items(), strict=True):\n", + " ax.hist2d(values[labels[0]], values[labels[1]], bins=60, cmin=1, rasterized=True)\n", + " ax.set_title(name)\n", + " ax.set_xlabel(labels[0])\n", + "np.atleast_1d(axes)[0].set_ylabel(labels[1])\n", + "fig.tight_layout()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Benchmark\n", + "\n", + "The timings above come from a single sample. For a more systematic comparison, we measure how long each backend takes to generate a weighted sample with {class}`.TFWeightedPhaseSpaceGenerator`, as a function of the sample size and of the number of final state particles. The hit-and-miss step of {class}`.TFPhaseSpaceGenerator` is left out, because it is the same for all backends. Each measurement is preceded by one call of the same size that is not timed, so that compilation does not count, and the fastest of three repetitions is shown." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from tensorwaves.data import TFWeightedPhaseSpaceGenerator\n", + "\n", + "\n", + "def measure(backend: str, masses: dict[int, float], size: int) -> float:\n", + " _, rng = generators[backend]\n", + " generator = TFWeightedPhaseSpaceGenerator(5.0, masses, backend=backend)\n", + " generator.generate(size, rng)\n", + " durations = []\n", + " for _ in range(3):\n", + " start = time.perf_counter()\n", + " generator.generate(size, rng)\n", + " durations.append(time.perf_counter() - start)\n", + " return min(durations)\n", + "\n", + "\n", + "pion_mass = 0.1396\n", + "sizes = [10_000, 30_000, 100_000, 300_000]\n", + "particle_counts = [3, 4, 5, 6, 7, 8]\n", + "timings_by_size = {\n", + " backend: [measure(backend, dict.fromkeys(range(3), pion_mass), n) for n in sizes]\n", + " for backend in generators\n", + "}\n", + "timings_by_particles = {\n", + " backend: [\n", + " measure(backend, dict.fromkeys(range(k), pion_mass), 100_000)\n", + " for k in particle_counts\n", + " ]\n", + " for backend in generators\n", + "}" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "jupyter": { + "source_hidden": true + }, + "mystnb": { + "code_prompt_show": "Plot benchmark" + }, + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(10, 3.5))\n", + "for backend in generators:\n", + " ax1.plot(sizes, timings_by_size[backend], marker=\"o\", label=backend)\n", + " ax2.plot(particle_counts, timings_by_particles[backend], marker=\"o\", label=backend)\n", + "ax1.set_xscale(\"log\")\n", + "ax1.set_xlabel(\"Number of events\")\n", + "ax1.set_title(\"Three-body decay\")\n", + "ax2.set_xlabel(\"Number of final state particles\")\n", + "ax2.set_title(\"100,000 events\")\n", + "for ax in (ax1, ax2):\n", + " ax.set_yscale(\"log\")\n", + " ax.set_ylabel(\"Time [s]\")\n", + "ax1.legend()\n", + "fig.tight_layout()\n", + "plt.show()" + ] + }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Which generator to choose\n", "\n", - "NumPy is the default choice, because it needs no additional dependencies and no compilation. TensorFlow reproduces samples from earlier TensorWaves versions, when combined with a {class}`.TFUniformRealNumberGenerator`. JAX can be useful if the rest of the analysis already uses it.\n", + "NumPy is the default choice, because it needs no additional dependencies and no compilation. TensorFlow and JAX pay for compilation on the first call, but are several times faster afterwards, as the [benchmark](#benchmark) shows. They are therefore worth it when generating large or many samples for the same decay. TensorFlow reproduces samples from earlier TensorWaves versions, when combined with a {class}`.TFUniformRealNumberGenerator`. JAX can be useful if the rest of the analysis already uses it.\n", "\n", "There are two things to keep in mind:\n", "\n", diff --git a/pyproject.toml b/pyproject.toml index e6e85263..71a472ae 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -628,6 +628,7 @@ include = [ "docs/usage.ipynb", "docs/usage/basics.ipynb", "docs/usage/binned-fit.ipynb", + "docs/usage/phase-space.ipynb", ] [tool.ty.overrides.rules] From b9e584496424fd424065870b8f5599a43af6f40c Mon Sep 17 00:00:00 2001 From: Remco de Boer <29308176+redeboer@users.noreply.github.com> Date: Sun, 8 Nov 2026 13:26:15 +0100 Subject: [PATCH 2/5] DX: build documentation with native uv support on Read the Docs --- .github/workflows/ci.yml | 2 -- .pre-commit-config.yaml | 2 +- .readthedocs.yml | 20 +++++++++----------- .vscode/settings.json | 7 +------ pyproject.toml | 2 +- 5 files changed, 12 insertions(+), 21 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1109b1ba..3bd1b9c3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -35,8 +35,6 @@ jobs: python-version: "3.13" test: uses: ComPWA/actions/.github/workflows/test.yml@826112415aa683bb2d73df87e84444a047f8cad7 # v4.1.8 - secrets: - CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} with: coverage-python-version: "3.13" macos-python-version: "3.11" diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 5199f7da..d4f661a8 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -16,7 +16,7 @@ repos: - id: check-useless-excludes - repo: https://github.com/ComPWA/policy - rev: 0.10.1 + rev: 0.10.3 hooks: - id: check-dev-files diff --git a/.readthedocs.yml b/.readthedocs.yml index cc704ce0..85b964b9 100644 --- a/.readthedocs.yml +++ b/.readthedocs.yml @@ -4,16 +4,14 @@ build: os: ubuntu-24.04 tools: python: "3.13" - commands: - - |- - export PIXI_HOME=$READTHEDOCS_VIRTUALENV_PATH - curl -fsSL https://pixi.sh/install.sh | bash - pixi global install graphviz uv - - |- - export UV_LINK_MODE=copy - uvx --from poethepoet poe doc - mkdir -p $READTHEDOCS_OUTPUT - mv docs/_build/html $READTHEDOCS_OUTPUT - + apt_packages: + - graphviz sphinx: configuration: docs/conf.py + fail_on_warning: true +python: + install: + - method: uv + command: sync + groups: + - doc diff --git a/.vscode/settings.json b/.vscode/settings.json index 374f5fc6..b16e6169 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -47,7 +47,6 @@ } ], "livePreview.defaultPreviewPath": "docs/_build/html", - "multiDiffEditor.experimental.enabled": true, "notebook.codeActionsOnSave": { "notebook.source.organizeImports": "explicit" }, @@ -72,9 +71,5 @@ "testing.showCoverageInExplorer": true, "ty.completions.autoImport": false, "ty.diagnosticMode": "workspace", - "ty.importStrategy": "fromEnvironment", - "yaml.schemas": { - "https://citation-file-format.github.io/1.2.0/schema.json": "CITATION.cff", - "https://json.schemastore.org/github-workflow.json": "./.github/workflows/requirements.yml" - } + "ty.importStrategy": "fromEnvironment" } diff --git a/pyproject.toml b/pyproject.toml index 71a472ae..10733920 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -619,7 +619,7 @@ key-empty = "off" [[tool.tombi.schemas]] root = "tool.compwa.policy" -path = "https://raw.githubusercontent.com/ComPWA/policy/0.10.1/compwa-policy.schema.json" +path = "https://raw.githubusercontent.com/ComPWA/policy/0.10.3/compwa-policy.schema.json" include = ["pyproject.toml"] [[tool.ty.overrides]] From 088a5483ff52a257d016223f91291d8d607df3a3 Mon Sep 17 00:00:00 2001 From: Remco de Boer <29308176+redeboer@users.noreply.github.com> Date: Sun, 8 Nov 2026 11:23:57 +0100 Subject: [PATCH 3/5] DOC: use EvtGen in all examples --- docs/amplitude-analysis.ipynb | 23 +- .../analytic-continuation.ipynb | 4 +- docs/install.md | 2 +- docs/usage/phase-space.ipynb | 216 +++++++++--------- src/tensorwaves/data/phasespace.py | 7 +- 5 files changed, 129 insertions(+), 123 deletions(-) diff --git a/docs/amplitude-analysis.ipynb b/docs/amplitude-analysis.ipynb index a525272b..46fb47f9 100644 --- a/docs/amplitude-analysis.ipynb +++ b/docs/amplitude-analysis.ipynb @@ -342,9 +342,9 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The {class}`~qrules.transition.ReactionInfo` class defines the constraints of the phase space. As such, we have enough information to generate a **phase-space sample** for this particle reaction. We do this with a {class}`.TFPhaseSpaceGenerator` class, which is a {class}`.DataGenerator` for a {obj}`.DataSample` of **four-momenta** arrays (using {obj}`tensorflow ` and the [`phasespace`](https://phasespace.readthedocs.io) package as a back-end). We also need to construct a {class}`.RealNumberGenerator` that can generate random numbers. {class}`.TFUniformRealNumberGenerator` is the natural choice here. See {doc}`/usage/phase-space` for an overview of the available generators.\n", + "The {class}`~qrules.transition.ReactionInfo` class defines the constraints of the phase space. As such, we have enough information to generate a **phase-space sample** for this particle reaction. We do this with an {class}`.EvtGenPhaseSpaceGenerator`, which is a {class}`.DataGenerator` for a {obj}`.DataSample` of **four-momenta** arrays that uses [EvtGen](https://gitlab.cern.ch/evtgen/evtgen) as a back-end. We also need to construct a {class}`.RealNumberGenerator` that can generate random numbers, such as a {class}`.NumpyUniformRNG`. See {doc}`/usage/phase-space` for an overview of the available generators.\n", "\n", - "As opposed to the main [](compwa-step-2) of the main usage example page, we will generate a **deterministic** data sample. This can be done by feeding a {class}`.RealNumberGenerator` with a specific {attr}`~.RealNumberGenerator.seed` and giving that generator to the {meth}`.TFPhaseSpaceGenerator.generate` method:" + "As opposed to the main [](compwa-step-2) of the main usage example page, we will generate a **deterministic** data sample. This can be done by feeding a {class}`.RealNumberGenerator` with a specific {attr}`~.RealNumberGenerator.seed` and giving that generator to the {meth}`.EvtGenPhaseSpaceGenerator.generate` method:" ] }, { @@ -375,10 +375,10 @@ }, "outputs": [], "source": [ - "from tensorwaves.data import NumpyUniformRNG, TFPhaseSpaceGenerator\n", + "from tensorwaves.data import EvtGenPhaseSpaceGenerator, NumpyUniformRNG\n", "\n", "rng = NumpyUniformRNG(seed=0)\n", - "phsp_generator = TFPhaseSpaceGenerator(\n", + "phsp_generator = EvtGenPhaseSpaceGenerator(\n", " initial_state_mass=reaction.initial_state[-1].mass,\n", " final_state_masses={i: p.mass for i, p in reaction.final_state.items()},\n", ")\n", @@ -462,7 +462,7 @@ "source": [ "'Data samples' are more complicated than phase space samples in that they represent the intensity profile resulting from a reaction. You therefore need a {class}`.Function` object that expresses an intensity distribution as well as a phase space over which to generate that distribution. We call such a data sample an **intensity-based sample**.\n", "\n", - "An intensity-based sample is generated over a phase space sample using the {class}`.IntensityDistributionGenerator`. Its usage is similar to {class}`.TFPhaseSpaceGenerator`, but now you have to provide a {obj}`.Function` as well as a {obj}`.DataTransformer` that is used to transform the four-momentum phase space sample to a data sample that can be understood by the {obj}`.Function`.\n", + "An intensity-based sample is generated over a phase space sample using the {class}`.IntensityDistributionGenerator`. Its usage is similar to {class}`.EvtGenPhaseSpaceGenerator`, but now you have to provide a {obj}`.Function` as well as a {obj}`.DataTransformer` that is used to transform the four-momentum phase space sample to a data sample that can be understood by the {obj}`.Function`.\n", "\n", "Now, recall that in [](compwa-step-1), we used the helicity formalism to mathematically express the reaction in terms of an amplitude model. TensorWaves needs to convert this {obj}`~ampform.helicity.HelicityModel` to a {obj}`.Function` object that can perform fast computations. This can be done with {func}`.create_parametrized_function`:" ] @@ -554,17 +554,10 @@ }, "outputs": [], "source": [ - "from tensorwaves.data import (\n", - " IntensityDistributionGenerator,\n", - " TFWeightedPhaseSpaceGenerator,\n", - ")\n", + "from tensorwaves.data import IntensityDistributionGenerator\n", "\n", - "weighted_phsp_generator = TFWeightedPhaseSpaceGenerator(\n", - " initial_state_mass=reaction.initial_state[-1].mass,\n", - " final_state_masses={i: p.mass for i, p in reaction.final_state.items()},\n", - ")\n", "data_generator = IntensityDistributionGenerator(\n", - " domain_generator=weighted_phsp_generator,\n", + " domain_generator=phsp_generator,\n", " function=intensity_func,\n", " domain_transformer=helicity_transformer,\n", ")\n", @@ -584,7 +577,7 @@ "\n", ":::{note}\n", "\n", - "Instead of constructing a {class}`.TFWeightedPhaseSpaceGenerator`, it's also possible to just reuse the **unweighted** {class}`.TFPhaseSpaceGenerator` that we constructed previously. This is, however, a bit slower, because the {class}`.TFPhaseSpaceGenerator` also uses a hit-and-miss strategy.\n", + "The {class}`.EvtGenPhaseSpaceGenerator` provides **unweighted** events, so the {class}`.IntensityDistributionGenerator` only has to perform hit-and-miss over the intensity. A {class}`.TFWeightedPhaseSpaceGenerator` provides weighted events instead, which the {class}`.IntensityDistributionGenerator` takes into account in the same hit-and-miss step. See {doc}`/usage/phase-space` for a comparison.\n", "\n", ":::" ] diff --git a/docs/amplitude-analysis/analytic-continuation.ipynb b/docs/amplitude-analysis/analytic-continuation.ipynb index ebdbd7b4..74e9940b 100644 --- a/docs/amplitude-analysis/analytic-continuation.ipynb +++ b/docs/amplitude-analysis/analytic-continuation.ipynb @@ -32,9 +32,9 @@ "from IPython.display import Markdown, Math\n", "\n", "from tensorwaves.data import (\n", + " EvtGenPhaseSpaceGenerator,\n", " NumpyUniformRNG,\n", " SympyDataTransformer,\n", - " TFPhaseSpaceGenerator,\n", ")\n", "from tensorwaves.function.sympy import create_parametrized_function\n", "\n", @@ -168,7 +168,7 @@ " model.kinematic_variables, backend=\"numpy\"\n", ")\n", "rng = NumpyUniformRNG(seed=0)\n", - "phsp_generator = TFPhaseSpaceGenerator(\n", + "phsp_generator = EvtGenPhaseSpaceGenerator(\n", " initial_state_mass=reaction.initial_state[-1].mass,\n", " final_state_masses={i: p.mass for i, p in reaction.final_state.items()},\n", ")\n", diff --git a/docs/install.md b/docs/install.md index 3dde05c5..f1470278 100644 --- a/docs/install.md +++ b/docs/install.md @@ -43,7 +43,7 @@ conda install -c conda-forge ampform phasespace ::: :::: -To generate phase space samples with [EvtGen](https://gitlab.cern.ch/evtgen/evtgen), install [`pyevtgen`](https://github.com/redeboer/pyevtgen-test) with the `evtgen` extra and use {class}`.EvtGenPhaseSpaceGenerator`. This package is not yet on PyPI and is available from [its package index](https://redeboer.github.io/pyevtgen-test): +The examples in this documentation generate phase space samples with [EvtGen](https://gitlab.cern.ch/evtgen/evtgen). To do the same, install [`pyevtgen`](https://github.com/redeboer/pyevtgen-test) with the `evtgen` extra and use {class}`.EvtGenPhaseSpaceGenerator`. This package is not yet on PyPI and is available from [its package index](https://redeboer.github.io/pyevtgen-test): ```shell uv pip install "tensorwaves[evtgen]" --index https://redeboer.github.io/pyevtgen-test/simple diff --git a/docs/usage/phase-space.ipynb b/docs/usage/phase-space.ipynb index 5f0868a4..949dd60c 100644 --- a/docs/usage/phase-space.ipynb +++ b/docs/usage/phase-space.ipynb @@ -4,7 +4,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "\n", + "\n", "\n", "# Phase space generators\n", "\n", @@ -16,7 +16,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Amplitude analysis needs samples of four-momenta that are distributed uniformly over the phase space of a decay. In TensorWaves, such a sample comes from a {class}`.DataGenerator`. There are two families of generators: {class}`.TFPhaseSpaceGenerator` uses [`phasespace`](https://phasespace.readthedocs.io), which can run on NumPy, TensorFlow, or JAX, and {class}`.EvtGenPhaseSpaceGenerator` uses [EvtGen](https://gitlab.cern.ch/evtgen/evtgen) through [`pyevtgen`](https://github.com/redeboer/pyevtgen-test). This page compares their performance and their distributions, so that you can decide which one fits your use case. All of them take the same masses and return a {obj}`.DataSample` of NumPy arrays with the same structure, so they can be swapped without changing the rest of an analysis." + "Amplitude analysis needs samples of four-momenta that are distributed uniformly over the phase space of a decay. In TensorWaves, such a sample comes from a {class}`.DataGenerator`. The recommended generator is {class}`.EvtGenPhaseSpaceGenerator`, which uses [EvtGen](https://gitlab.cern.ch/evtgen/evtgen) through [`pyevtgen`](https://github.com/redeboer/pyevtgen-test) and which all examples in this documentation use. Phase space samples can also be generated with {class}`.TFPhaseSpaceGenerator`, which uses [`phasespace`](https://phasespace.readthedocs.io) with NumPy, JAX, or TensorFlow as computational backend. This page compares the performance and the distributions of these generators. All of them take the same masses and return a {obj}`.DataSample` of NumPy arrays with the same structure, so they can be swapped without changing the rest of an analysis." ] }, { @@ -53,7 +53,7 @@ "source": [ "## Available generators\n", "\n", - "Despite its name, {class}`.TFPhaseSpaceGenerator` uses NumPy by default and does not require TensorFlow. Its backend is selected with the `backend` argument. Each generator below gets a {class}`.RealNumberGenerator` that it can use directly where possible. The mapping below is the single place that defines which generators this page compares. All tables and figures on this page loop over it." + "Despite its name, {class}`.TFPhaseSpaceGenerator` uses NumPy by default and does not require TensorFlow. Its backend is selected with the `backend` argument. Each generator below gets a {class}`.RealNumberGenerator` that it can use directly where possible. The function below is the single place that defines which generators this page compares. All tables and figures on this page loop over the generators it returns." ] }, { @@ -71,11 +71,10 @@ " TFUniformRealNumberGenerator,\n", ")\n", "\n", - "initial_state_mass = 3.0969\n", - "final_state_masses = {0: 0.1350, 1: 0.1396, 2: 0.4937}\n", - "\n", "\n", "def create_phasespace_generator(\n", + " initial_state_mass: float,\n", + " final_state_masses: dict[int, float],\n", " backend: Literal[\"numpy\", \"tensorflow\", \"jax\"],\n", ") -> TFPhaseSpaceGenerator:\n", " generator = TFPhaseSpaceGenerator(\n", @@ -85,21 +84,23 @@ " return generator\n", "\n", "\n", - "generators = {\n", - " \"phasespace (NumPy)\": (\n", - " create_phasespace_generator(\"numpy\"),\n", - " NumpyUniformRNG(seed=0),\n", - " ),\n", - " \"phasespace (TensorFlow)\": (\n", - " create_phasespace_generator(\"tensorflow\"),\n", - " TFUniformRealNumberGenerator(seed=0),\n", - " ),\n", - " \"phasespace (JAX)\": (create_phasespace_generator(\"jax\"), NumpyUniformRNG(seed=0)),\n", - " \"EvtGen\": (\n", - " EvtGenPhaseSpaceGenerator(initial_state_mass, final_state_masses),\n", - " NumpyUniformRNG(seed=0),\n", - " ),\n", - "}" + "def create_generators(initial_state_mass: float, final_state_masses: dict[int, float]):\n", + " masses = initial_state_mass, final_state_masses\n", + " return {\n", + " \"EvtGen\": (EvtGenPhaseSpaceGenerator(*masses), NumpyUniformRNG(seed=0)),\n", + " \"phasespace (NumPy)\": (\n", + " create_phasespace_generator(*masses, backend=\"numpy\"),\n", + " NumpyUniformRNG(seed=0),\n", + " ),\n", + " \"phasespace (JAX)\": (\n", + " create_phasespace_generator(*masses, backend=\"jax\"),\n", + " NumpyUniformRNG(seed=0),\n", + " ),\n", + " \"phasespace (TensorFlow)\": (\n", + " create_phasespace_generator(*masses, backend=\"tensorflow\"),\n", + " TFUniformRealNumberGenerator(seed=0),\n", + " ),\n", + " }" ] }, { @@ -108,10 +109,10 @@ "source": [ "| Generator | Package | Extra | Events | Use of the {class}`.RealNumberGenerator` |\n", "| --- | --- | --- | --- | --- |\n", + "| {class}`.EvtGenPhaseSpaceGenerator` | `pyevtgen` | `evtgen` | unweighted | any type only provides a seed |\n", "| {class}`.TFPhaseSpaceGenerator` with `backend=\"numpy\"` (default) | `phasespace` | `phsp` | unweighted through hit-and-miss | {class}`.NumpyUniformRNG` is used directly, any other type only provides a seed |\n", - "| {class}`.TFPhaseSpaceGenerator` with `backend=\"tensorflow\"` | `phasespace` | `phsp,tf` | unweighted through hit-and-miss | {class}`.TFUniformRealNumberGenerator` is used directly, any other type only provides a seed |\n", "| {class}`.TFPhaseSpaceGenerator` with `backend=\"jax\"` | `phasespace` | `phsp,jax` | unweighted through hit-and-miss | any type only provides a seed |\n", - "| {class}`.EvtGenPhaseSpaceGenerator` | `pyevtgen` | `evtgen` | unweighted | any type only provides a seed |\n", + "| {class}`.TFPhaseSpaceGenerator` with `backend=\"tensorflow\"` | `phasespace` | `phsp,tf` | unweighted through hit-and-miss | {class}`.TFUniformRealNumberGenerator` is used directly, any other type only provides a seed |\n", "\n", "{class}`.TFWeightedPhaseSpaceGenerator` takes the same `backend` argument and returns weighted events instead. The installation of these extras is described on {doc}`/install`." ] @@ -120,9 +121,9 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## Generating a sample\n", + "## Performance\n", "\n", - "Every generator has the same {meth}`~.DataGenerator.generate` method, which returns a {obj}`dict` of final state IDs to arrays of four-momenta $\\left(E, p_x, p_y, p_z\\right)$ of shape $n \\times 4$." + "We measure how long each generator takes for decays of the $J/\\psi$ into three, four, and five pions and for several sample sizes. TensorFlow and JAX compile functions the first time they are called and `phasespace` compiles them again after each change of backend, so we first call each generator once without timing it. After that, we take the fastest of three calls, which limits the influence of other processes on the machine. These timings only give an impression for these decays on the machine that builds this page." ] }, { @@ -131,11 +132,25 @@ "metadata": {}, "outputs": [], "source": [ - "n_events = 500_000\n", - "samples = {\n", - " name: generator.generate(n_events, rng)\n", - " for name, (generator, rng) in generators.items()\n", - "}" + "def measure(generator, rng, size: int) -> float:\n", + " start = time.perf_counter()\n", + " generator.generate(size, rng)\n", + " return time.perf_counter() - start\n", + "\n", + "\n", + "j_psi_mass = 3.0969\n", + "pion_mass = 0.1396\n", + "sample_sizes = [1_000, 10_000, 100_000]\n", + "n_repeats = 3\n", + "benchmark = {}\n", + "for n_particles in [3, 4, 5]:\n", + " pions = dict.fromkeys(range(n_particles), pion_mass)\n", + " for name, (generator, rng) in create_generators(j_psi_mass, pions).items():\n", + " measure(generator, rng, sample_sizes[0])\n", + " benchmark[n_particles, name] = [\n", + " min(measure(generator, rng, size) for _ in range(n_repeats))\n", + " for size in sample_sizes\n", + " ]" ] }, { @@ -146,7 +161,7 @@ "source_hidden": true }, "mystnb": { - "code_prompt_show": "Summarize samples" + "code_prompt_show": "Tabulate timings" }, "tags": [ "hide-input" @@ -154,71 +169,74 @@ }, "outputs": [], "source": [ - "pd.DataFrame(\n", - " {\n", - " \"Array type\": [type(sample[\"p0\"]).__name__ for sample in samples.values()],\n", - " \"Final state\": [sorted(sample) for sample in samples.values()],\n", - " \"Shape\": [sample[\"p0\"].shape for sample in samples.values()],\n", - " },\n", - " index=list(samples),\n", - ")" + "df_benchmark = pd.DataFrame(benchmark, index=sample_sizes).T\n", + "df_benchmark.index.names = [\"Final state particles\", \"Generator\"]\n", + "df_benchmark.columns = [f\"{size:,} events [s]\" for size in sample_sizes]\n", + "df_benchmark.style.format(\"{:.4f}\")" ] }, { - "cell_type": "markdown", - "metadata": {}, + "cell_type": "code", + "execution_count": null, + "metadata": { + "jupyter": { + "source_hidden": true + }, + "mystnb": { + "code_prompt_show": "Plot timings" + }, + "tags": [ + "hide-input" + ] + }, + "outputs": [], "source": [ - "## Performance\n", - "\n", - "TensorFlow and JAX compile functions the first time they are called and `phasespace` compiles them again after each change of backend, so we time a separate first call for each generator. After that, we take the fastest of three calls for several sample sizes, which is the common way to limit the influence of other processes on the machine. These timings only give an impression for this three-body decay on the machine that builds this page." + "n_particle_values = sorted({n for n, _ in benchmark})\n", + "fig, axes = plt.subplots(\n", + " ncols=len(n_particle_values),\n", + " figsize=(4 * len(n_particle_values), 3.5),\n", + " sharey=True,\n", + ")\n", + "for ax, n_particles in zip(axes, n_particle_values, strict=True):\n", + " for (n, name), durations in benchmark.items():\n", + " if n == n_particles:\n", + " ax.plot(sample_sizes, durations, marker=\"o\", label=name)\n", + " ax.set_title(f\"{n_particles}-body decay\")\n", + " ax.set_xscale(\"log\")\n", + " ax.set_yscale(\"log\")\n", + " ax.set_xlabel(\"Number of events\")\n", + "axes[0].set_ylabel(\"Time [s]\")\n", + "axes[0].legend(fontsize=\"small\")\n", + "fig.tight_layout()\n", + "plt.show()" ] }, { - "cell_type": "code", - "execution_count": null, + "cell_type": "markdown", "metadata": {}, - "outputs": [], "source": [ - "sample_sizes = [10_000, 100_000, 1_000_000]\n", - "n_repeats = 3\n", - "\n", - "\n", - "def measure(generator, rng, size: int) -> float:\n", - " start = time.perf_counter()\n", - " generator.generate(size, rng)\n", - " return time.perf_counter() - start\n", + "EvtGen is the fastest generator for all of these decays, and its advantage grows with the number of final state particles. The `phasespace` backends become slower with each additional particle, partly because a smaller fraction of the weighted events survive the hit-and-miss step.\n", "\n", + "## Comparing distributions\n", "\n", - "first_call = {}\n", - "benchmark = {}\n", - "for name, (generator, rng) in generators.items():\n", - " first_call[name] = measure(generator, rng, sample_sizes[0])\n", - " benchmark[name] = [\n", - " min(measure(generator, rng, size) for _ in range(n_repeats))\n", - " for size in sample_sizes\n", - " ]" + "We now generate a larger sample for a three-body decay with different final state masses. The events of different generators are not identical, not even with the same seed, but they should follow the same distribution." ] }, { "cell_type": "code", "execution_count": null, - "metadata": { - "jupyter": { - "source_hidden": true - }, - "mystnb": { - "code_prompt_show": "Tabulate timings" - }, - "tags": [ - "hide-input" - ] - }, + "metadata": {}, "outputs": [], "source": [ - "df_benchmark = pd.DataFrame(benchmark, index=sample_sizes).T\n", - "df_benchmark.columns = [f\"{size:,} events [s]\" for size in sample_sizes]\n", - "df_benchmark.insert(0, f\"First call, {sample_sizes[0]:,} events [s]\", first_call)\n", - "df_benchmark.round(3)" + "generators = create_generators(\n", + " initial_state_mass=3.0969,\n", + " final_state_masses={0: 0.1350, 1: 0.1396, 2: 0.4937},\n", + ")\n", + "n_events = 500_000\n", + "samples = {\n", + " name: generator.generate(n_events, rng)\n", + " for name, (generator, rng) in generators.items()\n", + "}" ] }, { @@ -229,7 +247,7 @@ "source_hidden": true }, "mystnb": { - "code_prompt_show": "Plot timings" + "code_prompt_show": "Summarize samples" }, "tags": [ "hide-input" @@ -237,25 +255,21 @@ }, "outputs": [], "source": [ - "fig, ax = plt.subplots(figsize=(6, 3.5))\n", - "for name, durations in benchmark.items():\n", - " ax.plot(sample_sizes, durations, marker=\"o\", label=name)\n", - "ax.set_xscale(\"log\")\n", - "ax.set_yscale(\"log\")\n", - "ax.set_xlabel(\"Number of events\")\n", - "ax.set_ylabel(\"Time [s]\")\n", - "ax.legend()\n", - "fig.tight_layout()\n", - "plt.show()" + "pd.DataFrame(\n", + " {\n", + " \"Array type\": [type(sample[\"p0\"]).__name__ for sample in samples.values()],\n", + " \"Final state\": [sorted(sample) for sample in samples.values()],\n", + " \"Shape\": [sample[\"p0\"].shape for sample in samples.values()],\n", + " },\n", + " index=list(samples),\n", + ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "## Comparing distributions\n", - "\n", - "The events of different generators are not identical, not even with the same seed, but they should follow the same distribution. A uniform phase space sample shows up as a flat Dalitz plot within the kinematic boundary." + "A uniform phase space sample shows up as a flat Dalitz plot within the kinematic boundary." ] }, { @@ -296,7 +310,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The invariant mass projections should agree between generators. The lower panels show the ratio of each generator to the first generator in the mapping, with the statistical uncertainty of the reference as a band." + "The invariant mass projections should agree between generators. The lower panels show the ratio of each generator to EvtGen, with the statistical uncertainty of the EvtGen sample as a band." ] }, { @@ -360,7 +374,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "To quantify the agreement, we compute a two-sample $\\chi^2$ per degree of freedom between each generator and the reference, using bins with sufficient statistics. Values around one mean that the samples are statistically compatible." + "To quantify the agreement, we compute a two-sample $\\chi^2$ per degree of freedom between each generator and EvtGen, using bins with sufficient statistics. Values around one mean that the samples are statistically compatible." ] }, { @@ -390,17 +404,15 @@ "source": [ "## Which generator to choose\n", "\n", - "{class}`.TFPhaseSpaceGenerator` with its default NumPy backend is the default choice and it is what the {doc}`/amplitude-analysis` page uses, because it needs no additional dependencies and no compilation. TensorFlow reproduces samples from earlier TensorWaves versions, when combined with a {class}`.TFUniformRealNumberGenerator`. JAX can be useful if the rest of the analysis already uses it. The {class}`.TFWeightedPhaseSpaceGenerator` variant provides event weights, which is useful for the {class}`.IntensityDistributionGenerator`.\n", + "{class}`.EvtGenPhaseSpaceGenerator` is the default choice: it is the fastest generator and needs neither TensorFlow nor JAX. It works with any {class}`.RealNumberGenerator`, which only provides a seed for the random engine of EvtGen. There are two limitations:\n", "\n", - "There are two things to keep in mind with these backends:\n", + "- It provides no weights, because EvtGen applies accept-reject sampling internally. The {class}`.IntensityDistributionGenerator` does not need them, as the {doc}`/amplitude-analysis` page shows.\n", + "- Its accept-reject efficiency depends on the masses of the final state. Generation can become impractically slow for many final state particles, and a running call cannot be interrupted.\n", "\n", - "- The same seed gives a different sample on each backend. Samples are only reproducible within one backend.\n", - "- `phasespace` selects its backend per process, and a generator activates its backend each time it generates. Each switch makes `phasespace` recompile, so alternating between backends is slower than the timings above suggest, and generators with different backends should not be used concurrently in threads.\n", - "\n", - "{class}`.EvtGenPhaseSpaceGenerator` works with any {class}`.RealNumberGenerator`, which only provides a seed for the random engine of EvtGen. There are two limitations:\n", + "{class}`.TFPhaseSpaceGenerator` and {class}`.TFWeightedPhaseSpaceGenerator` are useful where `pyevtgen` is not available. With the NumPy backend, `phasespace` only depends on NumPy, so these generators may also work where neither `pyevtgen`, TensorFlow, nor JAX can be installed, for instance in the browser through [Pyodide](https://pyodide.org). This has not been tested. TensorFlow reproduces samples from earlier TensorWaves versions, when combined with a {class}`.TFUniformRealNumberGenerator`. {class}`.TFWeightedPhaseSpaceGenerator` provides event weights. There are two things to keep in mind with these backends:\n", "\n", - "- It provides no weights, because EvtGen applies accept-reject sampling internally.\n", - "- Its accept-reject efficiency drops by about a factor of ten for each additional final state particle, which makes it impractically slow beyond about nine particles. A running call cannot be interrupted." + "- The same seed gives a different sample on each backend. Samples are only reproducible within one backend.\n", + "- `phasespace` selects its backend per process, and a generator activates its backend each time it generates. Each switch makes `phasespace` recompile, so alternating between backends is slower than the timings above suggest, and generators with different backends should not be used concurrently in threads." ] } ], diff --git a/src/tensorwaves/data/phasespace.py b/src/tensorwaves/data/phasespace.py index 8db09bf9..cd6a9f5b 100644 --- a/src/tensorwaves/data/phasespace.py +++ b/src/tensorwaves/data/phasespace.py @@ -66,7 +66,7 @@ def generate(self, size: int, rng: RealNumberGenerator) -> DataSample: Returns: A `.DataSample` of **four-momenta** arrays of shape :math:`n \times 4`. - .. seealso:: :ref:`amplitude-analysis:2.1 Generate phase space sample` + .. seealso:: :doc:`/usage/phase-space` """ progress_bar = tqdm( total=size, @@ -111,7 +111,7 @@ class TFWeightedPhaseSpaceGenerator(DataGenerator): by the backend, a seed is drawn from it, so the sample stays reproducible, but differs from the sample of another backend. - .. seealso:: :ref:`amplitude-analysis:2.2 Generate intensity-based sample` + .. seealso:: :doc:`/usage/phase-space` """ def __init__( @@ -171,7 +171,8 @@ class EvtGenPhaseSpaceGenerator(DataGenerator): initial_state_mass: Mass of the decaying state. final_state_masses: A mapping of final state IDs to the corresponding masses. - .. seealso:: :doc:`/usage/phase-space` + .. seealso:: :doc:`/usage/phase-space` and + :ref:`amplitude-analysis:2.1 Generate phase space sample` """ def __init__( From 29438c807ab0156f61680e220c25f42804552fb5 Mon Sep 17 00:00:00 2001 From: Remco de Boer <29308176+redeboer@users.noreply.github.com> Date: Sun, 8 Nov 2026 20:10:07 +0100 Subject: [PATCH 4/5] ENH: drop TF prefix from phase space generators --- benchmarks/ampform.py | 8 ++++---- docs/amplitude-analysis.ipynb | 2 +- docs/install.md | 2 +- docs/usage/basics.ipynb | 2 +- docs/usage/phase-space.ipynb | 20 ++++++++++---------- src/tensorwaves/data/__init__.py | 2 ++ src/tensorwaves/data/phasespace.py | 14 ++++++++++---- tests/data/test_data.py | 4 ++-- tests/data/test_phasespace.py | 27 +++++++++++++++++---------- 9 files changed, 48 insertions(+), 33 deletions(-) diff --git a/benchmarks/ampform.py b/benchmarks/ampform.py index d0c72b4a..ffe677c0 100644 --- a/benchmarks/ampform.py +++ b/benchmarks/ampform.py @@ -10,10 +10,10 @@ import tensorwaves as tw from tensorwaves.data import ( IntensityDistributionGenerator, + PhaseSpaceGenerator, SympyDataTransformer, - TFPhaseSpaceGenerator, TFUniformRealNumberGenerator, - TFWeightedPhaseSpaceGenerator, + WeightedPhaseSpaceGenerator, ) from tensorwaves.function.sympy import create_parametrized_function @@ -85,14 +85,14 @@ def generate_data( initial_state_mass = reaction.initial_state[-1].mass final_state_masses = {i: p.mass for i, p in final_state.items()} - phsp_generator = TFPhaseSpaceGenerator( + phsp_generator = PhaseSpaceGenerator( initial_state_mass, final_state_masses, backend="tensorflow" ) phsp = phsp_generator.generate( phsp_sample_size, rng=TFUniformRealNumberGenerator(seed=0) ) - weighted_phsp_generator = TFWeightedPhaseSpaceGenerator( + weighted_phsp_generator = WeightedPhaseSpaceGenerator( initial_state_mass, final_state_masses, backend="tensorflow" ) data_generator = IntensityDistributionGenerator( diff --git a/docs/amplitude-analysis.ipynb b/docs/amplitude-analysis.ipynb index 46fb47f9..7fd3c5d9 100644 --- a/docs/amplitude-analysis.ipynb +++ b/docs/amplitude-analysis.ipynb @@ -577,7 +577,7 @@ "\n", ":::{note}\n", "\n", - "The {class}`.EvtGenPhaseSpaceGenerator` provides **unweighted** events, so the {class}`.IntensityDistributionGenerator` only has to perform hit-and-miss over the intensity. A {class}`.TFWeightedPhaseSpaceGenerator` provides weighted events instead, which the {class}`.IntensityDistributionGenerator` takes into account in the same hit-and-miss step. See {doc}`/usage/phase-space` for a comparison.\n", + "The {class}`.EvtGenPhaseSpaceGenerator` provides **unweighted** events, so the {class}`.IntensityDistributionGenerator` only has to perform hit-and-miss over the intensity. A {class}`.WeightedPhaseSpaceGenerator` provides weighted events instead, which the {class}`.IntensityDistributionGenerator` takes into account in the same hit-and-miss step. See {doc}`/usage/phase-space` for a comparison.\n", "\n", ":::" ] diff --git a/docs/install.md b/docs/install.md index f1470278..621031aa 100644 --- a/docs/install.md +++ b/docs/install.md @@ -59,7 +59,7 @@ pip install tensorwaves[jax,scipy,tf] pip install tensorwaves[all] # all runtime dependencies ``` -The `phsp` and `pwa` extras generate phase space samples with NumPy and do not install TensorFlow. To generate them with TensorFlow or JAX, install the `tf` or `jax` extra as well and select it with the `backend` argument of {class}`.TFPhaseSpaceGenerator` or {class}`.TFWeightedPhaseSpaceGenerator`. +The `phsp` and `pwa` extras generate phase space samples with NumPy and do not install TensorFlow. To generate them with TensorFlow or JAX, install the `tf` or `jax` extra as well and select it with the `backend` argument of {class}`.PhaseSpaceGenerator` or {class}`.WeightedPhaseSpaceGenerator`. ## Backend precision diff --git a/docs/usage/basics.ipynb b/docs/usage/basics.ipynb index 55104ff5..97dac77f 100644 --- a/docs/usage/basics.ipynb +++ b/docs/usage/basics.ipynb @@ -523,7 +523,7 @@ "metadata": {}, "source": [ "```{note}\n", - "In PWA, the sample on which we perform hit-and-miss is not uniform, because the available space is limited by the masses of the initial and final state (phase space). See {class}`.TFPhaseSpaceGenerator` and {ref}`amplitude-analysis:Step 2: Generate data`.\n", + "In PWA, the sample on which we perform hit-and-miss is not uniform, because the available space is limited by the masses of the initial and final state (phase space). See {class}`.PhaseSpaceGenerator` and {ref}`amplitude-analysis:Step 2: Generate data`.\n", "```" ] }, diff --git a/docs/usage/phase-space.ipynb b/docs/usage/phase-space.ipynb index 949dd60c..57947838 100644 --- a/docs/usage/phase-space.ipynb +++ b/docs/usage/phase-space.ipynb @@ -16,7 +16,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Amplitude analysis needs samples of four-momenta that are distributed uniformly over the phase space of a decay. In TensorWaves, such a sample comes from a {class}`.DataGenerator`. The recommended generator is {class}`.EvtGenPhaseSpaceGenerator`, which uses [EvtGen](https://gitlab.cern.ch/evtgen/evtgen) through [`pyevtgen`](https://github.com/redeboer/pyevtgen-test) and which all examples in this documentation use. Phase space samples can also be generated with {class}`.TFPhaseSpaceGenerator`, which uses [`phasespace`](https://phasespace.readthedocs.io) with NumPy, JAX, or TensorFlow as computational backend. This page compares the performance and the distributions of these generators. All of them take the same masses and return a {obj}`.DataSample` of NumPy arrays with the same structure, so they can be swapped without changing the rest of an analysis." + "Amplitude analysis needs samples of four-momenta that are distributed uniformly over the phase space of a decay. In TensorWaves, such a sample comes from a {class}`.DataGenerator`. The recommended generator is {class}`.EvtGenPhaseSpaceGenerator`, which uses [EvtGen](https://gitlab.cern.ch/evtgen/evtgen) through [`pyevtgen`](https://github.com/redeboer/pyevtgen-test) and which all examples in this documentation use. Phase space samples can also be generated with {class}`.PhaseSpaceGenerator`, which uses [`phasespace`](https://phasespace.readthedocs.io) with NumPy, JAX, or TensorFlow as computational backend. This page compares the performance and the distributions of these generators. All of them take the same masses and return a {obj}`.DataSample` of NumPy arrays with the same structure, so they can be swapped without changing the rest of an analysis." ] }, { @@ -53,7 +53,7 @@ "source": [ "## Available generators\n", "\n", - "Despite its name, {class}`.TFPhaseSpaceGenerator` uses NumPy by default and does not require TensorFlow. Its backend is selected with the `backend` argument. Each generator below gets a {class}`.RealNumberGenerator` that it can use directly where possible. The function below is the single place that defines which generators this page compares. All tables and figures on this page loop over the generators it returns." + "{class}`.PhaseSpaceGenerator` uses NumPy by default and does not require TensorFlow. Its backend is selected with the `backend` argument. Each generator below gets a {class}`.RealNumberGenerator` that it can use directly where possible. The function below is the single place that defines which generators this page compares. All tables and figures on this page loop over the generators it returns." ] }, { @@ -67,7 +67,7 @@ "from tensorwaves.data import (\n", " EvtGenPhaseSpaceGenerator,\n", " NumpyUniformRNG,\n", - " TFPhaseSpaceGenerator,\n", + " PhaseSpaceGenerator,\n", " TFUniformRealNumberGenerator,\n", ")\n", "\n", @@ -76,8 +76,8 @@ " initial_state_mass: float,\n", " final_state_masses: dict[int, float],\n", " backend: Literal[\"numpy\", \"tensorflow\", \"jax\"],\n", - ") -> TFPhaseSpaceGenerator:\n", - " generator = TFPhaseSpaceGenerator(\n", + ") -> PhaseSpaceGenerator:\n", + " generator = PhaseSpaceGenerator(\n", " initial_state_mass, final_state_masses, backend=backend\n", " )\n", " generator.show_progress = False\n", @@ -110,11 +110,11 @@ "| Generator | Package | Extra | Events | Use of the {class}`.RealNumberGenerator` |\n", "| --- | --- | --- | --- | --- |\n", "| {class}`.EvtGenPhaseSpaceGenerator` | `pyevtgen` | `evtgen` | unweighted | any type only provides a seed |\n", - "| {class}`.TFPhaseSpaceGenerator` with `backend=\"numpy\"` (default) | `phasespace` | `phsp` | unweighted through hit-and-miss | {class}`.NumpyUniformRNG` is used directly, any other type only provides a seed |\n", - "| {class}`.TFPhaseSpaceGenerator` with `backend=\"jax\"` | `phasespace` | `phsp,jax` | unweighted through hit-and-miss | any type only provides a seed |\n", - "| {class}`.TFPhaseSpaceGenerator` with `backend=\"tensorflow\"` | `phasespace` | `phsp,tf` | unweighted through hit-and-miss | {class}`.TFUniformRealNumberGenerator` is used directly, any other type only provides a seed |\n", + "| {class}`.PhaseSpaceGenerator` with `backend=\"numpy\"` (default) | `phasespace` | `phsp` | unweighted through hit-and-miss | {class}`.NumpyUniformRNG` is used directly, any other type only provides a seed |\n", + "| {class}`.PhaseSpaceGenerator` with `backend=\"jax\"` | `phasespace` | `phsp,jax` | unweighted through hit-and-miss | any type only provides a seed |\n", + "| {class}`.PhaseSpaceGenerator` with `backend=\"tensorflow\"` | `phasespace` | `phsp,tf` | unweighted through hit-and-miss | {class}`.TFUniformRealNumberGenerator` is used directly, any other type only provides a seed |\n", "\n", - "{class}`.TFWeightedPhaseSpaceGenerator` takes the same `backend` argument and returns weighted events instead. The installation of these extras is described on {doc}`/install`." + "{class}`.WeightedPhaseSpaceGenerator` takes the same `backend` argument and returns weighted events instead. The installation of these extras is described on {doc}`/install`." ] }, { @@ -409,7 +409,7 @@ "- It provides no weights, because EvtGen applies accept-reject sampling internally. The {class}`.IntensityDistributionGenerator` does not need them, as the {doc}`/amplitude-analysis` page shows.\n", "- Its accept-reject efficiency depends on the masses of the final state. Generation can become impractically slow for many final state particles, and a running call cannot be interrupted.\n", "\n", - "{class}`.TFPhaseSpaceGenerator` and {class}`.TFWeightedPhaseSpaceGenerator` are useful where `pyevtgen` is not available. With the NumPy backend, `phasespace` only depends on NumPy, so these generators may also work where neither `pyevtgen`, TensorFlow, nor JAX can be installed, for instance in the browser through [Pyodide](https://pyodide.org). This has not been tested. TensorFlow reproduces samples from earlier TensorWaves versions, when combined with a {class}`.TFUniformRealNumberGenerator`. {class}`.TFWeightedPhaseSpaceGenerator` provides event weights. There are two things to keep in mind with these backends:\n", + "{class}`.PhaseSpaceGenerator` and {class}`.WeightedPhaseSpaceGenerator` are useful where `pyevtgen` is not available. With the NumPy backend, `phasespace` only depends on NumPy, so these generators may also work where neither `pyevtgen`, TensorFlow, nor JAX can be installed, for instance in the browser through [Pyodide](https://pyodide.org). This has not been tested. TensorFlow reproduces samples from earlier TensorWaves versions, when combined with a {class}`.TFUniformRealNumberGenerator`. {class}`.WeightedPhaseSpaceGenerator` provides event weights. There are two things to keep in mind with these backends:\n", "\n", "- The same seed gives a different sample on each backend. Samples are only reproducible within one backend.\n", "- `phasespace` selects its backend per process, and a generator activates its backend each time it generates. Each switch makes `phasespace` recompile, so alternating between backends is slower than the timings above suggest, and generators with different backends should not be used concurrently in threads." diff --git a/src/tensorwaves/data/__init__.py b/src/tensorwaves/data/__init__.py index 25f7d386..0926e418 100644 --- a/src/tensorwaves/data/__init__.py +++ b/src/tensorwaves/data/__init__.py @@ -23,8 +23,10 @@ ) from .phasespace import ( EvtGenPhaseSpaceGenerator, # ruff:ignore[unused-import] + PhaseSpaceGenerator, # ruff:ignore[unused-import] TFPhaseSpaceGenerator, # ruff:ignore[unused-import] TFWeightedPhaseSpaceGenerator, # ruff:ignore[unused-import] + WeightedPhaseSpaceGenerator, # ruff:ignore[unused-import] ) from .rng import NumpyUniformRNG, TFUniformRealNumberGenerator # ruff:ignore[unused-import] from .transform import IdentityTransformer, SympyDataTransformer # ruff:ignore[unused-import] diff --git a/src/tensorwaves/data/phasespace.py b/src/tensorwaves/data/phasespace.py index cd6a9f5b..cfbc6089 100644 --- a/src/tensorwaves/data/phasespace.py +++ b/src/tensorwaves/data/phasespace.py @@ -34,7 +34,7 @@ } -class TFPhaseSpaceGenerator(DataGenerator): +class PhaseSpaceGenerator(DataGenerator): """Implements a phase space generator on top of `phasespace `_. Args: @@ -42,7 +42,7 @@ class TFPhaseSpaceGenerator(DataGenerator): final_state_masses: A mapping of final state IDs to the corresponding masses. bunch_size: Size of a bunch that is generated during a hit-and-miss iteration. backend: Computational backend that phasespace uses to generate the sample. - See `TFWeightedPhaseSpaceGenerator`. + See `WeightedPhaseSpaceGenerator`. """ def __init__( @@ -53,7 +53,7 @@ def __init__( *, backend: Literal["numpy", "tensorflow", "jax"] = "numpy", ) -> None: - self.__phsp_generator = TFWeightedPhaseSpaceGenerator( + self.__phsp_generator = WeightedPhaseSpaceGenerator( initial_state_mass, final_state_masses, backend=backend ) self.__bunch_size = bunch_size @@ -95,7 +95,7 @@ def generate(self, size: int, rng: RealNumberGenerator) -> DataSample: return phsp -class TFWeightedPhaseSpaceGenerator(DataGenerator): +class WeightedPhaseSpaceGenerator(DataGenerator): """Implements a phase space generator **with weights** on top of `phasespace `_. The weights are provided in the returned `.DataSample` under the key @@ -232,3 +232,9 @@ def _get_seed( if backend == "tensorflow" and isinstance(rng, TFUniformRealNumberGenerator): return rng.generator return int(rng(1, min_value=0, max_value=2**31 - 1)[0]) + + +TFPhaseSpaceGenerator = PhaseSpaceGenerator +"""Alias of `PhaseSpaceGenerator` for backward compatibility.""" +TFWeightedPhaseSpaceGenerator = WeightedPhaseSpaceGenerator +"""Alias of `WeightedPhaseSpaceGenerator` for backward compatibility.""" diff --git a/tests/data/test_data.py b/tests/data/test_data.py index ee2f694a..7ec2a17f 100644 --- a/tests/data/test_data.py +++ b/tests/data/test_data.py @@ -10,7 +10,7 @@ IntensityDistributionGenerator, NumpyDomainGenerator, NumpyUniformRNG, - TFPhaseSpaceGenerator, + PhaseSpaceGenerator, TFUniformRealNumberGenerator, _generate_without_progress_bar, finalize_progress_bar, @@ -79,7 +79,7 @@ def it_reproduces_the_phase_space_for_a_flat_intensity(): sample_size = 5 initial_state_mass = 3.0 final_state_masses = {0: 0.135, 1: 0.135, 2: 0.135} - phsp_generator = TFPhaseSpaceGenerator(initial_state_mass, final_state_masses) + phsp_generator = PhaseSpaceGenerator(initial_state_mass, final_state_masses) data_generator = IntensityDistributionGenerator( phsp_generator, function=FlatDistribution(), diff --git a/tests/data/test_phasespace.py b/tests/data/test_phasespace.py index a96cfe02..6ad5d346 100644 --- a/tests/data/test_phasespace.py +++ b/tests/data/test_phasespace.py @@ -10,9 +10,11 @@ EvtGenPhaseSpaceGenerator, IntensityDistributionGenerator, NumpyUniformRNG, + PhaseSpaceGenerator, TFPhaseSpaceGenerator, TFUniformRealNumberGenerator, TFWeightedPhaseSpaceGenerator, + WeightedPhaseSpaceGenerator, ) from tensorwaves.interface import DataSample, Function @@ -22,7 +24,7 @@ from qrules import ParticleCollection -def describe_TFPhaseSpaceGenerator(): +def describe_PhaseSpaceGenerator(): @pytest.mark.parametrize( ("initial_state", "final_state", "expected_sample"), [ @@ -114,7 +116,7 @@ def it_generates_deterministic_four_momenta( ): sample_size = 3 rng = TFUniformRealNumberGenerator(seed=0) - phsp_generator = TFPhaseSpaceGenerator( + phsp_generator = PhaseSpaceGenerator( initial_state_mass=pdg[initial_state].mass, final_state_masses={ i: pdg[name].mass for i, name in enumerate(final_state) @@ -133,7 +135,7 @@ def it_generates_deterministic_four_momenta( def it_generates_an_empty_sample_for_zero_events(pdg: ParticleCollection): rng = NumpyUniformRNG() - phsp_generator = TFPhaseSpaceGenerator( + phsp_generator = PhaseSpaceGenerator( initial_state_mass=pdg["J/psi(1S)"].mass, final_state_masses={ i: pdg[name].mass for i, name in enumerate(["gamma", "pi0", "pi0"]) @@ -143,13 +145,13 @@ def it_generates_an_empty_sample_for_zero_events(pdg: ParticleCollection): assert len(phsp_momenta) == 0 -def describe_TFWeightedPhaseSpaceGenerator(): +def describe_WeightedPhaseSpaceGenerator(): def it_generates_deterministic_four_momenta_and_weights(pdg: ParticleCollection): sample_size = 5 initial_state_name = "J/psi(1S)" final_state_names = ["K0", "Sigma+", "p~"] rng = TFUniformRealNumberGenerator(seed=123) - phsp_generator = TFWeightedPhaseSpaceGenerator( + phsp_generator = WeightedPhaseSpaceGenerator( initial_state_mass=pdg[initial_state_name].mass, final_state_masses={ i: pdg[name].mass for i, name in enumerate(final_state_names) @@ -252,7 +254,7 @@ def it_matches_the_phasespace_generator(backend): masses = {0: 0.135, 1: 0.14, 2: 0.14} size = 100_000 evtgen = EvtGenPhaseSpaceGenerator(3.097, masses) - phsp_generator = TFPhaseSpaceGenerator( + phsp_generator = PhaseSpaceGenerator( 3.097, masses, bunch_size=size, backend=backend ) phsp_generator.show_progress = False @@ -280,6 +282,11 @@ def __call__(self, data: DataSample) -> np.ndarray: assert sample["p0"].shape == (50, 4) +def it_keeps_aliases_with_tf_prefix(): + assert TFPhaseSpaceGenerator is PhaseSpaceGenerator + assert TFWeightedPhaseSpaceGenerator is WeightedPhaseSpaceGenerator + + def describe_backend(): masses = {0: 0.135, 1: 0.135, 2: 0.135} @@ -288,7 +295,7 @@ def describe_backend(): "rng_type", [NumpyUniformRNG, TFUniformRealNumberGenerator] ) def it_returns_reproducible_numpy_arrays(backend, rng_type): - generator = TFPhaseSpaceGenerator(3.0, masses, backend=backend) + generator = PhaseSpaceGenerator(3.0, masses, backend=backend) sample1 = generator.generate(10, rng_type(seed=0)) sample2 = generator.generate(10, rng_type(seed=0)) assert set(sample1) == {"p0", "p1", "p2"} @@ -302,11 +309,11 @@ def it_returns_reproducible_numpy_arrays(backend, rng_type): def it_uses_numpy_by_default(): import phasespace - TFWeightedPhaseSpaceGenerator(3.0, masses) + WeightedPhaseSpaceGenerator(3.0, masses) assert phasespace.get_backend().name == "NUMPY" def it_advances_the_stream_of_an_rng_with_a_foreign_backend(): - generator = TFWeightedPhaseSpaceGenerator(3.0, masses) + generator = WeightedPhaseSpaceGenerator(3.0, masses) rng = TFUniformRealNumberGenerator(seed=0) sample1 = generator.generate(5, rng) sample2 = generator.generate(5, rng) @@ -315,4 +322,4 @@ def it_advances_the_stream_of_an_rng_with_a_foreign_backend(): def it_rejects_unknown_backends(): with pytest.raises(ValueError, match="Backend must be one of"): - TFWeightedPhaseSpaceGenerator(3.0, masses, backend="torch") # ty:ignore[invalid-argument-type] + WeightedPhaseSpaceGenerator(3.0, masses, backend="torch") # ty:ignore[invalid-argument-type] From f5c776d39ddc8e0366d4f3c39bfd36ede2b7af62 Mon Sep 17 00:00:00 2001 From: Remco de Boer <29308176+redeboer@users.noreply.github.com> Date: Sun, 8 Nov 2026 20:52:02 +0100 Subject: [PATCH 5/5] MAINT: lock pyevtgen version that is available on test index --- uv.lock | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/uv.lock b/uv.lock index 41c01eb7..4f162182 100644 --- a/uv.lock +++ b/uv.lock @@ -3460,22 +3460,24 @@ wheels = [ [[package]] name = "pyevtgen" -version = "0.0.1.dev18+g2c14941b7" +version = "0.0.1.dev24+g3c4f80f23" source = { registry = "https://redeboer.github.io/pyevtgen-test/simple" } dependencies = [ { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, { name = "numpy", version = "2.5.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, ] -sdist = { url = "https://redeboer.github.io/pyevtgen-test/simple/pyevtgen/pyevtgen-0.0.1.dev18%2Bg2c14941b7.tar.gz", hash = "sha256:2eeb529e276d5d2d4bad213b9f3f5a105ee85ed7d8e4373a4d9a570e9b41cd1c" } -wheels = [ - { url = "https://redeboer.github.io/pyevtgen-test/simple/pyevtgen/pyevtgen-0.0.1.dev18%2Bg2c14941b7-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:54ab0aec82ac4bf6025834c662ee9fd102d2699675fe3a9627795867f29d5779" }, - { url = "https://redeboer.github.io/pyevtgen-test/simple/pyevtgen/pyevtgen-0.0.1.dev18%2Bg2c14941b7-cp311-cp311-macosx_11_0_x86_64.whl", hash = "sha256:3e5bfe415ef056112ef7863fc0aa48e3eb215f02582a7e3a080ad1e86f8bb010" }, - { url = "https://redeboer.github.io/pyevtgen-test/simple/pyevtgen/pyevtgen-0.0.1.dev18%2Bg2c14941b7-cp311-cp311-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:bd24a70d64093a66a38cc763347f56268461cf101adb180a61ab732e000a1b7f" }, - { url = "https://redeboer.github.io/pyevtgen-test/simple/pyevtgen/pyevtgen-0.0.1.dev18%2Bg2c14941b7-cp311-cp311-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:2cd2de995f2fd51bab88340adfb5c054cfb8180665ec7ea15c5cb357e1b0c1dc" }, - { url = "https://redeboer.github.io/pyevtgen-test/simple/pyevtgen/pyevtgen-0.0.1.dev18%2Bg2c14941b7-cp312-abi3-macosx_11_0_arm64.whl", hash = "sha256:0580158c9695491de1707761036423670ab854b8a4af73b29e0f87239b4dd907" }, - { url = "https://redeboer.github.io/pyevtgen-test/simple/pyevtgen/pyevtgen-0.0.1.dev18%2Bg2c14941b7-cp312-abi3-macosx_11_0_x86_64.whl", hash = "sha256:54a27d4579a486197e3aced481bfc8f224e1d6cf810f1850fec24da80817780c" }, - { url = "https://redeboer.github.io/pyevtgen-test/simple/pyevtgen/pyevtgen-0.0.1.dev18%2Bg2c14941b7-cp312-abi3-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:25f65ddc9c3d8c4788bc67da5f8d3c60187c9129c0745124fd7bcdfc676e3d3c" }, - { url = "https://redeboer.github.io/pyevtgen-test/simple/pyevtgen/pyevtgen-0.0.1.dev18%2Bg2c14941b7-cp312-abi3-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d07846c737d9d41999da5aaeb51f1d9e977b5e851403d6a18dee6cb3b419e0b8" }, +sdist = { url = "https://redeboer.github.io/pyevtgen-test/simple/pyevtgen/pyevtgen-0.0.1.dev24%2Bg3c4f80f23.tar.gz", hash = "sha256:b95792e56394cfd7a337adc2cb57bc7ad39dcc79ab1daecf8bc04ef8d4bd9650" } +wheels = [ + { url = "https://redeboer.github.io/pyevtgen-test/simple/pyevtgen/pyevtgen-0.0.1.dev24%2Bg3c4f80f23-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:ee0422135bdd487b4f3d09bd37314be4e735ff6ed062e54956f2626521ac5a18" }, + { url = "https://redeboer.github.io/pyevtgen-test/simple/pyevtgen/pyevtgen-0.0.1.dev24%2Bg3c4f80f23-cp311-cp311-macosx_11_0_x86_64.whl", hash = "sha256:b35a98ed4b76c3b61dfa208541687c2f6e45908b82103a1a6ec86fb9e164afa9" }, + { url = "https://redeboer.github.io/pyevtgen-test/simple/pyevtgen/pyevtgen-0.0.1.dev24%2Bg3c4f80f23-cp311-cp311-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7d6d1fddbf9a7647c9fa8b9c2349993e2b9b833ef4ebc8af7fee8b2218b598ed" }, + { url = "https://redeboer.github.io/pyevtgen-test/simple/pyevtgen/pyevtgen-0.0.1.dev24%2Bg3c4f80f23-cp311-cp311-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ad2139feca50a9b258e8ac5569d4a730a928e7410acdee42401ec0d2d6705856" }, + { url = "https://redeboer.github.io/pyevtgen-test/simple/pyevtgen/pyevtgen-0.0.1.dev24%2Bg3c4f80f23-cp312-abi3-macosx_11_0_arm64.whl", hash = "sha256:4fdeed59d2f57449a18e983b593e4a44a5e4868fb0a152c0a2df6c2c201315e4" }, + { url = "https://redeboer.github.io/pyevtgen-test/simple/pyevtgen/pyevtgen-0.0.1.dev24%2Bg3c4f80f23-cp312-abi3-macosx_11_0_x86_64.whl", hash = "sha256:41dfa25f5d7726b11aaa563bb31efe00090fd73053cc6bdd447bcbc5edccd4b4" }, + { url = "https://redeboer.github.io/pyevtgen-test/simple/pyevtgen/pyevtgen-0.0.1.dev24%2Bg3c4f80f23-cp312-abi3-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:096cb976b46fb7f44dba69ff1e5d13859f71a807c75fcc9ee2b289b3a49f82ca" }, + { url = "https://redeboer.github.io/pyevtgen-test/simple/pyevtgen/pyevtgen-0.0.1.dev24%2Bg3c4f80f23-cp312-abi3-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b6fffaa7e90523e06c0e69e5035aa78345073f13bcbc386431a7dd560dd355c6" }, + { url = "https://redeboer.github.io/pyevtgen-test/simple/pyevtgen/pyevtgen-0.0.1.dev24%2Bg3c4f80f23-cp313-cp313-pyemscripten_2025_0_wasm32.whl", hash = "sha256:dd173eb8706f9b395d71605725cda79aa5bdf719b9142cd12f61fac98e974bf0" }, + { url = "https://redeboer.github.io/pyevtgen-test/simple/pyevtgen/pyevtgen-0.0.1.dev24%2Bg3c4f80f23-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:653cb52df01704ae8b4c8151c653d8257dbc3092b5421239199ea3267678eb06" }, ] [[package]]