forked from ax3l/pydantic-mad
-
Notifications
You must be signed in to change notification settings - Fork 3
Refactor MagneticMultipoleParameters
#44
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
EZoni
merged 4 commits into
pals-project:main
from
ax3l:topic-refactor-magnetic-multipole-param
Oct 30, 2025
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,62 +1,67 @@ | ||
| from pydantic import BaseModel, ConfigDict, model_validator | ||
| from typing import Any, Dict | ||
| from typing import Any | ||
|
|
||
| # Valid parameter prefixes, their expected format and description | ||
| _PARAMETER_PREFIXES = { | ||
| "tilt": ("tiltN", "Tilt"), | ||
| "Bn": ("BnN", "Normal component"), | ||
| "Bs": ("BsN", "Skew component"), | ||
| "Kn": ("KnN", "Normalized normal component"), | ||
| "Ks": ("KsN", "Normalized skew component"), | ||
| } | ||
|
|
||
|
|
||
| def _validate_order( | ||
| key_num: str, parameter_name: str, prefix: str, expected_format: str | ||
| ) -> None: | ||
| """Validate that the order number is a non-negative integer without leading zeros.""" | ||
| error_msg = ( | ||
| f"Invalid {parameter_name}: '{prefix}{key_num}'. " | ||
| f"Parameter must be of the form '{expected_format}', where 'N' is a non-negative integer without leading zeros." | ||
| ) | ||
| if not key_num.isdigit() or (key_num.startswith("0") and key_num != "0"): | ||
| raise ValueError(error_msg) | ||
|
|
||
|
|
||
| class MagneticMultipoleParameters(BaseModel): | ||
| """Magnetic multipole parameters""" | ||
| """Magnetic multipole parameters | ||
|
|
||
| # Allow arbitrary fields | ||
| model_config = ConfigDict(extra="allow") | ||
| Valid parameter formats: | ||
| - tiltN: Tilt of Nth order multipole | ||
| - BnN: Normal component of Nth order multipole | ||
| - BsN: Skew component of Nth order multipole | ||
| - KnN: Normalized normal component of Nth order multipole | ||
| - KsN: Normalized skew component of Nth order multipole | ||
| - *NL: Length-integrated versions of components (e.g., Bn3L, KsNL) | ||
|
|
||
| Where N is a positive integer without leading zeros (except "0" itself). | ||
| """ | ||
|
|
||
| # Custom validation of magnetic multipole order | ||
| def _validate_order(key_num, msg): | ||
| if key_num.isdigit(): | ||
| if key_num.startswith("0") and key_num != "0": | ||
| raise ValueError(msg) | ||
| else: | ||
| raise ValueError(msg) | ||
| model_config = ConfigDict(extra="allow") | ||
|
|
||
| # Custom validation to be applied before standard validation | ||
| @model_validator(mode="before") | ||
| def validate(cls, values: Dict[str, Any]) -> Dict[str, Any]: | ||
| # loop over all attributes | ||
| @classmethod | ||
| def validate(cls, values: dict[str, Any]) -> dict[str, Any]: | ||
| """Validate all parameter names match the expected multipole format.""" | ||
| for key in values: | ||
| # validate tilt parameters 'tiltN' | ||
| if key.startswith("tilt"): | ||
| key_num = key[4:] | ||
| msg = " ".join( | ||
| [ | ||
| f"Invalid tilt parameter: '{key}'.", | ||
| "Tilt parameter must be of the form 'tiltN', where 'N' is an integer.", | ||
| ] | ||
| ) | ||
| cls._validate_order(key_num, msg) | ||
| # validate normal component parameters 'BnN' | ||
| elif key.startswith("Bn"): | ||
| key_num = key[2:] | ||
| msg = " ".join( | ||
| [ | ||
| f"Invalid normal component parameter: '{key}'.", | ||
| "Normal component parameter must be of the form 'BnN', where 'N' is an integer.", | ||
| ] | ||
| ) | ||
| cls._validate_order(key_num, msg) | ||
| # validate skew component parameters 'BsN' | ||
| elif key.startswith("Bs"): | ||
| key_num = key[2:] | ||
| msg = " ".join( | ||
| [ | ||
| f"Invalid skew component parameter: '{key}'.", | ||
| "Skew component parameter must be of the form 'BsN', where 'N' is an integer.", | ||
| ] | ||
| ) | ||
| cls._validate_order(key_num, msg) | ||
| # Check if key ends with 'L' for length-integrated values | ||
| is_length_integrated = key.endswith("L") | ||
| base_key = key[:-1] if is_length_integrated else key | ||
|
|
||
| # No length-integrated values allowed for tilt parameter | ||
| if is_length_integrated and base_key.startswith("tilt"): | ||
| raise ValueError(f"Invalid magnetic multipole parameter: '{key}'. ") | ||
|
|
||
| # Find matching prefix | ||
| for prefix, (expected_format, description) in _PARAMETER_PREFIXES.items(): | ||
| if base_key.startswith(prefix): | ||
| key_num = base_key[len(prefix) :] | ||
| _validate_order(key_num, description, prefix, expected_format) | ||
| break | ||
| else: | ||
| msg = " ".join( | ||
| [ | ||
| f"Invalid magnetic multipole parameter: '{key}'.", | ||
| "Magnetic multipole parameters must be of the form 'tiltN', 'BnN', or 'BsN', where 'N' is an integer.", | ||
| ] | ||
| raise ValueError( | ||
| f"Invalid magnetic multipole parameter: '{key}'. " | ||
| f"Parameters must be of the form 'tiltN', 'BnN', 'BsN', 'KnN', or 'KsN' " | ||
| f"(with optional 'L' suffix for length-integrated), where 'N' is a non-negative integer." | ||
| ) | ||
| raise ValueError(msg) | ||
| return values | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What is the difference between using
dictandDict(fromtyping) and why is it better to usedicthere?Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
dictis a Python intrinsic and needs no import. Thus, better.Better generally is:
In terms of compatibility (i.e., more tools understand intrinsics than stdlib than 3rd part libs) and performance (e.g., less imports is better).