Skip to content

project

logger = logging.getLogger(__name__) module-attribute

Q_MIN = 0.001 module-attribute

Q_MAX = 0.3 module-attribute

Q_RESOLUTION = 500 module-attribute

DEFAULT_MINIMIZER = AvailableMinimizers.LMFit_leastsq module-attribute

CalculatorFactory

Bases: InterfaceFactoryTemplate

Source code in src/easyreflectometry/calculators/factory.py
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class CalculatorFactory(InterfaceFactoryTemplate):
    def __init__(self):
        """Init function."""
        super().__init__(interface_list=CalculatorBase._calculators)

    def reset_storage(self) -> None:
        """Reset storage."""
        return self().reset_storage()

    def sld_profile(self, model_id: str) -> tuple:
        """Sld profile."""
        return self().sld_profile(model_id)

    @property
    def fit_func(self) -> Callable:
        """Fit func."""
        """
        Pass through to the underlying interfaces fitting function.

        :param x_array: points to be calculated at
        :type x_array: np.ndarray
        :param args: positional arguments for the fitting function
        :type args: Any
        :param kwargs: key/value pair arguments for the fitting function.
        :type kwargs: Any
        :return: points calculated at positional values `x`
        :rtype: np.ndarray
        #"""

        def __fit_func(*args, **kwargs):
            """Fit func."""
            return self().reflectity_profile(*args, **kwargs)

        return __fit_func

fit_func property

Fit func.

__init__()

Init function.

Source code in src/easyreflectometry/calculators/factory.py
13
14
15
def __init__(self):
    """Init function."""
    super().__init__(interface_list=CalculatorBase._calculators)

reset_storage()

Reset storage.

Source code in src/easyreflectometry/calculators/factory.py
17
18
19
def reset_storage(self) -> None:
    """Reset storage."""
    return self().reset_storage()

sld_profile(model_id)

Sld profile.

Source code in src/easyreflectometry/calculators/factory.py
21
22
23
def sld_profile(self, model_id: str) -> tuple:
    """Sld profile."""
    return self().sld_profile(model_id)

DataSet1D

Bases: SerializerComponent

Source code in src/easyreflectometry/data/data_store.py
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
class DataSet1D(SerializerComponent):
    def __init__(
        self,
        name: str = 'Series',
        x: Optional[Union[np.ndarray, list]] = None,
        y: Optional[Union[np.ndarray, list]] = None,
        ye: Optional[Union[np.ndarray, list]] = None,
        xe: Optional[Union[np.ndarray, list]] = None,
        model: Optional['Model'] = None,  # delay type checking until runtime (quotes)
        x_label: str = 'x',
        y_label: str = 'y',
        auto_background: bool = True,
    ):
        """Init function."""
        self._model = model
        if y is not None and model is not None and auto_background:
            self._model.background = max(np.min(y), 1e-10)

        if x is None:
            x = np.array([])
        if y is None:
            y = np.array([])
        if ye is None:
            ye = np.zeros_like(x)
        if xe is None:
            xe = np.zeros_like(x)

        if len(x) != len(y):
            raise ValueError('x and y must be the same length')

        self.name = name
        if not isinstance(x, np.ndarray):
            x = np.array(x)
        if not isinstance(y, np.ndarray):
            y = np.array(y)
        if not isinstance(ye, np.ndarray):
            ye = np.array(ye)
        if not isinstance(xe, np.ndarray):
            xe = np.array(xe)

        self.x = x
        self.y = y
        self.ye = ye
        self.xe = xe

        self.x_label = x_label
        self.y_label = y_label

        self._color = None

    @property
    def model(self) -> 'Model':  # delay type checking until runtime (quotes)
        """Model function."""
        return self._model

    @model.setter
    def model(self, new_model: 'Model') -> None:
        """Model function."""
        self._model = new_model

    @property
    def is_experiment(self) -> bool:
        """Is experiment."""
        return self._model is not None

    @property
    def is_simulation(self) -> bool:
        """Is simulation."""
        return self._model is None

    def data_points(self) -> tuple[float, float, float, float]:
        """Data points."""
        return zip(self.x, self.y, self.ye, self.xe)

    def __repr__(self) -> str:
        """Repr function."""
        return "1D DataStore of '{:s}' Vs '{:s}' with {} data points".format(self.x_label, self.y_label, len(self.x))

model property writable

Model function.

is_experiment property

Is experiment.

is_simulation property

Is simulation.

__init__(name='Series', x=None, y=None, ye=None, xe=None, model=None, x_label='x', y_label='y', auto_background=True)

Init function.

Source code in src/easyreflectometry/data/data_store.py
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
def __init__(
    self,
    name: str = 'Series',
    x: Optional[Union[np.ndarray, list]] = None,
    y: Optional[Union[np.ndarray, list]] = None,
    ye: Optional[Union[np.ndarray, list]] = None,
    xe: Optional[Union[np.ndarray, list]] = None,
    model: Optional['Model'] = None,  # delay type checking until runtime (quotes)
    x_label: str = 'x',
    y_label: str = 'y',
    auto_background: bool = True,
):
    """Init function."""
    self._model = model
    if y is not None and model is not None and auto_background:
        self._model.background = max(np.min(y), 1e-10)

    if x is None:
        x = np.array([])
    if y is None:
        y = np.array([])
    if ye is None:
        ye = np.zeros_like(x)
    if xe is None:
        xe = np.zeros_like(x)

    if len(x) != len(y):
        raise ValueError('x and y must be the same length')

    self.name = name
    if not isinstance(x, np.ndarray):
        x = np.array(x)
    if not isinstance(y, np.ndarray):
        y = np.array(y)
    if not isinstance(ye, np.ndarray):
        ye = np.array(ye)
    if not isinstance(xe, np.ndarray):
        xe = np.array(xe)

    self.x = x
    self.y = y
    self.ye = ye
    self.xe = xe

    self.x_label = x_label
    self.y_label = y_label

    self._color = None

data_points()

Data points.

Source code in src/easyreflectometry/data/data_store.py
155
156
157
def data_points(self) -> tuple[float, float, float, float]:
    """Data points."""
    return zip(self.x, self.y, self.ye, self.xe)

__repr__()

Repr function.

Source code in src/easyreflectometry/data/data_store.py
159
160
161
def __repr__(self) -> str:
    """Repr function."""
    return "1D DataStore of '{:s}' Vs '{:s}' with {} data points".format(self.x_label, self.y_label, len(self.x))

MultiFitter

Source code in src/easyreflectometry/fitting.py
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
class MultiFitter:
    def __init__(self, *args: Model, objective: str = 'hybrid'):
        r"""A convenience class for the :py:class:`easyscience.Fitting.Fitting`
        which will populate the :py:class:`sc.DataGroup` appropriately
        after the fitting is performed.

        Parameters
        ----------
        *args : Model
            Reflectometry model(s).
        objective : str, optional
            Zero-variance handling strategy. One of
            ``'hybrid'`` (default, Mighell for zero-variance, WLS otherwise),
            ``'mighell'`` (Mighell transform for all points),
            ``'legacy_mask'`` (drop zero-variance points),
            ``'auto'`` (alias for ``'hybrid'``). By default, 'hybrid'.
        """

        # This lets the unique_name be passed with the fit_func.
        def func_wrapper(func, unique_name):
            """Func wrapper."""

            def wrapped(*args, **kwargs):
                """Wrapped function."""
                return func(*args, unique_name, **kwargs)

            return wrapped

        self._fit_func = [func_wrapper(m.interface.fit_func, m.unique_name) for m in args]
        self._models = args
        self.easy_science_multi_fitter = EasyScienceMultiFitter(args, self._fit_func)
        self._fit_results: list[FitResults] | None = None
        self._classical_fit_metrics: list[dict] | None = None
        self._objective = _validate_objective(objective)
        self._sampler: Sampler | None = None

    def fit(self, data: sc.DataGroup, id: int = 0, objective: str | None = None) -> sc.DataGroup:
        """Perform the fitting and populate the DataGroups with the result.

        Parameters
        ----------
        data : sc.DataGroup
            DataGroup to be fitted to and populated.
        id : int, optional
            Unused parameter kept for backward compatibility. By default, 0.
        objective : str | None, optional
            Per-call override for the zero-variance objective.
            If ``None``, uses the instance default set at construction. By default, None.

        Returns
        -------
        sc.DataGroup
            A new DataGroup with fitted model curves, SLD profiles, and fit statistics.
        """
        obj = _validate_objective(objective) if objective is not None else self._objective

        refl_nums = [k[3:] for k in data['coords'].keys() if 'Qz' == k[:2]]
        x = []
        y = []
        dy = []
        original_arrays = []

        # Process each reflectivity dataset
        for i in refl_nums:
            x_vals = data['coords'][f'Qz_{i}'].values
            y_vals = data['data'][f'R_{i}'].values
            variances = data['data'][f'R_{i}'].variances

            x_out, y_eff, weights, stats = _prepare_fit_arrays(x_vals, y_vals, variances, obj)

            if stats['masked'] > 0:
                warnings.warn(
                    f'Masked {stats["masked"]} data point(s) in reflectivity {i} due to zero variance during fitting.',
                    UserWarning,
                )
            if stats.get('transformed_all_points'):
                warnings.warn(
                    f'Applied Mighell transform to all {len(y_vals)} point(s) in reflectivity {i} during fitting.',
                    UserWarning,
                )
            elif stats['mighell_substituted'] > 0:
                warnings.warn(
                    f'Applied Mighell substitution to {stats["mighell_substituted"]} '
                    f'zero-variance point(s) in reflectivity {i} during fitting.',
                    UserWarning,
                )

            x.append(x_out)
            y.append(y_eff)
            dy.append(weights)
            original_arrays.append({'x': x_vals, 'y': y_vals, 'variances': variances})

        result = self.easy_science_multi_fitter.fit(x, y, weights=dy)
        self._fit_results = result
        self._classical_fit_metrics = []
        new_data = data.copy()
        for i, _ in enumerate(result):
            id = refl_nums[i]
            model_curve = self._fit_func[i](data['coords'][f'Qz_{id}'].values)
            new_data[f'R_{id}_model'] = sc.array(dims=[f'Qz_{id}'], values=model_curve)
            sld_profile = self.easy_science_multi_fitter._fit_objects[i].interface.sld_profile(self._models[i].unique_name)
            new_data[f'SLD_{id}'] = sc.array(dims=[f'z_{id}'], values=sld_profile[1] * 1e-6, unit=sc.Unit('1/angstrom') ** 2)
            if 'attrs' in new_data:
                new_data['attrs'][f'R_{id}_model'] = {'model': sc.scalar(self._models[i].as_dict())}
            new_data['coords'][f'z_{id}'] = sc.array(
                dims=[f'z_{id}'],
                values=sld_profile[0],
                unit=(1 / new_data['coords'][f'Qz_{id}'].unit).unit,
            )
            original = original_arrays[i]
            sigma_classical = np.sqrt(np.clip(original['variances'], 0.0, None))
            n_classical_points = int(np.sum(original['variances'] > 0.0))
            classical_chi2 = _compute_weighted_chi2(original['y'], model_curve, sigma_classical)
            classical_reduced_chi = _compute_reduced_chi2(classical_chi2, n_classical_points, result[i].n_pars)
            objective_chi2 = float(result[i].chi2)
            objective_reduced_chi = _fit_result_reduced_chi(result[i], np.size(result[i].x))

            self._classical_fit_metrics.append({
                'classical_chi2': classical_chi2,
                'classical_reduced_chi': classical_reduced_chi,
                'objective_chi2': objective_chi2,
                'objective_reduced_chi': objective_reduced_chi,
                'n_classical_points': n_classical_points,
            })

            new_data['objective_chi2'] = objective_chi2
            new_data['objective_reduced_chi'] = objective_reduced_chi
            new_data['classical_chi2'] = classical_chi2
            new_data['classical_reduced_chi'] = classical_reduced_chi
            new_data['reduced_chi'] = objective_reduced_chi
            new_data['success'] = result[i].success
        return new_data

    def fit_single_data_set_1d(self, data: DataSet1D, objective: str | None = None) -> FitResults:
        """Perform fitting on a single 1D dataset.

        Parameters
        ----------
        data : DataSet1D
            The 1D dataset to fit. Note that ``data.ye`` stores
            variances (σ²), not standard deviations.
        objective : str | None, optional
            Per-call override for the zero-variance objective.
            If ``None``, uses the instance default set at construction. By default, None.

        Returns
        -------
        FitResults
            Fit results from the minimizer.
        """
        obj = _validate_objective(objective) if objective is not None else self._objective

        x_vals = np.asarray(data.x)
        y_vals = np.asarray(data.y)
        variances = np.asarray(data.ye)

        x_out, y_eff, weights, stats = _prepare_fit_arrays(x_vals, y_vals, variances, obj)

        if stats['masked'] > 0:
            warnings.warn(
                f'Masked {stats["masked"]} data point(s) in single-dataset fit due to zero variance during fitting.',
                UserWarning,
            )
        if stats.get('transformed_all_points'):
            warnings.warn(
                f'Applied Mighell transform to all {len(y_vals)} point(s) in single-dataset fit during fitting.',
                UserWarning,
            )
        elif stats['mighell_substituted'] > 0:
            warnings.warn(
                f'Applied Mighell substitution to {stats["mighell_substituted"]} '
                'zero-variance point(s) in single-dataset fit during fitting.',
                UserWarning,
            )

        if obj == 'legacy_mask' and len(x_out) == 0:
            raise ValueError('Cannot fit single dataset: all points have zero variance.')

        result = self.easy_science_multi_fitter.fit(x=[x_out], y=[y_eff], weights=[weights])[0]
        self._fit_results = [result]
        sigma_classical = np.sqrt(np.clip(variances, 0.0, None))
        model_curve = self._fit_func[0](x_vals)
        n_classical_points = int(np.sum(variances > 0.0))
        classical_chi2 = _compute_weighted_chi2(y_vals, model_curve, sigma_classical)
        classical_reduced_chi = _compute_reduced_chi2(classical_chi2, n_classical_points, result.n_pars)
        self._classical_fit_metrics = [
            {
                'classical_chi2': classical_chi2,
                'classical_reduced_chi': classical_reduced_chi,
                'objective_chi2': float(result.chi2),
                'objective_reduced_chi': _fit_result_reduced_chi(result, len(x_out)),
                'n_classical_points': n_classical_points,
            }
        ]
        return result

    def mcmc_sample(
        self,
        data: sc.DataGroup,
        samples: int = 10000,
        burn: int = 2000,
        thin: int = 10,
        population: int | None = None,
        objective: str | None = None,
        initializer: str | None = None,
        progress_callback: Callable[..., Any] | None = None,
        abort_test: Callable[[], bool] | None = None,
    ) -> dict:
        """Run Bayesian MCMC sampling on reflectometry data using the DREAM sampler.

        Requires that the minimizer is a BUMPS instance (i.e. the minimizer was
        switched to ``AvailableMinimizers.Bumps``).

        :param data: DataGroup with reflectivity data.
        :param samples: Number of retained DREAM samples requested from BUMPS.
        :param burn: Burn-in steps.
        :param thin: Thinning interval.
        :param population: BUMPS DREAM population count for advanced users.
        :param objective: Zero-variance handling strategy.
        :param initializer: DREAM population initializer. One of ``'eps'``,
            ``'cov'``, ``'lhs'``, or ``'random'``. By default, None (BUMPS
            uses ``'eps'``).
        :param progress_callback: Optional callback for progress updates during
            sampling.  Forwarded to the core MultiFitter.
        :return: Dictionary with keys ``'draws'``, ``'param_names'``, ``'state'``,
            and ``'logp'``.
        :raises RuntimeError: If the current minimizer is not a BUMPS instance.

        The underlying :class:`~easyscience.fitting.Sampler` is retained on
        :attr:`sampler`, so the chain can be continued without re-running the
        burn-in::

            fitter.mcmc_sample(data, samples=2000, burn=500, thin=10)
            extended = fitter.sampler.extend(additional_samples=8000, thin=10)
        """
        minimizer = self.easy_science_multi_fitter.minimizer
        if not (hasattr(minimizer, 'package') and minimizer.package == 'bumps'):
            raise RuntimeError(
                'Bayesian sampling requires a BUMPS minimizer. '
                'Use ``fitter.switch_minimizer(AvailableMinimizers.Bumps)`` first.'
            )

        obj = _validate_objective(objective) if objective is not None else self._objective

        refl_nums = [k[3:] for k in data['coords'].keys() if k.startswith('Qz_')]
        x = []
        y = []
        dy = []

        # Process each reflectivity dataset
        for i in refl_nums:
            x_vals = data['coords'][f'Qz_{i}'].values
            y_vals = data['data'][f'R_{i}'].values
            variances = data['data'][f'R_{i}'].variances

            if obj != 'mighell' and np.all(np.asarray(variances) <= 0.0):
                raise ValueError(
                    f'Cannot run Bayesian sampling on reflectivity {i}: all points have zero variance. '
                    'The likelihood is undefined without measurement uncertainties. Supply uncertainties, '
                    "or explicitly opt in to the Mighell transform with objective='mighell' "
                    '(a chi-square bias correction, not a true likelihood).'
                )

            x_out, y_eff, weights, stats = _prepare_fit_arrays(x_vals, y_vals, variances, obj)

            if stats['masked'] > 0:
                warnings.warn(
                    f'Masked {stats["masked"]} data point(s) in reflectivity {i} due to zero variance during sampling.',
                    UserWarning,
                )
            if stats.get('transformed_all_points'):
                warnings.warn(
                    f'Applied Mighell transform to all {len(y_vals)} point(s) in reflectivity {i} during sampling. '
                    'The Mighell transform is a chi-square bias correction, not a true likelihood; '
                    'posterior widths may be unreliable.',
                    UserWarning,
                )
            elif stats['mighell_substituted'] > 0:
                warnings.warn(
                    f'Applied Mighell substitution to {stats["mighell_substituted"]} '
                    f'zero-variance point(s) in reflectivity {i} during sampling. '
                    'The Mighell transform is a chi-square bias correction, not a true likelihood; '
                    'posterior widths may be unreliable.',
                    UserWarning,
                )
            x.append(x_out)
            y.append(y_eff)
            dy.append(weights)

        # Delegate the actual BUMPS/DREAM sampling to the core ``Sampler``.
        # The core API moved from ``MultiFitter.mcmc_sample()`` to a dedicated
        # ``Sampler`` class: construct it with the configured fitter and the
        # bound data, then call ``sample()``. ``Sampler`` handles the
        # multi-dataset reshaping internally.
        sampler_kwargs = {}
        if initializer is not None:
            sampler_kwargs['init'] = initializer

        sampler = Sampler(
            self.easy_science_multi_fitter,
            x=x,
            y=y,
            weights=dy,
        )
        # Retained so the chain can be continued afterwards via ``self.sampler.extend()``.
        self._sampler = sampler
        results = sampler.sample(
            samples=samples,
            burn=burn,
            thin=thin,
            population=population,
            sampler_kwargs=sampler_kwargs or None,
            progress_callback=progress_callback,
            abort_test=abort_test,
        )
        return {
            'draws': results.draws,
            'param_names': results.param_names,
            'state': results.state,
            'logp': results.logp,
        }

    @property
    def sampler(self) -> Sampler | None:
        """The ``Sampler`` behind the most recent :meth:`mcmc_sample` call, or None.

        Holds the live BUMPS chain state, so the sampling run can be continued
        with ``fitter.sampler.extend(additional_samples=...)`` instead of
        starting a fresh chain.
        """
        return self._sampler

    @property
    def chi2(self) -> float | None:
        """Total chi-squared across all fitted datasets, or None if no fit has been performed."""
        if self._fit_results is None:
            return None
        return sum(r.chi2 for r in self._fit_results)

    @property
    def reduced_chi(self) -> float | None:
        """Reduced chi-squared from the most recent fit, or None if no fit has been performed."""
        if self._fit_results is None:
            return None
        total_chi2 = sum(r.chi2 for r in self._fit_results)
        total_points = sum(np.size(r.x) for r in self._fit_results)
        n_params = self._fit_results[0].n_pars
        total_dof = total_points - n_params

        if total_dof <= 0:
            return None

        return total_chi2 / total_dof

    @property
    def classical_chi2(self) -> float | None:
        """Classical chi-squared using only points with positive variances."""
        if self._classical_fit_metrics is None:
            return None
        return float(sum(metric['classical_chi2'] for metric in self._classical_fit_metrics))

    @property
    def classical_reduced_chi(self) -> float | None:
        """Reduced classical chi-squared using only points with positive variances."""
        if self._classical_fit_metrics is None or self._fit_results is None:
            return None
        total_chi2 = self.classical_chi2
        total_points = sum(metric['n_classical_points'] for metric in self._classical_fit_metrics)
        n_params = self._fit_results[0].n_pars
        return _compute_reduced_chi2(total_chi2, total_points, n_params)

    @property
    def objective_chi2(self) -> float | None:
        """Objective-space chi-squared returned by the minimizer."""
        return self.chi2

    @property
    def objective_reduced_chi(self) -> float | None:
        """Objective-space reduced chi-squared returned by the minimizer."""
        return self.reduced_chi

    def switch_minimizer(self, minimizer: AvailableMinimizers) -> None:
        """Switch the minimizer for the fitting.

        Parameters
        ----------
        minimizer : AvailableMinimizers
            Minimizer to be switched to.
        """
        self.easy_science_multi_fitter.switch_minimizer(minimizer)

sampler property

The Sampler behind the most recent :meth:mcmc_sample call, or None.

Holds the live BUMPS chain state, so the sampling run can be continued with fitter.sampler.extend(additional_samples=...) instead of starting a fresh chain.

chi2 property

Total chi-squared across all fitted datasets, or None if no fit has been performed.

reduced_chi property

Reduced chi-squared from the most recent fit, or None if no fit has been performed.

classical_chi2 property

Classical chi-squared using only points with positive variances.

classical_reduced_chi property

Reduced classical chi-squared using only points with positive variances.

objective_chi2 property

Objective-space chi-squared returned by the minimizer.

objective_reduced_chi property

Objective-space reduced chi-squared returned by the minimizer.

__init__(*args, objective='hybrid')

A convenience class for the 🇵🇾class:easyscience.Fitting.Fitting which will populate the 🇵🇾class:sc.DataGroup appropriately after the fitting is performed.

Parameters:

Name Type Description Default
*args Model

Reflectometry model(s).

()
objective str

Zero-variance handling strategy. One of 'hybrid' (default, Mighell for zero-variance, WLS otherwise), 'mighell' (Mighell transform for all points), 'legacy_mask' (drop zero-variance points), 'auto' (alias for 'hybrid'). By default, 'hybrid'.

'hybrid'
Source code in src/easyreflectometry/fitting.py
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
def __init__(self, *args: Model, objective: str = 'hybrid'):
    r"""A convenience class for the :py:class:`easyscience.Fitting.Fitting`
    which will populate the :py:class:`sc.DataGroup` appropriately
    after the fitting is performed.

    Parameters
    ----------
    *args : Model
        Reflectometry model(s).
    objective : str, optional
        Zero-variance handling strategy. One of
        ``'hybrid'`` (default, Mighell for zero-variance, WLS otherwise),
        ``'mighell'`` (Mighell transform for all points),
        ``'legacy_mask'`` (drop zero-variance points),
        ``'auto'`` (alias for ``'hybrid'``). By default, 'hybrid'.
    """

    # This lets the unique_name be passed with the fit_func.
    def func_wrapper(func, unique_name):
        """Func wrapper."""

        def wrapped(*args, **kwargs):
            """Wrapped function."""
            return func(*args, unique_name, **kwargs)

        return wrapped

    self._fit_func = [func_wrapper(m.interface.fit_func, m.unique_name) for m in args]
    self._models = args
    self.easy_science_multi_fitter = EasyScienceMultiFitter(args, self._fit_func)
    self._fit_results: list[FitResults] | None = None
    self._classical_fit_metrics: list[dict] | None = None
    self._objective = _validate_objective(objective)
    self._sampler: Sampler | None = None

fit(data, id=0, objective=None)

Perform the fitting and populate the DataGroups with the result.

Parameters:

Name Type Description Default
data sc.DataGroup

DataGroup to be fitted to and populated.

required
id int

Unused parameter kept for backward compatibility. By default, 0.

0
objective str | None

Per-call override for the zero-variance objective. If None, uses the instance default set at construction. By default, None.

None

Returns:

Type Description
sc.DataGroup

A new DataGroup with fitted model curves, SLD profiles, and fit statistics.

Source code in src/easyreflectometry/fitting.py
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
def fit(self, data: sc.DataGroup, id: int = 0, objective: str | None = None) -> sc.DataGroup:
    """Perform the fitting and populate the DataGroups with the result.

    Parameters
    ----------
    data : sc.DataGroup
        DataGroup to be fitted to and populated.
    id : int, optional
        Unused parameter kept for backward compatibility. By default, 0.
    objective : str | None, optional
        Per-call override for the zero-variance objective.
        If ``None``, uses the instance default set at construction. By default, None.

    Returns
    -------
    sc.DataGroup
        A new DataGroup with fitted model curves, SLD profiles, and fit statistics.
    """
    obj = _validate_objective(objective) if objective is not None else self._objective

    refl_nums = [k[3:] for k in data['coords'].keys() if 'Qz' == k[:2]]
    x = []
    y = []
    dy = []
    original_arrays = []

    # Process each reflectivity dataset
    for i in refl_nums:
        x_vals = data['coords'][f'Qz_{i}'].values
        y_vals = data['data'][f'R_{i}'].values
        variances = data['data'][f'R_{i}'].variances

        x_out, y_eff, weights, stats = _prepare_fit_arrays(x_vals, y_vals, variances, obj)

        if stats['masked'] > 0:
            warnings.warn(
                f'Masked {stats["masked"]} data point(s) in reflectivity {i} due to zero variance during fitting.',
                UserWarning,
            )
        if stats.get('transformed_all_points'):
            warnings.warn(
                f'Applied Mighell transform to all {len(y_vals)} point(s) in reflectivity {i} during fitting.',
                UserWarning,
            )
        elif stats['mighell_substituted'] > 0:
            warnings.warn(
                f'Applied Mighell substitution to {stats["mighell_substituted"]} '
                f'zero-variance point(s) in reflectivity {i} during fitting.',
                UserWarning,
            )

        x.append(x_out)
        y.append(y_eff)
        dy.append(weights)
        original_arrays.append({'x': x_vals, 'y': y_vals, 'variances': variances})

    result = self.easy_science_multi_fitter.fit(x, y, weights=dy)
    self._fit_results = result
    self._classical_fit_metrics = []
    new_data = data.copy()
    for i, _ in enumerate(result):
        id = refl_nums[i]
        model_curve = self._fit_func[i](data['coords'][f'Qz_{id}'].values)
        new_data[f'R_{id}_model'] = sc.array(dims=[f'Qz_{id}'], values=model_curve)
        sld_profile = self.easy_science_multi_fitter._fit_objects[i].interface.sld_profile(self._models[i].unique_name)
        new_data[f'SLD_{id}'] = sc.array(dims=[f'z_{id}'], values=sld_profile[1] * 1e-6, unit=sc.Unit('1/angstrom') ** 2)
        if 'attrs' in new_data:
            new_data['attrs'][f'R_{id}_model'] = {'model': sc.scalar(self._models[i].as_dict())}
        new_data['coords'][f'z_{id}'] = sc.array(
            dims=[f'z_{id}'],
            values=sld_profile[0],
            unit=(1 / new_data['coords'][f'Qz_{id}'].unit).unit,
        )
        original = original_arrays[i]
        sigma_classical = np.sqrt(np.clip(original['variances'], 0.0, None))
        n_classical_points = int(np.sum(original['variances'] > 0.0))
        classical_chi2 = _compute_weighted_chi2(original['y'], model_curve, sigma_classical)
        classical_reduced_chi = _compute_reduced_chi2(classical_chi2, n_classical_points, result[i].n_pars)
        objective_chi2 = float(result[i].chi2)
        objective_reduced_chi = _fit_result_reduced_chi(result[i], np.size(result[i].x))

        self._classical_fit_metrics.append({
            'classical_chi2': classical_chi2,
            'classical_reduced_chi': classical_reduced_chi,
            'objective_chi2': objective_chi2,
            'objective_reduced_chi': objective_reduced_chi,
            'n_classical_points': n_classical_points,
        })

        new_data['objective_chi2'] = objective_chi2
        new_data['objective_reduced_chi'] = objective_reduced_chi
        new_data['classical_chi2'] = classical_chi2
        new_data['classical_reduced_chi'] = classical_reduced_chi
        new_data['reduced_chi'] = objective_reduced_chi
        new_data['success'] = result[i].success
    return new_data

fit_single_data_set_1d(data, objective=None)

Perform fitting on a single 1D dataset.

Parameters:

Name Type Description Default
data DataSet1D

The 1D dataset to fit. Note that data.ye stores variances (σ²), not standard deviations.

required
objective str | None

Per-call override for the zero-variance objective. If None, uses the instance default set at construction. By default, None.

None

Returns:

Type Description
FitResults

Fit results from the minimizer.

Source code in src/easyreflectometry/fitting.py
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
def fit_single_data_set_1d(self, data: DataSet1D, objective: str | None = None) -> FitResults:
    """Perform fitting on a single 1D dataset.

    Parameters
    ----------
    data : DataSet1D
        The 1D dataset to fit. Note that ``data.ye`` stores
        variances (σ²), not standard deviations.
    objective : str | None, optional
        Per-call override for the zero-variance objective.
        If ``None``, uses the instance default set at construction. By default, None.

    Returns
    -------
    FitResults
        Fit results from the minimizer.
    """
    obj = _validate_objective(objective) if objective is not None else self._objective

    x_vals = np.asarray(data.x)
    y_vals = np.asarray(data.y)
    variances = np.asarray(data.ye)

    x_out, y_eff, weights, stats = _prepare_fit_arrays(x_vals, y_vals, variances, obj)

    if stats['masked'] > 0:
        warnings.warn(
            f'Masked {stats["masked"]} data point(s) in single-dataset fit due to zero variance during fitting.',
            UserWarning,
        )
    if stats.get('transformed_all_points'):
        warnings.warn(
            f'Applied Mighell transform to all {len(y_vals)} point(s) in single-dataset fit during fitting.',
            UserWarning,
        )
    elif stats['mighell_substituted'] > 0:
        warnings.warn(
            f'Applied Mighell substitution to {stats["mighell_substituted"]} '
            'zero-variance point(s) in single-dataset fit during fitting.',
            UserWarning,
        )

    if obj == 'legacy_mask' and len(x_out) == 0:
        raise ValueError('Cannot fit single dataset: all points have zero variance.')

    result = self.easy_science_multi_fitter.fit(x=[x_out], y=[y_eff], weights=[weights])[0]
    self._fit_results = [result]
    sigma_classical = np.sqrt(np.clip(variances, 0.0, None))
    model_curve = self._fit_func[0](x_vals)
    n_classical_points = int(np.sum(variances > 0.0))
    classical_chi2 = _compute_weighted_chi2(y_vals, model_curve, sigma_classical)
    classical_reduced_chi = _compute_reduced_chi2(classical_chi2, n_classical_points, result.n_pars)
    self._classical_fit_metrics = [
        {
            'classical_chi2': classical_chi2,
            'classical_reduced_chi': classical_reduced_chi,
            'objective_chi2': float(result.chi2),
            'objective_reduced_chi': _fit_result_reduced_chi(result, len(x_out)),
            'n_classical_points': n_classical_points,
        }
    ]
    return result

mcmc_sample(data, samples=10000, burn=2000, thin=10, population=None, objective=None, initializer=None, progress_callback=None, abort_test=None)

Run Bayesian MCMC sampling on reflectometry data using the DREAM sampler.

Requires that the minimizer is a BUMPS instance (i.e. the minimizer was switched to AvailableMinimizers.Bumps).

:param data: DataGroup with reflectivity data. :param samples: Number of retained DREAM samples requested from BUMPS. :param burn: Burn-in steps. :param thin: Thinning interval. :param population: BUMPS DREAM population count for advanced users. :param objective: Zero-variance handling strategy. :param initializer: DREAM population initializer. One of 'eps', 'cov', 'lhs', or 'random'. By default, None (BUMPS uses 'eps'). :param progress_callback: Optional callback for progress updates during sampling. Forwarded to the core MultiFitter. :return: Dictionary with keys 'draws', 'param_names', 'state', and 'logp'. :raises RuntimeError: If the current minimizer is not a BUMPS instance.

The underlying :class:~easyscience.fitting.Sampler is retained on :attr:sampler, so the chain can be continued without re-running the burn-in::

fitter.mcmc_sample(data, samples=2000, burn=500, thin=10)
extended = fitter.sampler.extend(additional_samples=8000, thin=10)
Source code in src/easyreflectometry/fitting.py
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
def mcmc_sample(
    self,
    data: sc.DataGroup,
    samples: int = 10000,
    burn: int = 2000,
    thin: int = 10,
    population: int | None = None,
    objective: str | None = None,
    initializer: str | None = None,
    progress_callback: Callable[..., Any] | None = None,
    abort_test: Callable[[], bool] | None = None,
) -> dict:
    """Run Bayesian MCMC sampling on reflectometry data using the DREAM sampler.

    Requires that the minimizer is a BUMPS instance (i.e. the minimizer was
    switched to ``AvailableMinimizers.Bumps``).

    :param data: DataGroup with reflectivity data.
    :param samples: Number of retained DREAM samples requested from BUMPS.
    :param burn: Burn-in steps.
    :param thin: Thinning interval.
    :param population: BUMPS DREAM population count for advanced users.
    :param objective: Zero-variance handling strategy.
    :param initializer: DREAM population initializer. One of ``'eps'``,
        ``'cov'``, ``'lhs'``, or ``'random'``. By default, None (BUMPS
        uses ``'eps'``).
    :param progress_callback: Optional callback for progress updates during
        sampling.  Forwarded to the core MultiFitter.
    :return: Dictionary with keys ``'draws'``, ``'param_names'``, ``'state'``,
        and ``'logp'``.
    :raises RuntimeError: If the current minimizer is not a BUMPS instance.

    The underlying :class:`~easyscience.fitting.Sampler` is retained on
    :attr:`sampler`, so the chain can be continued without re-running the
    burn-in::

        fitter.mcmc_sample(data, samples=2000, burn=500, thin=10)
        extended = fitter.sampler.extend(additional_samples=8000, thin=10)
    """
    minimizer = self.easy_science_multi_fitter.minimizer
    if not (hasattr(minimizer, 'package') and minimizer.package == 'bumps'):
        raise RuntimeError(
            'Bayesian sampling requires a BUMPS minimizer. '
            'Use ``fitter.switch_minimizer(AvailableMinimizers.Bumps)`` first.'
        )

    obj = _validate_objective(objective) if objective is not None else self._objective

    refl_nums = [k[3:] for k in data['coords'].keys() if k.startswith('Qz_')]
    x = []
    y = []
    dy = []

    # Process each reflectivity dataset
    for i in refl_nums:
        x_vals = data['coords'][f'Qz_{i}'].values
        y_vals = data['data'][f'R_{i}'].values
        variances = data['data'][f'R_{i}'].variances

        if obj != 'mighell' and np.all(np.asarray(variances) <= 0.0):
            raise ValueError(
                f'Cannot run Bayesian sampling on reflectivity {i}: all points have zero variance. '
                'The likelihood is undefined without measurement uncertainties. Supply uncertainties, '
                "or explicitly opt in to the Mighell transform with objective='mighell' "
                '(a chi-square bias correction, not a true likelihood).'
            )

        x_out, y_eff, weights, stats = _prepare_fit_arrays(x_vals, y_vals, variances, obj)

        if stats['masked'] > 0:
            warnings.warn(
                f'Masked {stats["masked"]} data point(s) in reflectivity {i} due to zero variance during sampling.',
                UserWarning,
            )
        if stats.get('transformed_all_points'):
            warnings.warn(
                f'Applied Mighell transform to all {len(y_vals)} point(s) in reflectivity {i} during sampling. '
                'The Mighell transform is a chi-square bias correction, not a true likelihood; '
                'posterior widths may be unreliable.',
                UserWarning,
            )
        elif stats['mighell_substituted'] > 0:
            warnings.warn(
                f'Applied Mighell substitution to {stats["mighell_substituted"]} '
                f'zero-variance point(s) in reflectivity {i} during sampling. '
                'The Mighell transform is a chi-square bias correction, not a true likelihood; '
                'posterior widths may be unreliable.',
                UserWarning,
            )
        x.append(x_out)
        y.append(y_eff)
        dy.append(weights)

    # Delegate the actual BUMPS/DREAM sampling to the core ``Sampler``.
    # The core API moved from ``MultiFitter.mcmc_sample()`` to a dedicated
    # ``Sampler`` class: construct it with the configured fitter and the
    # bound data, then call ``sample()``. ``Sampler`` handles the
    # multi-dataset reshaping internally.
    sampler_kwargs = {}
    if initializer is not None:
        sampler_kwargs['init'] = initializer

    sampler = Sampler(
        self.easy_science_multi_fitter,
        x=x,
        y=y,
        weights=dy,
    )
    # Retained so the chain can be continued afterwards via ``self.sampler.extend()``.
    self._sampler = sampler
    results = sampler.sample(
        samples=samples,
        burn=burn,
        thin=thin,
        population=population,
        sampler_kwargs=sampler_kwargs or None,
        progress_callback=progress_callback,
        abort_test=abort_test,
    )
    return {
        'draws': results.draws,
        'param_names': results.param_names,
        'state': results.state,
        'logp': results.logp,
    }

switch_minimizer(minimizer)

Switch the minimizer for the fitting.

Parameters:

Name Type Description Default
minimizer AvailableMinimizers

Minimizer to be switched to.

required
Source code in src/easyreflectometry/fitting.py
545
546
547
548
549
550
551
552
553
def switch_minimizer(self, minimizer: AvailableMinimizers) -> None:
    """Switch the minimizer for the fitting.

    Parameters
    ----------
    minimizer : AvailableMinimizers
        Minimizer to be switched to.
    """
    self.easy_science_multi_fitter.switch_minimizer(minimizer)

Model

Bases: BaseCore

Model is the class that represents the experiment.

It is used to store the information about the experiment and to perform the calculations.

Source code in src/easyreflectometry/model/model.py
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
class Model(BaseCore):
    """Model is the class that represents the experiment.

    It is used to store the information about the experiment and to perform the calculations.
    """

    def __init__(
        self,
        sample: Union[Sample, None] = None,
        scale: Union[Parameter, Number, None] = None,
        background: Union[Parameter, Number, None] = None,
        resolution_function: Union[ResolutionFunction, None] = None,
        name: str = 'Model',
        color: str = COLORS[0],
        unique_name: Optional[str] = None,
        interface=None,
    ):
        """Constructor.

        Parameters
        ----------
        unique_name : Optional[str], optional
            By default, None.
        color : str, optional
            By default, COLORS[0].
        sample : Union[Sample, None], optional
            The sample being modelled. By default, None.
        scale : Union[Parameter, Number, None], optional
            Scaling factor of profile. By default, None.
        background : Union[Parameter, Number, None], optional
            Linear background magnitude. By default, None.
        name : str, optional
            Name of the model. By default, 'Model'.
        resolution_function : Union[ResolutionFunction, None], optional
            Resolution function. By default, None.
        interface :
            Calculator interface. By default, None.
        """
        if unique_name is None:
            unique_name = global_object.generate_unique_name(self.__class__.__name__)

        if sample is None:
            sample = Sample(interface=interface)
        if resolution_function is None:
            resolution_function = PercentageFwhm(DEFAULTS['resolution']['value'])

        scale = get_as_parameter('scale', scale, DEFAULTS)
        apply_default_limits(scale, 'scale')
        background = get_as_parameter('background', background, DEFAULTS)
        self.color = color
        self._is_default = False
        self._resolution_function = resolution_function

        super().__init__(name=name, unique_name=unique_name)
        self._sample = sample
        self._scale = scale
        self._background = background

        # Set interface last — propagates to children via BaseCore.generate_bindings
        # and then sets the resolution function on the calculator (see setter).
        if interface is not None:
            self.interface = interface

    # ----- @property accessors for serialization round-trip -----

    @property
    def sample(self) -> Sample:
        return self._sample

    @sample.setter
    def sample(self, value: Sample) -> None:
        self._sample = value

    @property
    def scale(self) -> Parameter:
        return self._scale

    @scale.setter
    def scale(self, value: float) -> None:
        self._scale.value = value

    @property
    def background(self) -> Parameter:
        return self._background

    @background.setter
    def background(self, value: float) -> None:
        self._background.value = value

    # ----- assembly management -----

    def add_assemblies(self, *assemblies: list[BaseAssembly]) -> None:
        """Add assemblies to the model sample.

        Parameters
        ----------
        *assemblies : list[BaseAssembly]
            Assemblies to add to model sample.
        """
        if not assemblies:
            self.sample.add_assembly()
            if self.interface is not None:
                self.interface().add_item_to_model(self.sample[-1].unique_name, self.unique_name)
        else:
            for assembly in assemblies:
                if issubclass(assembly.__class__, BaseAssembly):
                    self.sample.add_assembly(assembly)
                    if self.interface is not None:
                        self.interface().add_item_to_model(self.sample[-1].unique_name, self.unique_name)
                else:
                    raise ValueError(f'Object {assembly} is not a valid type, must be a child of BaseAssembly.')

    def duplicate_assembly(self, index: int) -> None:
        """Duplicate a given item or layer in a sample.

        Parameters
        ----------
        index : int
        idx :
            Index of the item or layer to duplicate.
        """
        self.sample.duplicate_assembly(index)
        if self.interface is not None:
            self.interface().add_item_to_model(self.sample[-1].unique_name, self.unique_name)

    def remove_assembly(self, index: int) -> None:
        """Remove an assembly from the model.

        Parameters
        ----------
        index : int
        idx :
            Index of the item to remove.
        """
        assembly_unique_name = self.sample[index].unique_name
        self.sample.remove_assembly(index)
        if self.interface is not None:
            self.interface().remove_item_from_model(assembly_unique_name, self.unique_name)

    @property
    def is_default(self) -> bool:
        """Whether this model was created as a default placeholder."""
        return self._is_default

    @is_default.setter
    def is_default(self, value: bool) -> None:
        """Set whether this model is a default placeholder."""
        self._is_default = value

    # ----- resolution function -----

    @property
    def resolution_function(self) -> ResolutionFunction:
        """Return the resolution function."""
        return self._resolution_function

    @resolution_function.setter
    def resolution_function(self, resolution_function: ResolutionFunction) -> None:
        """Set the resolution function for the model."""
        self._resolution_function = resolution_function
        if self.interface is not None:
            self.interface().set_resolution_function(self._resolution_function)

    # ----- interface (override BaseCore's to add resolution-function side effect) -----

    @BaseCore.interface.setter
    def interface(self, new_interface) -> None:
        """Set the interface; runs `generate_bindings` and then refreshes the
        calculator's resolution function.
        """
        # Call BaseCore.interface.setter for the binding propagation.
        BaseCore.interface.fset(self, new_interface)
        if new_interface is not None:
            new_interface().set_resolution_function(self._resolution_function)

    # ----- representation -----

    @property
    def _dict_repr(self) -> dict[str, dict[str, str]]:
        """A simplified dict representation."""
        if isinstance(self._resolution_function, PercentageFwhm):
            resolution_value = self._resolution_function.as_dict()['constant']
            resolution = f'{resolution_value} %'
        else:
            resolution = 'function of Q'

        return {
            self.name: {
                'scale': float(self.scale.value),
                'background': float(self.background.value),
                'resolution': resolution,
                'color': self.color,
                'sample': self.sample._dict_repr,
            }
        }

    # ----- serialization (custom because resolution_function + interface need special handling) -----

    def to_dict(self, skip: Optional[list[str]] = None) -> dict:
        """Serialize the model, encoding the resolution function and interface name."""
        if skip is None:
            skip = []
        # Sample/resolution_function/interface get bespoke encoding below.
        skip_for_super = list(skip) + ['sample', 'resolution_function', 'interface']
        this_dict = super().to_dict(skip=skip_for_super)
        this_dict['sample'] = self.sample.as_dict(skip=skip)
        this_dict['resolution_function'] = self.resolution_function.as_dict(skip=skip)
        if self.interface is None:
            this_dict['interface'] = None
        else:
            this_dict['interface'] = self.interface().name
        return this_dict

    def as_dict(self, skip: Optional[list[str]] = None) -> dict:
        """Compatibility alias for :meth:`to_dict`."""
        return self.to_dict(skip=skip)

    def as_orso(self) -> dict:
        """Convert the model to a dictionary suitable for ORSO."""
        return self.as_dict()

    @classmethod
    def from_dict(cls, passed_dict: dict) -> Model:
        """Create a Model from a dictionary."""
        # Circular import if hoisted to module-top.
        from easyreflectometry.calculators import CalculatorFactory

        this_dict = copy.deepcopy(passed_dict)
        resolution_function = ResolutionFunction.from_dict(this_dict.pop('resolution_function'))
        interface_name = this_dict.pop('interface')
        if interface_name is not None:
            interface = CalculatorFactory()
            interface.switch(interface_name)
        else:
            interface = None

        model = super().from_dict(this_dict)

        model.resolution_function = resolution_function
        model.interface = interface
        return model

is_default property writable

Whether this model was created as a default placeholder.

resolution_function property writable

Return the resolution function.

__init__(sample=None, scale=None, background=None, resolution_function=None, name='Model', color=COLORS[0], unique_name=None, interface=None)

Constructor.

Parameters:

Name Type Description Default
unique_name Optional[str]

By default, None.

None
color str

By default, COLORS[0].

COLORS[0]
sample Union[Sample, None]

The sample being modelled. By default, None.

None
scale Union[Parameter, Number, None]

Scaling factor of profile. By default, None.

None
background Union[Parameter, Number, None]

Linear background magnitude. By default, None.

None
name str

Name of the model. By default, 'Model'.

'Model'
resolution_function Union[ResolutionFunction, None]

Resolution function. By default, None.

None
interface

Calculator interface. By default, None.

None
Source code in src/easyreflectometry/model/model.py
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
def __init__(
    self,
    sample: Union[Sample, None] = None,
    scale: Union[Parameter, Number, None] = None,
    background: Union[Parameter, Number, None] = None,
    resolution_function: Union[ResolutionFunction, None] = None,
    name: str = 'Model',
    color: str = COLORS[0],
    unique_name: Optional[str] = None,
    interface=None,
):
    """Constructor.

    Parameters
    ----------
    unique_name : Optional[str], optional
        By default, None.
    color : str, optional
        By default, COLORS[0].
    sample : Union[Sample, None], optional
        The sample being modelled. By default, None.
    scale : Union[Parameter, Number, None], optional
        Scaling factor of profile. By default, None.
    background : Union[Parameter, Number, None], optional
        Linear background magnitude. By default, None.
    name : str, optional
        Name of the model. By default, 'Model'.
    resolution_function : Union[ResolutionFunction, None], optional
        Resolution function. By default, None.
    interface :
        Calculator interface. By default, None.
    """
    if unique_name is None:
        unique_name = global_object.generate_unique_name(self.__class__.__name__)

    if sample is None:
        sample = Sample(interface=interface)
    if resolution_function is None:
        resolution_function = PercentageFwhm(DEFAULTS['resolution']['value'])

    scale = get_as_parameter('scale', scale, DEFAULTS)
    apply_default_limits(scale, 'scale')
    background = get_as_parameter('background', background, DEFAULTS)
    self.color = color
    self._is_default = False
    self._resolution_function = resolution_function

    super().__init__(name=name, unique_name=unique_name)
    self._sample = sample
    self._scale = scale
    self._background = background

    # Set interface last — propagates to children via BaseCore.generate_bindings
    # and then sets the resolution function on the calculator (see setter).
    if interface is not None:
        self.interface = interface

interface(new_interface)

Set the interface; runs generate_bindings and then refreshes the calculator's resolution function.

Source code in src/easyreflectometry/model/model.py
225
226
227
228
229
230
231
232
233
@BaseCore.interface.setter
def interface(self, new_interface) -> None:
    """Set the interface; runs `generate_bindings` and then refreshes the
    calculator's resolution function.
    """
    # Call BaseCore.interface.setter for the binding propagation.
    BaseCore.interface.fset(self, new_interface)
    if new_interface is not None:
        new_interface().set_resolution_function(self._resolution_function)

add_assemblies(*assemblies)

Add assemblies to the model sample.

Parameters:

Name Type Description Default
*assemblies list[BaseAssembly]

Assemblies to add to model sample.

()
Source code in src/easyreflectometry/model/model.py
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
def add_assemblies(self, *assemblies: list[BaseAssembly]) -> None:
    """Add assemblies to the model sample.

    Parameters
    ----------
    *assemblies : list[BaseAssembly]
        Assemblies to add to model sample.
    """
    if not assemblies:
        self.sample.add_assembly()
        if self.interface is not None:
            self.interface().add_item_to_model(self.sample[-1].unique_name, self.unique_name)
    else:
        for assembly in assemblies:
            if issubclass(assembly.__class__, BaseAssembly):
                self.sample.add_assembly(assembly)
                if self.interface is not None:
                    self.interface().add_item_to_model(self.sample[-1].unique_name, self.unique_name)
            else:
                raise ValueError(f'Object {assembly} is not a valid type, must be a child of BaseAssembly.')

duplicate_assembly(index)

Duplicate a given item or layer in a sample.

Parameters:

Name Type Description Default
index int
required
idx

Index of the item or layer to duplicate.

required
Source code in src/easyreflectometry/model/model.py
172
173
174
175
176
177
178
179
180
181
182
183
def duplicate_assembly(self, index: int) -> None:
    """Duplicate a given item or layer in a sample.

    Parameters
    ----------
    index : int
    idx :
        Index of the item or layer to duplicate.
    """
    self.sample.duplicate_assembly(index)
    if self.interface is not None:
        self.interface().add_item_to_model(self.sample[-1].unique_name, self.unique_name)

remove_assembly(index)

Remove an assembly from the model.

Parameters:

Name Type Description Default
index int
required
idx

Index of the item to remove.

required
Source code in src/easyreflectometry/model/model.py
185
186
187
188
189
190
191
192
193
194
195
196
197
def remove_assembly(self, index: int) -> None:
    """Remove an assembly from the model.

    Parameters
    ----------
    index : int
    idx :
        Index of the item to remove.
    """
    assembly_unique_name = self.sample[index].unique_name
    self.sample.remove_assembly(index)
    if self.interface is not None:
        self.interface().remove_item_from_model(assembly_unique_name, self.unique_name)

to_dict(skip=None)

Serialize the model, encoding the resolution function and interface name.

Source code in src/easyreflectometry/model/model.py
258
259
260
261
262
263
264
265
266
267
268
269
270
271
def to_dict(self, skip: Optional[list[str]] = None) -> dict:
    """Serialize the model, encoding the resolution function and interface name."""
    if skip is None:
        skip = []
    # Sample/resolution_function/interface get bespoke encoding below.
    skip_for_super = list(skip) + ['sample', 'resolution_function', 'interface']
    this_dict = super().to_dict(skip=skip_for_super)
    this_dict['sample'] = self.sample.as_dict(skip=skip)
    this_dict['resolution_function'] = self.resolution_function.as_dict(skip=skip)
    if self.interface is None:
        this_dict['interface'] = None
    else:
        this_dict['interface'] = self.interface().name
    return this_dict

as_dict(skip=None)

Compatibility alias for :meth:to_dict.

Source code in src/easyreflectometry/model/model.py
273
274
275
def as_dict(self, skip: Optional[list[str]] = None) -> dict:
    """Compatibility alias for :meth:`to_dict`."""
    return self.to_dict(skip=skip)

as_orso()

Convert the model to a dictionary suitable for ORSO.

Source code in src/easyreflectometry/model/model.py
277
278
279
def as_orso(self) -> dict:
    """Convert the model to a dictionary suitable for ORSO."""
    return self.as_dict()

from_dict(passed_dict) classmethod

Create a Model from a dictionary.

Source code in src/easyreflectometry/model/model.py
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
@classmethod
def from_dict(cls, passed_dict: dict) -> Model:
    """Create a Model from a dictionary."""
    # Circular import if hoisted to module-top.
    from easyreflectometry.calculators import CalculatorFactory

    this_dict = copy.deepcopy(passed_dict)
    resolution_function = ResolutionFunction.from_dict(this_dict.pop('resolution_function'))
    interface_name = this_dict.pop('interface')
    if interface_name is not None:
        interface = CalculatorFactory()
        interface.switch(interface_name)
    else:
        interface = None

    model = super().from_dict(this_dict)

    model.resolution_function = resolution_function
    model.interface = interface
    return model

ModelCollection

Bases: BaseCollection

Source code in src/easyreflectometry/model/model_collection.py
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
class ModelCollection(BaseCollection):
    def __init__(
        self,
        *models: Tuple[Model],
        name: str = 'Models',
        interface=None,
        unique_name: Optional[str] = None,
        populate_if_none: bool = True,
        next_color_index: Optional[int] = None,
        **kwargs,
    ):
        """Init function."""
        if not models:
            if populate_if_none:
                models = DEFAULT_ELEMENTS(interface)
            else:
                models = []

        # `_next_color_index` must exist before super().__init__ because each
        # `append` during construction routes through `_append_internal` →
        # `_advance_color_index`, which reads the attribute.
        self._next_color_index = next_color_index

        super().__init__(
            name,
            interface,
            *models,
            unique_name=unique_name,
            populate_if_none=False,
            **kwargs,
        )

        color_count = len(COLORS)
        if color_count == 0:
            self._next_color_index = 0
        elif next_color_index is None:
            self._next_color_index = len(self) % color_count
        else:
            self._next_color_index = next_color_index % color_count

    @property
    def next_color_index(self) -> Optional[int]:
        """Index of the next colour to assign — kept around so it round-trips."""
        return self._next_color_index

    def add_model(self, model: Optional[Model] = None):
        """Add a model to the collection.

        Parameters
        ----------
        model : Optional[Model], optional
            Model to add. By default, None.
        """
        if model is None:
            model = Model(name='Model', interface=self.interface, color=self._current_color())
        self.append(model)

    def duplicate_model(self, index: int):
        """Duplicate a model in the collection.

        Parameters
        ----------
        index : int
            Model to duplicate.
        """
        to_be_duplicated = self[index]
        duplicate = Model.from_dict(to_be_duplicated.as_dict(skip=['unique_name']))
        duplicate.name = duplicate.name + ' duplicate'
        self.append(duplicate)

    @classmethod
    def from_dict(cls, this_dict: dict) -> ModelCollection:
        """Create an instance of a collection from a dictionary."""
        collection_dict = dict(this_dict)
        dict_data = collection_dict.pop('data', [])
        next_color_index = collection_dict.pop('next_color_index', None)

        # Reconstruct empty collection via EasyList.from_dict (handles
        # protected_types and assigns name/unique_name/populate_if_none).
        collection = super().from_dict(collection_dict)

        # Append each model without advancing the colour index — the saved
        # `next_color_index` below is the source of truth.
        for model_data in dict_data:
            collection._append_internal(Model.from_dict(model_data), advance=False)

        if len(collection) != len(dict_data):
            raise ValueError(f'Expected {len(dict_data)} models, got {len(collection)}')

        color_count = len(COLORS)
        if color_count == 0:
            collection._next_color_index = 0
        elif next_color_index is None:
            collection._next_color_index = len(collection) % color_count
        else:
            collection._next_color_index = next_color_index % color_count

        return collection

    def append(self, model: Model) -> None:  # type: ignore[override]
        """Append function."""
        self._append_internal(model, advance=True)

    def _append_internal(self, model: Model, advance: bool) -> None:
        """Append internal."""
        # Bypass our own `append` override and go straight to EasyList's
        # `MutableSequence.append` → `insert` path. Calling `super().append`
        # would dispatch back to `ModelCollection.append` because Python
        # resolves `append` via MRO from MutableSequence which doesn't
        # define it on a class higher than ModelCollection.
        from collections.abc import MutableSequence

        MutableSequence.append(self, model)
        if advance:
            self._advance_color_index()

    def _advance_color_index(self) -> None:
        """Advance color index."""
        if not COLORS:
            self._next_color_index = 0
            return
        if self._next_color_index is None:
            self._next_color_index = len(self) % len(COLORS)
            return
        self._next_color_index = (self._next_color_index + 1) % len(COLORS)

    def _current_color(self) -> str:
        """Current color."""
        if not COLORS:
            raise ValueError('No colors defined for models.')
        if self._next_color_index is None:
            self._next_color_index = 0
        return COLORS[self._next_color_index]

next_color_index property

Index of the next colour to assign — kept around so it round-trips.

__init__(*models, name='Models', interface=None, unique_name=None, populate_if_none=True, next_color_index=None, **kwargs)

Init function.

Source code in src/easyreflectometry/model/model_collection.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
def __init__(
    self,
    *models: Tuple[Model],
    name: str = 'Models',
    interface=None,
    unique_name: Optional[str] = None,
    populate_if_none: bool = True,
    next_color_index: Optional[int] = None,
    **kwargs,
):
    """Init function."""
    if not models:
        if populate_if_none:
            models = DEFAULT_ELEMENTS(interface)
        else:
            models = []

    # `_next_color_index` must exist before super().__init__ because each
    # `append` during construction routes through `_append_internal` →
    # `_advance_color_index`, which reads the attribute.
    self._next_color_index = next_color_index

    super().__init__(
        name,
        interface,
        *models,
        unique_name=unique_name,
        populate_if_none=False,
        **kwargs,
    )

    color_count = len(COLORS)
    if color_count == 0:
        self._next_color_index = 0
    elif next_color_index is None:
        self._next_color_index = len(self) % color_count
    else:
        self._next_color_index = next_color_index % color_count

add_model(model=None)

Add a model to the collection.

Parameters:

Name Type Description Default
model Optional[Model]

Model to add. By default, None.

None
Source code in src/easyreflectometry/model/model_collection.py
66
67
68
69
70
71
72
73
74
75
76
def add_model(self, model: Optional[Model] = None):
    """Add a model to the collection.

    Parameters
    ----------
    model : Optional[Model], optional
        Model to add. By default, None.
    """
    if model is None:
        model = Model(name='Model', interface=self.interface, color=self._current_color())
    self.append(model)

duplicate_model(index)

Duplicate a model in the collection.

Parameters:

Name Type Description Default
index int

Model to duplicate.

required
Source code in src/easyreflectometry/model/model_collection.py
78
79
80
81
82
83
84
85
86
87
88
89
def duplicate_model(self, index: int):
    """Duplicate a model in the collection.

    Parameters
    ----------
    index : int
        Model to duplicate.
    """
    to_be_duplicated = self[index]
    duplicate = Model.from_dict(to_be_duplicated.as_dict(skip=['unique_name']))
    duplicate.name = duplicate.name + ' duplicate'
    self.append(duplicate)

from_dict(this_dict) classmethod

Create an instance of a collection from a dictionary.

Source code in src/easyreflectometry/model/model_collection.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
@classmethod
def from_dict(cls, this_dict: dict) -> ModelCollection:
    """Create an instance of a collection from a dictionary."""
    collection_dict = dict(this_dict)
    dict_data = collection_dict.pop('data', [])
    next_color_index = collection_dict.pop('next_color_index', None)

    # Reconstruct empty collection via EasyList.from_dict (handles
    # protected_types and assigns name/unique_name/populate_if_none).
    collection = super().from_dict(collection_dict)

    # Append each model without advancing the colour index — the saved
    # `next_color_index` below is the source of truth.
    for model_data in dict_data:
        collection._append_internal(Model.from_dict(model_data), advance=False)

    if len(collection) != len(dict_data):
        raise ValueError(f'Expected {len(dict_data)} models, got {len(collection)}')

    color_count = len(COLORS)
    if color_count == 0:
        collection._next_color_index = 0
    elif next_color_index is None:
        collection._next_color_index = len(collection) % color_count
    else:
        collection._next_color_index = next_color_index % color_count

    return collection

append(model)

Append function.

Source code in src/easyreflectometry/model/model_collection.py
120
121
122
def append(self, model: Model) -> None:  # type: ignore[override]
    """Append function."""
    self._append_internal(model, advance=True)

PercentageFwhm

Bases: ResolutionFunction

Source code in src/easyreflectometry/model/resolution_functions.py
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
class PercentageFwhm(ResolutionFunction):
    def __init__(self, constant: Union[None, float] = None):
        """Init function."""
        if constant is None:
            constant = DEFAULT_RESOLUTION_FWHM_PERCENTAGE
        self.constant = constant

    def smearing(self, q: Union[np.array, float]) -> np.array:
        """Return per-point sigma values from the constant FWHM percentage.

        ``constant`` is a FWHM percentage of ``q``; it is converted to an
        absolute sigma so the smearing() contract is sigma for all types.
        """
        q_array = np.asarray(q, dtype=float)
        fwhm = (self.constant / 100.0) * q_array
        return fwhm / SIGMA_TO_FWHM

    def as_dict(
        self, skip: Optional[List[str]] = None
    ) -> dict[str, str]:  # skip is kept for consistency of the as_dict signature
        """As dict."""
        return {'smearing': 'PercentageFwhm', 'constant': self.constant}

__init__(constant=None)

Init function.

Source code in src/easyreflectometry/model/resolution_functions.py
60
61
62
63
64
def __init__(self, constant: Union[None, float] = None):
    """Init function."""
    if constant is None:
        constant = DEFAULT_RESOLUTION_FWHM_PERCENTAGE
    self.constant = constant

smearing(q)

Return per-point sigma values from the constant FWHM percentage.

constant is a FWHM percentage of q; it is converted to an absolute sigma so the smearing() contract is sigma for all types.

Source code in src/easyreflectometry/model/resolution_functions.py
66
67
68
69
70
71
72
73
74
def smearing(self, q: Union[np.array, float]) -> np.array:
    """Return per-point sigma values from the constant FWHM percentage.

    ``constant`` is a FWHM percentage of ``q``; it is converted to an
    absolute sigma so the smearing() contract is sigma for all types.
    """
    q_array = np.asarray(q, dtype=float)
    fwhm = (self.constant / 100.0) * q_array
    return fwhm / SIGMA_TO_FWHM

as_dict(skip=None)

As dict.

Source code in src/easyreflectometry/model/resolution_functions.py
76
77
78
79
80
def as_dict(
    self, skip: Optional[List[str]] = None
) -> dict[str, str]:  # skip is kept for consistency of the as_dict signature
    """As dict."""
    return {'smearing': 'PercentageFwhm', 'constant': self.constant}

Pointwise

Bases: ResolutionFunction

Pointwise resolution defined by a per-point resolution provided with the data.

The resolution is supplied as the variance of the Qz values (sQz) at the measured Qz data points, which is the form produced by data reduction (e.g. Qz_0.variances). The resolution width at each point is sqrt(sQz). For a requested q the width is obtained by linearly interpolating onto q, exactly as :class:LinearSpline does for explicitly provided widths.

This is a convenience wrapper around :class:LinearSpline that derives the widths from the [Qz, R, sQz] triple loaded from a data file; the returned widths are consumed by the calculators (refnx x_err / refl1d dq), which perform the actual convolution against the model.

Source code in src/easyreflectometry/model/resolution_functions.py
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
class Pointwise(ResolutionFunction):
    """Pointwise resolution defined by a per-point resolution provided with the data.

    The resolution is supplied as the variance of the Qz values (``sQz``) at the
    measured Qz data points, which is the form produced by data reduction (e.g.
    ``Qz_0.variances``).  The resolution width at each point is ``sqrt(sQz)``.
    For a requested ``q`` the width is obtained by linearly interpolating onto
    ``q``, exactly as :class:`LinearSpline` does for explicitly provided widths.

    This is a convenience wrapper around :class:`LinearSpline` that derives the
    widths from the ``[Qz, R, sQz]`` triple loaded from a data file; the returned
    widths are consumed by the calculators (refnx ``x_err`` / refl1d ``dq``),
    which perform the actual convolution against the model.
    """

    def __init__(self, q_data_points: List[np.ndarray]):
        """Init function.

        Parameters
        ----------
        q_data_points : List[np.ndarray]
            ``[Qz, R, sQz]`` where ``Qz`` are the measured Qz values, ``R`` the
            measured reflectivity (kept only for serialization round-trips) and
            ``sQz`` the variance of ``Qz`` at each point.
        """
        self.q_data_points = q_data_points

    def smearing(self, q: Optional[Union[np.ndarray, float]] = None) -> np.ndarray:
        """Return the resolution sigma interpolated onto ``q``.

        ``sQz`` is the variance of ``Qz``, so the sigma at each data point is
        ``sqrt(sQz)``; values are linearly interpolated onto the requested
        ``q``.  This already satisfies the sigma smearing() contract, so no
        FWHM conversion is applied.  When ``q`` is ``None`` the sigma values
        are returned at the stored data points.
        """
        Qz = np.asarray(self.q_data_points[0], dtype=float)
        sQz = np.asarray(self.q_data_points[2], dtype=float)
        q_eval = Qz if q is None else np.asarray(q, dtype=float)
        widths = np.sqrt(sQz)
        return np.asarray(np.interp(q_eval, Qz, widths))

    def as_dict(
        self, skip: Optional[List[str]] = None
    ) -> dict[str, str]:  # skip is kept for consistency of the as_dict signature
        """As dict."""
        return {
            'smearing': 'Pointwise',
            'q_data_points': list(self.q_data_points[0]),
            'R_data_points': list(self.q_data_points[1]),
            'sQz_data_points': list(self.q_data_points[2]),
        }

__init__(q_data_points)

Init function.

Parameters:

Name Type Description Default
q_data_points List[np.ndarray]

[Qz, R, sQz] where Qz are the measured Qz values, R the measured reflectivity (kept only for serialization round-trips) and sQz the variance of Qz at each point.

required
Source code in src/easyreflectometry/model/resolution_functions.py
124
125
126
127
128
129
130
131
132
133
134
def __init__(self, q_data_points: List[np.ndarray]):
    """Init function.

    Parameters
    ----------
    q_data_points : List[np.ndarray]
        ``[Qz, R, sQz]`` where ``Qz`` are the measured Qz values, ``R`` the
        measured reflectivity (kept only for serialization round-trips) and
        ``sQz`` the variance of ``Qz`` at each point.
    """
    self.q_data_points = q_data_points

smearing(q=None)

Return the resolution sigma interpolated onto q.

sQz is the variance of Qz, so the sigma at each data point is sqrt(sQz); values are linearly interpolated onto the requested q. This already satisfies the sigma smearing() contract, so no FWHM conversion is applied. When q is None the sigma values are returned at the stored data points.

Source code in src/easyreflectometry/model/resolution_functions.py
136
137
138
139
140
141
142
143
144
145
146
147
148
149
def smearing(self, q: Optional[Union[np.ndarray, float]] = None) -> np.ndarray:
    """Return the resolution sigma interpolated onto ``q``.

    ``sQz`` is the variance of ``Qz``, so the sigma at each data point is
    ``sqrt(sQz)``; values are linearly interpolated onto the requested
    ``q``.  This already satisfies the sigma smearing() contract, so no
    FWHM conversion is applied.  When ``q`` is ``None`` the sigma values
    are returned at the stored data points.
    """
    Qz = np.asarray(self.q_data_points[0], dtype=float)
    sQz = np.asarray(self.q_data_points[2], dtype=float)
    q_eval = Qz if q is None else np.asarray(q, dtype=float)
    widths = np.sqrt(sQz)
    return np.asarray(np.interp(q_eval, Qz, widths))

as_dict(skip=None)

As dict.

Source code in src/easyreflectometry/model/resolution_functions.py
151
152
153
154
155
156
157
158
159
160
def as_dict(
    self, skip: Optional[List[str]] = None
) -> dict[str, str]:  # skip is kept for consistency of the as_dict signature
    """As dict."""
    return {
        'smearing': 'Pointwise',
        'q_data_points': list(self.q_data_points[0]),
        'R_data_points': list(self.q_data_points[1]),
        'sQz_data_points': list(self.q_data_points[2]),
    }

Layer

Bases: BaseCore

Source code in src/easyreflectometry/sample/elements/layers/layer.py
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
class Layer(BaseCore):
    def __init__(
        self,
        material: Union[Material, None] = None,
        thickness: Union[Parameter, float, None] = None,
        roughness: Union[Parameter, float, None] = None,
        name: str = 'EasyLayer',
        unique_name: Optional[str] = None,
        interface=None,
    ):
        """Constructor.

        Parameters
        ----------
        unique_name : Optional[str], optional
            By default, None.
        material : Union[Material, None], optional
            The material for the layer. By default, None.
        thickness : Union[Parameter, float, None], optional
            Layer thickness in Angstrom. By default, None.
        roughness : Union[Parameter, float, None], optional
            Upper roughness on the layer in Angstrom. By default, None.
        name : str, optional
            Name of the layer. By default, 'EasyLayer'.
        interface :
            Interface object. By default, None.
        """
        if material is None:
            material = Material(interface=interface)

        if unique_name is None:
            unique_name = global_object.generate_unique_name(self.__class__.__name__)

        thickness_value = thickness
        thickness = get_as_parameter(
            name='thickness',
            value=thickness,
            default_dict=DEFAULTS,
            unique_name_prefix=f'{unique_name}_Thickness',
        )
        thickness.default_limits_pending = not isinstance(thickness_value, Parameter)

        roughness_value = roughness
        roughness = get_as_parameter(
            name='roughness',
            value=roughness,
            default_dict=DEFAULTS,
            unique_name_prefix=f'{unique_name}_Roughness',
        )
        roughness.default_limits_pending = not isinstance(roughness_value, Parameter)

        super().__init__(name=name, unique_name=unique_name)
        self._material = material
        self._thickness = thickness
        self._roughness = roughness

        if interface is not None:
            self.interface = interface

    @property
    def material(self) -> Material:
        return self._material

    @material.setter
    def material(self, value: Material) -> None:
        self._material = value

    @property
    def thickness(self) -> Parameter:
        return self._thickness

    @thickness.setter
    def thickness(self, value: float) -> None:
        self._thickness.value = value

    @property
    def roughness(self) -> Parameter:
        return self._roughness

    @roughness.setter
    def roughness(self, value: float) -> None:
        self._roughness.value = value

    def assign_material(self, material: Material) -> None:
        """Assign a material to the layer interface.

        Parameters
        ----------
        material : Material
            The material to assign to the layer.
        """
        self._material = material
        if self.interface is not None:
            self.interface().assign_material_to_layer(self.material.unique_name, self.unique_name)

    # Representation
    @property
    def _dict_repr(self) -> dict[str, str]:
        """A simplified dict representation."""
        return {
            self.name: {
                'material': self.material._dict_repr,
                'thickness': f'{self.thickness.value:.3f} {self.thickness.unit}',
                'roughness': f'{self.roughness.value:.3f} {self.roughness.unit}',
            }
        }

__init__(material=None, thickness=None, roughness=None, name='EasyLayer', unique_name=None, interface=None)

Constructor.

Parameters:

Name Type Description Default
unique_name Optional[str]

By default, None.

None
material Union[Material, None]

The material for the layer. By default, None.

None
thickness Union[Parameter, float, None]

Layer thickness in Angstrom. By default, None.

None
roughness Union[Parameter, float, None]

Upper roughness on the layer in Angstrom. By default, None.

None
name str

Name of the layer. By default, 'EasyLayer'.

'EasyLayer'
interface

Interface object. By default, None.

None
Source code in src/easyreflectometry/sample/elements/layers/layer.py
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
def __init__(
    self,
    material: Union[Material, None] = None,
    thickness: Union[Parameter, float, None] = None,
    roughness: Union[Parameter, float, None] = None,
    name: str = 'EasyLayer',
    unique_name: Optional[str] = None,
    interface=None,
):
    """Constructor.

    Parameters
    ----------
    unique_name : Optional[str], optional
        By default, None.
    material : Union[Material, None], optional
        The material for the layer. By default, None.
    thickness : Union[Parameter, float, None], optional
        Layer thickness in Angstrom. By default, None.
    roughness : Union[Parameter, float, None], optional
        Upper roughness on the layer in Angstrom. By default, None.
    name : str, optional
        Name of the layer. By default, 'EasyLayer'.
    interface :
        Interface object. By default, None.
    """
    if material is None:
        material = Material(interface=interface)

    if unique_name is None:
        unique_name = global_object.generate_unique_name(self.__class__.__name__)

    thickness_value = thickness
    thickness = get_as_parameter(
        name='thickness',
        value=thickness,
        default_dict=DEFAULTS,
        unique_name_prefix=f'{unique_name}_Thickness',
    )
    thickness.default_limits_pending = not isinstance(thickness_value, Parameter)

    roughness_value = roughness
    roughness = get_as_parameter(
        name='roughness',
        value=roughness,
        default_dict=DEFAULTS,
        unique_name_prefix=f'{unique_name}_Roughness',
    )
    roughness.default_limits_pending = not isinstance(roughness_value, Parameter)

    super().__init__(name=name, unique_name=unique_name)
    self._material = material
    self._thickness = thickness
    self._roughness = roughness

    if interface is not None:
        self.interface = interface

assign_material(material)

Assign a material to the layer interface.

Parameters:

Name Type Description Default
material Material

The material to assign to the layer.

required
Source code in src/easyreflectometry/sample/elements/layers/layer.py
122
123
124
125
126
127
128
129
130
131
132
def assign_material(self, material: Material) -> None:
    """Assign a material to the layer interface.

    Parameters
    ----------
    material : Material
        The material to assign to the layer.
    """
    self._material = material
    if self.interface is not None:
        self.interface().assign_material_to_layer(self.material.unique_name, self.unique_name)

Material

Bases: BaseCore

Source code in src/easyreflectometry/sample/elements/materials/material.py
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
class Material(BaseCore):
    def __init__(
        self,
        sld: Union[Parameter, float, None] = None,
        isld: Union[Parameter, float, None] = None,
        name: str = 'EasyMaterial',
        unique_name: Optional[str] = None,
        interface=None,
    ):
        """Constructor.

        Parameters
        ----------
        unique_name : Optional[str], optional
            By default, None.
        sld : Union[Parameter, float, None], optional
            Real scattering length density. By default, None.
        isld : Union[Parameter, float, None], optional
            Imaginary scattering length density. By default, None.
        name : str, optional
            Name of the material. By default, 'EasyMaterial'.
        interface :
            Calculator interface. By default, None.
        """
        if unique_name is None:
            unique_name = global_object.generate_unique_name(self.__class__.__name__)

        sld = get_as_parameter(
            name='sld',
            value=sld,
            default_dict=DEFAULTS,
            unique_name_prefix=f'{unique_name}_Sld',
        )
        apply_default_limits(sld, 'sld')

        isld = get_as_parameter(
            name='isld',
            value=isld,
            default_dict=DEFAULTS,
            unique_name_prefix=f'{unique_name}_Isld',
        )
        apply_default_limits(isld, 'isld')

        super().__init__(name=name, unique_name=unique_name)
        self._sld = sld
        self._isld = isld

        if interface is not None:
            self.interface = interface

    @property
    def sld(self) -> Parameter:
        return self._sld

    @sld.setter
    def sld(self, value: float) -> None:
        self._sld.value = value

    @property
    def isld(self) -> Parameter:
        return self._isld

    @isld.setter
    def isld(self, value: float) -> None:
        self._isld.value = value

    # Representation
    @property
    def _dict_repr(self) -> dict[str, str]:
        """A simplified dict representation."""
        return {
            self.name: {
                'sld': f'{self._sld.value:.3f}e-6 {self._sld.unit}',
                'isld': f'{self._isld.value:.3f}e-6 {self._isld.unit}',
            }
        }

__init__(sld=None, isld=None, name='EasyMaterial', unique_name=None, interface=None)

Constructor.

Parameters:

Name Type Description Default
unique_name Optional[str]

By default, None.

None
sld Union[Parameter, float, None]

Real scattering length density. By default, None.

None
isld Union[Parameter, float, None]

Imaginary scattering length density. By default, None.

None
name str

Name of the material. By default, 'EasyMaterial'.

'EasyMaterial'
interface

Calculator interface. By default, None.

None
Source code in src/easyreflectometry/sample/elements/materials/material.py
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
def __init__(
    self,
    sld: Union[Parameter, float, None] = None,
    isld: Union[Parameter, float, None] = None,
    name: str = 'EasyMaterial',
    unique_name: Optional[str] = None,
    interface=None,
):
    """Constructor.

    Parameters
    ----------
    unique_name : Optional[str], optional
        By default, None.
    sld : Union[Parameter, float, None], optional
        Real scattering length density. By default, None.
    isld : Union[Parameter, float, None], optional
        Imaginary scattering length density. By default, None.
    name : str, optional
        Name of the material. By default, 'EasyMaterial'.
    interface :
        Calculator interface. By default, None.
    """
    if unique_name is None:
        unique_name = global_object.generate_unique_name(self.__class__.__name__)

    sld = get_as_parameter(
        name='sld',
        value=sld,
        default_dict=DEFAULTS,
        unique_name_prefix=f'{unique_name}_Sld',
    )
    apply_default_limits(sld, 'sld')

    isld = get_as_parameter(
        name='isld',
        value=isld,
        default_dict=DEFAULTS,
        unique_name_prefix=f'{unique_name}_Isld',
    )
    apply_default_limits(isld, 'isld')

    super().__init__(name=name, unique_name=unique_name)
    self._sld = sld
    self._isld = isld

    if interface is not None:
        self.interface = interface

MaterialCollection

Bases: BaseCollection

Source code in src/easyreflectometry/sample/collections/material_collection.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
class MaterialCollection(BaseCollection):
    def __init__(
        self,
        *materials: Tuple[Material],
        name: str = 'EasyMaterials',
        interface=None,
        unique_name: Optional[str] = None,
        populate_if_none: bool = True,
        **kwargs,
    ):
        """Init function."""
        if not materials:
            if populate_if_none:
                materials = DEFAULT_ELEMENTS(interface)
            else:
                materials = []

        super().__init__(
            name,
            interface,
            *materials,
            unique_name=unique_name,
            populate_if_none=False,
            **kwargs,
        )

    def add_material(self, material: Optional[Material] = None):
        """Add a material to the collection.

        Parameters
        ----------
        material : Optional[Material], optional
            Material to add. By default, None.
        """
        if material is None:
            material = Material(sld=0.0, isld=0.0, name='Material added')
        material.interface = self.interface
        self.append(material)

    def duplicate_material(self, index: int):
        """Duplicate a material in the collection.

        Parameters
        ----------
        index : int
        material :
            Assembly to add.
        """
        to_be_duplicated = self[index]
        duplicate = Material.from_dict(to_be_duplicated.as_dict(skip=['unique_name']))
        duplicate.name = duplicate.name + ' duplicate'
        self.append(duplicate)

__init__(*materials, name='EasyMaterials', interface=None, unique_name=None, populate_if_none=True, **kwargs)

Init function.

Source code in src/easyreflectometry/sample/collections/material_collection.py
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
def __init__(
    self,
    *materials: Tuple[Material],
    name: str = 'EasyMaterials',
    interface=None,
    unique_name: Optional[str] = None,
    populate_if_none: bool = True,
    **kwargs,
):
    """Init function."""
    if not materials:
        if populate_if_none:
            materials = DEFAULT_ELEMENTS(interface)
        else:
            materials = []

    super().__init__(
        name,
        interface,
        *materials,
        unique_name=unique_name,
        populate_if_none=False,
        **kwargs,
    )

add_material(material=None)

Add a material to the collection.

Parameters:

Name Type Description Default
material Optional[Material]

Material to add. By default, None.

None
Source code in src/easyreflectometry/sample/collections/material_collection.py
48
49
50
51
52
53
54
55
56
57
58
59
def add_material(self, material: Optional[Material] = None):
    """Add a material to the collection.

    Parameters
    ----------
    material : Optional[Material], optional
        Material to add. By default, None.
    """
    if material is None:
        material = Material(sld=0.0, isld=0.0, name='Material added')
    material.interface = self.interface
    self.append(material)

duplicate_material(index)

Duplicate a material in the collection.

Parameters:

Name Type Description Default
index int
required
material

Assembly to add.

required
Source code in src/easyreflectometry/sample/collections/material_collection.py
61
62
63
64
65
66
67
68
69
70
71
72
73
def duplicate_material(self, index: int):
    """Duplicate a material in the collection.

    Parameters
    ----------
    index : int
    material :
        Assembly to add.
    """
    to_be_duplicated = self[index]
    duplicate = Material.from_dict(to_be_duplicated.as_dict(skip=['unique_name']))
    duplicate.name = duplicate.name + ' duplicate'
    self.append(duplicate)

Multilayer

Bases: BaseAssembly

A multi layer is build from a single or a list of Layer or LayerCollection.

The multi layer will arrange the layers as slabs, allowing the reflectometry to be determined from them. The front layer is where the neutron beam starts in, it has an index of 0.

More information about the usage of this assembly is available in the multilayer documentation_

.. _multilayer documentation: ../sample/assemblies_library.html#multilayer

Source code in src/easyreflectometry/sample/assemblies/multilayer.py
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
class Multilayer(BaseAssembly):
    """A multi layer is build from a single or a list of `Layer` or `LayerCollection`.

    The multi layer will arrange the layers as slabs, allowing the reflectometry to be determined from them.
    The front layer is where the neutron beam starts in, it has an index of 0.

    More information about the usage of this assembly is available in the
    `multilayer documentation`_

    .. _`multilayer documentation`: ../sample/assemblies_library.html#multilayer
    """

    def __init__(
        self,
        layers: Union[Layer, list[Layer], LayerCollection, None] = None,
        name: str = 'EasyMultilayer',
        unique_name: Optional[str] = None,
        interface=None,
        type: str = 'Multi-layer',
        populate_if_none: Optional[bool] = True,
    ):
        """Constructor.

        Parameters
        ----------
        populate_if_none : Optional[bool], optional
            By default, True.
        unique_name : Optional[str], optional
            By default, None.
        layers : Union[Layer, list[Layer], LayerCollection, None], optional
            The layers that make up the multi-layer. By default, None.
        name : str, optional
            Name for multi layer. By default, 'EasyMultilayer'.
        interface :
            Calculator interface. By default, None.
        type : str, optional
            Type of the constructed instance. By default, 'Multi-layer'.
        """
        if layers is None:
            if populate_if_none:
                layers = LayerCollection([Layer(interface=interface)])
            else:
                layers = LayerCollection()
        elif isinstance(layers, Layer):
            layers = LayerCollection(layers, name=layers.name)
        elif isinstance(layers, list):
            layers = LayerCollection(*layers, name='/'.join([layer.name for layer in layers]))
        # Needed to ensure an empty list is created when saving and instatiating the object as_dict -> from_dict
        # Else collisions might occur in global_object.map
        self.populate_if_none = False

        super().__init__(
            name=name,
            type=type,
            interface=interface,
            layers=layers,
            unique_name=unique_name,
        )

    def add_layer(self, *layers: tuple[Layer]) -> None:
        """Add a layer to the multi layer.

        Parameters
        ----------
        *layers : tuple[Layer]
            Layers to add to the multi layer.
        """
        for arg in layers:
            if issubclass(arg.__class__, Layer):
                self.layers.append(arg)
                if self.interface is not None:
                    self.interface().add_layer_to_item(arg.unique_name, self.unique_name)

    def duplicate_layer(self, idx: int) -> None:
        """Duplicate a given layer.

        Parameters
        ----------
        idx : int
            Index of layer to duplicate.
        """
        to_duplicate = self.layers[idx]
        duplicate_layer = Layer(
            material=to_duplicate.material,
            thickness=to_duplicate.thickness.value,
            roughness=to_duplicate.roughness.value,
            name=to_duplicate.name + ' duplicate',
        )
        self.add_layer(duplicate_layer)

    def remove_layer(self, idx: int) -> None:
        """Remove a layer from the item.

        Parameters
        ----------
        idx : int
            Index of layer to remove.
        """
        if self.interface is not None:
            self.interface().remove_layer_from_item(self.layers[idx].unique_name, self.unique_name)
        del self.layers[idx]

    # Representation
    @property
    def _dict_repr(self) -> dict:
        """A simplified dict representation."""
        return {self.name: self.layers._dict_repr}

    @classmethod
    def from_dict(cls, data: dict) -> Multilayer:
        """Create a Multilayer from a dictionary."""
        multilayer = super().from_dict(data)
        return multilayer

__init__(layers=None, name='EasyMultilayer', unique_name=None, interface=None, type='Multi-layer', populate_if_none=True)

Constructor.

Parameters:

Name Type Description Default
populate_if_none Optional[bool]

By default, True.

True
unique_name Optional[str]

By default, None.

None
layers Union[Layer, list[Layer], LayerCollection, None]

The layers that make up the multi-layer. By default, None.

None
name str

Name for multi layer. By default, 'EasyMultilayer'.

'EasyMultilayer'
interface

Calculator interface. By default, None.

None
type str

Type of the constructed instance. By default, 'Multi-layer'.

'Multi-layer'
Source code in src/easyreflectometry/sample/assemblies/multilayer.py
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
def __init__(
    self,
    layers: Union[Layer, list[Layer], LayerCollection, None] = None,
    name: str = 'EasyMultilayer',
    unique_name: Optional[str] = None,
    interface=None,
    type: str = 'Multi-layer',
    populate_if_none: Optional[bool] = True,
):
    """Constructor.

    Parameters
    ----------
    populate_if_none : Optional[bool], optional
        By default, True.
    unique_name : Optional[str], optional
        By default, None.
    layers : Union[Layer, list[Layer], LayerCollection, None], optional
        The layers that make up the multi-layer. By default, None.
    name : str, optional
        Name for multi layer. By default, 'EasyMultilayer'.
    interface :
        Calculator interface. By default, None.
    type : str, optional
        Type of the constructed instance. By default, 'Multi-layer'.
    """
    if layers is None:
        if populate_if_none:
            layers = LayerCollection([Layer(interface=interface)])
        else:
            layers = LayerCollection()
    elif isinstance(layers, Layer):
        layers = LayerCollection(layers, name=layers.name)
    elif isinstance(layers, list):
        layers = LayerCollection(*layers, name='/'.join([layer.name for layer in layers]))
    # Needed to ensure an empty list is created when saving and instatiating the object as_dict -> from_dict
    # Else collisions might occur in global_object.map
    self.populate_if_none = False

    super().__init__(
        name=name,
        type=type,
        interface=interface,
        layers=layers,
        unique_name=unique_name,
    )

add_layer(*layers)

Add a layer to the multi layer.

Parameters:

Name Type Description Default
*layers tuple[Layer]

Layers to add to the multi layer.

()
Source code in src/easyreflectometry/sample/assemblies/multilayer.py
73
74
75
76
77
78
79
80
81
82
83
84
85
def add_layer(self, *layers: tuple[Layer]) -> None:
    """Add a layer to the multi layer.

    Parameters
    ----------
    *layers : tuple[Layer]
        Layers to add to the multi layer.
    """
    for arg in layers:
        if issubclass(arg.__class__, Layer):
            self.layers.append(arg)
            if self.interface is not None:
                self.interface().add_layer_to_item(arg.unique_name, self.unique_name)

duplicate_layer(idx)

Duplicate a given layer.

Parameters:

Name Type Description Default
idx int

Index of layer to duplicate.

required
Source code in src/easyreflectometry/sample/assemblies/multilayer.py
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
def duplicate_layer(self, idx: int) -> None:
    """Duplicate a given layer.

    Parameters
    ----------
    idx : int
        Index of layer to duplicate.
    """
    to_duplicate = self.layers[idx]
    duplicate_layer = Layer(
        material=to_duplicate.material,
        thickness=to_duplicate.thickness.value,
        roughness=to_duplicate.roughness.value,
        name=to_duplicate.name + ' duplicate',
    )
    self.add_layer(duplicate_layer)

remove_layer(idx)

Remove a layer from the item.

Parameters:

Name Type Description Default
idx int

Index of layer to remove.

required
Source code in src/easyreflectometry/sample/assemblies/multilayer.py
104
105
106
107
108
109
110
111
112
113
114
def remove_layer(self, idx: int) -> None:
    """Remove a layer from the item.

    Parameters
    ----------
    idx : int
        Index of layer to remove.
    """
    if self.interface is not None:
        self.interface().remove_layer_from_item(self.layers[idx].unique_name, self.unique_name)
    del self.layers[idx]

from_dict(data) classmethod

Create a Multilayer from a dictionary.

Source code in src/easyreflectometry/sample/assemblies/multilayer.py
122
123
124
125
126
@classmethod
def from_dict(cls, data: dict) -> Multilayer:
    """Create a Multilayer from a dictionary."""
    multilayer = super().from_dict(data)
    return multilayer

Sample

Bases: BaseCollection

A sample is a collection of assemblies that represent the structure for which experimental measurements exist.

Source code in src/easyreflectometry/sample/collections/sample.py
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
class Sample(BaseCollection):
    """A sample is a collection of assemblies that represent the structure for which experimental measurements exist."""

    def __init__(
        self,
        *assemblies: Optional[List[BaseAssembly]],
        name: str = 'EasySample',
        interface=None,
        unique_name: Optional[str] = None,
        populate_if_none: bool = True,
        **kwargs,
    ):
        """Constructor.

        Parameters
        ----------
        **kwargs :
        populate_if_none : bool, optional
            By default, True.
        unique_name : Optional[str], optional
            By default, None.
        *assemblies : Optional[List[BaseAssembly]]
        args :
            The assemblies in the sample.
        name : str, optional
            Name of the sample. By default, 'EasySample'.
        interface :
            Calculator interface. By default, None.
        """
        # `from_dict` (via `EasyList.from_dict`) passes the items as a single
        # list-positional arg; unpack that so validation and super() agree.
        if len(assemblies) == 1 and isinstance(assemblies[0], list):
            assemblies = tuple(assemblies[0])

        if not assemblies:
            if populate_if_none:
                assemblies = DEFAULT_ELEMENTS(interface)
            else:
                assemblies = []

        for assembly in assemblies:
            if not issubclass(type(assembly), BaseAssembly):
                raise ValueError('The elements must be an Assembly.')
        super().__init__(
            name,
            interface,
            *assemblies,
            unique_name=unique_name,
            populate_if_none=populate_if_none,
            **kwargs,
        )

    def add_assembly(self, assembly: Optional[BaseAssembly] = None):
        """Add an assembly to the sample.

        Parameters
        ----------
        assembly : Optional[BaseAssembly], optional
            Assembly to add. By default, None.
        """
        if assembly is None:
            assembly = Multilayer(
                name='EasyMultilayer added',
                interface=self.interface,
            )
        self.append(assembly)

    def duplicate_assembly(self, index: int):
        """Add an assembly to the sample.

        Parameters
        ----------
        index : int
        assembly :
            Assembly to add.
        """
        # Order matters: RepeatingMultilayer and SurfactantLayer are subclasses of
        # BaseAssembly but not Multilayer; however a RepeatingMultilayer IS a
        # Multilayer, so the most-specific check must come first to avoid
        # serialising it through the wrong `from_dict`.
        to_be_duplicated = self[index]
        if isinstance(to_be_duplicated, RepeatingMultilayer):
            duplicate = RepeatingMultilayer.from_dict(to_be_duplicated.as_dict(skip=['unique_name']))
        elif isinstance(to_be_duplicated, SurfactantLayer):
            duplicate = SurfactantLayer.from_dict(to_be_duplicated.as_dict(skip=['unique_name']))
        elif isinstance(to_be_duplicated, Multilayer):
            duplicate = Multilayer.from_dict(to_be_duplicated.as_dict(skip=['unique_name']))
        else:
            raise TypeError(f'Cannot duplicate assembly of type {type(to_be_duplicated).__name__}')
        duplicate.name = duplicate.name + ' duplicate'
        self.append(duplicate)

    def move_up(self, index: int):
        """Move the assembly at the given index up in the sample.

        Parameters
        ----------
        index : int
            Index of the assembly to move up.
        """
        super().move_up(index)

    def move_down(self, index: int):
        """Move the assembly at the given index down in the sample.

        Parameters
        ----------
        index : int
            Index of the assembly to move down.
        """
        super().move_down(index)

    def remove_assembly(self, index: int):
        """Remove the assembly at the given index from the sample.

        Parameters
        ----------
        index : int
            Index of the assembly to remove.
        """
        self.pop(index)

    @property
    def superphase(self) -> Layer:
        """The superphase of the sample."""
        return self[0].front_layer

    @property
    def subphase(self) -> Layer:
        """The subphase of the sample."""
        # This assembly only got one layer
        if self[-1].back_layer is None:
            return self[-1].front_layer
        else:
            return self[-1].back_layer

superphase property

The superphase of the sample.

subphase property

The subphase of the sample.

__init__(*assemblies, name='EasySample', interface=None, unique_name=None, populate_if_none=True, **kwargs)

Constructor.

Parameters:

Name Type Description Default
**kwargs
{}
populate_if_none bool

By default, True.

True
unique_name Optional[str]

By default, None.

None
*assemblies Optional[List[BaseAssembly]]
()
args

The assemblies in the sample.

required
name str

Name of the sample. By default, 'EasySample'.

'EasySample'
interface

Calculator interface. By default, None.

None
Source code in src/easyreflectometry/sample/collections/sample.py
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
def __init__(
    self,
    *assemblies: Optional[List[BaseAssembly]],
    name: str = 'EasySample',
    interface=None,
    unique_name: Optional[str] = None,
    populate_if_none: bool = True,
    **kwargs,
):
    """Constructor.

    Parameters
    ----------
    **kwargs :
    populate_if_none : bool, optional
        By default, True.
    unique_name : Optional[str], optional
        By default, None.
    *assemblies : Optional[List[BaseAssembly]]
    args :
        The assemblies in the sample.
    name : str, optional
        Name of the sample. By default, 'EasySample'.
    interface :
        Calculator interface. By default, None.
    """
    # `from_dict` (via `EasyList.from_dict`) passes the items as a single
    # list-positional arg; unpack that so validation and super() agree.
    if len(assemblies) == 1 and isinstance(assemblies[0], list):
        assemblies = tuple(assemblies[0])

    if not assemblies:
        if populate_if_none:
            assemblies = DEFAULT_ELEMENTS(interface)
        else:
            assemblies = []

    for assembly in assemblies:
        if not issubclass(type(assembly), BaseAssembly):
            raise ValueError('The elements must be an Assembly.')
    super().__init__(
        name,
        interface,
        *assemblies,
        unique_name=unique_name,
        populate_if_none=populate_if_none,
        **kwargs,
    )

add_assembly(assembly=None)

Add an assembly to the sample.

Parameters:

Name Type Description Default
assembly Optional[BaseAssembly]

Assembly to add. By default, None.

None
Source code in src/easyreflectometry/sample/collections/sample.py
78
79
80
81
82
83
84
85
86
87
88
89
90
91
def add_assembly(self, assembly: Optional[BaseAssembly] = None):
    """Add an assembly to the sample.

    Parameters
    ----------
    assembly : Optional[BaseAssembly], optional
        Assembly to add. By default, None.
    """
    if assembly is None:
        assembly = Multilayer(
            name='EasyMultilayer added',
            interface=self.interface,
        )
    self.append(assembly)

duplicate_assembly(index)

Add an assembly to the sample.

Parameters:

Name Type Description Default
index int
required
assembly

Assembly to add.

required
Source code in src/easyreflectometry/sample/collections/sample.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
def duplicate_assembly(self, index: int):
    """Add an assembly to the sample.

    Parameters
    ----------
    index : int
    assembly :
        Assembly to add.
    """
    # Order matters: RepeatingMultilayer and SurfactantLayer are subclasses of
    # BaseAssembly but not Multilayer; however a RepeatingMultilayer IS a
    # Multilayer, so the most-specific check must come first to avoid
    # serialising it through the wrong `from_dict`.
    to_be_duplicated = self[index]
    if isinstance(to_be_duplicated, RepeatingMultilayer):
        duplicate = RepeatingMultilayer.from_dict(to_be_duplicated.as_dict(skip=['unique_name']))
    elif isinstance(to_be_duplicated, SurfactantLayer):
        duplicate = SurfactantLayer.from_dict(to_be_duplicated.as_dict(skip=['unique_name']))
    elif isinstance(to_be_duplicated, Multilayer):
        duplicate = Multilayer.from_dict(to_be_duplicated.as_dict(skip=['unique_name']))
    else:
        raise TypeError(f'Cannot duplicate assembly of type {type(to_be_duplicated).__name__}')
    duplicate.name = duplicate.name + ' duplicate'
    self.append(duplicate)

move_up(index)

Move the assembly at the given index up in the sample.

Parameters:

Name Type Description Default
index int

Index of the assembly to move up.

required
Source code in src/easyreflectometry/sample/collections/sample.py
118
119
120
121
122
123
124
125
126
def move_up(self, index: int):
    """Move the assembly at the given index up in the sample.

    Parameters
    ----------
    index : int
        Index of the assembly to move up.
    """
    super().move_up(index)

move_down(index)

Move the assembly at the given index down in the sample.

Parameters:

Name Type Description Default
index int

Index of the assembly to move down.

required
Source code in src/easyreflectometry/sample/collections/sample.py
128
129
130
131
132
133
134
135
136
def move_down(self, index: int):
    """Move the assembly at the given index down in the sample.

    Parameters
    ----------
    index : int
        Index of the assembly to move down.
    """
    super().move_down(index)

remove_assembly(index)

Remove the assembly at the given index from the sample.

Parameters:

Name Type Description Default
index int

Index of the assembly to remove.

required
Source code in src/easyreflectometry/sample/collections/sample.py
138
139
140
141
142
143
144
145
146
def remove_assembly(self, index: int):
    """Remove the assembly at the given index from the sample.

    Parameters
    ----------
    index : int
        Index of the assembly to remove.
    """
    self.pop(index)

BaseCollection

Bases: EasyList

Local base for sample-tree collections (Material/Layer/Assembly/Model collections).

Built on top of easyscience.base_classes.EasyList (the replacement for the deprecated CollectionBase). On top of EasyList this class adds:

  • a name property
  • an interface property whose setter propagates the calculator interface to every contained item
  • propagation of the current interface to newly inserted items
  • a populate_if_none flag preserved for serialization round-trip
  • convenience helpers names, move_up, move_down, remove_at
  • a yaml-formatted __repr__ driven by _dict_repr
  • an as_dict alias for to_dict with skip= support and interface excluded by default

Subclasses (LayerCollection, MaterialCollection, Sample, ModelCollection) keep their existing constructor shape — they pass name and interface positionally to this class, items as *args, and additional configuration as kwargs.

Source code in src/easyreflectometry/sample/collections/base_collection.py
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
class BaseCollection(EasyList):
    """Local base for sample-tree collections (Material/Layer/Assembly/Model collections).

    Built on top of `easyscience.base_classes.EasyList` (the replacement for
    the deprecated `CollectionBase`). On top of `EasyList` this class adds:

    - a `name` property
    - an `interface` property whose setter propagates the calculator interface
      to every contained item
    - propagation of the current `interface` to newly inserted items
    - a `populate_if_none` flag preserved for serialization round-trip
    - convenience helpers `names`, `move_up`, `move_down`, `remove_at`
    - a yaml-formatted `__repr__` driven by `_dict_repr`
    - an `as_dict` alias for `to_dict` with `skip=` support and `interface`
      excluded by default

    Subclasses (`LayerCollection`, `MaterialCollection`, `Sample`,
    `ModelCollection`) keep their existing constructor shape — they pass
    `name` and `interface` positionally to this class, items as `*args`, and
    additional configuration as kwargs.
    """

    def __init__(
        self,
        name: str,
        interface: Any = None,
        *args: Any,
        unique_name: Optional[str] = None,
        populate_if_none: bool = False,
        **kwargs: Any,
    ):
        # `_interface` must exist before `super().__init__` because `EasyList`
        # calls `self.append(item)` for each positional arg, which routes
        # through our `insert` override and reads `self._interface`.
        self._interface = None
        self._name = name
        # Legacy `CollectionBase` accepted items either positionally or as a
        # list-valued keyword (e.g. ``LayerCollection(layers=[a, b])``). Pull
        # any list-valued kwarg into the positional stream so callers using
        # that older pattern keep working.
        extra_items = []
        for key in list(kwargs.keys()):
            if isinstance(kwargs[key], list) and kwargs[key] and key != 'data':
                extra_items.extend(kwargs.pop(key))
        if extra_items:
            args = tuple(args) + tuple(extra_items)
        super().__init__(*args, unique_name=unique_name, **kwargs)
        # `populate_if_none` is a control flag, not state. It is serialized so
        # `from_dict` knows whether the original construction filled in
        # defaults; the value should be `False` once the data is restored.
        self.populate_if_none = populate_if_none

        # Assign interface LAST — propagates to all contained items.
        if interface is not None:
            self.interface = interface

    # ----- name -----

    @property
    def name(self) -> str:
        return self._name

    @name.setter
    def name(self, value: str) -> None:
        self._name = value

    # ----- interface -----

    @property
    def interface(self) -> Any:
        return self._interface

    @interface.setter
    def interface(self, new_interface: Any) -> None:
        self._interface = new_interface
        if new_interface is None:
            return
        # Propagate to existing items.
        for item in self._data:
            if self._has_interface_setter(type(item)):
                item.interface = new_interface
        # Tell the calculator to bind to self (matches the legacy CollectionBase
        # behavior which called `interface.generate_bindings(self)` once per
        # collection).
        if hasattr(new_interface, 'generate_bindings'):
            new_interface.generate_bindings(self)

    def _get_key(self, obj):
        """Use the item's `name` for string-indexed lookups.

        Matches the legacy `CollectionBase.__getitem__` behaviour which
        searched by `item.name`. `EasyList` defaults to `unique_name`; the
        existing `Project` code (and callers) look items up by their pretty
        name (e.g. `materials['Air']`).
        """
        return getattr(obj, 'name', None) or obj.unique_name

    @staticmethod
    def _has_interface_setter(obj_type: type) -> bool:
        for klass in obj_type.__mro__:
            prop = klass.__dict__.get('interface')
            if isinstance(prop, property):
                return prop.fset is not None
        return False

    # ----- mutable-sequence overrides that propagate interface -----

    def insert(self, index: int, value: Any) -> None:
        """Insert and (if an interface is set) propagate it to the new item.

        Legacy `CollectionBase.insert` did `value.interface = self.interface`
        after registering the item; we replicate the same behaviour here so
        downstream calculator state stays in sync when items are appended
        after the collection's interface was already set.

        The type check from `EasyList.insert` is bypassed: each subclass
        accepts a single item type (Layer / Material / BaseAssembly / Model)
        and enforces it elsewhere, while the EasyList check would require
        every item to be a `NewBase` subclass — which was historically not
        guaranteed and forces an extra coupling we don't need.
        """
        if not isinstance(index, int):
            raise TypeError('Index must be an integer')
        # Skip the EasyList protected-types check; mimic the rest of its insert
        # (duplicate-name warning + append-to-_data).
        import warnings as _warnings

        if value in self:
            _warnings.warn(f'Item with unique name "{self._get_key(value)}" already in collection, it will be ignored')
            return
        self._data.insert(index, value)
        if self._interface is not None and self._has_interface_setter(type(value)):
            value.interface = self._interface

    # ----- helpers -----

    @property
    def names(self) -> list:
        """List of item names."""
        return [getattr(item, 'name', None) for item in self._data]

    @property
    def data(self) -> list:
        """Read-only view of the underlying item list.

        Provided for compatibility with code (and tests) written against the
        legacy `CollectionBase` shape, which exposed items via `.data`.
        """
        return list(self._data)

    def move_up(self, index: int) -> None:
        """Move the element at the given index up in the collection."""
        if index == 0:
            return
        self.insert(index - 1, self.pop(index))

    def move_down(self, index: int) -> None:
        """Move the element at the given index down in the collection."""
        if index == len(self) - 1:
            return
        self.insert(index + 1, self.pop(index))

    def remove_at(self, index: int) -> None:
        """Remove the item at *index* from the collection.

        Renamed from the legacy `BaseCollection.remove(index)` which shadowed
        `MutableSequence.remove(value)` (remove-by-value, inherited from
        `EasyList`). Callers that meant "remove by index" should use this; the
        standard `remove(value)` is still available with its usual semantics.
        """
        self.pop(index)

    # ----- compatibility shims (kept until call sites migrate) -----

    def get_parameters(self) -> List[Parameter]:
        """Compatibility alias for legacy callers; prefer `get_all_parameters`."""
        return self.get_all_parameters()

    def get_all_variables(self) -> List:
        """Flat list of every Parameter/Descriptor across all items.

        Walks each item in the collection and unions whatever each item
        exposes via its own `get_all_variables` (for `ModelBase` /
        `BaseCore` children) or, for objects that lack that hook,
        unions any direct `DescriptorBase` attributes.
        """
        from easyscience.variable.descriptor_base import DescriptorBase

        out: list = []
        seen: set[int] = set()
        for item in self._data:
            if hasattr(item, 'get_all_variables'):
                for v in item.get_all_variables():
                    if id(v) not in seen:
                        seen.add(id(v))
                        out.append(v)
            elif isinstance(item, DescriptorBase):
                if id(item) not in seen:
                    seen.add(id(item))
                    out.append(item)
        return out

    def get_all_parameters(self) -> List[Parameter]:
        return [v for v in self.get_all_variables() if isinstance(v, Parameter)]

    def get_free_parameters(self) -> List[Parameter]:
        return [p for p in self.get_all_parameters() if p.independent and not p.fixed]

    def get_fit_parameters(self) -> List[Parameter]:
        """Alias kept for the minimizer; matches `ModelBase.get_fit_parameters`."""
        return self.get_free_parameters()

    def _get_linkable_attributes(self) -> List[Parameter]:
        """Bridge for `easyscience.fitting.calculators.interface_factory.generate_bindings`."""
        return self.get_all_variables()

    # ----- repr -----

    @property
    def _dict_repr(self) -> dict:
        """A simplified dict representation."""
        return {self.name: [getattr(i, '_dict_repr', repr(i)) for i in self._data]}

    def __repr__(self) -> str:
        try:
            return yaml_dump(self._dict_repr)
        except Exception:
            return super().__repr__()

    # ----- serialization -----

    def _convert_to_dict(self, d: dict, encoder=None, skip: Optional[List[str]] = None, **kwargs) -> dict:
        """Serializer hook used when this collection is encoded as a *child*
        attribute (e.g. `Multilayer.layers`).

        `SerializerBase._convert_to_dict` iterates `_arg_spec` to populate the
        base dict and then calls `obj._convert_to_dict(d, ...)` if defined.
        Because `data` is supplied via `*args` (VAR_POSITIONAL — not part of
        `_arg_spec`), without this hook the nested encoding would miss the
        items entirely and round-trip would reconstruct an empty collection.
        """
        if skip is None:
            skip = []
        if self._protected_types != [NewBase] and 'protected_types' not in d:
            d['protected_types'] = [{'@module': c.__module__, '@class': c.__name__} for c in self._protected_types]
        # Encode each item. Defer to the encoder's recursive walk so nested
        # ModelBase / NewBase items get properly serialized.
        item_skip = list(skip)
        items: list = []
        for item in self._data:
            if encoder is not None and hasattr(encoder, '_recursive_encoder'):
                items.append(encoder._recursive_encoder(item, skip=item_skip, encoder=encoder, full_encode=False))
            elif hasattr(item, 'to_dict'):
                try:
                    items.append(item.to_dict(skip=list(item_skip)))
                except TypeError:
                    items.append(item.to_dict())
            else:
                items.append(item)
        d['data'] = items
        return d

    def to_dict(self, skip: Optional[List[str]] = None) -> dict:
        """Serialize with `skip` support; `interface` excluded by default.

        `EasyList.to_dict` doesn't accept a `skip` argument and is hard-wired
        to dump `data` plus the parent's `_arg_spec` view. We reimplement here
        so existing callers (`Project`, `Model.as_dict`, etc.) can keep
        passing `skip=['unique_name']` or similar.

        ``NewBase.to_dict`` mutates the ``skip`` list in-place (e.g. it
        appends ``'unique_name'`` when the collection's own unique_name is
        default-generated). We therefore pass a *copy* to it, otherwise the
        mutation would leak into the per-item serialization below and force
        every item Parameter dict to drop its ``unique_name`` — breaking the
        from_dict round-trip.
        """
        skip = list(skip or [])
        if 'interface' not in skip:
            skip.append('interface')
        # Matches legacy `BasedBase.as_dict`: drop unique_name from the
        # serialized form so nested Parameters don't get explicit names that
        # would collide with the auto-generated names produced when the global
        # counter restarts during reconstruction.
        if 'unique_name' not in skip:
            skip.append('unique_name')
        dict_repr = NewBase.to_dict(self, skip=list(skip))
        if self._protected_types != [NewBase]:
            dict_repr['protected_types'] = [{'@module': c.__module__, '@class': c.__name__} for c in self._protected_types]
        dict_repr['data'] = []
        for item in self._data:
            # Items that are ModelBase / BaseCore subclasses accept `skip`;
            # other shapes use their no-arg `to_dict`/`as_dict`.
            if hasattr(item, 'to_dict'):
                try:
                    dict_repr['data'].append(item.to_dict(skip=list(skip)))
                except TypeError:
                    dict_repr['data'].append(item.to_dict())
            else:
                dict_repr['data'].append(item.as_dict(skip=list(skip)))
        return dict_repr

    def as_dict(self, skip: Optional[List[str]] = None) -> dict:
        """Compatibility alias for :meth:`to_dict`."""
        return self.to_dict(skip=skip)

    def __deepcopy__(self, memo):
        """Round-trip via dict-skip-unique to get a fresh copy.

        `NewBase.__copy__` already does this; the override is kept (rather
        than deleted) to mirror the legacy `BaseCollection.__deepcopy__`
        semantics — callers that relied on `copy.deepcopy(collection)` still
        get a clone built from `from_dict(as_dict(skip=['unique_name']))`.
        """
        return self.from_dict(self.as_dict(skip=['unique_name']))

names property

List of item names.

data property

Read-only view of the underlying item list.

Provided for compatibility with code (and tests) written against the legacy CollectionBase shape, which exposed items via .data.

insert(index, value)

Insert and (if an interface is set) propagate it to the new item.

Legacy CollectionBase.insert did value.interface = self.interface after registering the item; we replicate the same behaviour here so downstream calculator state stays in sync when items are appended after the collection's interface was already set.

The type check from EasyList.insert is bypassed: each subclass accepts a single item type (Layer / Material / BaseAssembly / Model) and enforces it elsewhere, while the EasyList check would require every item to be a NewBase subclass — which was historically not guaranteed and forces an extra coupling we don't need.

Source code in src/easyreflectometry/sample/collections/base_collection.py
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
def insert(self, index: int, value: Any) -> None:
    """Insert and (if an interface is set) propagate it to the new item.

    Legacy `CollectionBase.insert` did `value.interface = self.interface`
    after registering the item; we replicate the same behaviour here so
    downstream calculator state stays in sync when items are appended
    after the collection's interface was already set.

    The type check from `EasyList.insert` is bypassed: each subclass
    accepts a single item type (Layer / Material / BaseAssembly / Model)
    and enforces it elsewhere, while the EasyList check would require
    every item to be a `NewBase` subclass — which was historically not
    guaranteed and forces an extra coupling we don't need.
    """
    if not isinstance(index, int):
        raise TypeError('Index must be an integer')
    # Skip the EasyList protected-types check; mimic the rest of its insert
    # (duplicate-name warning + append-to-_data).
    import warnings as _warnings

    if value in self:
        _warnings.warn(f'Item with unique name "{self._get_key(value)}" already in collection, it will be ignored')
        return
    self._data.insert(index, value)
    if self._interface is not None and self._has_interface_setter(type(value)):
        value.interface = self._interface

move_up(index)

Move the element at the given index up in the collection.

Source code in src/easyreflectometry/sample/collections/base_collection.py
167
168
169
170
171
def move_up(self, index: int) -> None:
    """Move the element at the given index up in the collection."""
    if index == 0:
        return
    self.insert(index - 1, self.pop(index))

move_down(index)

Move the element at the given index down in the collection.

Source code in src/easyreflectometry/sample/collections/base_collection.py
173
174
175
176
177
def move_down(self, index: int) -> None:
    """Move the element at the given index down in the collection."""
    if index == len(self) - 1:
        return
    self.insert(index + 1, self.pop(index))

remove_at(index)

Remove the item at index from the collection.

Renamed from the legacy BaseCollection.remove(index) which shadowed MutableSequence.remove(value) (remove-by-value, inherited from EasyList). Callers that meant "remove by index" should use this; the standard remove(value) is still available with its usual semantics.

Source code in src/easyreflectometry/sample/collections/base_collection.py
179
180
181
182
183
184
185
186
187
def remove_at(self, index: int) -> None:
    """Remove the item at *index* from the collection.

    Renamed from the legacy `BaseCollection.remove(index)` which shadowed
    `MutableSequence.remove(value)` (remove-by-value, inherited from
    `EasyList`). Callers that meant "remove by index" should use this; the
    standard `remove(value)` is still available with its usual semantics.
    """
    self.pop(index)

get_parameters()

Compatibility alias for legacy callers; prefer get_all_parameters.

Source code in src/easyreflectometry/sample/collections/base_collection.py
191
192
193
def get_parameters(self) -> List[Parameter]:
    """Compatibility alias for legacy callers; prefer `get_all_parameters`."""
    return self.get_all_parameters()

get_all_variables()

Flat list of every Parameter/Descriptor across all items.

Walks each item in the collection and unions whatever each item exposes via its own get_all_variables (for ModelBase / BaseCore children) or, for objects that lack that hook, unions any direct DescriptorBase attributes.

Source code in src/easyreflectometry/sample/collections/base_collection.py
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
def get_all_variables(self) -> List:
    """Flat list of every Parameter/Descriptor across all items.

    Walks each item in the collection and unions whatever each item
    exposes via its own `get_all_variables` (for `ModelBase` /
    `BaseCore` children) or, for objects that lack that hook,
    unions any direct `DescriptorBase` attributes.
    """
    from easyscience.variable.descriptor_base import DescriptorBase

    out: list = []
    seen: set[int] = set()
    for item in self._data:
        if hasattr(item, 'get_all_variables'):
            for v in item.get_all_variables():
                if id(v) not in seen:
                    seen.add(id(v))
                    out.append(v)
        elif isinstance(item, DescriptorBase):
            if id(item) not in seen:
                seen.add(id(item))
                out.append(item)
    return out

get_fit_parameters()

Alias kept for the minimizer; matches ModelBase.get_fit_parameters.

Source code in src/easyreflectometry/sample/collections/base_collection.py
225
226
227
def get_fit_parameters(self) -> List[Parameter]:
    """Alias kept for the minimizer; matches `ModelBase.get_fit_parameters`."""
    return self.get_free_parameters()

to_dict(skip=None)

Serialize with skip support; interface excluded by default.

EasyList.to_dict doesn't accept a skip argument and is hard-wired to dump data plus the parent's _arg_spec view. We reimplement here so existing callers (Project, Model.as_dict, etc.) can keep passing skip=['unique_name'] or similar.

NewBase.to_dict mutates the skip list in-place (e.g. it appends 'unique_name' when the collection's own unique_name is default-generated). We therefore pass a copy to it, otherwise the mutation would leak into the per-item serialization below and force every item Parameter dict to drop its unique_name — breaking the from_dict round-trip.

Source code in src/easyreflectometry/sample/collections/base_collection.py
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
def to_dict(self, skip: Optional[List[str]] = None) -> dict:
    """Serialize with `skip` support; `interface` excluded by default.

    `EasyList.to_dict` doesn't accept a `skip` argument and is hard-wired
    to dump `data` plus the parent's `_arg_spec` view. We reimplement here
    so existing callers (`Project`, `Model.as_dict`, etc.) can keep
    passing `skip=['unique_name']` or similar.

    ``NewBase.to_dict`` mutates the ``skip`` list in-place (e.g. it
    appends ``'unique_name'`` when the collection's own unique_name is
    default-generated). We therefore pass a *copy* to it, otherwise the
    mutation would leak into the per-item serialization below and force
    every item Parameter dict to drop its ``unique_name`` — breaking the
    from_dict round-trip.
    """
    skip = list(skip or [])
    if 'interface' not in skip:
        skip.append('interface')
    # Matches legacy `BasedBase.as_dict`: drop unique_name from the
    # serialized form so nested Parameters don't get explicit names that
    # would collide with the auto-generated names produced when the global
    # counter restarts during reconstruction.
    if 'unique_name' not in skip:
        skip.append('unique_name')
    dict_repr = NewBase.to_dict(self, skip=list(skip))
    if self._protected_types != [NewBase]:
        dict_repr['protected_types'] = [{'@module': c.__module__, '@class': c.__name__} for c in self._protected_types]
    dict_repr['data'] = []
    for item in self._data:
        # Items that are ModelBase / BaseCore subclasses accept `skip`;
        # other shapes use their no-arg `to_dict`/`as_dict`.
        if hasattr(item, 'to_dict'):
            try:
                dict_repr['data'].append(item.to_dict(skip=list(skip)))
            except TypeError:
                dict_repr['data'].append(item.to_dict())
        else:
            dict_repr['data'].append(item.as_dict(skip=list(skip)))
    return dict_repr

as_dict(skip=None)

Compatibility alias for :meth:to_dict.

Source code in src/easyreflectometry/sample/collections/base_collection.py
319
320
321
def as_dict(self, skip: Optional[List[str]] = None) -> dict:
    """Compatibility alias for :meth:`to_dict`."""
    return self.to_dict(skip=skip)

__deepcopy__(memo)

Round-trip via dict-skip-unique to get a fresh copy.

NewBase.__copy__ already does this; the override is kept (rather than deleted) to mirror the legacy BaseCollection.__deepcopy__ semantics — callers that relied on copy.deepcopy(collection) still get a clone built from from_dict(as_dict(skip=['unique_name'])).

Source code in src/easyreflectometry/sample/collections/base_collection.py
323
324
325
326
327
328
329
330
331
def __deepcopy__(self, memo):
    """Round-trip via dict-skip-unique to get a fresh copy.

    `NewBase.__copy__` already does this; the override is kept (rather
    than deleted) to mirror the legacy `BaseCollection.__deepcopy__`
    semantics — callers that relied on `copy.deepcopy(collection)` still
    get a clone built from `from_dict(as_dict(skip=['unique_name']))`.
    """
    return self.from_dict(self.as_dict(skip=['unique_name']))

Project

Source code in src/easyreflectometry/project.py
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
class Project:
    def __init__(self):
        """Init function."""
        self._info = self._default_info()
        self._path_project_parent = Path(os.path.expanduser('~'))
        self._models = ModelCollection(populate_if_none=False, unique_name='project_models')
        self._materials = MaterialCollection(populate_if_none=False, unique_name='project_materials')
        self._calculator = CalculatorFactory()
        self._experiments: Dict[DataGroup] = {}
        self._fitter: MultiFitter = None
        self._minimizer_selection: AvailableMinimizers = DEFAULT_MINIMIZER
        self._colors: list[str] = None
        self._report = None
        self._q_min: float = None
        self._q_max: float = None
        self._q_resolution: int = None
        self._current_material_index = 0
        self._current_model_index = 0
        self._current_assembly_index = 0
        self._current_layer_index = 0
        self._fitter_model_index = None
        self._current_experiment_index = 0

        # Project flags
        self._created = False
        self._with_experiments = False

    def reset(self):
        """Reset function."""
        del self._models
        del self._materials
        global_object.map._clear()

        self.__init__()

    @property
    def parameters(self) -> List[Parameter]:
        """Get all unique parameters from all models in the project.

        Parameters shared across multiple models (e.g. material SLD) are
        only included once to avoid double-counting.
        """
        parameters = []
        seen_ids: set[int] = set()
        if self._models is not None:
            for model in self._models:
                for param in model.get_all_parameters():
                    pid = id(param)
                    if pid not in seen_ids:
                        seen_ids.add(pid)
                        parameters.append(param)
        return parameters

    def _sync_parameter_states(self) -> None:
        """Apply project-level parameter enablement and default limits.

        Superphase thickness/roughness and subphase thickness are physically
        meaningless and are marked as disabled. Thickness and roughness default
        ranges are then applied only to enabled parameters created from project
        defaults, leaving explicit user-provided bounds untouched.
        """
        if self._models is None:
            return

        disabled_ids: set[int] = set()
        for model in self._models:
            sample = model.sample
            if sample is None or len(sample) == 0:
                continue
            superphase = sample.superphase
            if superphase is not None:
                disabled_ids.add(id(superphase.thickness))
                disabled_ids.add(id(superphase.roughness))
            subphase = sample.subphase
            if subphase is not None:
                disabled_ids.add(id(subphase.thickness))

        for model in self._models:
            sample = model.sample
            if sample is None or len(sample) == 0:
                continue
            for assembly in sample:
                for layer in assembly.layers:
                    self._sync_layer_parameter_state(layer.thickness, 'thickness', disabled_ids)
                    self._sync_layer_parameter_state(layer.roughness, 'roughness', disabled_ids)

    def _sync_layer_parameter_state(self, parameter: Parameter, kind: str, disabled_ids: set[int]) -> None:
        """Update a layer parameter's enabled state and pending default limits."""
        if id(parameter) in disabled_ids:
            parameter.enabled = False
            return

        if getattr(parameter, 'default_limits_pending', False):
            delattr(parameter, 'default_limits_pending')
            if getattr(parameter, 'enabled', True):
                parameter.min = -np.inf
                parameter.max = np.inf
                apply_default_limits(parameter, kind)

    @property
    def q_min(self):
        """Q min."""
        if self._q_min is None:
            return Q_MIN
        return self._q_min

    @q_min.setter
    def q_min(self, value: float) -> None:
        """Q min."""
        self._q_min = value

    @property
    def q_max(self):
        """Q max."""
        if self._q_max is None:
            return Q_MAX
        return self._q_max

    @q_max.setter
    def q_max(self, value: float) -> None:
        """Q max."""
        self._q_max = value

    @property
    def q_resolution(self):
        """Q resolution."""
        if self._q_resolution is None:
            return Q_RESOLUTION
        return self._q_resolution

    @q_resolution.setter
    def q_resolution(self, value: int) -> None:
        """Q resolution."""
        self._q_resolution = value

    @property
    def current_material_index(self) -> Optional[int]:
        """Current material index."""
        return self._current_material_index

    @current_material_index.setter
    def current_material_index(self, value: int) -> None:
        """Current material index."""
        if value < 0 or value >= len(self._materials):
            raise ValueError(f'Index {value} out of range')
        if self._current_material_index != value:
            self._current_material_index = value

    @property
    def current_model_index(self) -> Optional[int]:
        """Current model index."""
        return self._current_model_index

    @current_model_index.setter
    def current_model_index(self, value: int) -> None:
        """Current model index."""
        if value < 0 or value >= len(self._models):
            raise ValueError(f'Index {value} out of range')
        if self._current_model_index != value:
            self._current_model_index = value
            self._current_assembly_index = 0
            self._current_layer_index = 0

    @property
    def current_assembly_index(self) -> Optional[int]:
        """Current assembly index."""
        return self._current_assembly_index

    @current_assembly_index.setter
    def current_assembly_index(self, value: int) -> None:
        """Current assembly index."""
        if value < 0 or value >= len(self._models[self._current_model_index].sample):
            raise ValueError(f'Index {value} out of range')
        if self._current_assembly_index != value:
            self._current_assembly_index = value
            self._current_layer_index = 0

    @property
    def current_layer_index(self) -> Optional[int]:
        """Current layer index."""
        return self._current_layer_index

    @current_layer_index.setter
    def current_layer_index(self, value: int) -> None:
        """Current layer index."""
        if value < 0 or value >= len(self._models[self._current_model_index].sample[self._current_assembly_index].layers):
            raise ValueError(f'Index {value} out of range')
        if self._current_layer_index != value:
            self._current_layer_index = value

    @property
    def current_experiment_index(self) -> Optional[int]:
        """Current experiment index."""
        return self._current_experiment_index

    @current_experiment_index.setter
    def current_experiment_index(self, value: int) -> None:
        """Current experiment index."""
        if value < 0 or value >= len(self._experiments):
            raise ValueError(f'Index {value} out of range')
        if self._current_experiment_index != value:
            self._current_experiment_index = value
            # Resetting the model index to 0 when changing the experiment
            # self.current_model_index = 0

    @property
    def created(self) -> bool:
        """Created function."""
        return self._created

    @property
    def path(self):
        """Path function."""
        return self._path_project_parent / self._info['name']

    def set_path_project_parent(self, path: Union[Path, str]):
        """Set path project parent."""
        self._path_project_parent = Path(path)

    @property
    def models(self) -> ModelCollection:
        """Models function."""
        return self._models

    @models.setter
    def models(self, models: ModelCollection) -> None:
        """Models function."""
        self._replace_collection(models, self._models)
        # Use setter to update indicies for current model, assembly and layer
        self.current_model_index = 0
        self._materials.extend(self._get_materials_in_models())
        for model in self._models:
            model.interface = self._calculator
        self._sync_parameter_states()

    @property
    def fitter(self) -> MultiFitter:
        """Fitter function."""
        if len(self._models):
            if (self._fitter is None) or (self._fitter_model_index != self._current_model_index):
                self._fitter = MultiFitter(self._models[self._current_model_index])
                self._fitter.easy_science_multi_fitter.switch_minimizer(self._minimizer_selection)
                self._fitter_model_index = self._current_model_index
        return self._fitter

    @property
    def calculator(self) -> str:
        """Calculator function."""
        return self._calculator.current_interface_name

    @calculator.setter
    def calculator(self, calculator: str) -> None:
        """Calculator function."""
        if calculator == self._calculator.current_interface_name:
            return

        self._calculator.switch(calculator)
        self._calculator.reset_storage()

        for model in self._models:
            model.generate_bindings()

        self._fitter = None
        self._fitter_model_index = None

    @property
    def minimizer(self) -> AvailableMinimizers:
        """Minimizer function."""
        if self._fitter is not None:
            return self._fitter.easy_science_multi_fitter.minimizer.enum
        return self._minimizer_selection

    @minimizer.setter
    def minimizer(self, minimizer: AvailableMinimizers) -> None:
        """Minimizer function."""
        old_name = getattr(self._minimizer_selection, 'name', str(self._minimizer_selection))
        new_name = getattr(minimizer, 'name', str(minimizer))
        logger.info(
            'Minimizer changed from %s to %s (fitter active: %s)',
            old_name,
            new_name,
            self._fitter is not None,
        )
        self._minimizer_selection = minimizer
        if self._fitter is not None:
            self._fitter.easy_science_multi_fitter.switch_minimizer(minimizer)

    @property
    def experiments(self) -> Dict[int, DataSet1D]:
        """Experiments function."""
        return self._experiments

    @experiments.setter
    def experiments(self, experiments: Dict[int, DataSet1D]) -> None:
        """Experiments function."""
        self._experiments = experiments

    @property
    def path_json(self):
        """Path json."""
        return self.path / 'project.json'

    def get_index_air(self) -> int:
        """Get index air."""
        if 'Air' not in [material.name for material in self._materials]:
            self._materials.add_material(Material(name='Air', sld=0.0, isld=0.0))
        return [material.name for material in self._materials].index('Air')

    def get_index_si(self) -> int:
        """Get index si."""
        if 'Si' not in [material.name for material in self._materials]:
            self._materials.add_material(Material(name='Si', sld=2.07, isld=0.0))
        return [material.name for material in self._materials].index('Si')

    def get_index_sio2(self) -> int:
        """Get index sio2."""
        if 'SiO2' not in [material.name for material in self._materials]:
            self._materials.add_material(Material(name='SiO2', sld=3.47, isld=0.0))
        return [material.name for material in self._materials].index('SiO2')

    def get_index_d2o(self) -> int:
        """Get index d2o."""
        if 'D2O' not in [material.name for material in self._materials]:
            self._materials.add_material(Material(name='D2O', sld=6.36, isld=0.0))
        return [material.name for material in self._materials].index('D2O')

    def load_orso_file(self, path: Union[Path, str]) -> None:
        """Load an ORSO file and optionally create a model and a data from it."""
        from easyreflectometry.orso_utils import LoadOrso

        model, data = LoadOrso(path)
        if model is not None:
            if isinstance(model, Sample):
                model = Model(sample=model, name=model.name)
            self.models = ModelCollection([model])
        else:
            self.default_model()
        if data is not None:
            self._experiments[0] = data
            self._experiments[0].name = 'Experiment from ORSO'
            self._experiments[0].model = self.models[0]
            self._with_experiments = True
        pass

    def set_sample_from_orso(self, sample: Sample) -> None:
        """Replace the current project model collection with a single model built from an ORSO-parsed sample.

        This is a convenience helper for the ORSO import pipeline where a complete
        :class:`~easyreflectometry.sample.Sample` is constructed elsewhere.

        Parameters
        ----------
        sample : Sample
            Sample to set as the project's (single) model.

        Returns
        -------
        None
            ``None``.
        """
        model = Model(sample=sample)
        self.models = ModelCollection([model])

    def add_sample_from_orso(self, sample: Sample) -> None:
        """Add a new model with the given sample to the existing model collection.

        The created model is appended to :attr:`models`, its calculator interface is
        set to the project's current calculator, and any materials referenced in the
        sample are added to the project's material collection.

        After adding the model, :attr:`current_model_index` is updated to point to
        the newly added model.

        Parameters
        ----------
        sample : Sample
            Sample to add as a new model.

        Returns
        -------
        None
            ``None``.
        """
        if sample is None:
            raise ValueError('The ORSO file does not contain a valid sample model definition.')
        model = Model(sample=sample)
        self.models.add_model(model)
        # Set interface after adding to collection
        model.interface = self._calculator
        # Extract materials from the new model and add to project materials
        self._materials.extend(self._get_materials_from_model(model))
        self._sync_parameter_states()
        # Switch to the newly added model so its data is visible in the UI
        self.current_model_index = len(self._models) - 1

    def replace_models_from_orso(self, sample: Sample) -> None:
        """Replace all models and materials with a single model from an ORSO sample.

        All existing models and their associated materials are removed. A new
        model is created from *sample*, assigned to the project's calculator,
        and the material collection is rebuilt from the new model only.

        Parameters
        ----------
        sample : Sample
            Sample to set as the project's only model.

        Returns
        -------
        None
            ``None``.
        """
        if sample is None:
            raise ValueError('The ORSO file does not contain a valid sample model definition.')
        model = Model(sample=sample)
        if sample.name:
            model.user_data['original_name'] = sample.name  # Store original name for reference
        self.models = ModelCollection([model])
        model.interface = self._calculator
        self._materials = self._get_materials_from_model(model)
        self.current_model_index = 0

    def _get_materials_from_model(self, model: Model) -> 'MaterialCollection':
        """Get all materials from a single model's sample."""
        materials_in_model = MaterialCollection(populate_if_none=False)
        for assembly in model.sample:
            for layer in assembly.layers:
                if layer.material not in materials_in_model:
                    materials_in_model.append(layer.material)
        return materials_in_model

    def _apply_experiment_metadata(
        self,
        path: Union[Path, str],
        experiment: DataSet1D,
        fallback_name: str,
        data_group=None,
        data_key: Optional[str] = None,
    ) -> None:
        """Set experiment name from ORSO title and configure the resolution function.

        Parameters
        ----------
        path : Union[Path, str]
            Path to the experiment data file.
        experiment : DataSet1D
            The loaded experiment dataset to configure.
        fallback_name : str
            Name to use when no ORSO title is available.
        data_group :
            Pre-loaded scipp DataGroup (avoids reloading the file). By default, None.
        data_key : Optional[str], optional
            Specific dataset key to use for title extraction (e.g. ``'R_1'``). By default, None.
        """
        # Prefer ORSO title when available (keeps UI descriptive)
        title = None
        try:
            if data_group is None:
                data_group = load_data_from_orso_file(str(path))
            if data_key is None:
                data_key = list(data_group['data'].keys())[0]
            title = extract_orso_title(data_group, data_key)
        except (KeyError, AttributeError, ValueError, IndexError):
            title = None

        if title:
            experiment.name = title
        elif not experiment.name or experiment.name == 'Series':
            experiment.name = fallback_name

    def _apply_resolution_function(
        self,
        experiment: DataSet1D,
        model: Model,
    ) -> None:
        """Set the resolution function on *model* based on variance data in *experiment*.

        Uses the measured per-point q-resolution (``Pointwise``) when the
        experiment carries q-variance data (``xe``, i.e. sQz²); otherwise
        falls back to the default 5% FWHM percentage resolution.

        Parameters
        ----------
        experiment : DataSet1D
            The experiment whose variance data drives the choice.
        model : Model
            The model whose resolution function is set.
        """
        if experiment.xe is not None and np.any(experiment.xe):
            model.resolution_function = Pointwise(q_data_points=[experiment.x, experiment.y, experiment.xe])
        else:
            model.resolution_function = PercentageFwhm(5.0)

    @staticmethod
    def _auto_set_background(experiment: DataSet1D) -> None:
        """Set the model background to the minimum y-value of the experiment data."""
        if experiment.model is not None and len(experiment.y) > 0:
            experiment.model.background = max(np.min(experiment.y), 1e-10)

    def load_new_experiment(self, path: Union[Path, str]) -> None:
        """Load new experiment."""
        new_experiment = load_as_dataset(str(path))
        new_index = len(self._experiments)

        model_index = 0
        if new_index < len(self.models):
            model_index = new_index

        self._apply_experiment_metadata(path, new_experiment, f'Experiment {new_index}')
        new_experiment.model = self.models[model_index]
        self._auto_set_background(new_experiment)
        self._experiments[new_index] = new_experiment
        self._with_experiments = True
        self._apply_resolution_function(new_experiment, self.models[model_index])

    def count_datasets_in_file(self, path: Union[Path, str]) -> int:
        """Return the number of datasets contained in the file at *path*.

        Parameters
        ----------
        path : Union[Path, str]
            Path to the data file.

        Returns
        -------
        int
            Number of datasets found; 1 if the file cannot be introspected.
        """
        try:
            data_group = load_data_from_orso_file(str(path))
            return len(data_group['data'])
        except Exception:
            return 1

    def load_all_experiments_from_file(self, path: Union[Path, str]) -> int:
        """Load all datasets from a file as separate experiments sharing the current model.

        For a multi-dataset ORSO file (e.g. a multi-angle measurement), each dataset is
        registered as an independent experiment.  All experiments share the model that is
        currently selected.  Falls back to :meth:`load_new_experiment` for single-dataset
        files or on any loading error.

        Parameters
        ----------
        path : Union[Path, str]
            Path to the data file.

        Returns
        -------
        int
            Number of experiments that were added.
        """
        try:
            data_group = load_data_from_orso_file(str(path))
        except Exception:
            self.load_new_experiment(path)
            return 1

        data_keys = sorted(data_group['data'].keys())
        if len(data_keys) <= 1:
            self.load_new_experiment(path)
            return 1

        model_index = self._current_model_index
        for data_key in data_keys:
            coord_key = data_key.replace('R_', 'Qz_')
            new_index = len(self._experiments)

            d = data_group['data'][data_key]
            c = data_group['coords'][coord_key]

            new_experiment = DataSet1D(
                name=f'Experiment {new_index}',
                x=c.values,
                y=d.values,
                ye=d.variances,
                xe=c.variances if c.variances is not None else None,
            )
            self._apply_experiment_metadata(
                path,
                new_experiment,
                f'Experiment {new_index}',
                data_group=data_group,
                data_key=data_key,
            )
            new_experiment.model = self.models[model_index]
            self._auto_set_background(new_experiment)
            self._experiments[new_index] = new_experiment
            self._apply_resolution_function(new_experiment, self.models[model_index])

        self._with_experiments = True
        return len(data_keys)

    def load_experiment_for_model_at_index(self, path: Union[Path, str], index: Optional[int] = 0) -> None:
        """Load experiment for model at index."""
        experiment = load_as_dataset(str(path))

        self._apply_experiment_metadata(path, experiment, f'Experiment {index}')
        experiment.model = self.models[index]
        self._auto_set_background(experiment)
        self._experiments[index] = experiment
        self._with_experiments = True
        self._apply_resolution_function(experiment, self._models[index])

    def sld_data_for_model_at_index(self, index: int = 0) -> DataSet1D:
        """Sld data for model at index."""
        self.models[index].interface = self._calculator
        sld = self.models[index].interface().sld_profile(self._models[index].unique_name)
        return DataSet1D(
            name=f'SLD for Model {index}',
            x=sld[0],
            y=sld[1],
        )

    def sample_data_for_model_at_index(self, index: int = 0, q_range: Optional[np.array] = None) -> DataSet1D:
        """Sample data for model at index."""
        original_resolution_function = self.models[index].resolution_function
        self.models[index].resolution_function = PercentageFwhm(0)
        reflectivity_data = self.model_data_for_model_at_index(index, q_range)
        self.models[index].resolution_function = original_resolution_function

        return reflectivity_data

    def model_data_for_model_at_index(self, index: int = 0, q_range: Optional[np.array] = None) -> DataSet1D:
        """Model data for model at index."""
        if q_range is None:
            q_range = np.linspace(self.q_min, self.q_max, self.q_resolution)
        self.models[index].interface = self._calculator
        reflectivity = self.models[index].interface().reflectity_profile(q_range, self._models[index].unique_name)
        return DataSet1D(
            name=f'Reflectivity for Model {index}',
            x=q_range,
            y=reflectivity,
        )

    def experimental_data_for_model_at_index(self, index: int = 0) -> DataSet1D:
        """Experimental data for model at index."""
        if index in self._experiments.keys():
            return self._experiments[index]
        else:
            raise IndexError(f'No experiment data for model at index {index}')

    def default_model(self):
        """Default model."""
        self._replace_collection(MaterialCollection(interface=self._calculator), self._materials)

        layers = [
            Layer(
                material=self._materials[0],
                thickness=0.0,
                roughness=0.0,
                name='Vacuum Layer',
                interface=self._calculator,
            ),
            Layer(
                material=self._materials[1],
                thickness=100.0,
                roughness=3.0,
                name='D2O Layer',
                interface=self._calculator,
            ),
            Layer(
                material=self._materials[2],
                thickness=0.0,
                roughness=1.2,
                name='Si Layer',
                interface=self._calculator,
            ),
        ]
        assemblies = [
            Multilayer(layers[0], name='Superphase', interface=self._calculator),
            Multilayer(layers[1], name='D2O', interface=self._calculator),
            Multilayer(layers[2], name='Subphase', interface=self._calculator),
        ]
        sample = Sample(*assemblies, interface=self._calculator)
        model = Model(sample=sample, interface=self._calculator)
        model.is_default = True
        self.models = ModelCollection([model])

    def is_default_model(self, index: int) -> bool:
        """Check if the model at the given index is a default model.

        Parameters
        ----------
        index : int
            Index of the model to check.

        Returns
        -------
        bool
            True if the model was created as a default placeholder.
        """
        if index < 0 or index >= len(self._models):
            return False

        return self._models[index].is_default

    def remove_model_at_index(self, index: int) -> None:
        """Remove the model at the given index.

        Removes the model from the model collection, removes the experiment at the
        same index (if any), and reindexes experiments above the removed index so
        model/experiment indices stay aligned.

        Adjusts the current model index if necessary.

        Parameters
        ----------
        index : int
            Index of the model to remove.

        Raises
        ------
        IndexError :
            If the index is out of range.
        ValueError :
            If trying to remove the last remaining model.
        """
        if index < 0 or index >= len(self._models):
            raise IndexError(f'Model index {index} out of range')

        if len(self._models) <= 1:
            raise ValueError('Cannot remove the last model from the project')

        # Remove the model from the collection
        self._models.pop(index)

        # Remove experiment mapped to the removed model index.
        if index in self._experiments:
            self._experiments.pop(index)

        # Reindex experiments above the removed model index to keep mapping aligned.
        reindexed_experiments: dict[int, DataSet1D] = {}
        for exp_index, experiment in sorted(self._experiments.items()):
            if exp_index > index:
                reindexed_experiments[exp_index - 1] = experiment
            else:
                reindexed_experiments[exp_index] = experiment
        self._experiments = reindexed_experiments

        # Adjust current model index if necessary
        if self._current_model_index >= len(self._models):
            self._current_model_index = len(self._models) - 1
        elif self._current_model_index > index:
            self._current_model_index -= 1

        # Reset assembly and layer indices for the new current model
        self._current_assembly_index = 0
        self._current_layer_index = 0

    def add_material(self, material: MaterialCollection) -> None:
        """Add material."""
        if material in self._materials:
            print(f'WARNING: Material {material} is already in material collection')
        else:
            self._materials.append(material)

    def remove_material(self, index: int) -> None:
        """Remove material."""
        if self._materials[index] in self._get_materials_in_models():
            print(f'ERROR: Material {self._materials[index]} is used in models')
        else:
            self._materials.pop(index)

    def _default_info(self):
        """Default info."""
        return dict(
            name='DefaultEasyReflectometryProject',
            short_description='Reflectometry, 1D',
            modified=datetime.datetime.now().strftime('%d.%m.%Y %H:%M'),
        )

    def create(self):
        """Create function."""
        if not os.path.exists(self.path):
            os.makedirs(self.path)
            os.makedirs(self.path / 'experiments')
            self._created = True
            self._timestamp_modification()
        else:
            print(f'ERROR: Directory {self.path} already exists')

    def save_as_json(self, overwrite=False):
        """Save as json."""
        if self.path_json.exists() and overwrite:
            print(f'File already exists {self.path_json}. Overwriting...')
            self.path_json.unlink()
        try:
            project_json = json.dumps(self.as_dict(include_materials_not_in_model=True), indent=4)
            self.path_json.parent.mkdir(exist_ok=True, parents=True)
            with open(self.path_json, mode='x') as file:
                file.write(project_json)
        except Exception as exception:
            print(exception)

    def load_from_json(self, path: Optional[Union[Path, str]] = None):
        """Load from json."""
        if path is None:
            path = self.path_json
        path = Path(path)
        if path.exists():
            with open(path, 'r') as file:
                project_dict = json.load(file)
                self.reset()
                self.from_dict(project_dict)
            self._path_project_parent = path.parents[1]
            self._created = True
        else:
            print(f'ERROR: File {path} does not exist')

    #: Schema version embedded in every serialized project. Bumped from 1 → 2
    #: when the sample/model classes migrated from the legacy
    #: ``easyscience.ObjBase``/``CollectionBase`` pipeline to
    #: ``ModelBase``/``EasyList``. The on-disk shape of nested objects (Layer,
    #: Material, MaterialMixture, MaterialSolvated, LayerAreaPerMolecule, etc.)
    #: changed in a way that is not backward-compatible with v1 files.
    FILE_FORMAT = 2

    def as_dict(self, include_materials_not_in_model=False):
        """As dict."""
        project_dict = {}
        project_dict['file_format'] = self.FILE_FORMAT
        project_dict['info'] = self._info
        project_dict['with_experiments'] = self._with_experiments
        if self._models is not None:
            project_dict['models'] = self._models.as_dict()
            project_dict['models']['unique_name'] = self._models.unique_name + '_to_prevent_collisions_on_load'
        if include_materials_not_in_model:
            self._as_dict_add_materials_not_in_model_dict(project_dict)
        if self._with_experiments:
            self._as_dict_add_experiments(project_dict)
        if self.fitter is not None:
            project_dict['fitter_minimizer'] = self.fitter.easy_science_multi_fitter.minimizer.name
        elif self._minimizer_selection is not None:
            project_dict['fitter_minimizer'] = self._minimizer_selection.name
        if self._calculator is not None:
            project_dict['calculator'] = self._calculator.current_interface_name
        if self._colors is not None:
            project_dict['colors'] = self._colors
        return project_dict

    def _as_dict_add_materials_not_in_model_dict(self, project_dict: dict):
        """As dict add materials not in model dict."""
        materials_not_in_model = []
        for material in self._materials:
            if material not in self._get_materials_in_models():
                materials_not_in_model.append(material)
        if len(materials_not_in_model) > 0:
            project_dict['materials_not_in_model'] = MaterialCollection(materials_not_in_model).as_dict(skip=['interface'])

    def _as_dict_add_experiments(self, project_dict: dict):
        """As dict add experiments."""
        project_dict['experiments'] = {}
        project_dict['experiments_models'] = {}
        project_dict['experiments_names'] = {}

        for key, experiment in self._experiments.items():
            project_dict['experiments'][key] = [
                list(experiment.x),
                list(experiment.y),
                list(experiment.ye),
            ]
            if experiment.xe is not None:
                project_dict['experiments'][key].append(list(experiment.xe))
                project_dict['experiments_models'][key] = experiment.model.name
                project_dict['experiments_names'][key] = experiment.name

    def from_dict(self, project_dict: dict):
        """From dict."""
        keys = list(project_dict.keys())
        # Validate file format. v1 files were written by the legacy
        # `ObjBase`/`CollectionBase` pipeline; their inner shapes (Layer,
        # Material, MaterialMixture, …) are not compatible with the v2
        # `ModelBase`/`EasyList` deserializer. Older files must be re-created.
        file_format = project_dict.get('file_format')
        if file_format is None:
            raise ValueError(
                'This project file predates file_format=2 and cannot be loaded by '
                'this version of easyreflectometry. The serialization format changed '
                'when the sample/model classes migrated from the legacy ObjBase / '
                'CollectionBase pipeline. Please re-create the project from its '
                'underlying data using the current API.'
            )
        if file_format != self.FILE_FORMAT:
            raise ValueError(
                f'Unsupported project file_format={file_format!r}; this version of '
                f'easyreflectometry only reads file_format={self.FILE_FORMAT}. Please '
                'either update easyreflectometry or re-create the project.'
            )
        self._info = project_dict['info']
        self._with_experiments = project_dict['with_experiments']
        if 'calculator' in keys:
            self._calculator.switch(project_dict['calculator'])
        if 'models' in keys:
            self.models = ModelCollection.from_dict(project_dict['models'])
        self._replace_collection(self._get_materials_in_models(), self._materials)
        if 'materials_not_in_model' in keys:
            self._materials.extend(MaterialCollection.from_dict(project_dict['materials_not_in_model']))
        if 'fitter_minimizer' in keys:
            self.minimizer = AvailableMinimizers[project_dict['fitter_minimizer']]
        else:
            self._fitter = None
        if 'experiments' in keys:
            self._experiments = self._from_dict_extract_experiments(project_dict)
        else:
            self._experiments = {}

        # Resolve any pending parameter dependencies (constraints) after all objects are loaded
        resolve_all_parameter_dependencies(self)

    def _from_dict_extract_experiments(self, project_dict: dict) -> Dict[int, DataSet1D]:
        """From dict extract experiments."""
        experiments = {}
        for key in project_dict['experiments'].keys():
            experiments[int(key)] = DataSet1D(
                name=project_dict['experiments_names'][key],
                x=project_dict['experiments'][key][0],
                y=project_dict['experiments'][key][1],
                ye=project_dict['experiments'][key][2],
                xe=project_dict['experiments'][key][3],
                model=self._models[project_dict['experiments_models'][key]],
                auto_background=False,
            )
        return experiments

    def _get_materials_in_models(self) -> MaterialCollection:
        """Get materials in models."""
        materials_in_model = MaterialCollection(populate_if_none=False)
        for model in self._models:
            for assembly in model.sample:
                for layer in assembly.layers:
                    materials_in_model.append(layer.material)
        return materials_in_model

    def _replace_collection(self, src_collection: BaseCollection, dst_collection: BaseCollection) -> None:
        """Replace collection."""
        # Clear the destination collection
        for i in range(len(dst_collection)):
            dst_collection.pop(0)

        for element in src_collection:
            dst_collection.append(element)

    def _timestamp_modification(self):
        """Timestamp modification."""
        self._info['modified'] = datetime.datetime.now().strftime('%d.%m.%Y %H:%M')

parameters property

Get all unique parameters from all models in the project.

Parameters shared across multiple models (e.g. material SLD) are only included once to avoid double-counting.

q_min property writable

Q min.

q_max property writable

Q max.

q_resolution property writable

Q resolution.

current_material_index property writable

Current material index.

current_model_index property writable

Current model index.

current_assembly_index property writable

Current assembly index.

current_layer_index property writable

Current layer index.

current_experiment_index property writable

Current experiment index.

created property

Created function.

path property

Path function.

models property writable

Models function.

fitter property

Fitter function.

calculator property writable

Calculator function.

minimizer property writable

Minimizer function.

experiments property writable

Experiments function.

path_json property

Path json.

__init__()

Init function.

Source code in src/easyreflectometry/project.py
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
def __init__(self):
    """Init function."""
    self._info = self._default_info()
    self._path_project_parent = Path(os.path.expanduser('~'))
    self._models = ModelCollection(populate_if_none=False, unique_name='project_models')
    self._materials = MaterialCollection(populate_if_none=False, unique_name='project_materials')
    self._calculator = CalculatorFactory()
    self._experiments: Dict[DataGroup] = {}
    self._fitter: MultiFitter = None
    self._minimizer_selection: AvailableMinimizers = DEFAULT_MINIMIZER
    self._colors: list[str] = None
    self._report = None
    self._q_min: float = None
    self._q_max: float = None
    self._q_resolution: int = None
    self._current_material_index = 0
    self._current_model_index = 0
    self._current_assembly_index = 0
    self._current_layer_index = 0
    self._fitter_model_index = None
    self._current_experiment_index = 0

    # Project flags
    self._created = False
    self._with_experiments = False

reset()

Reset function.

Source code in src/easyreflectometry/project.py
75
76
77
78
79
80
81
def reset(self):
    """Reset function."""
    del self._models
    del self._materials
    global_object.map._clear()

    self.__init__()

set_path_project_parent(path)

Set path project parent.

Source code in src/easyreflectometry/project.py
263
264
265
def set_path_project_parent(self, path: Union[Path, str]):
    """Set path project parent."""
    self._path_project_parent = Path(path)

get_index_air()

Get index air.

Source code in src/easyreflectometry/project.py
350
351
352
353
354
def get_index_air(self) -> int:
    """Get index air."""
    if 'Air' not in [material.name for material in self._materials]:
        self._materials.add_material(Material(name='Air', sld=0.0, isld=0.0))
    return [material.name for material in self._materials].index('Air')

get_index_si()

Get index si.

Source code in src/easyreflectometry/project.py
356
357
358
359
360
def get_index_si(self) -> int:
    """Get index si."""
    if 'Si' not in [material.name for material in self._materials]:
        self._materials.add_material(Material(name='Si', sld=2.07, isld=0.0))
    return [material.name for material in self._materials].index('Si')

get_index_sio2()

Get index sio2.

Source code in src/easyreflectometry/project.py
362
363
364
365
366
def get_index_sio2(self) -> int:
    """Get index sio2."""
    if 'SiO2' not in [material.name for material in self._materials]:
        self._materials.add_material(Material(name='SiO2', sld=3.47, isld=0.0))
    return [material.name for material in self._materials].index('SiO2')

get_index_d2o()

Get index d2o.

Source code in src/easyreflectometry/project.py
368
369
370
371
372
def get_index_d2o(self) -> int:
    """Get index d2o."""
    if 'D2O' not in [material.name for material in self._materials]:
        self._materials.add_material(Material(name='D2O', sld=6.36, isld=0.0))
    return [material.name for material in self._materials].index('D2O')

load_orso_file(path)

Load an ORSO file and optionally create a model and a data from it.

Source code in src/easyreflectometry/project.py
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
def load_orso_file(self, path: Union[Path, str]) -> None:
    """Load an ORSO file and optionally create a model and a data from it."""
    from easyreflectometry.orso_utils import LoadOrso

    model, data = LoadOrso(path)
    if model is not None:
        if isinstance(model, Sample):
            model = Model(sample=model, name=model.name)
        self.models = ModelCollection([model])
    else:
        self.default_model()
    if data is not None:
        self._experiments[0] = data
        self._experiments[0].name = 'Experiment from ORSO'
        self._experiments[0].model = self.models[0]
        self._with_experiments = True
    pass

set_sample_from_orso(sample)

Replace the current project model collection with a single model built from an ORSO-parsed sample.

This is a convenience helper for the ORSO import pipeline where a complete :class:~easyreflectometry.sample.Sample is constructed elsewhere.

Parameters:

Name Type Description Default
sample Sample

Sample to set as the project's (single) model.

required

Returns:

Type Description
None

None.

Source code in src/easyreflectometry/project.py
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
def set_sample_from_orso(self, sample: Sample) -> None:
    """Replace the current project model collection with a single model built from an ORSO-parsed sample.

    This is a convenience helper for the ORSO import pipeline where a complete
    :class:`~easyreflectometry.sample.Sample` is constructed elsewhere.

    Parameters
    ----------
    sample : Sample
        Sample to set as the project's (single) model.

    Returns
    -------
    None
        ``None``.
    """
    model = Model(sample=sample)
    self.models = ModelCollection([model])

add_sample_from_orso(sample)

Add a new model with the given sample to the existing model collection.

The created model is appended to :attr:models, its calculator interface is set to the project's current calculator, and any materials referenced in the sample are added to the project's material collection.

After adding the model, :attr:current_model_index is updated to point to the newly added model.

Parameters:

Name Type Description Default
sample Sample

Sample to add as a new model.

required

Returns:

Type Description
None

None.

Source code in src/easyreflectometry/project.py
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
def add_sample_from_orso(self, sample: Sample) -> None:
    """Add a new model with the given sample to the existing model collection.

    The created model is appended to :attr:`models`, its calculator interface is
    set to the project's current calculator, and any materials referenced in the
    sample are added to the project's material collection.

    After adding the model, :attr:`current_model_index` is updated to point to
    the newly added model.

    Parameters
    ----------
    sample : Sample
        Sample to add as a new model.

    Returns
    -------
    None
        ``None``.
    """
    if sample is None:
        raise ValueError('The ORSO file does not contain a valid sample model definition.')
    model = Model(sample=sample)
    self.models.add_model(model)
    # Set interface after adding to collection
    model.interface = self._calculator
    # Extract materials from the new model and add to project materials
    self._materials.extend(self._get_materials_from_model(model))
    self._sync_parameter_states()
    # Switch to the newly added model so its data is visible in the UI
    self.current_model_index = len(self._models) - 1

replace_models_from_orso(sample)

Replace all models and materials with a single model from an ORSO sample.

All existing models and their associated materials are removed. A new model is created from sample, assigned to the project's calculator, and the material collection is rebuilt from the new model only.

Parameters:

Name Type Description Default
sample Sample

Sample to set as the project's only model.

required

Returns:

Type Description
None

None.

Source code in src/easyreflectometry/project.py
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
def replace_models_from_orso(self, sample: Sample) -> None:
    """Replace all models and materials with a single model from an ORSO sample.

    All existing models and their associated materials are removed. A new
    model is created from *sample*, assigned to the project's calculator,
    and the material collection is rebuilt from the new model only.

    Parameters
    ----------
    sample : Sample
        Sample to set as the project's only model.

    Returns
    -------
    None
        ``None``.
    """
    if sample is None:
        raise ValueError('The ORSO file does not contain a valid sample model definition.')
    model = Model(sample=sample)
    if sample.name:
        model.user_data['original_name'] = sample.name  # Store original name for reference
    self.models = ModelCollection([model])
    model.interface = self._calculator
    self._materials = self._get_materials_from_model(model)
    self.current_model_index = 0

load_new_experiment(path)

Load new experiment.

Source code in src/easyreflectometry/project.py
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
def load_new_experiment(self, path: Union[Path, str]) -> None:
    """Load new experiment."""
    new_experiment = load_as_dataset(str(path))
    new_index = len(self._experiments)

    model_index = 0
    if new_index < len(self.models):
        model_index = new_index

    self._apply_experiment_metadata(path, new_experiment, f'Experiment {new_index}')
    new_experiment.model = self.models[model_index]
    self._auto_set_background(new_experiment)
    self._experiments[new_index] = new_experiment
    self._with_experiments = True
    self._apply_resolution_function(new_experiment, self.models[model_index])

count_datasets_in_file(path)

Return the number of datasets contained in the file at path.

Parameters:

Name Type Description Default
path Union[Path, str]

Path to the data file.

required

Returns:

Type Description
int

Number of datasets found; 1 if the file cannot be introspected.

Source code in src/easyreflectometry/project.py
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
def count_datasets_in_file(self, path: Union[Path, str]) -> int:
    """Return the number of datasets contained in the file at *path*.

    Parameters
    ----------
    path : Union[Path, str]
        Path to the data file.

    Returns
    -------
    int
        Number of datasets found; 1 if the file cannot be introspected.
    """
    try:
        data_group = load_data_from_orso_file(str(path))
        return len(data_group['data'])
    except Exception:
        return 1

load_all_experiments_from_file(path)

Load all datasets from a file as separate experiments sharing the current model.

For a multi-dataset ORSO file (e.g. a multi-angle measurement), each dataset is registered as an independent experiment. All experiments share the model that is currently selected. Falls back to :meth:load_new_experiment for single-dataset files or on any loading error.

Parameters:

Name Type Description Default
path Union[Path, str]

Path to the data file.

required

Returns:

Type Description
int

Number of experiments that were added.

Source code in src/easyreflectometry/project.py
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
def load_all_experiments_from_file(self, path: Union[Path, str]) -> int:
    """Load all datasets from a file as separate experiments sharing the current model.

    For a multi-dataset ORSO file (e.g. a multi-angle measurement), each dataset is
    registered as an independent experiment.  All experiments share the model that is
    currently selected.  Falls back to :meth:`load_new_experiment` for single-dataset
    files or on any loading error.

    Parameters
    ----------
    path : Union[Path, str]
        Path to the data file.

    Returns
    -------
    int
        Number of experiments that were added.
    """
    try:
        data_group = load_data_from_orso_file(str(path))
    except Exception:
        self.load_new_experiment(path)
        return 1

    data_keys = sorted(data_group['data'].keys())
    if len(data_keys) <= 1:
        self.load_new_experiment(path)
        return 1

    model_index = self._current_model_index
    for data_key in data_keys:
        coord_key = data_key.replace('R_', 'Qz_')
        new_index = len(self._experiments)

        d = data_group['data'][data_key]
        c = data_group['coords'][coord_key]

        new_experiment = DataSet1D(
            name=f'Experiment {new_index}',
            x=c.values,
            y=d.values,
            ye=d.variances,
            xe=c.variances if c.variances is not None else None,
        )
        self._apply_experiment_metadata(
            path,
            new_experiment,
            f'Experiment {new_index}',
            data_group=data_group,
            data_key=data_key,
        )
        new_experiment.model = self.models[model_index]
        self._auto_set_background(new_experiment)
        self._experiments[new_index] = new_experiment
        self._apply_resolution_function(new_experiment, self.models[model_index])

    self._with_experiments = True
    return len(data_keys)

load_experiment_for_model_at_index(path, index=0)

Load experiment for model at index.

Source code in src/easyreflectometry/project.py
641
642
643
644
645
646
647
648
649
650
def load_experiment_for_model_at_index(self, path: Union[Path, str], index: Optional[int] = 0) -> None:
    """Load experiment for model at index."""
    experiment = load_as_dataset(str(path))

    self._apply_experiment_metadata(path, experiment, f'Experiment {index}')
    experiment.model = self.models[index]
    self._auto_set_background(experiment)
    self._experiments[index] = experiment
    self._with_experiments = True
    self._apply_resolution_function(experiment, self._models[index])

sld_data_for_model_at_index(index=0)

Sld data for model at index.

Source code in src/easyreflectometry/project.py
652
653
654
655
656
657
658
659
660
def sld_data_for_model_at_index(self, index: int = 0) -> DataSet1D:
    """Sld data for model at index."""
    self.models[index].interface = self._calculator
    sld = self.models[index].interface().sld_profile(self._models[index].unique_name)
    return DataSet1D(
        name=f'SLD for Model {index}',
        x=sld[0],
        y=sld[1],
    )

sample_data_for_model_at_index(index=0, q_range=None)

Sample data for model at index.

Source code in src/easyreflectometry/project.py
662
663
664
665
666
667
668
669
def sample_data_for_model_at_index(self, index: int = 0, q_range: Optional[np.array] = None) -> DataSet1D:
    """Sample data for model at index."""
    original_resolution_function = self.models[index].resolution_function
    self.models[index].resolution_function = PercentageFwhm(0)
    reflectivity_data = self.model_data_for_model_at_index(index, q_range)
    self.models[index].resolution_function = original_resolution_function

    return reflectivity_data

model_data_for_model_at_index(index=0, q_range=None)

Model data for model at index.

Source code in src/easyreflectometry/project.py
671
672
673
674
675
676
677
678
679
680
681
def model_data_for_model_at_index(self, index: int = 0, q_range: Optional[np.array] = None) -> DataSet1D:
    """Model data for model at index."""
    if q_range is None:
        q_range = np.linspace(self.q_min, self.q_max, self.q_resolution)
    self.models[index].interface = self._calculator
    reflectivity = self.models[index].interface().reflectity_profile(q_range, self._models[index].unique_name)
    return DataSet1D(
        name=f'Reflectivity for Model {index}',
        x=q_range,
        y=reflectivity,
    )

experimental_data_for_model_at_index(index=0)

Experimental data for model at index.

Source code in src/easyreflectometry/project.py
683
684
685
686
687
688
def experimental_data_for_model_at_index(self, index: int = 0) -> DataSet1D:
    """Experimental data for model at index."""
    if index in self._experiments.keys():
        return self._experiments[index]
    else:
        raise IndexError(f'No experiment data for model at index {index}')

default_model()

Default model.

Source code in src/easyreflectometry/project.py
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
def default_model(self):
    """Default model."""
    self._replace_collection(MaterialCollection(interface=self._calculator), self._materials)

    layers = [
        Layer(
            material=self._materials[0],
            thickness=0.0,
            roughness=0.0,
            name='Vacuum Layer',
            interface=self._calculator,
        ),
        Layer(
            material=self._materials[1],
            thickness=100.0,
            roughness=3.0,
            name='D2O Layer',
            interface=self._calculator,
        ),
        Layer(
            material=self._materials[2],
            thickness=0.0,
            roughness=1.2,
            name='Si Layer',
            interface=self._calculator,
        ),
    ]
    assemblies = [
        Multilayer(layers[0], name='Superphase', interface=self._calculator),
        Multilayer(layers[1], name='D2O', interface=self._calculator),
        Multilayer(layers[2], name='Subphase', interface=self._calculator),
    ]
    sample = Sample(*assemblies, interface=self._calculator)
    model = Model(sample=sample, interface=self._calculator)
    model.is_default = True
    self.models = ModelCollection([model])

is_default_model(index)

Check if the model at the given index is a default model.

Parameters:

Name Type Description Default
index int

Index of the model to check.

required

Returns:

Type Description
bool

True if the model was created as a default placeholder.

Source code in src/easyreflectometry/project.py
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
def is_default_model(self, index: int) -> bool:
    """Check if the model at the given index is a default model.

    Parameters
    ----------
    index : int
        Index of the model to check.

    Returns
    -------
    bool
        True if the model was created as a default placeholder.
    """
    if index < 0 or index >= len(self._models):
        return False

    return self._models[index].is_default

remove_model_at_index(index)

Remove the model at the given index.

Removes the model from the model collection, removes the experiment at the same index (if any), and reindexes experiments above the removed index so model/experiment indices stay aligned.

Adjusts the current model index if necessary.

Parameters:

Name Type Description Default
index int

Index of the model to remove.

required

Raises:

Type Description
IndexError :

If the index is out of range.

ValueError :

If trying to remove the last remaining model.

Source code in src/easyreflectometry/project.py
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
def remove_model_at_index(self, index: int) -> None:
    """Remove the model at the given index.

    Removes the model from the model collection, removes the experiment at the
    same index (if any), and reindexes experiments above the removed index so
    model/experiment indices stay aligned.

    Adjusts the current model index if necessary.

    Parameters
    ----------
    index : int
        Index of the model to remove.

    Raises
    ------
    IndexError :
        If the index is out of range.
    ValueError :
        If trying to remove the last remaining model.
    """
    if index < 0 or index >= len(self._models):
        raise IndexError(f'Model index {index} out of range')

    if len(self._models) <= 1:
        raise ValueError('Cannot remove the last model from the project')

    # Remove the model from the collection
    self._models.pop(index)

    # Remove experiment mapped to the removed model index.
    if index in self._experiments:
        self._experiments.pop(index)

    # Reindex experiments above the removed model index to keep mapping aligned.
    reindexed_experiments: dict[int, DataSet1D] = {}
    for exp_index, experiment in sorted(self._experiments.items()):
        if exp_index > index:
            reindexed_experiments[exp_index - 1] = experiment
        else:
            reindexed_experiments[exp_index] = experiment
    self._experiments = reindexed_experiments

    # Adjust current model index if necessary
    if self._current_model_index >= len(self._models):
        self._current_model_index = len(self._models) - 1
    elif self._current_model_index > index:
        self._current_model_index -= 1

    # Reset assembly and layer indices for the new current model
    self._current_assembly_index = 0
    self._current_layer_index = 0

add_material(material)

Add material.

Source code in src/easyreflectometry/project.py
798
799
800
801
802
803
def add_material(self, material: MaterialCollection) -> None:
    """Add material."""
    if material in self._materials:
        print(f'WARNING: Material {material} is already in material collection')
    else:
        self._materials.append(material)

remove_material(index)

Remove material.

Source code in src/easyreflectometry/project.py
805
806
807
808
809
810
def remove_material(self, index: int) -> None:
    """Remove material."""
    if self._materials[index] in self._get_materials_in_models():
        print(f'ERROR: Material {self._materials[index]} is used in models')
    else:
        self._materials.pop(index)

create()

Create function.

Source code in src/easyreflectometry/project.py
820
821
822
823
824
825
826
827
828
def create(self):
    """Create function."""
    if not os.path.exists(self.path):
        os.makedirs(self.path)
        os.makedirs(self.path / 'experiments')
        self._created = True
        self._timestamp_modification()
    else:
        print(f'ERROR: Directory {self.path} already exists')

save_as_json(overwrite=False)

Save as json.

Source code in src/easyreflectometry/project.py
830
831
832
833
834
835
836
837
838
839
840
841
def save_as_json(self, overwrite=False):
    """Save as json."""
    if self.path_json.exists() and overwrite:
        print(f'File already exists {self.path_json}. Overwriting...')
        self.path_json.unlink()
    try:
        project_json = json.dumps(self.as_dict(include_materials_not_in_model=True), indent=4)
        self.path_json.parent.mkdir(exist_ok=True, parents=True)
        with open(self.path_json, mode='x') as file:
            file.write(project_json)
    except Exception as exception:
        print(exception)

load_from_json(path=None)

Load from json.

Source code in src/easyreflectometry/project.py
843
844
845
846
847
848
849
850
851
852
853
854
855
856
def load_from_json(self, path: Optional[Union[Path, str]] = None):
    """Load from json."""
    if path is None:
        path = self.path_json
    path = Path(path)
    if path.exists():
        with open(path, 'r') as file:
            project_dict = json.load(file)
            self.reset()
            self.from_dict(project_dict)
        self._path_project_parent = path.parents[1]
        self._created = True
    else:
        print(f'ERROR: File {path} does not exist')

as_dict(include_materials_not_in_model=False)

As dict.

Source code in src/easyreflectometry/project.py
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
def as_dict(self, include_materials_not_in_model=False):
    """As dict."""
    project_dict = {}
    project_dict['file_format'] = self.FILE_FORMAT
    project_dict['info'] = self._info
    project_dict['with_experiments'] = self._with_experiments
    if self._models is not None:
        project_dict['models'] = self._models.as_dict()
        project_dict['models']['unique_name'] = self._models.unique_name + '_to_prevent_collisions_on_load'
    if include_materials_not_in_model:
        self._as_dict_add_materials_not_in_model_dict(project_dict)
    if self._with_experiments:
        self._as_dict_add_experiments(project_dict)
    if self.fitter is not None:
        project_dict['fitter_minimizer'] = self.fitter.easy_science_multi_fitter.minimizer.name
    elif self._minimizer_selection is not None:
        project_dict['fitter_minimizer'] = self._minimizer_selection.name
    if self._calculator is not None:
        project_dict['calculator'] = self._calculator.current_interface_name
    if self._colors is not None:
        project_dict['colors'] = self._colors
    return project_dict

from_dict(project_dict)

From dict.

Source code in src/easyreflectometry/project.py
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
def from_dict(self, project_dict: dict):
    """From dict."""
    keys = list(project_dict.keys())
    # Validate file format. v1 files were written by the legacy
    # `ObjBase`/`CollectionBase` pipeline; their inner shapes (Layer,
    # Material, MaterialMixture, …) are not compatible with the v2
    # `ModelBase`/`EasyList` deserializer. Older files must be re-created.
    file_format = project_dict.get('file_format')
    if file_format is None:
        raise ValueError(
            'This project file predates file_format=2 and cannot be loaded by '
            'this version of easyreflectometry. The serialization format changed '
            'when the sample/model classes migrated from the legacy ObjBase / '
            'CollectionBase pipeline. Please re-create the project from its '
            'underlying data using the current API.'
        )
    if file_format != self.FILE_FORMAT:
        raise ValueError(
            f'Unsupported project file_format={file_format!r}; this version of '
            f'easyreflectometry only reads file_format={self.FILE_FORMAT}. Please '
            'either update easyreflectometry or re-create the project.'
        )
    self._info = project_dict['info']
    self._with_experiments = project_dict['with_experiments']
    if 'calculator' in keys:
        self._calculator.switch(project_dict['calculator'])
    if 'models' in keys:
        self.models = ModelCollection.from_dict(project_dict['models'])
    self._replace_collection(self._get_materials_in_models(), self._materials)
    if 'materials_not_in_model' in keys:
        self._materials.extend(MaterialCollection.from_dict(project_dict['materials_not_in_model']))
    if 'fitter_minimizer' in keys:
        self.minimizer = AvailableMinimizers[project_dict['fitter_minimizer']]
    else:
        self._fitter = None
    if 'experiments' in keys:
        self._experiments = self._from_dict_extract_experiments(project_dict)
    else:
        self._experiments = {}

    # Resolve any pending parameter dependencies (constraints) after all objects are loaded
    resolve_all_parameter_dependencies(self)

load_as_dataset(fname)

Load data from an ORSO .ort file as a DataSet1D.

Source code in src/easyreflectometry/data/measurement.py
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
def load_as_dataset(fname: Union[TextIO, str]) -> DataSet1D:
    """Load data from an ORSO .ort file as a DataSet1D."""
    data_group = load(fname)
    basename = os.path.splitext(os.path.basename(fname))[0]
    data_name = 'R_' + basename
    coords_name = 'Qz_' + basename
    coords_name = list(data_group['coords'].keys())[0] if coords_name not in data_group['coords'] else coords_name
    data_name = list(data_group['data'].keys())[0] if data_name not in data_group['data'] else data_name
    dataset = DataSet1D(
        x=data_group['coords'][coords_name].values,
        y=data_group['data'][data_name].values,
        ye=data_group['data'][data_name].variances,
        xe=data_group['coords'][coords_name].variances,
    )
    return dataset

extract_orso_title(data_group, data_name)

Extract orso title.

Source code in src/easyreflectometry/data/measurement.py
47
48
49
50
51
52
53
54
55
56
57
def extract_orso_title(data_group: sc.DataGroup, data_name: str) -> str | None:
    """Extract orso title."""
    try:
        header = data_group['attrs'][data_name]['orso_header']
        title = header.values.get('data_source', {}).get('experiment', {}).get('title')
    except (AttributeError, KeyError, TypeError):
        return None
    if title is None:
        return None
    title_str = str(title).strip()
    return title_str or None

load_data_from_orso_file(fname)

Load data from an ORSO file.

Source code in src/easyreflectometry/orso_utils.py
45
46
47
48
49
50
51
def load_data_from_orso_file(fname: str) -> sc.DataGroup:
    """Load data from an ORSO file."""
    try:
        orso_data = orso.load_orso(fname)
    except Exception as e:
        raise ValueError(f'Error loading ORSO file: {e}')
    return load_orso_data(orso_data)

apply_default_limits(parameter, kind)

Apply default min/max to a parameter if current bounds are infinite.

Parameters:

Name Type Description Default
parameter Parameter

The parameter to adjust.

required
kind str

One of 'thickness', 'roughness', 'sld', 'isld', 'scale'.

required
Source code in src/easyreflectometry/limits.py
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
def apply_default_limits(parameter: Parameter, kind: str) -> None:
    """Apply default min/max to a parameter if current bounds are infinite.

    Parameters
    ----------
    parameter : Parameter
        The parameter to adjust.
    kind : str
        One of 'thickness', 'roughness', 'sld', 'isld', 'scale'.
    """
    if not parameter.independent:
        return

    if kind in ('thickness', 'roughness'):
        _apply_percentage_limits(parameter)
    elif kind in ('sld', 'isld'):
        _apply_fixed_limits(parameter, *SLD_LIMITS)
    elif kind == 'scale':
        _apply_fixed_limits(parameter, *SCALE_LIMITS)