|
| 1 | +"""Private shared base class for multipole parameter groups. |
| 2 | +
|
| 3 | +Both :class:`MagneticMultipoleParameters` and :class:`ElectricMultipoleParameters` |
| 4 | +allow arbitrary order-indexed extra fields (e.g. ``Bn1``, ``Es3``, ``Kn0L``). |
| 5 | +Because these fields are not declared with a type, Pydantic would otherwise |
| 6 | +store them as-is, preserving non-native numeric inputs like ``numpy.float64``. |
| 7 | +That breaks downstream YAML serialization (PyYAML emits unsafe Python-object |
| 8 | +tags for numpy scalars). See pals-project/pals-python#67. |
| 9 | +
|
| 10 | +This module centralizes the name-validation logic and adds numpy-to-native |
| 11 | +coercion at construction time. |
| 12 | +""" |
| 13 | + |
| 14 | +from typing import Any, ClassVar |
| 15 | + |
| 16 | +from pydantic import BaseModel, ConfigDict, model_validator |
| 17 | + |
| 18 | + |
| 19 | +def _coerce_numpy_value(value: Any) -> Any: |
| 20 | + """Convert numpy scalars/arrays to Python-native equivalents. |
| 21 | +
|
| 22 | + Recurses through ``list``/``tuple``/``dict`` containers so nested |
| 23 | + structures are also cleaned. Returns ``value`` unchanged when numpy is |
| 24 | + not installed or the value is not a numpy type. numpy remains an optional |
| 25 | + dependency of this project. |
| 26 | + """ |
| 27 | + try: |
| 28 | + import numpy as np |
| 29 | + except ImportError: |
| 30 | + return value |
| 31 | + |
| 32 | + if isinstance(value, np.ndarray): |
| 33 | + if value.ndim == 0: |
| 34 | + return value.item() |
| 35 | + return _coerce_numpy_value(value.tolist()) |
| 36 | + if isinstance(value, np.generic): |
| 37 | + return value.item() |
| 38 | + if isinstance(value, list): |
| 39 | + return [_coerce_numpy_value(v) for v in value] |
| 40 | + if isinstance(value, tuple): |
| 41 | + return tuple(_coerce_numpy_value(v) for v in value) |
| 42 | + if isinstance(value, dict): |
| 43 | + return {k: _coerce_numpy_value(v) for k, v in value.items()} |
| 44 | + return value |
| 45 | + |
| 46 | + |
| 47 | +def _validate_order( |
| 48 | + key_num: str, parameter_name: str, prefix: str, expected_format: str |
| 49 | +) -> None: |
| 50 | + """Validate that the order number is a non-negative integer without leading zeros.""" |
| 51 | + error_msg = ( |
| 52 | + f"Invalid {parameter_name}: '{prefix}{key_num}'. " |
| 53 | + f"Parameter must be of the form '{expected_format}', " |
| 54 | + f"where 'N' is a non-negative integer without leading zeros." |
| 55 | + ) |
| 56 | + if not key_num.isdigit() or (key_num.startswith("0") and key_num != "0"): |
| 57 | + raise ValueError(error_msg) |
| 58 | + |
| 59 | + |
| 60 | +class _MultipoleBase(BaseModel): |
| 61 | + """Private shared base for multipole parameter groups. |
| 62 | +
|
| 63 | + Subclasses must set :attr:`_PARAMETER_PREFIXES` and :attr:`_KIND_NAME`. |
| 64 | + Both are ``ClassVar`` and are not exposed as Pydantic fields. |
| 65 | + """ |
| 66 | + |
| 67 | + # Subclasses override these: |
| 68 | + _PARAMETER_PREFIXES: ClassVar[dict[str, tuple[str, str]]] = {} |
| 69 | + _KIND_NAME: ClassVar[str] = "multipole" |
| 70 | + |
| 71 | + model_config = ConfigDict(extra="allow") |
| 72 | + |
| 73 | + @model_validator(mode="before") |
| 74 | + @classmethod |
| 75 | + def _validate_and_coerce(cls, values: dict[str, Any]) -> dict[str, Any]: |
| 76 | + """Validate parameter names and coerce numpy values to Python natives.""" |
| 77 | + coerced: dict[str, Any] = {} |
| 78 | + for key, value in values.items(): |
| 79 | + is_length_integrated = key.endswith("L") |
| 80 | + base_key = key[:-1] if is_length_integrated else key |
| 81 | + |
| 82 | + if is_length_integrated and base_key.startswith("tilt"): |
| 83 | + raise ValueError( |
| 84 | + f"Invalid {cls._KIND_NAME} multipole parameter: '{key}'. " |
| 85 | + ) |
| 86 | + |
| 87 | + for prefix, ( |
| 88 | + expected_format, |
| 89 | + description, |
| 90 | + ) in cls._PARAMETER_PREFIXES.items(): |
| 91 | + if base_key.startswith(prefix): |
| 92 | + key_num = base_key[len(prefix) :] |
| 93 | + _validate_order(key_num, description, prefix, expected_format) |
| 94 | + break |
| 95 | + else: |
| 96 | + prefix_list = ", ".join( |
| 97 | + f"'{p}N'" for p in cls._PARAMETER_PREFIXES if p != "tilt" |
| 98 | + ) |
| 99 | + raise ValueError( |
| 100 | + f"Invalid {cls._KIND_NAME} multipole parameter: '{key}'. " |
| 101 | + f"Parameters must be of the form 'tiltN', {prefix_list} " |
| 102 | + f"(with optional 'L' suffix for length-integrated), " |
| 103 | + f"where 'N' is a non-negative integer." |
| 104 | + ) |
| 105 | + |
| 106 | + coerced[key] = _coerce_numpy_value(value) |
| 107 | + |
| 108 | + return coerced |
0 commit comments