Skip to content

Complex constraints: expressions #283

Open

Description

@rozyczko

We need a way for users to define more sophisticated constraints, including maths functions, e.g.

a = sqrt(b) + exp(1/c)

similar to complex constraints in SasView

Activity

  1. added
    [scope] enhancement
    [priority] medium
    on Oct 22, 2025
  2. self-assigned this
    on Jan 28, 2026
  3. rozyczko commented on Aug 23, 2026

    @rozyczko
    MemberAuthor

    Question: Do GenX, refl1d, refnx and BornAgain only provide single constraints
    between two parameters, or do they offer ways to constrain multiple parameters
    based on physics, in one go? What can EasyReflectometry learn and implement?

    Short answer: none of the four does only pairwise constraints.
    Every one of them has at least two of three richer mechanisms:

    1. Expression engines : one parameter as an arbitrary function of many others

    2. Physics reparameterizations : components that replace many raw profile
      parameters with a few physical ones, coupling everything internally in one run
      (refnx LipidLeaflet, refl1d PolymerBrush/FreeInterface/Magnetism,
      GenX model libraries, BornAgain repeated-layer/magnetic builders).

    3. Inequality / penalty constraints: t1 + t2 < 100 enforced during fitting
      (bumps first-class Constraint objects; refnx via priors and scipy
      NonlinearConstraint; GenX via reparameterization tricks and FOM penalties).

    EasyReflectometry already has a version of (1) and a good chunk of (2) in the
    library. The biggest gaps are (3) inequalities, derived read-only parameters,
    GUI exposure of the existing physics constraints, and constraint persistence.

  4. rozyczko commented on Aug 23, 2026

    @rozyczko
    MemberAuthor

    Comparison with other codes

    Capability refnx refl1d/bumps GenX BornAgain (modern) EasyReflectometry today
    Pairwise tie (a = b) p.constraint = q p.equals(q) / shared object Sim assignment callback reuse of dict key constrain_equal ✅
    Multi-parameter expression ✅ operator overloading + callables ✅ Expression slots + @function ✅ arbitrary Python ✅ arbitrary Python ✅ constrain(p, expr, **map)
    Derived read-only parameters (e.g. total thickness) usable in expressions partial (expressions) ✅ Calculation slots scripted scripted ❌
    Cross-parameter inequalities (t1 + t2 < T) scipy NonlinearConstraint, logp_extra ✅ first-class Constraint, penalty-enforced reparameterization trick reparameterization / external minimizer ❌ (≥/≤ only set own bounds)
    Soft (Gaussian-prior) constraints ✅ bounds = PDF(...) ✅ p.dev(), p.soft_range() ✅ new_sys_err ❌ ❌
    Physics components constraining many params in one go ✅ LipidLeaflet, solvation ✅ polymer/spline/Chebyshev/magnetism model libraries builder patterns ✅ bilayer/surfactant/APM/mixture/density (lib) — barely exposed in GUI
    Bulk/pattern ganging ("all X at once") manual loop copy_linked, shared_beam scripted loop (old wildcard API, removed) constrainModelsParameters (cross-model only)
    User-defined master parameters ✅ auxiliary_params ✅ free Parameter objects ✅ UserVars dict keys are free-form ❌
    Constraints survive save/load ✅ pickle + code-gen ✅ JSON schema with uuid refs ✅ script in project file GUI XML only ❌ (easyscience drops dependency graph)

    What we can implement

    Ranked by value-for-effort for EasyReflectometry (library) and ERA (app).

    High value

    (a) Cross-parameter inequality constraints as fit penalties (from bumps).
    Today ERA's ≥/≤ relations only clamp a parameter's own bounds. The bumps design is
    directly portable to easyscience: a comparison on parameters/expressions yields a
    Constraint object; the fit's cost function adds violation² + big_penalty when
    unsatisfied and skips the model evaluation while infeasible. This unlocks the
    constraints users actually ask for: layer ordering (t_head < t_tail), total
    thickness budget (Σ tᵢ < T), SLD ordering, positive contrast. A cheaper interim
    step is GenX's reparameterization idiom packaged as a helper:
    constrain_fraction(t1, of=t_total) (fit a [0,1] fraction; guarantees t1 ≤ t_total
    without touching the minimizer).

    (b) Derived read-only "calculation" parameters (from bumps Calculation).
    Expose e.g. sample.total_thickness, assembly.thickness, a material's contrast,
    as live computed parameters that can appear on the right-hand side of constrain
    expressions and in the GUI parameter table (read-only rows). Combined with (a),
    "keep total film thickness constant while fitting the split" becomes one constraint
    instead of hand-written algebra the user must maintain.

    (c) Expose the existing physics constraints in the ERA GUI. The library already
    has conformal roughness, APM coupling, solvation, mixtures, density-derived SLD —
    but the app's constraint UI only offers generic expressions. A "physics constraints"
    panel with toggles/recipes would surface what already works:

    • conformal roughness across an assembly (exists: _setup_roughness_constraints),
    • equal APM head/tail (exists: SurfactantLayer.constrain_area_per_molecule),
    • constant multilayer period Λ = d₁ + d₂ (new, trivial with (b)),
    • fractions sum to 1 for mixtures (exists inside MaterialMixture),
    • "same material everywhere it appears" (identity sharing).

    Each recipe is one checkbox that creates/removes a named group of dependencies,
    displayed as a single row in the constraints list rather than N cryptic entries.

  5. rozyczko commented on Aug 23, 2026

    @rozyczko
    MemberAuthor

    Medium value

    (d) Bulk ganging within a model (from BornAgain's old wildcard API and refl1d's
    shared_beam)
    . ERA already gangs parameters across models; add the same within a
    model: "constrain all roughnesses in this sample to layer 1's", "all repetitions of
    Ti share one thickness". Implementation is a loop over constrain_equal. The work
    is UI (multi-select in the parameter table with "tie selected to…"). Full wildcard
    string patterns are not needed; BornAgain itself abandoned them.

    (e) User-defined master parameters (from GenX UserVars / refnx
    auxiliary_params)
    . Let the user create a free parameter that belongs to no model
    object (Λ, a stoichiometry fraction, a hydration level) and constrain model
    parameters to expressions of it. easyscience Parameter objects already support
    this; the gap is project/app plumbing: registering them with the fit and showing
    them in the parameter table.

    (f) Constraint persistence (from bumps). All four codes preserve constraints
    across save/load; easyscience currently drops the dependency graph (noted in
    constraints.py). bumps shows the fix: give parameters stable ids, serialize
    dependency expressions + id-references, rebuild the graph on load (the lib's own
    physics classes already do exactly this per-class in from_dict: it needs doing
    once, generically, in easyscience).
    Until then, ERA could serialize its own _constraint_states (expression + unique_names)
    into the project file and replay them on load.

  6. rozyczko commented on Oct 29, 2026

    @rozyczko
    MemberAuthor

    Waiting for easyscience/core#329 to be done, so we can extend complex constraints here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

[priority] medium[scope] enhancementenhancement

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions