Skip to content

Add set_parameter_Q_dependence to ModelBase - #299

Merged
henrikjacobsenfys merged 26 commits into
developfrom
issue-70-q-dependence
Nov 24, 2026
Merged

henrikjacobsenfys merged 26 commits into
developfrom
issue-70-q-dependence

Conversation

@henrikjacobsenfys

@henrikjacobsenfys henrikjacobsenfys commented Nov 12, 2026 •

Copy link
Copy Markdown
Member

Part of #70 (third of four PRs). #297 and #298 are merged, and so is #310, which keeps units such as meV*angstrom from being rescaled.

Problem

Giving a parameter a specific Q dependence was only possible by writing a diffusion model, or by calling EasyScience's make_dependent_on on each per-Q parameter by hand.

Change

(D,) = sample_model.set_parameter_Q_dependence(
    'Lorentzian',
    'width',
    expression='hbar * D * Q**2',
    parameters={'D': 2.4e-9},
    parameter_units={'D': 'm**2/s'},
)
analysis.fit(fit_method='simultaneous')

The width at every Q becomes dependent on D, a new Parameter owned by the model and shared by all Q. The fit varies D.

  • API: parameters and parameter_units work as in ExpressionComponent. Symbols without a unit are dimensionless. The new Parameters are returned in the order given and are named '<component> <parameter> <symbol>', e.g. 'Lorentzian width D'.
  • Symbols: Q (in 1/Å), hbar and kb are provided and reserved.
  • Units: EasyScience carries units through the expression, and the result must be convertible to the unit of the parameter. 'D * Q**2' for a width in meV raises a UnitError. Nothing in the model is changed when the expression is rejected.
  • Fitting and reporting: the new Parameters are returned by get_all_variables, so they are fitted and appear in parameters_to_dataset.
  • Rebuilds: the model stores the dependence and reapplies it, with the same shared Parameters, after the per-Q collections are rebuilt or patched and when Q is set later. Removing the component drops it.
  • Replacing and undoing: a new call replaces any existing Q constraint on the parameter. remove_parameter_Q_constraint undoes it, each Q keeping its current value.

Limitation

Only + - * / ** work in the expression. Functions such as exp or sinc do not, because EasyScience cannot apply them to a Parameter yet (the gap behind #272). The next PR adds a temporary workaround.

Tutorial

Tutorial 1 gets a section at the end, "Making your own diffusion model". It 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 (D = 1.126e-08 ± 9.8e-11 m²/s, scale = 0.6938 ± 0.0043 meV in both).

Tests

Added to the # Q constraints (issue #70) section in test_model_base.py. I also checked by hand that a simultaneous fit of simulated data with width = hbar * D * Q**2 recovers D.

Review

An independent review reproduced one serious bug and two smaller ones, all fixed and covered:

  • Units with a numeric factor were silently rescaled. {'D': 0.1} with 'meV*angstrom**2' came back as 1.6e-43 kN*L; setting D.value afterwards gave widths of about 1e41 meV, and a simultaneous fit failed with NaN. Ten of the tests used such a unit and passed only because they never touched the value afterwards. Keep units with a numeric factor, such as meV*angstrom #310 fixes this for every Parameter, so the new Parameters are now simply created with their unit.
  • make_parameter_Q_independent on a parameter with a Q dependence raised instead of replacing it.
  • remove_parameter_Q_constraint left the bounds of the expression, so a width ended up with no lower bound. The bounds of the template are restored.

Corrections to the text above:

  • "work as in ExpressionComponent" holds for the units now. Two differences remain: a Parameter instance as a value raises TypeError, and a symbol missing from parameters raises NameError rather than defaulting to 1.
  • A symbol in parameters that the expression does not use becomes a free fit parameter with no effect.

Q-independent is now a constant Q dependence

make_parameter_Q_independent (from #298) is now implemented as a Q dependence, so both kinds of constraint share one store and one code path. The separate list, its branches in _apply_Q_constraints and remove_parameter_Q_constraint, and the Q index 0 special case in _get_parameters_with_template are gone.

This changes behaviour from #298: the width at every Q, including Q index 0, now depends on a new model-owned Parameter, '<component> <parameter> (all Q)'. It is returned, and it starts with the value, unit, bounds and fixed flag of the width at Q index 0. You set, fix and bound that Parameter. fix_parameter on the per-Q widths raises, as it already did for a Q dependence. Calling make_parameter_Q_independent again returns the same Parameter.

Copying and serialization

copy and to_dict/from_dict now keep the Q dependences, including their shared Parameters' value, unit, bounds and fixed flag. The copy follows its own Parameters. With #310, a unit such as meV*angstrom survives the round trip without its value being rescaled.

🤖 Generated with Claude Code

henrikjacobsenfys and others added 3 commits November 12, 2026 12:08
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]>
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]>
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]>
@henrikjacobsenfys henrikjacobsenfys added [scope] enhancement Adds/improves features (major.MINOR.patch) [priority] medium Normal/default priority labels Nov 12, 2026
@codecov

codecov Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.61111% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 98.28%. Comparing base (e1616c4) to head (4e566c5).

Files with missing lines Patch % Lines
src/easydynamics/sample_model/model_base.py 98.61% 0 Missing and 1 partial ⚠️
Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##           develop     #299      +/-   ##
===========================================
- Coverage    98.28%   98.28%   -0.01%     
===========================================
  Files           66       66              
  Lines         6593     6638      +45     
  Branches      1113     1118       +5     
===========================================
+ Hits          6480     6524      +44     
  Misses          60       60              
- Partials        53       54       +1     
Flag Coverage Δ
unittests 98.28% <98.61%> (-0.01%) ⬇️

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

Files with missing lines Coverage Δ
src/easydynamics/sample_model/model_base.py 99.69% <98.61%> (-0.31%) ⬇️
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

henrikjacobsenfys and others added 13 commits November 12, 2026 23:39
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]>
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]>
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]>
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]>
…eter

# Conflicts:
#	tests/unit/easydynamics/sample_model/test_model_base.py
#	tests/unit/easydynamics/sample_model/test_sample_model.py
…ue-70-q-independent

# Conflicts:
#	tests/unit/easydynamics/sample_model/test_model_base.py
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]>
…ue-70-q-dependence

# Conflicts:
#	src/easydynamics/sample_model/model_base.py
#	tests/unit/easydynamics/sample_model/test_model_base.py
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]>
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]>
# Conflicts:
#	src/easydynamics/sample_model/model_base.py
#	tests/unit/easydynamics/sample_model/test_model_base.py
#	tests/unit/easydynamics/sample_model/test_sample_model.py
@henrikjacobsenfys
henrikjacobsenfys changed the base branch from issue-70-q-independent to develop November 24, 2026 10:45
henrikjacobsenfys and others added 3 commits November 24, 2026 11:50
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]>
_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]>
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]>
henrikjacobsenfys and others added 3 commits November 24, 2026 12:59
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]>
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 changed the base branch from develop to keep-units-with-numeric-factor November 24, 2026 12:03
# Conflicts:
#	src/easydynamics/sample_model/model_base.py
@henrikjacobsenfys
henrikjacobsenfys changed the base branch from keep-units-with-numeric-factor to develop November 24, 2026 12:36
@henrikjacobsenfys
henrikjacobsenfys merged commit 3db80b4 into develop Nov 24, 2026
28 checks passed
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] enhancement Adds/improves features (major.MINOR.patch)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant