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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ repos:
- id: check-ast

- repo: https://github.com/PyCQA/docformatter
rev: v1.7.7
rev: v1.7.8
hooks:
- id: docformatter
args:
Expand All @@ -42,7 +42,7 @@ repos:
- id: rst-directive-colons

- repo: https://github.com/PyCQA/isort
rev: 8.0.1
rev: 9.0.2
hooks:
- id: isort

Expand Down Expand Up @@ -81,7 +81,7 @@ repos:
- id: nbstripout

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: "v0.15.9"
rev: "v0.16.10"
hooks:
- id: ruff
types_or: [ python, pyi, jupyter ]
Expand Down
1 change: 1 addition & 0 deletions benchmark/bench_phasespace.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from timeit import default_timer

import tensorflow as tf

from phasespace import phasespace

sys.path.append(os.path.dirname(__file__))
Expand Down
8 changes: 4 additions & 4 deletions data/download_test_files.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,19 +18,19 @@ def _is_silent():
FILE_URLS = [
(
"B2K1Gamma_RapidSim_7TeV_K1KstarNonResonant_Tree.root",
"https://cernbox.cern.ch/remote.php/dav/public-files/8mN10X8U7VGfaRc/B2K1Gamma_RapidSim_7TeV_K1KstarNonResonant_Tree.root", # noqa: E501
"https://cernbox.cern.ch/remote.php/dav/public-files/8mN10X8U7VGfaRc/B2K1Gamma_RapidSim_7TeV_K1KstarNonResonant_Tree.root",
),
(
"B2K1Gamma_RapidSim_7TeV_Tree.root",
"https://cernbox.cern.ch/remote.php/dav/public-files/pr3aM8n2hPT4Pag/B2K1Gamma_RapidSim_7TeV_Tree.root", # noqa: E501
"https://cernbox.cern.ch/remote.php/dav/public-files/pr3aM8n2hPT4Pag/B2K1Gamma_RapidSim_7TeV_Tree.root",
),
(
"B2KstGamma_RapidSim_7TeV_KstarNonResonant_Tree.root",
"https://cernbox.cern.ch/remote.php/dav/public-files/QuP2cHeISTTSLVv/B2KstGamma_RapidSim_7TeV_KstarNonResonant_Tree.root", # noqa: E501
"https://cernbox.cern.ch/remote.php/dav/public-files/QuP2cHeISTTSLVv/B2KstGamma_RapidSim_7TeV_KstarNonResonant_Tree.root",
),
(
"B2KstGamma_RapidSim_7TeV_Tree.root",
"https://cernbox.cern.ch/remote.php/dav/public-files/EH5yrCpGko7P7Mc/B2KstGamma_RapidSim_7TeV_Tree.root", # noqa: E501
"https://cernbox.cern.ch/remote.php/dav/public-files/EH5yrCpGko7P7Mc/B2KstGamma_RapidSim_7TeV_Tree.root",
),
]

Expand Down
4 changes: 2 additions & 2 deletions docs/GenMultiDecay_Tutorial.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,10 @@
"# Import libraries\n",
"from pprint import pprint\n",
"\n",
"import tensorflow as tf\n",
"import zfit\n",
"from decaylanguage import DecayChain, DecayChainViewer, DecayMode, DecFileParser\n",
"from particle import Particle\n",
"from decaylanguage import DecFileParser, DecayChainViewer, DecayChain, DecayMode\n",
"import tensorflow as tf\n",
"\n",
"from phasespace.fromdecay import GenMultiDecay"
]
Expand Down
4 changes: 2 additions & 2 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
warnings.filterwarnings("ignore")

# Suppress TensorFlow C++ logging to stderr
import logging # noqa: E402
import logging

logging.getLogger("tensorflow").setLevel(logging.ERROR)

Expand All @@ -43,7 +43,7 @@
except ImportError:
pass

import phasespace # noqa: E402
import phasespace

# -- General configuration ---------------------------------------------

Expand Down
4 changes: 2 additions & 2 deletions src/phasespace/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@

__credits__ = ["Jonas Eschle <Jonas.Eschle@cern.ch>"]

__all__ = ["nbody_decay", "GenParticle", "random", "to_vectors", "numpy"]
__all__ = ["GenParticle", "nbody_decay", "numpy", "random", "to_vectors"]

import tensorflow.experimental.numpy as numpy
from tensorflow.experimental import numpy

from . import random
from .phasespace import GenParticle, nbody_decay, to_vectors
Expand Down
2 changes: 1 addition & 1 deletion src/phasespace/fromdecay/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

import sys

from .genmultidecay import GenMultiDecay # noqa: F401
from .genmultidecay import GenMultiDecay

try:
import zfit # noqa: F401
Expand Down
11 changes: 6 additions & 5 deletions src/phasespace/fromdecay/genmultidecay.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import tensorflow as tf
import tensorflow.experimental.numpy as tnp
from particle import Particle

from phasespace import GenParticle

from .mass_functions import DEFAULT_CONVERTER
Expand All @@ -28,9 +29,9 @@ def __init__(self, gen_particles: list[tuple[float, GenParticle]]):
def from_dict(
cls,
dec_dict: dict,
mass_converter: dict[str, Callable] = None,
tolerance: float = None,
particle_model_map: dict[str, str] = None,
mass_converter: dict[str, Callable] | None = None,
tolerance: float | None = None,
particle_model_map: dict[str, str] | None = None,
):
"""Create a ``GenMultiDecay`` instance from a dict in the ``DecayLanguage`` package format.

Expand Down Expand Up @@ -215,7 +216,7 @@ def _unique_name(name: str, preexisting_particles: set[str]) -> str:
name += " [0]"
i = 1
while name in preexisting_particles:
name = name[: name.rfind("[")] + f"[{str(i)}]"
name = name[: name.rfind("[")] + f"[{i!s}]"
i += 1
preexisting_particles.add(name)
return name
Expand Down Expand Up @@ -254,7 +255,7 @@ def _recursively_traverse(
mass_converter: dict[str, Callable],
particle_model_map: dict[str, str],
tolerance: float,
preexisting_particles: set[str] = None,
preexisting_particles: set[str] | None = None,
) -> list[tuple[float, GenParticle]]:
"""Create all possible GenParticles by recursively traversing a dict from DecayLanguage, see Examples.

Expand Down
1 change: 1 addition & 0 deletions src/phasespace/kinematics.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"""Basic kinematics."""

import tensorflow.experimental.numpy as tnp

from phasespace.backend import function, function_jit


Expand Down
37 changes: 17 additions & 20 deletions src/phasespace/phasespace.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,9 +97,7 @@ class GenParticle:
converted to array-like.
"""

def __init__(
self, name: str, mass: Callable | int | float | np.typing.ArrayLike
) -> None: # noqa
def __init__(self, name: str, mass: Callable | float | np.typing.ArrayLike) -> None:
self.name = name
self.children = []
self._mass_val = mass
Expand Down Expand Up @@ -185,7 +183,7 @@ def get_mass(

@property
def has_fixed_mass(self):
"""bool: Is the mass a callable function?"""
"""Bool: Is the mass a callable function?"""
return not callable(self._mass)

def set_children(self, *children):
Expand Down Expand Up @@ -222,12 +220,12 @@ def set_children(self, *children):

@property
def has_children(self):
"""bool: Does the particle have children?"""
"""Bool: Does the particle have children?"""
return bool(self.children)

@property
def has_grandchildren(self):
"""bool: Does the particle have grandchildren?"""
"""Bool: Does the particle have grandchildren?"""
if not self.children:
return False
return any(child.has_children for child in self.children)
Expand Down Expand Up @@ -257,14 +255,13 @@ def _preprocess(momentum, n_events):
if len(momentum.shape) not in (1, 2):
raise ValueError(f"Bad shape for momentum -> {list(momentum.shape)}")
# Check compatibility of inputs
if len(momentum.shape) == 2:
if n_events is not None:
momentum_shape = momentum.shape[0]
if momentum_shape is None:
momentum_shape = tf.shape(momentum)[0]
momentum_shape = tnp.asarray(momentum_shape, tnp.int64)
else:
momentum_shape = tnp.asarray(momentum_shape, dtype=tnp.int64)
if len(momentum.shape) == 2 and n_events is not None:
momentum_shape = momentum.shape[0]
if momentum_shape is None:
momentum_shape = tf.shape(momentum)[0]
momentum_shape = tnp.asarray(momentum_shape, tnp.int64)
else:
momentum_shape = tnp.asarray(momentum_shape, dtype=tnp.int64)
# tf.assert_equal(
# n_events,
# momentum_shape,
Expand Down Expand Up @@ -698,9 +695,8 @@ def generate(
f"The number of events requested ({n_events}) doesn't match the boost_to input size "
f"of {boost_to.shape}"
)
if n_events is not None:
if boost_to.shape[0] not in (n_events, 1):
raise ValueError(message)
if n_events is not None and boost_to.shape[0] not in (n_events, 1):
raise ValueError(message)
if not isinstance(n_events, tf.Variable):
n_events = tnp.asarray(n_events, dtype=tnp.int64)
weights, weights_max, parts, _ = self._recursive_generate(
Expand Down Expand Up @@ -754,7 +750,6 @@ def generate_tensor(
ValueError: If ``n_events`` and the size of ``boost_to`` don't match.
See ``GenParticle.generate_unnormalized``.
"""

# Run generation
raise RuntimeError(
"This function is removed. Use `generate` which does not return a Tensor as well."
Expand All @@ -775,7 +770,9 @@ def __init__(self):
)


def nbody_decay(mass_top: float, masses: list, top_name: str = "", names: list = None):
def nbody_decay(
mass_top: float, masses: list, top_name: str = "", names: list | None = None
):
"""Shortcut to build an n-body decay of a GenParticle.

If the particle names are not given, the top particle is called 'top' and the
Expand Down Expand Up @@ -831,7 +828,7 @@ def to_vectors(particles: dict[str, tf.Tensor]) -> dict[str, vector.Momentum]:
newparticles = {}
for name, particle in particles.items():
px, py, pz, e = np.moveaxis(particle, -1, 0) # numpy "unstack"
newparticles[name] = vector.array(dict(px=px, py=py, pz=pz, energy=e))
newparticles[name] = vector.array({"px": px, "py": py, "pz": pz, "energy": e})
return newparticles


Expand Down
1 change: 1 addition & 0 deletions tests/fromdecay/test_fromdecay.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import pytest
from decaylanguage import DecayChain, DecayMode
from numpy.testing import assert_almost_equal

from phasespace.fromdecay import GenMultiDecay
from phasespace.fromdecay.mass_functions import DEFAULT_CONVERTER

Expand Down
3 changes: 2 additions & 1 deletion tests/fromdecay/test_mass_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@

from collections.abc import Callable

import phasespace.fromdecay.mass_functions as mf
import pytest
import tensorflow as tf
import tensorflow_probability as tfp
from particle import Particle

import phasespace.fromdecay.mass_functions as mf

_kstarz = Particle.from_evtgen_name("K*0")
KSTARZ_MASS = _kstarz.mass
KSTARZ_WIDTH = _kstarz.width
Expand Down
1 change: 1 addition & 0 deletions tests/helpers/decays.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

import tensorflow as tf
import tensorflow_probability as tfp

from phasespace import GenParticle

# Use RapidSim values (https://github.com/gcowan/RapidSim/blob/master/config/particles.dat)
Expand Down
3 changes: 2 additions & 1 deletion tests/test_chain.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,12 @@

import numpy as np
import pytest

from phasespace import GenParticle

sys.path.append(os.path.dirname(__file__))

from .helpers import decays # noqa: E402
from .helpers import decays


def test_name_clashes():
Expand Down
5 changes: 3 additions & 2 deletions tests/test_generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,13 @@
import sys

import numpy as np
import phasespace
import pytest

import phasespace

sys.path.append(os.path.dirname(__file__))

from .helpers import decays # noqa: E402
from .helpers import decays

B0_MASS = decays.B0_MASS
PION_MASS = decays.PION_MASS
Expand Down
1 change: 1 addition & 0 deletions tests/test_nbody_decay.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"""Test n-body decay generator."""

import pytest

from phasespace import nbody_decay

from .helpers import decays
Expand Down
17 changes: 9 additions & 8 deletions tests/test_physics.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,13 @@
import matplotlib.pyplot as plt
import tensorflow as tf
import uproot

from phasespace import phasespace

sys.path.append(os.path.dirname(__file__))

from .helpers import decays, rapidsim # noqa: E402
from .helpers.plotting import make_norm_histo # noqa: E402
from .helpers import decays, rapidsim
from .helpers.plotting import make_norm_histo

BASE_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
PLOT_DIR = os.path.join(BASE_PATH, "tests", "plots")
Expand Down Expand Up @@ -191,12 +192,12 @@ def run_kstargamma(input_file, kstar_width, b_at_rest, suffix, use_vector):
booster = booster.transpose()
if use_vector:
booster = vector.array(
dict(
px=booster[:, 0],
py=booster[:, 1],
pz=booster[:, 2],
e=booster[:, 3],
)
{
"px": booster[:, 0],
"py": booster[:, 1],
"pz": booster[:, 2],
"e": booster[:, 3],
}
)
rapidsim_getter = rapidsim.get_tree
decay = decays.b0_to_kstar_gamma(kstar_width=kstar_width)
Expand Down
3 changes: 2 additions & 1 deletion tests/test_random.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import numpy as np
import phasespace as phsp
import pytest
import tensorflow as tf

import phasespace as phsp


@pytest.mark.parametrize(
"seed", [lambda: 15, lambda: tf.random.Generator.from_seed(15)]
Expand Down
Loading