From 19dcef2c049be1fe03ecbc4069a94b262b38cf4d Mon Sep 17 00:00:00 2001 From: Fabian Steube <206550910+Flomber@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:55:32 +0100 Subject: [PATCH 1/3] FEAT: add unknown state to Parity --- src/qrules/quantum_numbers.py | 77 +++++++++++++++++++++++++++--- tests/unit/test_quantum_numbers.py | 63 ++++++++++++++++++++++-- 2 files changed, 131 insertions(+), 9 deletions(-) diff --git a/src/qrules/quantum_numbers.py b/src/qrules/quantum_numbers.py index 44d5fa5d..06fa8078 100644 --- a/src/qrules/quantum_numbers.py +++ b/src/qrules/quantum_numbers.py @@ -8,9 +8,10 @@ from __future__ import annotations +from enum import Enum from fractions import Fraction from functools import total_ordering -from typing import TYPE_CHECKING, Any, Literal, NewType, Protocol, TypeVar +from typing import TYPE_CHECKING, Any, ClassVar, Literal, NewType, Protocol, TypeVar from attrs import field, frozen @@ -20,9 +21,32 @@ from collections.abc import Generator -def _to_parity_int(value: int | Parity) -> Literal[-1, 1]: +class _Unknown(Enum): + """Sentinel type for a `Parity` that exists but whose value is not known. + + An `~enum.Enum` with a single member is the typed sentinel pattern recommended by + :PEP:`484#support-for-singleton-types-in-unions`. Unlike a bare `object`, its + identity survives `copy.deepcopy` and `pickle`, it has a readable `repr`, and type + checkers can narrow on it. Once Python 3.15 is the minimal supported version, it can + be replaced by the builtin ``sentinel()`` from :PEP:`661`. + """ + + UNKNOWN = "?" + + def __repr__(self) -> str: + return "UNKNOWN" + + +_UNKNOWN = _Unknown.UNKNOWN + + +def _to_parity_value( + value: int | Parity | _Unknown, +) -> Literal[-1, 1, _Unknown.UNKNOWN]: if isinstance(value, Parity): return value.value + if value is _UNKNOWN: + return _UNKNOWN if not isinstance(value, int): msg = f"Parity must be an integer, not {type(value)}" raise TypeError(msg) @@ -30,14 +54,36 @@ def _to_parity_int(value: int | Parity) -> Literal[-1, 1]: return -1 if value == +1: return 1 - msg = f"Parity can only be +1 or -1, not {value}" + msg = f"Parity can only be +1, -1, or unknown, not {value}" raise ValueError(msg) @total_ordering @frozen(eq=False, hash=True, order=False, repr=False) class Parity: # ruff: ignore[eq-without-hash] - value: Literal[-1, 1] = field(converter=_to_parity_int) + """Intrinsic parity that is either :math:`+1`, :math:`-1`, or unknown. + + Use `Parity.UNKNOWN` for a parity that exists, but whose value is not (yet) known. + This is different from `None`, which expresses that a parity (like C-parity or + G-parity) is not defined for a particle at all. + + >>> Parity(+1) + Parity(+1) + >>> -Parity(-1) + Parity(+1) + >>> Parity.UNKNOWN + Parity.UNKNOWN + >>> -Parity.UNKNOWN + Parity.UNKNOWN + """ + + value: Literal[-1, 1, _Unknown.UNKNOWN] = field(converter=_to_parity_value) + UNKNOWN: ClassVar[Parity] + """A parity that exists, but whose value is unknown.""" + + @property + def is_unknown(self) -> bool: + return self.value is _UNKNOWN def __eq__(self, other: object) -> bool: if isinstance(other, Parity): @@ -45,18 +91,37 @@ def __eq__(self, other: object) -> bool: return self.value == other def __gt__(self, other: Any) -> bool: + # Total order for sorting: None < UNKNOWN < -1 < +1 if other is None: return True - return self.value > int(other) + if isinstance(other, Parity): + return self.__sort_key() > other.__sort_key() + return int(self) > int(other) + + def __sort_key(self) -> int: + if self.value is _UNKNOWN: + return -2 + return self.value def __int__(self) -> Literal[-1, 1]: + if self.value is _UNKNOWN: + msg = "Cannot convert an unknown parity to int" + raise ValueError(msg) return self.value def __neg__(self) -> Parity: + if self.value is _UNKNOWN: + return self return Parity(-self.value) def __repr__(self) -> str: - return f"{type(self).__name__}({_float_as_signed_str(self.value)})" + class_name = type(self).__name__ + if self.value is _UNKNOWN: + return f"{class_name}.UNKNOWN" + return f"{class_name}({_float_as_signed_str(self.value)})" + + +Parity.UNKNOWN = Parity(_UNKNOWN) def _float_as_signed_str(value: float, render_plus: bool = False) -> str: diff --git a/tests/unit/test_quantum_numbers.py b/tests/unit/test_quantum_numbers.py index d4d477e2..3910972f 100644 --- a/tests/unit/test_quantum_numbers.py +++ b/tests/unit/test_quantum_numbers.py @@ -1,4 +1,5 @@ -from copy import deepcopy +import pickle # ruff: ignore[suspicious-pickle-import] +from copy import copy, deepcopy from fractions import Fraction import pytest @@ -35,7 +36,7 @@ def it_hash(): def it_neg(): parity = Parity(+1) flipped_parity = -parity - assert flipped_parity.value == -parity.value + assert flipped_parity == Parity(-1) @pytest.mark.parametrize("value", [-1, +1]) def it_repr(value): @@ -46,9 +47,65 @@ def it_repr(value): def it_exceptions(): with pytest.raises(TypeError): Parity(1.2) # ty: ignore[invalid-argument-type] - with pytest.raises(ValueError, match=r"Parity can only be \+1 or -1, not 0"): + with pytest.raises( + ValueError, match=r"Parity can only be \+1, -1, or unknown, not 0" + ): Parity(0) + def describe_unknown(): + def it_is_distinct_from_known_parities(): + unknown = Parity.UNKNOWN + assert unknown.is_unknown + assert not Parity(+1).is_unknown + assert not Parity(-1).is_unknown + assert unknown != Parity(+1) + assert unknown != Parity(-1) + assert unknown != +1 + assert unknown != -1 + assert unknown is not None + + def it_init_from_unknown(): + assert Parity(Parity.UNKNOWN) == Parity.UNKNOWN + assert Parity(Parity.UNKNOWN.value) == Parity.UNKNOWN + + def it_survives_copy_and_pickle(): + unknown = Parity.UNKNOWN + for copied in [ + copy(unknown), + deepcopy(unknown), + pickle.loads(pickle.dumps(unknown)), # ruff: ignore[suspicious-pickle-usage] + ]: + assert copied == unknown + assert copied.is_unknown + assert copied.value is unknown.value + + def it_hash(): + assert {Parity.UNKNOWN, deepcopy(Parity.UNKNOWN), Parity(+1)} == { + Parity(+1), + Parity.UNKNOWN, + } + + def it_neg(): + assert -Parity.UNKNOWN == Parity.UNKNOWN + + def it_int_raises(): + with pytest.raises(ValueError, match=r"unknown parity"): + int(Parity.UNKNOWN) + + def it_compares_with_int_raises(): + with pytest.raises(ValueError, match=r"unknown parity"): + _ = Parity.UNKNOWN > 0 + + def it_sorts(): + unsorted = [Parity(+1), Parity.UNKNOWN, Parity(-1)] + assert sorted(unsorted) == [Parity.UNKNOWN, Parity(-1), Parity(+1)] + assert Parity.UNKNOWN > None + assert Parity(-1) > Parity.UNKNOWN + + def it_repr(): + assert repr(Parity.UNKNOWN) == "Parity.UNKNOWN" + assert eval(repr(Parity.UNKNOWN)) == Parity.UNKNOWN + @pytest.mark.parametrize( ("value", "render_plus", "expected"), From f73e52e4ab6c7eeab80a8d7da200d8873bd93d9f Mon Sep 17 00:00:00 2001 From: Fabian Steube <206550910+Flomber@users.noreply.github.com> Date: Tue, 17 Nov 2026 16:42:46 +0100 Subject: [PATCH 2/3] ENH: distinguish unknown from undefined parities in particle adapters --- src/qrules/io/_dict.py | 13 +++- src/qrules/io/_labels.py | 9 ++- src/qrules/particle-validation.json | 2 +- src/qrules/particle/__init__.py | 4 +- src/qrules/particle/_adapter/__init__.py | 58 +++++++++++++++++ src/qrules/particle/_adapter/pdg.py | 44 +++++++------ src/qrules/particle/_adapter/scikit_hep.py | 5 +- tests/unit/io/test_dict.py | 34 +++++++++- tests/unit/io/test_labels.py | 8 ++- tests/unit/particle/adapter/test_adapter.py | 65 +++++++++++++++++++ tests/unit/particle/adapter/test_pdg.py | 21 ++++++ .../unit/particle/adapter/test_scikit_hep.py | 25 +++++++ 12 files changed, 262 insertions(+), 26 deletions(-) create mode 100644 tests/unit/particle/adapter/test_adapter.py diff --git a/src/qrules/io/_dict.py b/src/qrules/io/_dict.py index a3c92623..af80f647 100644 --- a/src/qrules/io/_dict.py +++ b/src/qrules/io/_dict.py @@ -15,6 +15,9 @@ from qrules.topology import Edge, FrozenTransition, Topology from qrules.transition import ReactionInfo, State +_UNKNOWN_PARITY = "?" +"""Serialized value of `.Parity.UNKNOWN`.""" + def from_particle_collection(particles: ParticleCollection) -> dict: """Serialize a `.ParticleCollection`, sorted by particle name. @@ -49,6 +52,8 @@ def _value_serializer(inst: type, field: attrs.Attribute, value: Any) -> Any: # if isinstance(value, Particle): return value.name if isinstance(value, Parity): + if value.is_unknown: + return {"value": _UNKNOWN_PARITY} return {"value": value.value} if isinstance(value, Spin): return { @@ -68,6 +73,12 @@ def build_particle_collection( return ParticleCollection(build_particle(p) for p in definition["particles"]) +def _build_parity(definition: dict) -> Parity: + if definition["value"] == _UNKNOWN_PARITY: + return Parity.UNKNOWN + return Parity(**definition) + + def build_particle(definition: dict) -> Particle: isospin_def = definition.get("isospin") if isospin_def is not None: @@ -75,7 +86,7 @@ def build_particle(definition: dict) -> Particle: for parity in ["parity", "c_parity", "g_parity"]: parity_def = definition.get(parity) if parity_def is not None: - definition[parity] = Parity(**parity_def) + definition[parity] = _build_parity(parity_def) return Particle(**definition) diff --git a/src/qrules/io/_labels.py b/src/qrules/io/_labels.py index 674706c3..e834361c 100644 --- a/src/qrules/io/_labels.py +++ b/src/qrules/io/_labels.py @@ -10,7 +10,7 @@ import attrs from qrules.particle import Particle, ParticleWithSpin, Spin, _render_fraction -from qrules.quantum_numbers import InteractionProperties +from qrules.quantum_numbers import InteractionProperties, _Unknown from qrules.solving import ( EdgeSettings, GraphEdgePropertyMap, @@ -319,6 +319,13 @@ def _(_: None) -> str: return R"\mathrm{None}" +@as_latex.register(_Unknown) +@as_string.register(_Unknown) +def _(_: _Unknown) -> str: + """Render the value of an unknown `.Parity`, for instance in edge properties.""" + return "?" + + @as_string.register(dict) def _(obj: dict) -> str: return __render_mapping(obj, _PLAIN_FORMATTER) diff --git a/src/qrules/particle-validation.json b/src/qrules/particle-validation.json index 956d4612..49d1bee8 100644 --- a/src/qrules/particle-validation.json +++ b/src/qrules/particle-validation.json @@ -10,7 +10,7 @@ "type": "object", "required": ["value"], "properties": { - "value": { "enum": [-1, 1] }, + "value": { "enum": [-1, 1, "?"] }, "additionalProperties": false } }, diff --git a/src/qrules/particle/__init__.py b/src/qrules/particle/__init__.py index c1d9ed79..0f41ff2d 100644 --- a/src/qrules/particle/__init__.py +++ b/src/qrules/particle/__init__.py @@ -227,7 +227,9 @@ def _repr_pretty_(self, p: RepresentationPrinter, cycle: bool) -> None: if value != attribute.default: p.breakable() p.text(f"{attribute.name}=") - if isinstance(value, Parity): + if isinstance(value, Parity) and value.is_unknown: + p.text(repr(value)) + elif isinstance(value, Parity): p.text(_float_as_signed_str(int(value), render_plus=True)) else: p.pretty(value) diff --git a/src/qrules/particle/_adapter/__init__.py b/src/qrules/particle/_adapter/__init__.py index e69de29b..45f0064b 100644 --- a/src/qrules/particle/_adapter/__init__.py +++ b/src/qrules/particle/_adapter/__init__.py @@ -0,0 +1,58 @@ +"""Shared helpers for converting external particle databases to QRules particles.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import attrs + +from qrules.quantum_numbers import Parity + +if TYPE_CHECKING: + from qrules.particle import Particle + + +def mark_unknown_parities(particle: Particle) -> Particle: + """Distinguish parities that are not defined from parities that are unknown. + + Particle databases do not consistently distinguish a parity that does not exist for + a particle from a parity that exists, but has not been measured. This function + decides that based on the other quantum numbers of the particle: + + - The (spatial) parity exists for all particles, so a missing parity is unknown. + - :math:`C`-parity exists only for particles that are their own antiparticle. + - :math:`G`-parity exists only for non-strange, flavorless mesons with isospin. + + Missing parities that exist are set to `.Parity.UNKNOWN`, the others stay `None`. + """ + changes: dict[str, Parity] = {} + if particle.parity is None: + changes["parity"] = Parity.UNKNOWN + if particle.c_parity is None and _has_c_parity(particle): + changes["c_parity"] = Parity.UNKNOWN + if particle.g_parity is None and _has_g_parity(particle): + changes["g_parity"] = Parity.UNKNOWN + if not changes: + return particle + return attrs.evolve(particle, **changes) + + +def _has_c_parity(particle: Particle) -> bool: + return particle.charge == 0 and _is_flavorless_boson(particle) + + +def _has_g_parity(particle: Particle) -> bool: + return particle.isospin is not None and _is_flavorless_boson(particle) + + +def _is_flavorless_boson(particle: Particle) -> bool: + return not any(( + particle.baryon_number, + particle.strangeness, + particle.charmness, + particle.bottomness, + particle.topness, + particle.electron_lepton_number, + particle.muon_lepton_number, + particle.tau_lepton_number, + )) diff --git a/src/qrules/particle/_adapter/pdg.py b/src/qrules/particle/_adapter/pdg.py index 2b78a601..681f7ee9 100644 --- a/src/qrules/particle/_adapter/pdg.py +++ b/src/qrules/particle/_adapter/pdg.py @@ -12,6 +12,7 @@ from pdg.units import convert from qrules.particle import Particle, ParticleCollection, Spin +from qrules.particle._adapter import mark_unknown_parities from qrules.quantum_numbers import Parity if TYPE_CHECKING: @@ -107,25 +108,28 @@ def _convert_particle(source: PdgParticle) -> Particle: parity = Parity(+1 if mcid > 0 else -1) c_parity = _to_parity(source.quantum_C) if source.self_conjugate else None - return Particle( - name=source.name, - pid=mcid, - spin=spin, - mass=mass, - width=width, - charge=charge, - isospin=isospin, - strangeness=strangeness, - charmness=charmness, - bottomness=bottomness, - topness=topness, - baryon_number=baryon_number, - electron_lepton_number=lepton_numbers[0], - muon_lepton_number=lepton_numbers[1], - tau_lepton_number=lepton_numbers[2], - parity=parity, - c_parity=c_parity, - g_parity=_to_parity(source.quantum_G), + # The PDG API leaves out parities that are undefined or not listed (like for W, Z) + return mark_unknown_parities( + Particle( + name=source.name, + pid=mcid, + spin=spin, + mass=mass, + width=width, + charge=charge, + isospin=isospin, + strangeness=strangeness, + charmness=charmness, + bottomness=bottomness, + topness=topness, + baryon_number=baryon_number, + electron_lepton_number=lepton_numbers[0], + muon_lepton_number=lepton_numbers[1], + tau_lepton_number=lepton_numbers[2], + parity=parity, + c_parity=c_parity, + g_parity=_to_parity(source.quantum_G), + ) ) @@ -233,6 +237,8 @@ def _to_parity(value: str | None) -> Parity | None: return Parity(+1) if value == "-": return Parity(-1) + if value == "?": + return Parity.UNKNOWN return None diff --git a/src/qrules/particle/_adapter/scikit_hep.py b/src/qrules/particle/_adapter/scikit_hep.py index 26b044e2..599c4280 100644 --- a/src/qrules/particle/_adapter/scikit_hep.py +++ b/src/qrules/particle/_adapter/scikit_hep.py @@ -10,6 +10,7 @@ from particle import Particle as PdgDatabase from qrules.particle import Particle, ParticleCollection, Spin +from qrules.particle._adapter import mark_unknown_parities from qrules.quantum_numbers import Parity if TYPE_CHECKING: @@ -73,7 +74,7 @@ def convert_spin(value: Fraction | float | None) -> float: latex = None if pdg_particle.latex_name != "Unknown": latex = str(pdg_particle.latex_name) - return Particle( + particle = Particle( name=str(pdg_particle.name), latex=latex, pid=int(pdg_particle.pdgid), @@ -94,6 +95,8 @@ def convert_spin(value: Fraction | float | None) -> float: c_parity=__create_parity(pdg_particle.C), g_parity=__create_parity(pdg_particle.G), ) + # Scikit-HEP uses Parity.u for both undefined and unknown parities + return mark_unknown_parities(particle) def __compute_quark_numbers( diff --git a/tests/unit/io/test_dict.py b/tests/unit/io/test_dict.py index f44d8b55..eacd1e2c 100644 --- a/tests/unit/io/test_dict.py +++ b/tests/unit/io/test_dict.py @@ -1,7 +1,10 @@ import pytest +from jsonschema import ValidationError from qrules import io -from qrules.particle import ParticleCollection +from qrules.io._dict import validate_particle_collection +from qrules.particle import Particle, ParticleCollection +from qrules.quantum_numbers import Parity def describe_serialization(): @@ -14,6 +17,35 @@ def it_ignores_insertion_order(particle_selection: ParticleCollection): reversed_collection.update(reversed(list(particle_selection))) assert io.asdict(reversed_collection) == io.asdict(particle_selection) + def it_round_trips_unknown_parities(): + particle = Particle( + name="X0", + pid=1, + mass=1.0, + spin=0, + parity=Parity.UNKNOWN, + c_parity=Parity.UNKNOWN, + g_parity=-1, + ) + definition = io.asdict(particle) + assert definition["parity"] == {"value": "?"} + assert definition["c_parity"] == {"value": "?"} + assert definition["g_parity"] == {"value": -1} + collection_definition = {"particles": [definition]} + validate_particle_collection(collection_definition) + imported = io.fromdict(collection_definition) + assert isinstance(imported, ParticleCollection) + assert imported["X0"] == particle + + def it_rejects_invalid_parity_values(): + definition = { + "particles": [ + {"name": "X0", "pid": 1, "mass": 1.0, "spin": 0, "parity": {"value": 0}} + ] + } + with pytest.raises(ValidationError): + validate_particle_collection(definition) + def it_not_implemented_errors( output_dir: str, particle_selection: ParticleCollection ): diff --git a/tests/unit/io/test_labels.py b/tests/unit/io/test_labels.py index ef58a6b2..3305da50 100644 --- a/tests/unit/io/test_labels.py +++ b/tests/unit/io/test_labels.py @@ -16,7 +16,7 @@ strip_projections, ) from qrules.particle import Particle, ParticleCollection -from qrules.quantum_numbers import InteractionProperties +from qrules.quantum_numbers import InteractionProperties, Parity from qrules.solving import QNProblemSet, QNResult from qrules.transition import ProblemSet, ReactionInfo, State @@ -114,6 +114,12 @@ def it_dict_and_basic_values(): assert not as_latex({}) assert as_latex({"pid": 1}) == R"\text{pid} = 1" + def it_renders_unknown_parity_values(): + unknown = Parity.UNKNOWN.value + assert as_string(unknown) == "?" + assert as_latex(unknown) == "?" + assert as_string({"parity": unknown}) == "parity = ?" + def it_collapsed_particle_tuple(particle_database: ParticleCollection): particles = ( particle_database["f(0)(980)"], diff --git a/tests/unit/particle/adapter/test_adapter.py b/tests/unit/particle/adapter/test_adapter.py new file mode 100644 index 00000000..4ac3d6c6 --- /dev/null +++ b/tests/unit/particle/adapter/test_adapter.py @@ -0,0 +1,65 @@ +import pytest + +from qrules.particle import Particle, Spin +from qrules.particle._adapter import mark_unknown_parities +from qrules.quantum_numbers import Parity + + +def describe_mark_unknown_parities(): + def it_marks_missing_parity_as_unknown(): + particle = Particle(name="X", pid=1, mass=1.0, spin=0) + assert particle.parity is None + assert mark_unknown_parities(particle).parity == Parity.UNKNOWN + + def it_keeps_known_parities(): + particle = Particle( + name="X0", pid=1, mass=1.0, spin=0, parity=-1, c_parity=+1, g_parity=-1 + ) + assert mark_unknown_parities(particle) is particle + + def it_marks_c_and_g_parity_of_flavorless_neutral_meson_as_unknown(): + particle = Particle( + name="X0", pid=1, mass=1.0, spin=0, parity=-1, isospin=Spin(1, 0) + ) + marked = mark_unknown_parities(particle) + assert marked.c_parity == Parity.UNKNOWN + assert marked.g_parity == Parity.UNKNOWN + + def it_marks_only_g_parity_of_charged_meson_as_unknown(): + particle = Particle( + name="X+", + pid=1, + mass=1.0, + spin=0, + charge=+1, + parity=-1, + isospin=Spin(1, +1), + ) + marked = mark_unknown_parities(particle) + assert marked.c_parity is None + assert marked.g_parity == Parity.UNKNOWN + + def it_does_not_mark_g_parity_without_isospin(): + particle = Particle(name="X0", pid=1, mass=1.0, spin=1, parity=-1) + marked = mark_unknown_parities(particle) + assert marked.c_parity == Parity.UNKNOWN + assert marked.g_parity is None + + @pytest.mark.parametrize( + "flavor", + [ + {"baryon_number": 1}, + {"strangeness": 1}, + {"charmness": 1}, + {"bottomness": 1}, + {"topness": 1}, + {"electron_lepton_number": 1}, + {"muon_lepton_number": 1}, + {"tau_lepton_number": 1}, + ], + ) + def it_does_not_mark_c_and_g_parity_of_flavored_particles(flavor: dict): + particle = Particle(name="X", pid=1, mass=1.0, spin=0, parity=-1, **flavor) + marked = mark_unknown_parities(particle) + assert marked.c_parity is None + assert marked.g_parity is None diff --git a/tests/unit/particle/adapter/test_pdg.py b/tests/unit/particle/adapter/test_pdg.py index 44afbf89..05c16847 100644 --- a/tests/unit/particle/adapter/test_pdg.py +++ b/tests/unit/particle/adapter/test_pdg.py @@ -62,6 +62,27 @@ def it_loads_pion_quantum_numbers( assert pion.c_parity is None assert pion.g_parity == Parity(-1) + @pytest.mark.parametrize( + ("mcid", "parity", "c_parity", "g_parity"), + [ + (111, Parity(-1), Parity(+1), Parity(-1)), + (23, Parity.UNKNOWN, Parity.UNKNOWN, None), # Z0: P not listed + (24, Parity.UNKNOWN, None, None), # W+: P not listed + (203312, Parity.UNKNOWN, None, None), # Xi(1690)-: P listed as "?" + ], + ) + def it_distinguishes_unknown_from_undefined_parities( + official_particles: ParticleCollection, + mcid: int, + parity: Parity, + c_parity: Parity | None, + g_parity: Parity | None, + ): + particle = official_particles.find(mcid) + assert particle.parity == parity + assert particle.c_parity == c_parity + assert particle.g_parity == g_parity + def it_loads_antiproton_quantum_numbers( official_particles: ParticleCollection, ): diff --git a/tests/unit/particle/adapter/test_scikit_hep.py b/tests/unit/particle/adapter/test_scikit_hep.py index fcec0a66..2dc39019 100644 --- a/tests/unit/particle/adapter/test_scikit_hep.py +++ b/tests/unit/particle/adapter/test_scikit_hep.py @@ -3,6 +3,7 @@ import pytest from qrules.particle import ParticleCollection, _get_name_root, create_antiparticle +from qrules.quantum_numbers import Parity def _get_omega_mesons() -> list[str]: @@ -94,6 +95,30 @@ def it_loads_filterable_particle_properties( expected.update({"K(2)*(1980)+", "K(2)*(1980)0"}) assert sorted_result == sorted(expected) + @pytest.mark.parametrize( + ("name", "parity", "c_parity", "g_parity"), + [ + ("pi+", Parity(-1), None, Parity(-1)), + ("pi0", Parity(-1), Parity(+1), Parity(-1)), + ("K+", Parity(-1), None, None), + ("Z0", Parity.UNKNOWN, Parity.UNKNOWN, None), + ("W+", Parity.UNKNOWN, None, None), + ("D(s)*+", Parity.UNKNOWN, None, None), + ("Xi(1690)-", Parity.UNKNOWN, None, None), + ], + ) + def it_distinguishes_unknown_from_undefined_parities( + particle_database: ParticleCollection, + name: str, + parity: Parity, + c_parity: Parity | None, + g_parity: Parity | None, + ): + particle = particle_database[name] + assert particle.parity == parity + assert particle.c_parity == c_parity + assert particle.g_parity == g_parity + def it_loads_particle_properties(particle_database: ParticleCollection): f2_1950 = particle_database.find(9050225) assert f2_1950.name == "f(2)(1950)" From c270b3dc6bbc680e8191890c0f233bca30150c0b Mon Sep 17 00:00:00 2001 From: Fabian Steube <206550910+Flomber@users.noreply.github.com> Date: Tue, 17 Nov 2026 17:03:59 +0100 Subject: [PATCH 3/3] BEHAVIOR: allow particles with unknown parity in solutions --- src/qrules/argument_handling.py | 3 + src/qrules/conservation_rules.py | 74 ++++++++++--------- src/qrules/solving.py | 7 +- .../unit/conservation_rules/test_c_parity.py | 26 +++++++ .../unit/conservation_rules/test_g_parity.py | 45 +++++++++++ .../test_parity_conservation.py | 32 ++++++++ tests/unit/test_solving.py | 29 +++++++- 7 files changed, 180 insertions(+), 36 deletions(-) diff --git a/src/qrules/argument_handling.py b/src/qrules/argument_handling.py index c9bde757..29c0a5ab 100644 --- a/src/qrules/argument_handling.py +++ b/src/qrules/argument_handling.py @@ -28,6 +28,7 @@ GraphElementRule, ) from qrules.quantum_numbers import ( + _UNKNOWN, EdgeQuantumNumber, NodeQuantumNumber, Parity, @@ -150,6 +151,8 @@ def __extract( return None supertype = getattr(self.__obj_type, "__supertype__", None) if supertype == Parity: + if value is _UNKNOWN: # value of an unknown parity in a property map + return Parity.UNKNOWN return Parity(int(value)) # ty: ignore[invalid-return-type] return self.__obj_type(value) diff --git a/src/qrules/conservation_rules.py b/src/qrules/conservation_rules.py index 1d6b8474..e02ff11d 100644 --- a/src/qrules/conservation_rules.py +++ b/src/qrules/conservation_rules.py @@ -47,7 +47,7 @@ """ import operator -from collections.abc import Callable +from collections.abc import Callable, Iterable from copy import deepcopy from fractions import Fraction from functools import reduce @@ -215,16 +215,29 @@ def parity_conservation( outgoing_edge_qns: list[EdgeQN.parity], l_magnitude: NodeQN.l_magnitude, ) -> bool: - r"""Implement :math:`P_{in} = P_{out} \cdot (-1)^L`.""" - if any(p is None for p in [*ingoing_edge_qns, *outgoing_edge_qns]): - return False + r"""Implement :math:`P_{in} = P_{out} \cdot (-1)^L`. + + The rule cannot be checked if any of the parities is unknown and then passes. + """ + if not _all_parities_known([*ingoing_edge_qns, *outgoing_edge_qns]): + return True if len(ingoing_edge_qns) == 1 and len(outgoing_edge_qns) == 2: - parity_in = reduce(lambda x, y: x * y.value, ingoing_edge_qns, 1) - parity_out = reduce(lambda x, y: x * y.value, outgoing_edge_qns, 1) + parity_in = reduce(lambda x, y: x * int(y), ingoing_edge_qns, 1) + parity_out = reduce(lambda x, y: x * int(y), outgoing_edge_qns, 1) return parity_in == (parity_out * (-1) ** l_magnitude) return True +def _all_parities_known(parities: Iterable[Parity | None]) -> bool: + return all(p is not None and not p.is_unknown for p in parities) + + +def _known_parity_value(parity: Parity | None) -> int | None: + if parity is None or parity.is_unknown: + return None + return int(parity) + + @frozen class HelicityParityEdgeInput: parity: EdgeParity = field(converter=to_parity) @@ -254,14 +267,15 @@ def parity_conservation_helicity( Only the special case :math:`\lambda_1=\lambda_2=0` may return `False` independent on the parity prefactor. + + The rule cannot be checked if any of the parities is unknown and then passes. """ if len(ingoing_edge_qns) == 1 and len(outgoing_edge_qns) == 2: + edge_qns = ingoing_edge_qns + outgoing_edge_qns + if not _all_parities_known(x.parity for x in edge_qns): + return True out_spins = [x.spin_magnitude for x in outgoing_edge_qns] - parity_product = reduce( - lambda x, y: x * y.parity.value if y.parity else x, - ingoing_edge_qns + outgoing_edge_qns, - 1, - ) + parity_product = reduce(lambda x, y: x * int(y.parity), edge_qns, 1) prefactor = parity_product * (-1.0) ** ( sum(out_spins) - ingoing_edge_qns[0].spin_magnitude @@ -297,15 +311,17 @@ def c_parity_conservation( ) -> bool: """Check for :math:`C`-parity conservation. - Implements :math:`C_{in} = C_{out}`. + Implements :math:`C_{in} = C_{out}`. An unknown :math:`C`-parity is treated like an + undefined one: the rule passes if the :math:`C`-parity of a side cannot be + determined. """ def _get_c_parity_multiparticle( part_qns: list[CParityEdgeInput], interaction_qns: CParityNodeInput ) -> int | None: - c_parities_part = [x.c_parity.value for x in part_qns if x.c_parity] - # if all states have C parity defined, then just multiply them - if len(c_parities_part) == len(part_qns): + c_parities_part = [_known_parity_value(x.c_parity) for x in part_qns] + # if all states have C parity defined and known, then just multiply them + if all(c is not None for c in c_parities_part): return reduce(operator.mul, c_parities_part, 1) # two particle case @@ -354,7 +370,9 @@ def g_parity_conservation( # ruff: ignore[complex-structure] ) -> bool: """Check for :math:`G`-parity conservation. - Implements for :math:`G_{in} = G_{out}`. + Implements for :math:`G_{in} = G_{out}`. An unknown :math:`G`-parity is treated like + an undefined one: the rule passes if the :math:`G`-parity of a side cannot be + determined. """ def check_multistate_g_parity( @@ -382,28 +400,18 @@ def check_g_parity_isobar( single_state.isospin_magnitude, (couple_state[0], couple_state[1]), ) - single_state_g_parity = ( - ingoing_edge_qns[0].g_parity.value if ingoing_edge_qns[0].g_parity else None - ) + single_state_g_parity = _known_parity_value(ingoing_edge_qns[0].g_parity) if not couple_state_g_parity or not single_state_g_parity: return True return couple_state_g_parity == single_state_g_parity - no_g_parity_in_part = [True for x in ingoing_edge_qns if x.g_parity is None] - no_g_parity_out_part = [True for x in outgoing_edge_qns if x.g_parity is None] - # if all states have G parity defined, then just multiply them - if not any(no_g_parity_in_part + no_g_parity_out_part): - in_g_parity = reduce( - lambda x, y: x * y.g_parity.value if y.g_parity else x, - ingoing_edge_qns, - 1, - ) - out_g_parity = reduce( - lambda x, y: x * y.g_parity.value if y.g_parity else x, - outgoing_edge_qns, - 1, - ) + # if all states have G parity defined and known, then just multiply them + in_g_parities = [_known_parity_value(x.g_parity) for x in ingoing_edge_qns] + out_g_parities = [_known_parity_value(x.g_parity) for x in outgoing_edge_qns] + if all(g is not None for g in in_g_parities + out_g_parities): + in_g_parity = reduce(operator.mul, in_g_parities, 1) + out_g_parity = reduce(operator.mul, out_g_parities, 1) return in_g_parity == out_g_parity # two particle case diff --git a/src/qrules/solving.py b/src/qrules/solving.py index 47162b05..e9d03141 100644 --- a/src/qrules/solving.py +++ b/src/qrules/solving.py @@ -36,6 +36,7 @@ get_required_qns, ) from qrules.quantum_numbers import ( + _UNKNOWN, EdgeQuantumNumber, EdgeQuantumNumbers, EdgeQuantumNumberTypes, @@ -337,7 +338,11 @@ def __is_sub_mapping( continue if qn_type not in reference_state: return False - if qn_value != reference_state[qn_type]: + reference_value = reference_state[qn_type] + if reference_value is _UNKNOWN and qn_value is not None: + # A particle with an unknown parity can have any (defined) parity value + continue + if qn_value != reference_value: return False return True diff --git a/tests/unit/conservation_rules/test_c_parity.py b/tests/unit/conservation_rules/test_c_parity.py index 09f643db..f384a276 100644 --- a/tests/unit/conservation_rules/test_c_parity.py +++ b/tests/unit/conservation_rules/test_c_parity.py @@ -100,3 +100,29 @@ def it_c_parity_multiparticle_boson(rule_input, expected): ) def it_c_parity_multiparticle_fermion(rule_input, expected): assert c_parity_conservation(*rule_input) is expected + + +def describe_unknown_c_parity(): + @pytest.mark.parametrize("c_parity_in", [Parity(-1), Parity(+1), Parity.UNKNOWN]) + def it_passes_if_one_side_is_unknown(c_parity_in: Parity): + ingoing = [CParityEdgeInput(spin_magnitude=0, pid=1, c_parity=c_parity_in)] + outgoing = [ + CParityEdgeInput(spin_magnitude=0, pid=2, c_parity=Parity.UNKNOWN), + CParityEdgeInput(spin_magnitude=0, pid=3, c_parity=Parity(+1)), + ] + node = CParityNodeInput(l_magnitude=0, s_magnitude=0) + assert c_parity_conservation(ingoing, outgoing, node) is True + + @pytest.mark.parametrize( + ("c_parity_in", "expected"), + [(Parity(-1), True), (Parity(+1), False), (Parity.UNKNOWN, True)], + ) + def it_uses_c_parity_of_boson_pair(c_parity_in: Parity, expected: bool): + # C of a boson-antiboson pair is (-1)^L, independent of the individual parities + ingoing = [CParityEdgeInput(spin_magnitude=1, pid=1, c_parity=c_parity_in)] + outgoing = [ + CParityEdgeInput(spin_magnitude=0, pid=+5, c_parity=Parity.UNKNOWN), + CParityEdgeInput(spin_magnitude=0, pid=-5, c_parity=Parity.UNKNOWN), + ] + node = CParityNodeInput(l_magnitude=1, s_magnitude=0) + assert c_parity_conservation(ingoing, outgoing, node) is expected diff --git a/tests/unit/conservation_rules/test_g_parity.py b/tests/unit/conservation_rules/test_g_parity.py index 6bb690d9..231b378f 100644 --- a/tests/unit/conservation_rules/test_g_parity.py +++ b/tests/unit/conservation_rules/test_g_parity.py @@ -96,3 +96,48 @@ def it_g_parity_all_defined(rule_input, expected): ) def it_g_parity_multiparticle_boson(rule_input, expected): assert g_parity_conservation(*rule_input) is expected + + +def describe_unknown_g_parity(): + @pytest.mark.parametrize( + ("g_parity_in", "g_parities_out"), + [ + (Parity.UNKNOWN, (Parity(-1), Parity(-1))), + (Parity(-1), (Parity.UNKNOWN, Parity(-1))), + (Parity(+1), (Parity(-1), Parity.UNKNOWN)), + ], + ) + def it_passes_if_one_state_is_unknown( + g_parity_in: Parity, g_parities_out: tuple[Parity, Parity] + ): + ingoing = [ + GParityEdgeInput( + isospin_magnitude=0, spin_magnitude=0, pid=1, g_parity=g_parity_in + ) + ] + outgoing = [ + GParityEdgeInput(isospin_magnitude=1, spin_magnitude=0, pid=2, g_parity=g) + for g in g_parities_out + ] + node = GParityNodeInput(l_magnitude=Fraction(0), s_magnitude=Fraction(0)) + assert g_parity_conservation(ingoing, outgoing, node) is True + + @pytest.mark.parametrize( + ("g_parity_in", "expected"), + [(Parity(-1), True), (Parity(+1), False), (Parity.UNKNOWN, True)], + ) + def it_uses_g_parity_of_boson_pair(g_parity_in: Parity, expected: bool): + # G of a boson-antiboson pair is (-1)^(L+I), independent of individual parities + ingoing = [ + GParityEdgeInput( + isospin_magnitude=1, spin_magnitude=0, pid=1, g_parity=g_parity_in + ) + ] + outgoing = [ + GParityEdgeInput( + isospin_magnitude=1, spin_magnitude=0, pid=pid, g_parity=Parity.UNKNOWN + ) + for pid in (+5, -5) + ] + node = GParityNodeInput(l_magnitude=Fraction(0), s_magnitude=Fraction(0)) + assert g_parity_conservation(ingoing, outgoing, node) is expected diff --git a/tests/unit/conservation_rules/test_parity_conservation.py b/tests/unit/conservation_rules/test_parity_conservation.py index 566b05da..56d84635 100644 --- a/tests/unit/conservation_rules/test_parity_conservation.py +++ b/tests/unit/conservation_rules/test_parity_conservation.py @@ -107,3 +107,35 @@ def it_helicity(in_parities, out_parities, l_magnitude, expected): parity_conservation_helicity(in_parities, out_parities, l_magnitude) is expected ) + + +def describe_unknown_parity(): + @pytest.mark.parametrize( + ("in_parities", "out_parities"), + [ + ([Parity.UNKNOWN], [Parity(-1), Parity(-1)]), + ([Parity(+1)], [Parity.UNKNOWN, Parity(-1)]), + ([Parity(+1)], [Parity(-1), None]), + ], + ) + @pytest.mark.parametrize("l_magnitude", range(3)) + def it_passes_parity_conservation(in_parities, out_parities, l_magnitude: int): + l_mag = NodeQuantumNumbers.l_magnitude(Fraction(l_magnitude)) + assert parity_conservation(in_parities, out_parities, l_mag) is True + + @pytest.mark.parametrize("parity_prefactor", [-1, +1]) + @pytest.mark.parametrize("unknown_edge", range(3)) + def it_passes_parity_conservation_helicity( + parity_prefactor: int, unknown_edge: int + ): + # λ1 = λ2 = 0 with prefactor -1 would normally fail independent of the prefactor + edges = [ + HelicityParityEdgeInput(parity=-1, spin_magnitude=0, spin_projection=0), + HelicityParityEdgeInput(parity=+1, spin_magnitude=0, spin_projection=0), + HelicityParityEdgeInput(parity=+1, spin_magnitude=0, spin_projection=0), + ] + edges[unknown_edge] = HelicityParityEdgeInput( + parity=Parity.UNKNOWN, spin_magnitude=0, spin_projection=0 + ) + prefactor = NodeQuantumNumbers.parity_prefactor(parity_prefactor) + assert parity_conservation_helicity(edges[:1], edges[1:], prefactor) is True diff --git a/tests/unit/test_solving.py b/tests/unit/test_solving.py index d383d951..7bcd6fa7 100644 --- a/tests/unit/test_solving.py +++ b/tests/unit/test_solving.py @@ -12,7 +12,7 @@ spin_magnitude_conservation, spin_validity, ) -from qrules.quantum_numbers import EdgeQuantumNumbers, NodeQuantumNumbers +from qrules.quantum_numbers import EdgeQuantumNumbers, NodeQuantumNumbers, Parity from qrules.solving import CSPSolver, QNProblemSet, filter_quantum_number_problem_set if TYPE_CHECKING: @@ -30,7 +30,8 @@ def it_finds_solutions( @pytest.mark.parametrize( ("with_spin_projection", "expected_solutions"), - [(True, 321), (False, 129)], + # Includes resonances with unknown parity, like D(s)*+, W+, and Z0 + [(True, 404), (False, 158)], ids=["with-spin-projection", "without-spin-projection"], ) def it_with_filtered_quantum_number_problem_set( @@ -91,3 +92,27 @@ def quantum_number_problem_set() -> QNProblemSet: for strength in sorted(problem_sets) for p in problem_sets[strength] ) + + +def describe_get_candidate_states(): + @pytest.mark.parametrize( + ("solved_value", "expected"), + [(-1, True), (+1, True), (None, False)], + ) + def it_matches_unknown_parity_with_any_defined_value( + solved_value: int | None, expected: bool + ): + get_candidate_states = getattr(qrules.solving, "__get_candidate_states") + unknown = Parity.UNKNOWN.value + candidate = {EdgeQuantumNumbers.pid: 23, EdgeQuantumNumbers.c_parity: unknown} + state = {EdgeQuantumNumbers.pid: 23, EdgeQuantumNumbers.c_parity: solved_value} + candidates = get_candidate_states(state, [candidate]) + assert (candidates == [candidate]) is expected + + def it_does_not_match_known_parity_with_other_value(): + get_candidate_states = getattr(qrules.solving, "__get_candidate_states") + candidate = {EdgeQuantumNumbers.parity: -1} + assert get_candidate_states({EdgeQuantumNumbers.parity: +1}, [candidate]) == [] + assert get_candidate_states({EdgeQuantumNumbers.parity: -1}, [candidate]) == [ + candidate + ]