Skip to content

Keep units with a numeric factor, such as meV*angstrom - #310

Merged
henrikjacobsenfys merged 2 commits into
developfrom
keep-units-with-numeric-factor
Nov 24, 2026
Merged

henrikjacobsenfys merged 2 commits into
developfrom
keep-units-with-numeric-factor

Conversation

@henrikjacobsenfys

@henrikjacobsenfys henrikjacobsenfys commented Nov 24, 2026 •

Copy link
Copy Markdown
Member

Problem

Scipp writes a unit it has no name for with a numeric factor: meV*angstrom is 1.602176634e-32 J*m. EasyScience strips that factor whenever it creates a DescriptorNumber or Parameter, including the result of every arithmetic operation, and rescales the value to match. The value is physically the same, but the number changes silently:

Before After
Parameter(value=0.1, unit='meV*angstrom') 1.6e-33 J*m 0.1 meV*Å
then parameter.value = 0.2 read in J*m read in meV*Å
Parameter.from_dict(p.to_dict()) value rescaled again unchanged
2 meV * 3 Å 9.6e-32 J*m 6 meV*Å
E * L / L 3.2e-22 J 2 meV
(2 meV)**2 1.03e-43 J^2 4 meV^2
1 m / 1 mm 1000 dimensionless 1000 dimensionless (unchanged)

The stripping exists for the last row: a unit that is only a number, such as 1000 from m/mm, should become dimensionless.

Change

easydynamics/base_unit_patch.py replaces EasyScience's DescriptorNumber._base_unit, the unit a new object is converted to, with one that strips only a unit that is just a number and keeps any other. It is applied first thing when easydynamics is imported.

  • Temporary: remove the module once EasyScience stops stripping the factor.
  • Scope: it patches the EasyScience class, so it applies to every EasyScience DescriptorNumber and Parameter in the process, not only ours. Overriding _base_unit in our subclasses alone is not enough: EasyScience builds arithmetic results with its own classes.
  • Speed: unchanged. I also tried overriding the arithmetic in our subclasses instead; it worked but made dependency updates about twice as slow (about 90 ms instead of about 46 ms per parameter change with 50 Q), because every operation then built two objects.
  • Display: a unit with a factor still prints in scipp's form, e.g. meV*angstrom**2 as 1.6e-42*kN*L. Only the value is affected by this PR.

Not covered: two EasyDynamics DescriptorNumbers still cannot be added, subtracted, multiplied or divided, because EasyScience only accepts its own exact class there. Our code never does this.

Follow-up

Once merged, #299 can drop its three workarounds that set a unit after construction (in make_parameter_Q_independent, set_parameter_Q_dependence and ModelBase.from_dict), about 20 lines.

Tests

tests/unit/easydynamics/test_base_unit_patch.py: construction, setting a value, to_dict/from_dict, arithmetic (product, chain, power), and a dependency without desired_unit. The pure-number case is tested over 13 ratios: scipp gives any ratio of compatible units with different prefixes a unit that is only a number, above or below 1 (1000 for m/mm, 0.001 for mm/m, 1.6e-22 for meV/J, 0.1 for meV*angstrom / meV*nm), and all must stay dimensionless. A ratio of unrelated units (meV/THz) keeps its unit.

Without the patch, 8 tests fail; the ratio tests pass either way, as that behaviour is unchanged. All unit tests and tutorial notebooks pass.

🤖 Generated with Claude Code

Scipp writes a unit it has no name for with a numeric factor, e.g.
meV*angstrom as 1.602176634e-32 J*m. EasyScience strips that factor
whenever it creates a DescriptorNumber or Parameter, including every
arithmetic result, so the unit became J*m and the value was rescaled:
Parameter(value=0.1, unit='meV*angstrom') had the value 1.6e-33, a value
set later was read in J*m, and 2 meV * 3 angstrom gave 9.6e-32 J*m.

A temporary patch of EasyScience's DescriptorNumber._base_unit, applied
when easydynamics is imported, now strips only a unit that is just a
number (1000 from m/mm still becomes dimensionless) and keeps any other.
Values, bounds and arithmetic results keep their unit, at no extra cost.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@codecov

codecov Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 98.28%. Comparing base (1fc0ce8) to head (a916091).
⚠️ Report is 1 commits behind head on develop.

Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##           develop     #310      +/-   ##
===========================================
+ Coverage    98.27%   98.28%   +0.01%     
===========================================
  Files           65       66       +1     
  Lines         6548     6593      +45     
  Branches      1105     1113       +8     
===========================================
+ Hits          6435     6480      +45     
  Misses          60       60              
  Partials        53       53              
Flag Coverage Δ
unittests 98.28% <100.00%> (+0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
src/easydynamics/__init__.py 100.00% <100.00%> (ø)
src/easydynamics/base_unit_patch.py 100.00% <100.00%> (ø)

... and 3 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@henrikjacobsenfys henrikjacobsenfys added [scope] bug Bug report or fix (major.minor.PATCH) [priority] medium Normal/default priority labels Nov 24, 2026
Scipp gives a ratio of compatible units with different prefixes a unit
that is only a number, above or below 1 (1000 for m/mm, 0.001 for mm/m,
1.6e-22 for meV/J). Cover a range of them, and a ratio of unrelated
units, which keeps its unit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
henrikjacobsenfys added a commit that referenced this pull request Nov 24, 2026
With #310, a Parameter created with a unit such as meV*angstrom keeps its
value, so make_parameter_Q_independent, set_parameter_Q_dependence and
ModelBase.from_dict no longer set the unit after construction. The
shared relabel_parameter_unit helper this PR added for them is dropped
again; ExpressionComponent.set_unit, which relabels a unit on purpose,
keeps its own copy as on develop.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@henrikjacobsenfys
henrikjacobsenfys merged commit e1616c4 into develop Nov 24, 2026
32 of 33 checks passed
henrikjacobsenfys added a commit that referenced this pull request Nov 24, 2026
* Add get_parameters, fix_parameter and free_parameter to ModelBase

Address one Parameter of a named component at every Q, or at a single Q,
without looping over the per-Q component collections by hand. Fixing or
freeing at every Q also updates the template, so it survives a rebuild.

Part of #70.

Co-Authored-By: Claude Fable 5.2 <[email protected]>

* Add make_parameter_Q_independent to ModelBase

Tie one Parameter of a named component to a single value across Q, by
making it at every other Q dependent on the one at Q index 0. The model
stores the tie and reapplies it whenever the per-Q collections are
rebuilt or patched. remove_parameter_Q_constraint undoes it.

Part of #70.

Co-Authored-By: Claude Fable 5.2 <[email protected]>

* Add set_parameter_Q_dependence to ModelBase

Make one Parameter of a named component follow an expression in Q, in
terms of new Parameters owned by the model and shared by all Q. Units
are carried through the expression by EasyScience. The model stores the
dependence and reapplies it whenever the per-Q collections are rebuilt
or patched.

Part of #70.

Co-Authored-By: Claude Fable 5.2 <[email protected]>

* Test the error for a dependent parameter; do not pin a library message

The description promises that fixing a dependent parameter raises the
EasyScience AttributeError; that is now tested. Two tests matched the
full text of an EasyScience KeyError and only need the missing name.

Co-Authored-By: Claude Fable 5.2 <[email protected]>

* Drop Q constraints with their component in two more cases

Found by an independent review, each reproduced with a script.

- A constraint on a component generated by a diffusion model outlived
  remove_diffusion_model, and remove_parameter_Q_constraint then raised
  a KeyError. SampleModel recorded the diffusion models' versions after
  the base class reapplied the constraints, which it skips while the
  collections count as stale. The two lines are swapped.
- clear_components without Q kept the constraint for a later component
  of the same name, since pruning only runs on per-Q collections.
  clear_components now clears the constraints.

Also: say in the docstring which fixed flags a removed constraint
leaves, and drop a test that repeated get_parameters' own.

Co-Authored-By: Claude Fable 5.2 <[email protected]>

* Keep the value of a new Parameter whose unit has a numeric factor

Found by an independent review and reproduced with scripts.

set_parameter_Q_dependence created its Parameters with the unit in the
constructor. EasyScience rewrites a unit such as meV*angstrom**2 in
base units and rescales the value with it, so {'D': 0.1} came back as
1.6e-43 kN*L, setting D.value afterwards gave widths of about 1e41 meV,
and a fit failed with NaN. The unit is now set after construction with
the relabelling ExpressionComponent already used, which moves to
utils.relabel_parameter_unit.

Also:

- make_parameter_Q_independent replaces an existing Q dependence, as
  the description says and as the reverse already did; it raised.
- remove_parameter_Q_constraint restores the bounds of the template.
  The parameters kept those of the expression, so a width was left
  without a lower bound.
- clear_components clears the Q dependences too.

Co-Authored-By: Claude Fable 5.2 <[email protected]>

* Test removing a Q constraint from a diffusion-model component

Such a component has no template, so there are no template bounds to
restore. Codecov flagged that branch as not covered.

Co-Authored-By: Claude Fable 5.2 <[email protected]>

* Keep Q-independent parameters when copying or serializing a model

copy and to_dict/from_dict re-create a model from its __init__
arguments, so constraints added with make_parameter_Q_independent were
lost. to_dict now writes them under 'Q_independent_parameters', and
from_dict reapplies them after construction.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Keep Q dependences when copying or serializing a model

to_dict now writes each set_parameter_Q_dependence as its expression and
its shared Parameters, and from_dict reinstates them, so the copy follows
its own Parameters. The Parameters are read without their unit and
relabelled afterwards, because EasyScience rescales the value of a
Parameter created with a unit such as meV*angstrom.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Treat a Q-independent Parameter as a constant Q dependence

make_parameter_Q_independent now makes the Parameter at every Q depend on
one new model-owned Parameter, '<component> <parameter> (all Q)', which
starts from the value, unit, bounds and fixed flag at Q index 0 and is
returned. This drops the separate list of Q-independent parameters, its
branch in _apply_Q_constraints and remove_parameter_Q_constraint, the Q
index 0 special case in _get_parameters_with_template, and its own
serialization key; Q-independent and Q-dependent Parameters now share
one store and one code path.

As for a Q dependence, the per-Q Parameters are all dependent, so they
are set, fixed and bounded through the returned Parameter; fix_parameter
on them raises.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Show how to build a diffusion model yourself in tutorial 1

A new section at the end makes the Lorentzian area Q-independent and its
width follow hbar * D * Q**2, fits all Q simultaneously, and gets the
same D and scale as the prebuilt BrownianTranslationalDiffusion model.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Store each Q dependence as a small named record

_Q_dependences mapped each parameter to a bare (expression, parameters)
tuple, read as dependence[0] and dependence[1]. A _QDependence dataclass
with expression and parameters fields makes the type and its uses easier
to read, and the key is unpacked by name instead of as key[0].

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Keep units with a numeric factor, such as meV*angstrom

Scipp writes a unit it has no name for with a numeric factor, e.g.
meV*angstrom as 1.602176634e-32 J*m. EasyScience strips that factor
whenever it creates a DescriptorNumber or Parameter, including every
arithmetic result, so the unit became J*m and the value was rescaled:
Parameter(value=0.1, unit='meV*angstrom') had the value 1.6e-33, a value
set later was read in J*m, and 2 meV * 3 angstrom gave 9.6e-32 J*m.

A temporary patch of EasyScience's DescriptorNumber._base_unit, applied
when easydynamics is imported, now strips only a unit that is just a
number (1000 from m/mm still becomes dimensionless) and keeps any other.
Values, bounds and arithmetic results keep their unit, at no extra cost.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Test that every ratio of compatible units stays dimensionless

Scipp gives a ratio of compatible units with different prefixes a unit
that is only a number, above or below 1 (1000 for m/mm, 0.001 for mm/m,
1.6e-22 for meV/J). Cover a range of them, and a ratio of unrelated
units, which keeps its unit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Build Parameters with their unit directly, now that units are kept

With #310, a Parameter created with a unit such as meV*angstrom keeps its
value, so make_parameter_Q_independent, set_parameter_Q_dependence and
ModelBase.from_dict no longer set the unit after construction. The
shared relabel_parameter_unit helper this PR added for them is dropped
again; ExpressionComponent.set_unit, which relabels a unit on purpose,
keeps its own copy as on develop.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Fable 5.2 <[email protected]>
henrikjacobsenfys added a commit that referenced this pull request Nov 24, 2026
* Add get_parameters, fix_parameter and free_parameter to ModelBase

Address one Parameter of a named component at every Q, or at a single Q,
without looping over the per-Q component collections by hand. Fixing or
freeing at every Q also updates the template, so it survives a rebuild.

Part of #70.

Co-Authored-By: Claude Fable 5.2 <[email protected]>

* Add make_parameter_Q_independent to ModelBase

Tie one Parameter of a named component to a single value across Q, by
making it at every other Q dependent on the one at Q index 0. The model
stores the tie and reapplies it whenever the per-Q collections are
rebuilt or patched. remove_parameter_Q_constraint undoes it.

Part of #70.

Co-Authored-By: Claude Fable 5.2 <[email protected]>

* Add set_parameter_Q_dependence to ModelBase

Make one Parameter of a named component follow an expression in Q, in
terms of new Parameters owned by the model and shared by all Q. Units
are carried through the expression by EasyScience. The model stores the
dependence and reapplies it whenever the per-Q collections are rebuilt
or patched.

Part of #70.

Co-Authored-By: Claude Fable 5.2 <[email protected]>

* Allow exp, sin, cos and sinc in set_parameter_Q_dependence

EasyScience cannot apply functions to a Parameter in a dependency
expression yet. Until it can, map callable DescriptorNumbers to the
function names in the dependency map, so the expression calls those.

Part of #70.

Co-Authored-By: Claude Fable 5.2 <[email protected]>

* Test the error for a dependent parameter; do not pin a library message

The description promises that fixing a dependent parameter raises the
EasyScience AttributeError; that is now tested. Two tests matched the
full text of an EasyScience KeyError and only need the missing name.

Co-Authored-By: Claude Fable 5.2 <[email protected]>

* Drop Q constraints with their component in two more cases

Found by an independent review, each reproduced with a script.

- A constraint on a component generated by a diffusion model outlived
  remove_diffusion_model, and remove_parameter_Q_constraint then raised
  a KeyError. SampleModel recorded the diffusion models' versions after
  the base class reapplied the constraints, which it skips while the
  collections count as stale. The two lines are swapped.
- clear_components without Q kept the constraint for a later component
  of the same name, since pruning only runs on per-Q collections.
  clear_components now clears the constraints.

Also: say in the docstring which fixed flags a removed constraint
leaves, and drop a test that repeated get_parameters' own.

Co-Authored-By: Claude Fable 5.2 <[email protected]>

* Keep the value of a new Parameter whose unit has a numeric factor

Found by an independent review and reproduced with scripts.

set_parameter_Q_dependence created its Parameters with the unit in the
constructor. EasyScience rewrites a unit such as meV*angstrom**2 in
base units and rescales the value with it, so {'D': 0.1} came back as
1.6e-43 kN*L, setting D.value afterwards gave widths of about 1e41 meV,
and a fit failed with NaN. The unit is now set after construction with
the relabelling ExpressionComponent already used, which moves to
utils.relabel_parameter_unit.

Also:

- make_parameter_Q_independent replaces an existing Q dependence, as
  the description says and as the reverse already did; it raised.
- remove_parameter_Q_constraint restores the bounds of the template.
  The parameters kept those of the expression, so a width was left
  without a lower bound.
- clear_components clears the Q dependences too.

Co-Authored-By: Claude Fable 5.2 <[email protected]>

* Test removing a Q constraint from a diffusion-model component

Such a component has no template, so there are no template bounds to
restore. Codecov flagged that branch as not covered.

Co-Authored-By: Claude Fable 5.2 <[email protected]>

* Keep Q-independent parameters when copying or serializing a model

copy and to_dict/from_dict re-create a model from its __init__
arguments, so constraints added with make_parameter_Q_independent were
lost. to_dict now writes them under 'Q_independent_parameters', and
from_dict reapplies them after construction.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Keep Q dependences when copying or serializing a model

to_dict now writes each set_parameter_Q_dependence as its expression and
its shared Parameters, and from_dict reinstates them, so the copy follows
its own Parameters. The Parameters are read without their unit and
relabelled afterwards, because EasyScience rescales the value of a
Parameter created with a unit such as meV*angstrom.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Treat a Q-independent Parameter as a constant Q dependence

make_parameter_Q_independent now makes the Parameter at every Q depend on
one new model-owned Parameter, '<component> <parameter> (all Q)', which
starts from the value, unit, bounds and fixed flag at Q index 0 and is
returned. This drops the separate list of Q-independent parameters, its
branch in _apply_Q_constraints and remove_parameter_Q_constraint, the Q
index 0 special case in _get_parameters_with_template, and its own
serialization key; Q-independent and Q-dependent Parameters now share
one store and one code path.

As for a Q dependence, the per-Q Parameters are all dependent, so they
are set, fixed and bounded through the returned Parameter; fix_parameter
on them raises.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Show how to build a diffusion model yourself in tutorial 1

A new section at the end makes the Lorentzian area Q-independent and its
width follow hbar * D * Q**2, fits all Q simultaneously, and gets the
same D and scale as the prebuilt BrownianTranslationalDiffusion model.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Mention the dependency functions in tutorial 1

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Store each Q dependence as a small named record

_Q_dependences mapped each parameter to a bare (expression, parameters)
tuple, read as dependence[0] and dependence[1]. A _QDependence dataclass
with expression and parameters fields makes the type and its uses easier
to read, and the key is unpacked by name instead of as key[0].

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Keep units with a numeric factor, such as meV*angstrom

Scipp writes a unit it has no name for with a numeric factor, e.g.
meV*angstrom as 1.602176634e-32 J*m. EasyScience strips that factor
whenever it creates a DescriptorNumber or Parameter, including every
arithmetic result, so the unit became J*m and the value was rescaled:
Parameter(value=0.1, unit='meV*angstrom') had the value 1.6e-33, a value
set later was read in J*m, and 2 meV * 3 angstrom gave 9.6e-32 J*m.

A temporary patch of EasyScience's DescriptorNumber._base_unit, applied
when easydynamics is imported, now strips only a unit that is just a
number (1000 from m/mm still becomes dimensionless) and keeps any other.
Values, bounds and arithmetic results keep their unit, at no extra cost.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Test that every ratio of compatible units stays dimensionless

Scipp gives a ratio of compatible units with different prefixes a unit
that is only a number, above or below 1 (1000 for m/mm, 0.001 for mm/m,
1.6e-22 for meV/J). Cover a range of them, and a ratio of unrelated
units, which keeps its unit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Build Parameters with their unit directly, now that units are kept

With #310, a Parameter created with a unit such as meV*angstrom keeps its
value, so make_parameter_Q_independent, set_parameter_Q_dependence and
ModelBase.from_dict no longer set the unit after construction. The
shared relabel_parameter_unit helper this PR added for them is dropped
again; ExpressionComponent.set_unit, which relabels a unit on purpose,
keeps its own copy as on develop.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Use sinc in the Chudley-Elliott width, so the jump length keeps its unit

The width expression wrote sin(x)/x out with the jump length's bare
value, since sin could not take a Parameter, so it assumed angstrom:
converting the jump length to nm made the widths about 100 times too
small. It now uses sinc from the dependency functions on Q * l with
units, which also resolves the TODO waiting for sinc (#272).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Add canary tests that fail once EasyScience no longer needs the workarounds

One test per dependency function checks that EasyScience still cannot
apply exp, sin, cos or sinc to a Parameter, and one checks that, without
the unit patch, EasyScience still rescales meV*angstrom to J*m. When
EasyScience is fixed they fail, and their docstrings say what to remove.
The unit patch keeps EasyScience's own _base_unit for this.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Fable 5.2 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

[priority] medium Normal/default priority [scope] bug Bug report or fix (major.minor.PATCH)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant