Skip to content

Calculators

The calculator translates an EasyReflectometry model into a backend engine (refl1d or refnx) and computes reflectivity.

Polarized reflectivity

With the refl1d calculator and include_magnetism enabled, all four spin channels are available:

  • polarized_reflectivity_profiles(x_array, model_id) returns the reflectivity of all four channels as a dictionary keyed 'pp', 'pm', 'mp', 'mm' (in that order).
  • polarization_channel selects which channel reflectity_profile — and hence fitting — uses (default 'pp').
  • magnetic_sld_profile(model_id) returns the nuclear and magnetic scattering length density profiles as a tuple z, sld(z), rhoM(z) (magnetic SLD) and thetaM(z) (magnetic angle).

Note that polarization_channel is state of the currently active calculator instance, not of a model or dataset: it affects every subsequent calculation using that calculator, and switching calculators via the factory constructs a fresh instance, which resets the channel (along with include_magnetism). Calculators without magnetism support (refnx) raise NotImplementedError when magnetism is enabled.

polarization

POLARIZATION_CHANNEL_TO_INDEX = {PolarizationChannel.PP: 3, PolarizationChannel.PM: 2, PolarizationChannel.MP: 1, PolarizationChannel.MM: 0} module-attribute

PolarizationChannel

Bases: str, Enum

Spin cross-section channels for polarized neutron reflectometry.

The accepted spellings are exactly the enum values ('pp', 'pm', 'mp', 'mm'); uppercase strings are rejected.

Source code in src/easyreflectometry/calculators/polarization.py
 7
 8
 9
10
11
12
13
14
15
16
17
class PolarizationChannel(str, Enum):
    """Spin cross-section channels for polarized neutron reflectometry.

    The accepted spellings are exactly the enum values ('pp', 'pm', 'mp', 'mm');
    uppercase strings are rejected.
    """

    PP = 'pp'  # non-spin-flip, up-up
    PM = 'pm'  # spin-flip, up-down
    MP = 'mp'  # spin-flip, down-up
    MM = 'mm'  # non-spin-flip, down-down

calculator_base

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
 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
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,
        guide_field_angle: Union[Parameter, Number, None] = None,
        applied_field: Union[Parameter, Number, None] = 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.
        guide_field_angle : Union[Parameter, Number, None], optional
            Field angle about the beam axis in degrees (refl1d ``Aguide``). By default, 270 (in-plane).
        applied_field : Union[Parameter, Number, None], optional
            Applied field in tesla (refl1d ``H``). By default, 0.
        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)
        guide_field_angle = get_as_parameter('guide_field_angle', guide_field_angle, DEFAULTS)
        applied_field = get_as_parameter('applied_field', applied_field, 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
        self._guide_field_angle = guide_field_angle
        self._applied_field = applied_field

        # Derived, read-only "calculation" parameter (see `total_thickness`).
        # Rebuilt by every constructor call — including `from_dict` — and
        # deliberately *not* serialized: it is a function of the layers.
        self._total_thickness = Parameter(
            display_name='total_thickness',
            value=0.0,
            unit='angstrom',
            fixed=True,
            description='Total thickness of the film: the sum of all layer thicknesses '
            'between the superphase and the subphase (derived, read-only).',
        )
        self._total_thickness_sources: list[Parameter] = []
        self.refresh_derived()

        # 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

    @property
    def guide_field_angle(self) -> Parameter:
        """Field angle about the beam axis in degrees (refl1d ``Aguide``); only magnetic calculators use it."""
        return self._guide_field_angle

    @guide_field_angle.setter
    def guide_field_angle(self, value: float) -> None:
        self._guide_field_angle.value = value

    @property
    def applied_field(self) -> Parameter:
        """Applied field in tesla (refl1d ``H``); only magnetic calculators use it."""
        return self._applied_field

    @applied_field.setter
    def applied_field(self, value: float) -> None:
        self._applied_field.value = value

    # ----- derived parameters -----

    def _film_layers(self) -> list:
        """Layers between the superphase and the subphase (first and last layer of the sample)."""
        layers = [layer for assembly in self.sample for layer in assembly.layers]
        return layers[1:-1] if len(layers) >= 3 else []

    def refresh_derived(self) -> None:
        """Re-derive the model's computed parameters from the current layer structure.

        Cheap (a few string operations) and idempotent: the dependency is
        only rebuilt when the set of contributing layers changed. Called on
        every access to :attr:`total_thickness`, so layers added or removed
        through *any* path (`Model.add_assemblies`, `assembly.layers.append`,
        ...) are picked up without explicit notification.
        """
        sources = [layer.thickness for layer in self._film_layers()]
        current = self._total_thickness_sources
        if len(sources) == len(current) and all(a is b for a, b in zip(sources, current)):
            return
        self._total_thickness_sources = sources
        total = self._total_thickness
        if not sources:
            if not total.independent:
                total.make_independent()
            # `make_dependent_on` clears `fixed`, and `make_independent` does not
            # put it back; without this the parameter would resurface as a free
            # fit parameter once the film is emptied.
            total.fixed = True
            total.value = 0.0
            return
        dependency_map = {f't{index}': source for index, source in enumerate(sources)}
        total.make_dependent_on(
            dependency_expression=' + '.join(dependency_map.keys()),
            dependency_map=dependency_map,
        )

    @property
    def total_thickness(self) -> Parameter:
        """Read-only parameter: the summed thickness of the film layers.

        The superphase (first layer of the sample) and the subphase (last
        layer) are semi-infinite and excluded. The parameter is *dependent*:
        it tracks the layer thicknesses, never enters a fit and cannot be
        set; it can be referenced from constraint expressions and
        inequality constraints like any other parameter.
        """
        self.refresh_derived()
        return self._total_thickness

    # ----- 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()
        else:
            for assembly in assemblies:
                if issubclass(assembly.__class__, BaseAssembly):
                    self.sample.add_assembly(assembly)
                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
            Index of the item or layer to duplicate.
        """
        self.sample.duplicate_assembly(index)

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

        Parameters
        ----------
        index : int
            Index of the item to remove.
        """
        self.sample.remove_assembly(index)

    @property
    def has_magnetism(self) -> bool:
        """Whether any layer in the sample carries magnetic properties."""
        return any(getattr(layer, 'magnetism', None) is not None for assembly in self.sample for layer in assembly.layers)

    @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:
            # Registered per model: one calculator serves every model of a
            # project, each possibly with a different resolution.
            self.interface().set_resolution_function(self._resolution_function, self.unique_name)

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

    def generate_bindings(self) -> None:
        """Propagate the interface over the sample tree, then register this
        model's resolution function on the calculator.

        Runs on every interface assignment and on every engine switch (the
        project regenerates bindings on a fresh calculator then), so the new
        calculator always knows this model's resolution.
        """
        super().generate_bindings()
        self._interface().set_resolution_function(self._resolution_function, self.unique_name)

    # ----- 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:
        """The sample as an ORSO simple-model (``sample.model``) dictionary.

        Slab representation: lengths in angstrom, SLDs in 1/angstrom^2,
        repeating multilayers via the inline ``N ( ... )`` stack syntax.

        Returns
        -------
        dict
            The ORSO model-language dictionary (the content of an .ort file's
            ``data_source.sample.model`` section).
        """
        # Circular import if hoisted to module-top.
        from orsopy.fileio import Header

        from easyreflectometry.orso_utils import sample_to_orso_model

        if self.guide_field_angle.value != 270.0 or self.applied_field.value != 0.0:
            warnings.warn(
                'The guide field angle and applied field are not written: the ORSO model language has no field.',
                UserWarning,
                stacklevel=2,
            )
        return Header.asdict(sample_to_orso_model(self.sample))

    @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

guide_field_angle property writable

Field angle about the beam axis in degrees (refl1d Aguide); only magnetic calculators use it.

applied_field property writable

Applied field in tesla (refl1d H); only magnetic calculators use it.

total_thickness property

Read-only parameter: the summed thickness of the film layers.

The superphase (first layer of the sample) and the subphase (last layer) are semi-infinite and excluded. The parameter is dependent: it tracks the layer thicknesses, never enters a fit and cannot be set; it can be referenced from constraint expressions and inequality constraints like any other parameter.

has_magnetism property

Whether any layer in the sample carries magnetic properties.

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, guide_field_angle=None, applied_field=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
guide_field_angle Union[Parameter, Number, None]

Field angle about the beam axis in degrees (refl1d Aguide). By default, 270 (in-plane).

None
applied_field Union[Parameter, Number, None]

Applied field in tesla (refl1d H). By default, 0.

None
interface

Calculator interface. By default, None.

None
Source code in src/easyreflectometry/model/model.py
 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
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,
    guide_field_angle: Union[Parameter, Number, None] = None,
    applied_field: Union[Parameter, Number, None] = 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.
    guide_field_angle : Union[Parameter, Number, None], optional
        Field angle about the beam axis in degrees (refl1d ``Aguide``). By default, 270 (in-plane).
    applied_field : Union[Parameter, Number, None], optional
        Applied field in tesla (refl1d ``H``). By default, 0.
    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)
    guide_field_angle = get_as_parameter('guide_field_angle', guide_field_angle, DEFAULTS)
    applied_field = get_as_parameter('applied_field', applied_field, 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
    self._guide_field_angle = guide_field_angle
    self._applied_field = applied_field

    # Derived, read-only "calculation" parameter (see `total_thickness`).
    # Rebuilt by every constructor call — including `from_dict` — and
    # deliberately *not* serialized: it is a function of the layers.
    self._total_thickness = Parameter(
        display_name='total_thickness',
        value=0.0,
        unit='angstrom',
        fixed=True,
        description='Total thickness of the film: the sum of all layer thicknesses '
        'between the superphase and the subphase (derived, read-only).',
    )
    self._total_thickness_sources: list[Parameter] = []
    self.refresh_derived()

    # 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

refresh_derived()

Re-derive the model's computed parameters from the current layer structure.

Cheap (a few string operations) and idempotent: the dependency is only rebuilt when the set of contributing layers changed. Called on every access to :attr:total_thickness, so layers added or removed through any path (Model.add_assemblies, assembly.layers.append, ...) are picked up without explicit notification.

Source code in src/easyreflectometry/model/model.py
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
def refresh_derived(self) -> None:
    """Re-derive the model's computed parameters from the current layer structure.

    Cheap (a few string operations) and idempotent: the dependency is
    only rebuilt when the set of contributing layers changed. Called on
    every access to :attr:`total_thickness`, so layers added or removed
    through *any* path (`Model.add_assemblies`, `assembly.layers.append`,
    ...) are picked up without explicit notification.
    """
    sources = [layer.thickness for layer in self._film_layers()]
    current = self._total_thickness_sources
    if len(sources) == len(current) and all(a is b for a, b in zip(sources, current)):
        return
    self._total_thickness_sources = sources
    total = self._total_thickness
    if not sources:
        if not total.independent:
            total.make_independent()
        # `make_dependent_on` clears `fixed`, and `make_independent` does not
        # put it back; without this the parameter would resurface as a free
        # fit parameter once the film is emptied.
        total.fixed = True
        total.value = 0.0
        return
    dependency_map = {f't{index}': source for index, source in enumerate(sources)}
    total.make_dependent_on(
        dependency_expression=' + '.join(dependency_map.keys()),
        dependency_map=dependency_map,
    )

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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
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()
    else:
        for assembly in assemblies:
            if issubclass(assembly.__class__, BaseAssembly):
                self.sample.add_assembly(assembly)
            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

Index of the item or layer to duplicate.

required
Source code in src/easyreflectometry/model/model.py
281
282
283
284
285
286
287
288
289
def duplicate_assembly(self, index: int) -> None:
    """Duplicate a given item or layer in a sample.

    Parameters
    ----------
    index : int
        Index of the item or layer to duplicate.
    """
    self.sample.duplicate_assembly(index)

remove_assembly(index)

Remove an assembly from the model.

Parameters:

Name Type Description Default
index int

Index of the item to remove.

required
Source code in src/easyreflectometry/model/model.py
291
292
293
294
295
296
297
298
299
def remove_assembly(self, index: int) -> None:
    """Remove an assembly from the model.

    Parameters
    ----------
    index : int
        Index of the item to remove.
    """
    self.sample.remove_assembly(index)

generate_bindings()

Propagate the interface over the sample tree, then register this model's resolution function on the calculator.

Runs on every interface assignment and on every engine switch (the project regenerates bindings on a fresh calculator then), so the new calculator always knows this model's resolution.

Source code in src/easyreflectometry/model/model.py
334
335
336
337
338
339
340
341
342
343
def generate_bindings(self) -> None:
    """Propagate the interface over the sample tree, then register this
    model's resolution function on the calculator.

    Runs on every interface assignment and on every engine switch (the
    project regenerates bindings on a fresh calculator then), so the new
    calculator always knows this model's resolution.
    """
    super().generate_bindings()
    self._interface().set_resolution_function(self._resolution_function, 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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
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
383
384
385
def as_dict(self, skip: Optional[list[str]] = None) -> dict:
    """Compatibility alias for :meth:`to_dict`."""
    return self.to_dict(skip=skip)

as_orso()

The sample as an ORSO simple-model (sample.model) dictionary.

Slab representation: lengths in angstrom, SLDs in 1/angstrom^2, repeating multilayers via the inline N ( ... ) stack syntax.

Returns:

Type Description
dict

The ORSO model-language dictionary (the content of an .ort file's data_source.sample.model section).

Source code in src/easyreflectometry/model/model.py
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
def as_orso(self) -> dict:
    """The sample as an ORSO simple-model (``sample.model``) dictionary.

    Slab representation: lengths in angstrom, SLDs in 1/angstrom^2,
    repeating multilayers via the inline ``N ( ... )`` stack syntax.

    Returns
    -------
    dict
        The ORSO model-language dictionary (the content of an .ort file's
        ``data_source.sample.model`` section).
    """
    # Circular import if hoisted to module-top.
    from orsopy.fileio import Header

    from easyreflectometry.orso_utils import sample_to_orso_model

    if self.guide_field_angle.value != 270.0 or self.applied_field.value != 0.0:
        warnings.warn(
            'The guide field angle and applied field are not written: the ORSO model language has no field.',
            UserWarning,
            stacklevel=2,
        )
    return Header.asdict(sample_to_orso_model(self.sample))

from_dict(passed_dict) classmethod

Create a Model from a dictionary.

Source code in src/easyreflectometry/model/model.py
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
@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

ResolutionFunction

Source code in src/easyreflectometry/model/resolution_functions.py
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
class ResolutionFunction:
    @abstractmethod
    def smearing(self, q: Union[np.array, float]) -> np.array:
        """Return the resolution as sigma (standard deviation) at each ``q``."""
        ...

    @abstractmethod
    def as_dict(self, skip: Optional[List[str]] = None) -> dict: ...

    @classmethod
    def from_dict(cls, data: dict) -> ResolutionFunction:
        """Smearing function."""
        if data['smearing'] == 'PercentageFwhm':
            return PercentageFwhm(data['constant'])
        if data['smearing'] == 'LinearSpline':
            return LinearSpline(data['q_data_points'], data['fwhm_values'])
        if data['smearing'] == 'Pointwise':
            return Pointwise([
                data['q_data_points'],
                data['R_data_points'],
                data['sQz_data_points'],
            ])
        raise ValueError('Unknown resolution function type')

smearing(q) abstractmethod

Return the resolution as sigma (standard deviation) at each q.

Source code in src/easyreflectometry/model/resolution_functions.py
35
36
37
38
@abstractmethod
def smearing(self, q: Union[np.array, float]) -> np.array:
    """Return the resolution as sigma (standard deviation) at each ``q``."""
    ...

from_dict(data) classmethod

Smearing function.

Source code in src/easyreflectometry/model/resolution_functions.py
43
44
45
46
47
48
49
50
51
52
53
54
55
56
@classmethod
def from_dict(cls, data: dict) -> ResolutionFunction:
    """Smearing function."""
    if data['smearing'] == 'PercentageFwhm':
        return PercentageFwhm(data['constant'])
    if data['smearing'] == 'LinearSpline':
        return LinearSpline(data['q_data_points'], data['fwhm_values'])
    if data['smearing'] == 'Pointwise':
        return Pointwise([
            data['q_data_points'],
            data['R_data_points'],
            data['sQz_data_points'],
        ])
    raise ValueError('Unknown resolution function type')

CalculatorBase

A calculator: a thin layer over its wrapper, which reads the models it serves.

Every non-abstract subclass registers itself in _calculators and so becomes available in :class:CalculatorFactory.

Source code in src/easyreflectometry/calculators/calculator_base.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
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
class CalculatorBase(metaclass=ABCMeta):
    """A calculator: a thin layer over its wrapper, which reads the models it serves.

    Every non-abstract subclass registers itself in ``_calculators`` and so
    becomes available in :class:`CalculatorFactory`.
    """

    _calculators: list[type[CalculatorBase]] = []  # class variable to store all calculators

    def __init_subclass__(cls, is_abstract: bool = False, **kwargs) -> None:
        r"""Register every subclass, unless *is_abstract*, so that the factory can create it."""
        super().__init_subclass__(**kwargs)
        if not is_abstract:
            cls._calculators.append(cls)

    def __init__(self):
        """Init function."""
        self._wrapper = None  # set by each subclass

    # ----- membership -----

    def bind(self, obj) -> None:
        """Called for every object of a sample tree attached to this calculator; only models are kept."""
        if isinstance(obj, Model):
            self.register_model(obj)

    def register_model(self, model: Model) -> None:
        """Serve *model*."""
        self._wrapper.register_model(model)

    def discard_model(self, model_id: str) -> None:
        """Stop serving the model with *model_id*."""
        self._wrapper.discard_model(model_id)

    def reset_storage(self) -> None:
        """Stop serving every model."""
        self._wrapper.reset_storage()

    @property
    def models(self) -> dict[str, Model]:
        """The models served, keyed by ``unique_name``."""
        return self._wrapper.models

    def reconcile_magnetism(self) -> None:
        """Switch `include_magnetism` off when the served models have just stopped being magnetic."""
        self._wrapper.reconcile_magnetism()

    # ----- evaluation -----

    def _before_evaluation(self) -> None:
        """Run at the start of every evaluation and profile.

        Covers structural removals (a magnetic layer, an assembly) that nothing
        reports to the calculator.
        """
        self.reconcile_magnetism()

    def reflectity_profile(
        self,
        x_array: np.ndarray,
        model_id: str,
        resolution_function: ResolutionFunction | None = None,
    ) -> np.ndarray:
        """Determines the reflectivity profile for the given range and model.

        Parameters
        ----------
        x_array : np.ndarray
            Points to be calculated at.
        model_id : str
            The model id.
        resolution_function : ResolutionFunction | None, optional
            Resolution to smear with; by default the one registered for the
            model through :meth:`set_resolution_function`.
        """
        self._before_evaluation()
        return self._wrapper.calculate(x_array, model_id, resolution_function=resolution_function)

    def reflectivity_profile_channel(
        self,
        x_array: np.ndarray,
        model_id: str,
        channel,
        resolution_function: ResolutionFunction | None = None,
    ) -> np.ndarray:
        """Determine the reflectivity profile of one explicit spin channel.

        Unlike `polarization_channel` (global calculator state), the channel is an
        argument, so several channels can be evaluated against the same model —
        one per dataset in a simultaneous multi-channel fit.

        Parameters
        ----------
        x_array : np.ndarray
            Points to be calculated at.
        model_id : str
            The model id.
        channel : PolarizationChannel | str
            One of 'pp', 'pm', 'mp', 'mm' (or the corresponding enum member).
        resolution_function : ResolutionFunction | None, optional
            Resolution to smear with; by default the one registered for the model.

        Returns
        -------
        np.ndarray
            Reflectivity of the requested channel at q.
        """
        self._before_evaluation()
        return self._wrapper.calculate_channel(x_array, model_id, channel, resolution_function=resolution_function)

    def polarized_reflectivity_profiles(
        self,
        x_array: np.ndarray,
        model_id: str,
        resolution_function: ResolutionFunction | None = None,
    ) -> dict[str, np.ndarray]:
        """Determines the reflectivity profiles of all four spin channels for the given range and model.

        Requires `include_magnetism` to be enabled and a calculator that supports it (refl1d).

        Parameters
        ----------
        x_array : np.ndarray
            Points to be calculated at.
        model_id : str
            The model id.
        resolution_function : ResolutionFunction | None, optional
            Resolution to smear with; by default the one registered for the model.

        Returns
        -------
        dict[str, np.ndarray]
            Reflectivity per spin channel, keyed 'pp', 'pm', 'mp', 'mm' (in that order).
        """
        self._before_evaluation()
        return self._wrapper.calculate_polarized(x_array, model_id, resolution_function=resolution_function)

    def sld_profile(self, model_id: str) -> tuple[np.ndarray, np.ndarray]:
        """Return the scattering length density profile.

        Parameters
        ----------
        model_id : str
            The model id.

        Returns
        -------
        tuple[np.ndarray, np.ndarray]
            z and sld(z).
        """
        self._before_evaluation()
        return self._wrapper.sld_profile(model_id)

    def magnetic_sld_profile(self, model_id: str) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
        """Return the nuclear and magnetic scattering length density profiles.

        Requires `include_magnetism` to be enabled and a calculator that supports it (refl1d).

        Parameters
        ----------
        model_id : str
            The model id.

        Returns
        -------
        tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]
            z, sld(z), magnetic sld rhoM(z) and magnetic angle thetaM(z).
        """
        self._before_evaluation()
        return self._wrapper.magnetic_sld_profile(model_id)

    def set_resolution_function(self, resolution_function: ResolutionFunction, model_id: str | None = None) -> None:
        """Set the resolution function of one model, or the default for all others.

        Parameters
        ----------
        resolution_function : ResolutionFunction
            The resolution function.
        model_id : str | None, optional
            The model id. ``None`` sets the default used by every model that
            has not registered a resolution of its own.
        """
        return self._wrapper.set_resolution_function(resolution_function, model_id)

    def resolution_function_for(self, model_id: str | None = None) -> ResolutionFunction:
        """The resolution function used when calculating the model with *model_id*."""
        return self._wrapper.resolution_function_for(model_id)

    @property
    def supports_magnetism(self) -> bool:
        """Whether this calculator backend can model magnetic samples."""
        return self._wrapper.supports_magnetism

    @property
    def include_magnetism(self):
        """Include magnetism."""
        return self._wrapper.magnetism

    @include_magnetism.setter
    def include_magnetism(self, magnetism: bool):
        """Set the magnetism flag for the calculator.

        It stays as set until the served models stop being magnetic (see
        :meth:`reconcile_magnetism`).

        Parameters
        ----------
        magnetism : bool
            True if the calculator should include magnetism.
        """
        self._wrapper.magnetism = magnetism

    @property
    def polarization_channel(self):
        """The spin channel ('pp', 'pm', 'mp' or 'mm') used by `reflectity_profile` when magnetism is enabled.

        Note: this state belongs to the currently-active calculator instance; switching
        calculators via the factory constructs a fresh instance and resets it.
        """
        return self._wrapper.polarization_channel

    @polarization_channel.setter
    def polarization_channel(self, channel) -> None:
        """Set the spin channel for reflectivity calculations.

        Parameters
        ----------
        channel : PolarizationChannel | str
            One of 'pp', 'pm', 'mp', 'mm' (or the corresponding enum member).
        """
        self._wrapper.polarization_channel = channel

models property

The models served, keyed by unique_name.

supports_magnetism property

Whether this calculator backend can model magnetic samples.

include_magnetism property writable

Include magnetism.

polarization_channel property writable

The spin channel ('pp', 'pm', 'mp' or 'mm') used by reflectity_profile when magnetism is enabled.

Note: this state belongs to the currently-active calculator instance; switching calculators via the factory constructs a fresh instance and resets it.

__init_subclass__(is_abstract=False, **kwargs)

Register every subclass, unless is_abstract, so that the factory can create it.

Source code in src/easyreflectometry/calculators/calculator_base.py
23
24
25
26
27
def __init_subclass__(cls, is_abstract: bool = False, **kwargs) -> None:
    r"""Register every subclass, unless *is_abstract*, so that the factory can create it."""
    super().__init_subclass__(**kwargs)
    if not is_abstract:
        cls._calculators.append(cls)

__init__()

Init function.

Source code in src/easyreflectometry/calculators/calculator_base.py
29
30
31
def __init__(self):
    """Init function."""
    self._wrapper = None  # set by each subclass

bind(obj)

Called for every object of a sample tree attached to this calculator; only models are kept.

Source code in src/easyreflectometry/calculators/calculator_base.py
35
36
37
38
def bind(self, obj) -> None:
    """Called for every object of a sample tree attached to this calculator; only models are kept."""
    if isinstance(obj, Model):
        self.register_model(obj)

register_model(model)

Serve model.

Source code in src/easyreflectometry/calculators/calculator_base.py
40
41
42
def register_model(self, model: Model) -> None:
    """Serve *model*."""
    self._wrapper.register_model(model)

discard_model(model_id)

Stop serving the model with model_id.

Source code in src/easyreflectometry/calculators/calculator_base.py
44
45
46
def discard_model(self, model_id: str) -> None:
    """Stop serving the model with *model_id*."""
    self._wrapper.discard_model(model_id)

reset_storage()

Stop serving every model.

Source code in src/easyreflectometry/calculators/calculator_base.py
48
49
50
def reset_storage(self) -> None:
    """Stop serving every model."""
    self._wrapper.reset_storage()

reconcile_magnetism()

Switch include_magnetism off when the served models have just stopped being magnetic.

Source code in src/easyreflectometry/calculators/calculator_base.py
57
58
59
def reconcile_magnetism(self) -> None:
    """Switch `include_magnetism` off when the served models have just stopped being magnetic."""
    self._wrapper.reconcile_magnetism()

reflectity_profile(x_array, model_id, resolution_function=None)

Determines the reflectivity profile for the given range and model.

Parameters:

Name Type Description Default
x_array np.ndarray

Points to be calculated at.

required
model_id str

The model id.

required
resolution_function ResolutionFunction | None

Resolution to smear with; by default the one registered for the model through :meth:set_resolution_function.

None
Source code in src/easyreflectometry/calculators/calculator_base.py
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
def reflectity_profile(
    self,
    x_array: np.ndarray,
    model_id: str,
    resolution_function: ResolutionFunction | None = None,
) -> np.ndarray:
    """Determines the reflectivity profile for the given range and model.

    Parameters
    ----------
    x_array : np.ndarray
        Points to be calculated at.
    model_id : str
        The model id.
    resolution_function : ResolutionFunction | None, optional
        Resolution to smear with; by default the one registered for the
        model through :meth:`set_resolution_function`.
    """
    self._before_evaluation()
    return self._wrapper.calculate(x_array, model_id, resolution_function=resolution_function)

reflectivity_profile_channel(x_array, model_id, channel, resolution_function=None)

Determine the reflectivity profile of one explicit spin channel.

Unlike polarization_channel (global calculator state), the channel is an argument, so several channels can be evaluated against the same model — one per dataset in a simultaneous multi-channel fit.

Parameters:

Name Type Description Default
x_array np.ndarray

Points to be calculated at.

required
model_id str

The model id.

required
channel PolarizationChannel | str

One of 'pp', 'pm', 'mp', 'mm' (or the corresponding enum member).

required
resolution_function ResolutionFunction | None

Resolution to smear with; by default the one registered for the model.

None

Returns:

Type Description
np.ndarray

Reflectivity of the requested channel at q.

Source code in src/easyreflectometry/calculators/calculator_base.py
 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
def reflectivity_profile_channel(
    self,
    x_array: np.ndarray,
    model_id: str,
    channel,
    resolution_function: ResolutionFunction | None = None,
) -> np.ndarray:
    """Determine the reflectivity profile of one explicit spin channel.

    Unlike `polarization_channel` (global calculator state), the channel is an
    argument, so several channels can be evaluated against the same model —
    one per dataset in a simultaneous multi-channel fit.

    Parameters
    ----------
    x_array : np.ndarray
        Points to be calculated at.
    model_id : str
        The model id.
    channel : PolarizationChannel | str
        One of 'pp', 'pm', 'mp', 'mm' (or the corresponding enum member).
    resolution_function : ResolutionFunction | None, optional
        Resolution to smear with; by default the one registered for the model.

    Returns
    -------
    np.ndarray
        Reflectivity of the requested channel at q.
    """
    self._before_evaluation()
    return self._wrapper.calculate_channel(x_array, model_id, channel, resolution_function=resolution_function)

polarized_reflectivity_profiles(x_array, model_id, resolution_function=None)

Determines the reflectivity profiles of all four spin channels for the given range and model.

Requires include_magnetism to be enabled and a calculator that supports it (refl1d).

Parameters:

Name Type Description Default
x_array np.ndarray

Points to be calculated at.

required
model_id str

The model id.

required
resolution_function ResolutionFunction | None

Resolution to smear with; by default the one registered for the model.

None

Returns:

Type Description
dict[str, np.ndarray]

Reflectivity per spin channel, keyed 'pp', 'pm', 'mp', 'mm' (in that order).

Source code in src/easyreflectometry/calculators/calculator_base.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 polarized_reflectivity_profiles(
    self,
    x_array: np.ndarray,
    model_id: str,
    resolution_function: ResolutionFunction | None = None,
) -> dict[str, np.ndarray]:
    """Determines the reflectivity profiles of all four spin channels for the given range and model.

    Requires `include_magnetism` to be enabled and a calculator that supports it (refl1d).

    Parameters
    ----------
    x_array : np.ndarray
        Points to be calculated at.
    model_id : str
        The model id.
    resolution_function : ResolutionFunction | None, optional
        Resolution to smear with; by default the one registered for the model.

    Returns
    -------
    dict[str, np.ndarray]
        Reflectivity per spin channel, keyed 'pp', 'pm', 'mp', 'mm' (in that order).
    """
    self._before_evaluation()
    return self._wrapper.calculate_polarized(x_array, model_id, resolution_function=resolution_function)

sld_profile(model_id)

Return the scattering length density profile.

Parameters:

Name Type Description Default
model_id str

The model id.

required

Returns:

Type Description
tuple[np.ndarray, np.ndarray]

z and sld(z).

Source code in src/easyreflectometry/calculators/calculator_base.py
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
def sld_profile(self, model_id: str) -> tuple[np.ndarray, np.ndarray]:
    """Return the scattering length density profile.

    Parameters
    ----------
    model_id : str
        The model id.

    Returns
    -------
    tuple[np.ndarray, np.ndarray]
        z and sld(z).
    """
    self._before_evaluation()
    return self._wrapper.sld_profile(model_id)

magnetic_sld_profile(model_id)

Return the nuclear and magnetic scattering length density profiles.

Requires include_magnetism to be enabled and a calculator that supports it (refl1d).

Parameters:

Name Type Description Default
model_id str

The model id.

required

Returns:

Type Description
tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]

z, sld(z), magnetic sld rhoM(z) and magnetic angle thetaM(z).

Source code in src/easyreflectometry/calculators/calculator_base.py
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
def magnetic_sld_profile(self, model_id: str) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
    """Return the nuclear and magnetic scattering length density profiles.

    Requires `include_magnetism` to be enabled and a calculator that supports it (refl1d).

    Parameters
    ----------
    model_id : str
        The model id.

    Returns
    -------
    tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]
        z, sld(z), magnetic sld rhoM(z) and magnetic angle thetaM(z).
    """
    self._before_evaluation()
    return self._wrapper.magnetic_sld_profile(model_id)

set_resolution_function(resolution_function, model_id=None)

Set the resolution function of one model, or the default for all others.

Parameters:

Name Type Description Default
resolution_function ResolutionFunction

The resolution function.

required
model_id str | None

The model id. None sets the default used by every model that has not registered a resolution of its own.

None
Source code in src/easyreflectometry/calculators/calculator_base.py
185
186
187
188
189
190
191
192
193
194
195
196
def set_resolution_function(self, resolution_function: ResolutionFunction, model_id: str | None = None) -> None:
    """Set the resolution function of one model, or the default for all others.

    Parameters
    ----------
    resolution_function : ResolutionFunction
        The resolution function.
    model_id : str | None, optional
        The model id. ``None`` sets the default used by every model that
        has not registered a resolution of its own.
    """
    return self._wrapper.set_resolution_function(resolution_function, model_id)

resolution_function_for(model_id=None)

The resolution function used when calculating the model with model_id.

Source code in src/easyreflectometry/calculators/calculator_base.py
198
199
200
def resolution_function_for(self, model_id: str | None = None) -> ResolutionFunction:
    """The resolution function used when calculating the model with *model_id*."""
    return self._wrapper.resolution_function_for(model_id)