Skip to content

Implement SI unit conversion via pint - #511

Merged
GamelinAl merged 9 commits into
mainfrom
350-si-unit-conversion
Nov 26, 2026
Merged

GamelinAl merged 9 commits into
mainfrom
350-si-unit-conversion

Conversation

@GamelinAl

@GamelinAl GamelinAl commented Nov 11, 2026 •

Copy link
Copy Markdown
Member

Implements #350: pyAML works in SI everywhere.

What it does

  • Live values are now converted to the same units the simulator uses: m, rad, V, Hz, tune, and the magnet model's hardware unit. A script gives the same result in live and design.
  • set() accepts a pint.Quantity, and get(quantity=True) returns one. get() still returns plain floats.
  • unit() returns the pyAML unit, and the new control_system_unit() returns the device unit.
  • Tune devices that report a frequency (Hz, kHz…) are converted to the fractional tune using the new RFPlant.revolution_frequency(). The new tune_above_half option handles fractional tunes above 0.5.
sr.live.rf.frequency.set(352.37 * ureg.MHz)   # converted to Hz, then to the device unit
sr.live.rf.frequency.get()                     # float in Hz
sr.live.rf.frequency.control_system_unit()     # "MHz"

Design choices

  • Conversion in the core, not in the backends. The source unit is the device's configured unit, and the target unit is fixed by pyAML. Backends need no change, and there is no new configuration key.
  • A device without a unit is assumed to already be in SI, so existing configurations are unchanged. An incompatible or unknown unit raises at load.
  • unit() returns one unit, unless the values really have different units (combined-function magnets, mixed families). Unit strings are canonical (m-1 → 1/m), so different spellings of the same unit compare equal.

Breaking changes

  • Live values of devices declared in non-SI units change, e.g. mm → m.
  • Arrays return a single unit instead of a list.
  • get_devices_access() is replaced by get_si_device_access() / get_si_devices_access().
  • New dependency: pint>=0.24.

Tested with the unit suite (543 passed) and on the TANGO twin.

🤖 Generated with Claude Code

GamelinAl and others added 3 commits November 10, 2026 18:01
New pyaml.common.units module: shared pint registry, multiplicative
conversion factors (accelerator notation such as m-1 or T.m supported,
offset units and mismatched base units rejected), Quantity stripping for
user inputs, and the SI units exposed by PyAML. pint becomes a required
dependency.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Live accessors now read and write the same SI units as the simulator:
backend devices are wrapped in SIDeviceAccess / SIDeviceAccessList, with
the target unit fixed by the accessor (m, rad, V, Hz, magnet hardware
unit). Devices without unit are passed through; incompatible units raise
at load time. Backend aggregators still receive raw devices.

ControlSystem.get_devices_access is replaced by get_si_device_access /
get_si_devices_access. Tests using BPMs declared in mm now expect metres.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Read/write interfaces and scalar aggregators inherit the AcceptsQuantity
mixin, so every set()/set_and_wait() implementation, including external
ones, converts a pint.Quantity to its unit() before writing. get() still
returns plain floats. Add tests for the whole SI conversion feature.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@GamelinAl GamelinAl self-assigned this Nov 11, 2026
@GamelinAl
GamelinAl marked this pull request as draft November 11, 2026 16:57
@gubaidulinvadim

Copy link
Copy Markdown
Member

What is the interest in returning unit() when it's all SI?

@yhidaka if you have some time for us, maybe you could also look at this PR? It implements pint unit conversion for pyAML. You're the only pint-experienced person we know :)

@GamelinAl

Copy link
Copy Markdown
Member Author

What is the interest in returning unit() when it's all SI?

I agree it's not super useful, but these methods were already there and might be useful for users who don't know (or are not sure) what our unit convention is.

@gubaidulinvadim

Copy link
Copy Markdown
Member

What is the interest in returning unit() when it's all SI?

I agree it's not super useful, but these methods were already there and might be useful for users who don't know (or are not sure) what our unit convention is.

The idea of this was to put there a control system unit. For example MHz for RF frequency at SOLEIL. If you follow @JeanLucPons suggestion there's unit() for control system unit and SI_unit() for SI/pyAML unit (where only energy is not in SI).

@GamelinAl
GamelinAl marked this pull request as ready for review November 17, 2026 10:27

@gupichon-soleil gupichon-soleil left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If no unit is specified for a device ("", "1", ...), its values are assumed to be in SI units. The unit() method should then return the corresponding SI unit, for clarity.

I agree with @gubaidulinvadim and @JeanLucPons: a new method should be added to retrieve the underlying device unit. In design mode, it could return unit() or None, to be decided.

RWTotalVoltage.unit() should return SI_VOLTAGE.

@gubaidulinvadim gubaidulinvadim left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems to work. Let's try to have several approvals on this PR before merging. In my opinion, we still miss

  1. an opportunity to easily have get() with units in the same way it is done for set.
  2. Conversion from Hz to dimensionless (divide by revolution frequency). Could be useful for tunes. BPMs could also be not in meters (but in Volts or something dimensionless when calibration is not present)
  3. I don't really support the idea to return SI_UNIT with unit(). I believe unit() should return control system unit not pyAML unit. Or have two method control_system_unit() and pyaml_unit.

Comment thread pyaml/common/units.py Resolved
Comment thread pyaml/common/units.py Resolved
@GamelinAl

Copy link
Copy Markdown
Member Author

@gubaidulinvadim

  1. You want an additional method which gives you not a float but a pint quantity? Or the get with an optional arg to get pint quantities?
  2. You mean that if you get tune in Hz from CS, you need to be able to convert it to tune? It's a bit more complex as it is not a fixed multiplicative factor but I see the use case.
  3. I disagree, unit should return what you use in pyAML. We can have another device_unit or control_system_unit method for CS unit.

@gubaidulinvadim

Copy link
Copy Markdown
Member

@gubaidulinvadim

1. You want an additional method which gives you not a float but a pint quantity? Or the get with an optional arg to get pint quantities?

2. You mean that if you get tune in Hz from CS, you need to be able to convert it to tune? It's a bit more complex as it is not a fixed multiplicative factor but I see the use case.

3. I disagree, unit should return what you use in pyAML. We can have another device_unit or control_system_unit method for CS unit.
  1. Same as set() currently. But it's not a critical requirement.
  2. Yes I mean this. Could be a separate issue. There are some labs that for some reason have this in cs.
  3. You can keep it like this. For me, returning SI unit is pointless.

@gupichon-soleil

Copy link
Copy Markdown
Contributor

If I may comment:

  1. If you can pass a pint quantity to set(), you should be able to retrieve a pint quantity from get().
  2. No opinion on the matter.
  3. The external interface of pyaml should use either SI units or user units, as long as it is clear. A secondary method should then allow retrieving either the internal units used for computation or the user units, depending on the initial choice. Either way, it's a matter of taste, enforcing SI units or keeping user units are both understandable approaches.

@gubaidulinvadim gubaidulinvadim added this to the ESRF Workshop milestone Nov 20, 2026
@gubaidulinvadim gubaidulinvadim linked an issue Nov 20, 2026 that may be closed by this pull request
GamelinAl and others added 3 commits November 20, 2026 15:48
- Add get(quantity=True) returning a pint.Quantity in unit(), and
  control_system_unit() reporting the unit of the control-system devices
  (same as unit() when no device holds the value).
- unit()/control_system_unit() return a single unit when all values share
  it, one unit per value (shaped like get()) only when they differ, e.g.
  combined-function magnets or mixed magnet families. This changes the
  return type of the BPM, magnet, CFM and serialized arrays, which always
  returned one unit per element.
- Report units in a canonical form (pint compact format, "1" for
  dimensionless) so that equivalent spellings compare equal: m-1 -> 1/m,
  T.m -> m*T. Accepted unit formats are documented in pyaml.common.units.
- Fix serialized magnet arrays building unit() by extending a list with a
  string, which split the unit into characters.
- Reject a dimensioned device unit for a dimensionless target (e.g. a tune
  device declared in Hz or mm) instead of passing it through; fix the
  tune unit in tests/config/EBSTuneOATango.yaml.
- Divide by the conversion factor on write so that setpoints are correctly
  rounded (352.372e6 Hz is written as 352.372 MHz).
- Harmonise unit() and control_system_unit() docstrings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A tune monitor device declared in a frequency unit (Hz, kHz...) is read
in Hz and converted to the fractional tune with the revolution frequency
f_rev = f_RF / h, read on every call from the monitor's RF plant and the
accelerator harmonic number.

A frequency only gives the tune modulo 1 and up to q / 1 - q (betatron
sidebands (n +/- q) f_rev): frac(f / f_rev) is folded into [0, 0.5], and
the new tune_above_half option returns 1 - q for a plane whose fractional
tune is above the half-integer.

Tune devices in a frequency unit without rf_plant_name raise at load.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The revolution frequency f_RF / h belongs to the RF plant: RFPlant gains
set_harmonic() and revolution_frequency(), which reads the RF frequency on
every call. BetatronTuneMonitor no longer stores the harmonic number; its
frequency property and the control-system tune conversion use the
revolution frequency of the RF plant rf_plant_name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Pass the revolution frequency to RBetatronTuneArray at construction
  instead of through a setter.
- Factor the resolution of magnet devices in their hardware unit into
  ControlSystem._get_magnet_devices().
- Remove a misleading comment in _hardware_unit and an unneeded list
  branch in wrap_si; fix a comment typo in units.py.
- Shorten the get(quantity=True) docstring note.
- Merge overlapping tests in tests/test_units.py (32 -> 23 tests) without
  losing coverage.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@gubaidulinvadim

Copy link
Copy Markdown
Member

I don't like so much having only noninteger part and a flag for above integer. The tune can be changed via set() or step() in the tuning tool. This could also change the integer part (if you are not SOLEIL II) or put you above/below an integer. But these are changes on the tuning tool side.

@gubaidulinvadim gubaidulinvadim left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd prefer explicit unit_in_pyaml() over implicit unit().

Comment on lines 194 to 196
def unit(self) -> str:
"""Return the frequency unit label."""
"""Return the pyAML unit for this quantity, i.e. returned by get()."""
return "Hz"

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is the pyAML unit for tune in Hz and not dimensionless!?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hz is only an option that this class provide, look at the surrounding code. The default tune unit is SI_TUNE

@GamelinAl

Copy link
Copy Markdown
Member Author

I don't like so much having only noninteger part and a flag for above integer. The tune can be changed via set() or step() in the tuning tool. This could also change the integer part (if you are not SOLEIL II) or put you above/below an integer. But these are changes on the tuning tool side.

Could you propose an alternative?

@gubaidulinvadim

Copy link
Copy Markdown
Member

@GamelinAl, track separately integer and noninteger in Tune tool (not in TuneMonitor). If step() goes outside integer/halfinteger change the integer part. Maybe a flag in Monitor can remain and also become mutable. But I do not know exactly. Maybe there's some facility in collaboration that deals with working points above half-integer?

@GamelinAl

Copy link
Copy Markdown
Member Author

@GamelinAl, track separately integer and noninteger in Tune tool (not in TuneMonitor). If step() goes outside integer/halfinteger change the integer part. Maybe a flag in Monitor can remain and also become mutable. But I do not know exactly. Maybe there's some facility in collaboration that deals with working points above half-integer?

If it's fine for you, let's flag it in a separate issue and merge this one?

@GamelinAl

Copy link
Copy Markdown
Member Author

I'd prefer explicit unit_in_pyaml() over implicit unit().

@gubaidulinvadim For me it's strange to refer to the code name you are using in a method name.
But it you wish I can rename unit to pyaml_unit, should I do that?

Resolve the conflicts with the serialized-magnet rework (#481, #516):
- Keep main's serialized family accessors and apply the SI unit conventions
  to them: a single unit when values share it, the standard unit() docstring,
  control_system_unit() on hardware accessors. The family average strength
  reports its pyAML unit, since no device holds it.
- Build the CSHardwareScalarAggregator with SI device access and give it
  per-magnet unit() and control_system_unit(): the inherited ones listed one
  unit per power supply.
- Take main's deprecated SerializedMagnetsArray, which now relies on the unit
  handling of MagnetArray.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@GamelinAl
GamelinAl merged commit 085e349 into main Nov 26, 2026
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Simple unit convertion to SI on set()

3 participants