Skip to content

analysis

Analysis

Bases: AnalysisBase

For analysing two-dimensional data, i.e. intensity as function of energy and Q. Supports independent fits of each Q value and simultaneous fits of all Q.

Parameters:

Name Type Description Default
display_name str

Display name of the analysis.

'MyAnalysis'
unique_name str or None

Unique name of the analysis. If None, a unique name is automatically generated.

None
experiment Experiment | None

The Experiment associated with this Analysis. If None, a default Experiment is created.

None
sample_model SampleModel | None

The SampleModel associated with this Analysis. If None, a default SampleModel is created.

None
instrument_model InstrumentModel | None

The InstrumentModel associated with this Analysis. If None, a default InstrumentModel is created.

None
extra_parameters Parameter | list[Parameter] | None

Extra parameters to be included in the analysis for advanced users. If None, no extra parameters are added.

None

Attributes:

Name Type Description
experiment Experiment

The Experiment associated with this Analysis.

sample_model SampleModel

The SampleModel associated with this Analysis.

instrument_model InstrumentModel

The InstrumentModel associated with this Analysis.

Q Variable | None

The Q values from the associated Experiment, if available.

energy Variable | None

The energy values from the associated Experiment, if available.

temperature Parameter | None

The temperature from the associated SampleModel, if available.

extra_parameters list[Parameter]

The extra parameters included in this Analysis.

Source code in src/easydynamics/analysis/analysis.py
 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
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
class Analysis(AnalysisBase):
    """For analysing two-dimensional data, i.e. intensity as function of
    energy and Q. Supports independent fits of each Q value and
    simultaneous fits of all Q.

    Args:
        display_name (str): Display name of the analysis.
        unique_name (str or None): Unique name of the analysis. If None,
            a unique name is automatically generated.
        experiment (Experiment | None): The Experiment associated with
            this Analysis. If None, a default Experiment is created.
        sample_model (SampleModel | None): The SampleModel associated
            with this Analysis. If None, a default SampleModel is
            created.
        instrument_model (InstrumentModel | None): The InstrumentModel
            associated with this Analysis. If None, a default
            InstrumentModel is created.
        extra_parameters (Parameter | list[Parameter] | None): Extra
            parameters to be included in the analysis for advanced
            users. If None, no extra parameters are added.

    Attributes:
        experiment (Experiment): The Experiment associated with this
            Analysis.
        sample_model (SampleModel): The SampleModel associated with this
            Analysis.
        instrument_model (InstrumentModel): The InstrumentModel
            associated with this Analysis.
        Q (sc.Variable | None): The Q values from the associated
            Experiment, if available.
        energy (sc.Variable | None): The energy values from the
            associated Experiment, if available.
        temperature (Parameter | None): The temperature from the
            associated SampleModel, if available.
        extra_parameters (list[Parameter]): The extra parameters
            included in this Analysis.
    """

    def __init__(
        self,
        display_name: str = 'MyAnalysis',
        unique_name: str | None = None,
        experiment: Experiment | None = None,
        sample_model: SampleModel | None = None,
        instrument_model: InstrumentModel | None = None,
        extra_parameters: Parameter | list[Parameter] | None = None,
    ):
        """Initialize an Analysis object.

        Args:
            display_name (str): Display name of the analysis.
            unique_name (str or None): Unique name of the analysis. If
                None, a unique name is automatically generated.
            experiment (Experiment | None): The Experiment associated
                with this Analysis. If None, a default Experiment is
                created.
            sample_model (SampleModel | None): The SampleModel
                associated with this Analysis. If None, a default
                SampleModel is created.
            instrument_model (InstrumentModel | None): The
                InstrumentModel associated with this Analysis. If None,
                a default InstrumentModel is created.
            extra_parameters (Parameter | list[Parameter] | None): Extra
                parameters to be included in the analysis for advanced
                users. If None, no extra parameters are added.
        """

        # Avoid triggering updates before the object is fully
        # initialized
        self._call_updaters = False
        super().__init__(
            display_name=display_name,
            unique_name=unique_name,
            experiment=experiment,
            sample_model=sample_model,
            instrument_model=instrument_model,
            extra_parameters=extra_parameters,
        )

        self._analysis_list = []
        if self.Q is not None:
            for Q_index in range(len(self.Q)):
                analysis = Analysis1d(
                    display_name=f'{self.display_name}_Q{Q_index}',
                    unique_name=(f'{self.unique_name}_Q{Q_index}'),
                    experiment=self.experiment,
                    sample_model=self.sample_model,
                    instrument_model=self.instrument_model,
                    extra_parameters=self._extra_parameters,
                    Q_index=Q_index,
                )
                self._analysis_list.append(analysis)
        # Now we can allow updates to trigger recalculations
        self._call_updaters = True

    #############
    # Properties
    #############

    @property
    def analysis_list(self) -> list[Analysis1d]:
        """Get the Analysis1d objects associated with this Analysis.

        Returns:
            list[Analysis1d]: A list of Analysis1d objects, one for
                each Q index.
        """
        return self._analysis_list

    @analysis_list.setter
    def analysis_list(self, value: list[Analysis1d]) -> None:
        """analysis_list is read-only.

        To change the analysis list, modify the experiment, sample
        model, or instrument model.

        Raises:
            AttributeError: Always raised, since analysis_list is
                read-only.
        """

        raise AttributeError(
            'analysis_list is read-only. '
            'To change the analysis list, modify the experiment, sample model, '
            'or instrument model.'
        )

    #############
    # Other methods
    #############
    def calculate(
        self,
        Q_index: int | None = None,
    ) -> list[np.ndarray] | np.ndarray:
        """Calculate model data for a specific Q index. If Q_index is
        None, calculate for all Q indices and return a list of arrays.

        Args:
            Q_index (int or None): Index of the Q value to calculate
                for. If None, calculate for all Q values.

        Returns:
            list[np.ndarray] | np.ndarray: If Q_index is None, returns
                a list of numpy arrays, one for each Q index.
                If Q_index is an integer, returns a single numpy array
                for that Q index.

        Raises:
            IndexError: If Q_index is not None and is out of bounds.
        """

        if Q_index is None:
            return [analysis.calculate() for analysis in self.analysis_list]

        Q_index = self._verify_Q_index(Q_index)
        return self.analysis_list[Q_index].calculate()

    def fit(
        self,
        fit_method: str = 'independent',
        Q_index: int | None = None,
    ) -> FitResults | list[FitResults]:
        """Fit the model to the experimental data.

        Args:
            fit_method (str): Method to use for fitting. Options are
                "independent" (fit each Q index independently, one after
                the other) or "simultaneous" (fit all Q indices
                simultaneously). Default is "independent".
            Q_index (int or None): If fit_method is "independent",
                specify which Q index to fit. If None, fit all Q indices
                independently. Ignored if fit_method is "simultaneous".
                Default is None.

        Returns:
            FitResults: a list of FitResults if fitting independently,
                or a single FitResults object if fitting simultaneously.

        Raises:
            ValueError: If fit_method is not "independent" or
                "simultaneous"
            IndexError: If fit_method is "independent" and Q_index is
                out of bounds.
        """

        if self.Q is None:
            raise ValueError(
                'No Q values available for fitting. Please check the experiment data.'
            )

        Q_index = self._verify_Q_index(Q_index)

        if fit_method == 'independent':
            if Q_index is not None:
                return self._fit_single_Q(Q_index)
            else:
                return self._fit_all_Q_independently()
        elif fit_method == 'simultaneous':
            return self._fit_all_Q_simultaneously()
        else:
            raise ValueError("Invalid fit method. Choose 'independent' or 'simultaneous'.")

    def plot_data_and_model(
        self,
        Q_index: int | None = None,
        plot_components: bool = True,
        add_background: bool = True,
        **kwargs,
    ) -> InteractiveFigure:
        """Plot the experimental data and the model prediction.
        Optionally also plot the individual components of the model.

        Uses Plopp for plotting: https://scipp.github.io/plopp/

        Args:
            Q_index (int or None): Index of the Q value to plot. If
                None, plot all Q values. Default is None.
            plot_components (bool): Whether to plot the individual
                components. Default is True.
            add_background (bool): Whether to add background components
                to the sample model components when plotting. Default is
                True.
            **kwargs (Any): Additional keyword arguments passed to plopp
                for customizing the plot.

        Raises:
            ValueError: If Q_index is out of bounds, or if there is no
                data to plot, or if there are no Q values available for
                plotting.
            RuntimeError: If not in a Jupyter notebook environment.
            TypeError: If plot_components or add_background is not True
                or False.

        Returns:
            InteractiveFigure: A Plopp InteractiveFigure containing the
                plot of the data and model.
        """

        if Q_index is not None:
            Q_index = self._verify_Q_index(Q_index)
            return self.analysis_list[Q_index].plot_data_and_model(
                plot_components=plot_components,
                add_background=add_background,
                **kwargs,
            )

        if self.experiment.binned_data is None:
            raise ValueError('No data to plot. Please load data first.')

        if not _in_notebook():
            raise RuntimeError('plot_data() can only be used in a Jupyter notebook environment.')

        if self.Q is None:
            raise ValueError(
                'No Q values available for plotting. Please check the experiment data.'
            )

        if not isinstance(plot_components, bool):
            raise TypeError('plot_components must be True or False.')

        if not isinstance(add_background, bool):
            raise TypeError('add_background must be True or False.')

        import plopp as pp

        plot_kwargs_defaults = {
            'title': self.display_name,
            'linestyle': {'Data': 'none', 'Model': '-'},
            'marker': {'Data': 'o', 'Model': None},
            'color': {'Data': 'black', 'Model': 'red'},
            'markerfacecolor': {'Data': 'none', 'Model': 'none'},
            'keep': 'energy',
        }
        data_and_model = {
            'Data': self.experiment.binned_data,
            'Model': self._create_model_array(),
        }

        if plot_components:
            components = self._create_components_dataset(add_background=add_background)
            for key in components.keys():
                data_and_model[key] = components[key]
                plot_kwargs_defaults['linestyle'][key] = '--'
                plot_kwargs_defaults['marker'][key] = None

        # Overwrite defaults with any user-provided kwargs
        plot_kwargs_defaults.update(kwargs)

        fig = pp.slicer(
            data_and_model,
            **plot_kwargs_defaults,
        )
        return fig

    def parameters_to_dataset(self) -> sc.Dataset:
        """Creates a scipp dataset with copies of the Parameters in the
        model.

        Ensures unit consistency across Q.

        Returns:
            sc.Dataset: A dataset where each entry is a parameter, with
            dimensions "Q" and values corresponding to the parameter
            values.

        Raises:
            UnitError: If there are inconsistent units for the same
                parameter across different Q values.
        """

        ds = sc.Dataset(coords={'Q': self.Q})

        # Collect all parameter names
        all_names = {
            param.name
            for analysis in self.analysis_list
            for param in analysis.get_all_parameters()
        }

        # Storage
        values = {name: [] for name in all_names}
        variances = {name: [] for name in all_names}
        units = {}

        for analysis in self.analysis_list:
            pars = {p.name: p for p in analysis.get_all_parameters()}

            for name in all_names:
                if name in pars:
                    p = pars[name]

                    # Unit consistency check
                    if name not in units:
                        units[name] = p.unit
                    elif units[name] != p.unit:
                        try:
                            p.convert_unit(units[name])
                        except Exception as e:
                            raise UnitError(
                                f"Inconsistent units for parameter '{name}': "
                                f'{units[name]} vs {p.unit}'
                            ) from e

                    values[name].append(p.value)
                    variances[name].append(p.variance)
                else:
                    values[name].append(np.nan)
                    variances[name].append(np.nan)

        # Build dataset variables
        for name in all_names:
            ds[name] = sc.Variable(
                dims=['Q'],
                values=np.asarray(values[name], dtype=float),
                variances=np.asarray(variances[name], dtype=float),
                unit=units.get(name, None),
            )

        return ds

    def plot_parameters(
        self,
        names: str | list[str] | None = None,
        **kwargs,
    ) -> InteractiveFigure:
        """Plot fitted parameters as a function of Q.

        Args:
            names (str | list[str] | None): Name(s) of the parameter(s)
                to plot. If None, plots all parameters.
            kwargs (Any): Additional keyword arguments passed to
                plopp.slicer for customizing the plot (e.g., title,
                linestyle, marker, color).

        Returns:
            InteractiveFigure: A Plopp InteractiveFigure containing the
                plot of the parameters.
        """

        ds = self.parameters_to_dataset()

        if not names:
            names = list(ds.keys())

        if isinstance(names, str):
            names = [names]

        if not isinstance(names, list) or not all(isinstance(name, str) for name in names):
            raise TypeError('names must be a string or a list of strings.')

        for name in names:
            if name not in ds:
                raise ValueError(f"Parameter '{name}' not found in dataset.")

        data_to_plot = {name: ds[name] for name in names}
        plot_kwargs_defaults = {
            'linestyle': {name: 'none' for name in names},
            'marker': {name: 'o' for name in names},
            'markerfacecolor': {name: 'none' for name in names},
        }

        plot_kwargs_defaults.update(kwargs)

        import plopp as pp

        fig = pp.plot(
            data_to_plot,
            **plot_kwargs_defaults,
        )
        return fig

    #############
    # Private methods - updating models when things change
    #############

    def _on_experiment_changed(self) -> None:
        """Update the Q values in the sample and instrument models when
        the experiment changes.

        Also update all the Analysi1d objects with the new experiment.
        """
        if self._call_updaters:
            super()._on_experiment_changed()
            for analysis in self.analysis_list:
                analysis.experiment = self.experiment

    def _on_sample_model_changed(self) -> None:
        """Update the Q values in the sample model when the sample model
        changes.

        Also update all the Analysi1d objects with the new sample model.
        """
        if self._call_updaters:
            super()._on_sample_model_changed()
            for analysis in self.analysis_list:
                analysis.sample_model = self.sample_model

    def _on_instrument_model_changed(self) -> None:
        """Update the Q values in the instrument model when the
        instrument model changes.

        Also update all the Analysi1d objects with the new instrument
        model.
        """
        if self._call_updaters:
            super()._on_instrument_model_changed()
            for analysis in self.analysis_list:
                analysis.instrument_model = self.instrument_model

    #############
    # Private methods
    #############

    def _fit_single_Q(self, Q_index: int) -> FitResults:
        """Fit data for a single Q index.

        Args:
            Q_index (int): Index of the Q value to fit.

        Returns:
            FitResults: The results of the fit for the specified
                Q index.
        """

        Q_index = self._verify_Q_index(Q_index)

        return self.analysis_list[Q_index].fit()

    def _fit_all_Q_independently(self) -> list[FitResults]:
        """Fit data for all Q indices independently.

        Returns:
            list[FitResults]: A list of FitResults, one for each Q
                index.
        """
        return [analysis.fit() for analysis in self.analysis_list]

    def _fit_all_Q_simultaneously(self) -> FitResults:
        """Fit data for all Q indices simultaneously.

        Returns:
            FitResults: The results of the simultaneous fit across all
                Q indices.
        """

        xs = []
        ys = []
        ws = []

        for analysis in self.analysis_list:
            x, y, weight = self.experiment._extract_x_y_weights_only_finite(analysis.Q_index)
            xs.append(x)
            ys.append(y)
            ws.append(weight)

            # Make sure the convolver is up to date for this Q index
            analysis._convolver = analysis._create_convolver()

        mf = MultiFitter(
            fit_objects=self.analysis_list,
            fit_functions=self.get_fit_functions(),
        )

        results = mf.fit(
            x=xs,
            y=ys,
            weights=ws,
        )
        return results

    def get_fit_functions(self) -> list[callable]:
        """Get fit functions for all Q indices, which can be used for
        simultaneous fitting.

        Returns:
            list[callable]: A list of fit functions, one for each
                Q index.
        """
        return [analysis.as_fit_function() for analysis in self.analysis_list]

    def _create_model_array(self) -> sc.DataArray:
        """Create a scipp array for the model.

        Returns:
            sc.DataArray: A DataArray containing the model values, with
                dimensions "Q" and "energy".
        """

        model = sc.array(dims=['Q', 'energy'], values=self.calculate())
        model_data_array = sc.DataArray(
            data=model,
            coords={'Q': self.Q, 'energy': self.experiment.energy},
        )
        return model_data_array

    def _create_components_dataset(self, add_background: bool = True) -> sc.Dataset:
        """Create a scipp dataset containing the individual components
        of the model for plotting.

        Args:
            add_background (bool): Whether to add background components
                to the sample model components when creating the
                dataset. Default is True.

        Raises:
            TypeError: If add_background is not True or False.

        Returns:
            sc.Dataset: A scipp Dataset where each entry is a component
                of the model, with dimensions "Q".
        """
        if not isinstance(add_background, bool):
            raise TypeError('add_background must be True or False.')

        datasets = [
            analysis._create_components_dataset_single_Q(add_background=add_background)
            for analysis in self.analysis_list
        ]

        return sc.concat(datasets, dim='Q')

__init__(display_name='MyAnalysis', unique_name=None, experiment=None, sample_model=None, instrument_model=None, extra_parameters=None)

Initialize an Analysis object.

Parameters:

Name Type Description Default
display_name str

Display name of the analysis.

'MyAnalysis'
unique_name str or None

Unique name of the analysis. If None, a unique name is automatically generated.

None
experiment Experiment | None

The Experiment associated with this Analysis. If None, a default Experiment is created.

None
sample_model SampleModel | None

The SampleModel associated with this Analysis. If None, a default SampleModel is created.

None
instrument_model InstrumentModel | None

The InstrumentModel associated with this Analysis. If None, a default InstrumentModel is created.

None
extra_parameters Parameter | list[Parameter] | None

Extra parameters to be included in the analysis for advanced users. If None, no extra parameters are added.

None
Source code in src/easydynamics/analysis/analysis.py
 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
def __init__(
    self,
    display_name: str = 'MyAnalysis',
    unique_name: str | None = None,
    experiment: Experiment | None = None,
    sample_model: SampleModel | None = None,
    instrument_model: InstrumentModel | None = None,
    extra_parameters: Parameter | list[Parameter] | None = None,
):
    """Initialize an Analysis object.

    Args:
        display_name (str): Display name of the analysis.
        unique_name (str or None): Unique name of the analysis. If
            None, a unique name is automatically generated.
        experiment (Experiment | None): The Experiment associated
            with this Analysis. If None, a default Experiment is
            created.
        sample_model (SampleModel | None): The SampleModel
            associated with this Analysis. If None, a default
            SampleModel is created.
        instrument_model (InstrumentModel | None): The
            InstrumentModel associated with this Analysis. If None,
            a default InstrumentModel is created.
        extra_parameters (Parameter | list[Parameter] | None): Extra
            parameters to be included in the analysis for advanced
            users. If None, no extra parameters are added.
    """

    # Avoid triggering updates before the object is fully
    # initialized
    self._call_updaters = False
    super().__init__(
        display_name=display_name,
        unique_name=unique_name,
        experiment=experiment,
        sample_model=sample_model,
        instrument_model=instrument_model,
        extra_parameters=extra_parameters,
    )

    self._analysis_list = []
    if self.Q is not None:
        for Q_index in range(len(self.Q)):
            analysis = Analysis1d(
                display_name=f'{self.display_name}_Q{Q_index}',
                unique_name=(f'{self.unique_name}_Q{Q_index}'),
                experiment=self.experiment,
                sample_model=self.sample_model,
                instrument_model=self.instrument_model,
                extra_parameters=self._extra_parameters,
                Q_index=Q_index,
            )
            self._analysis_list.append(analysis)
    # Now we can allow updates to trigger recalculations
    self._call_updaters = True

analysis_list property writable

Get the Analysis1d objects associated with this Analysis.

Returns:

Type Description
list[Analysis1d]

list[Analysis1d]: A list of Analysis1d objects, one for each Q index.

calculate(Q_index=None)

Calculate model data for a specific Q index. If Q_index is None, calculate for all Q indices and return a list of arrays.

Parameters:

Name Type Description Default
Q_index int or None

Index of the Q value to calculate for. If None, calculate for all Q values.

None

Returns:

Type Description
list[ndarray] | ndarray

list[np.ndarray] | np.ndarray: If Q_index is None, returns a list of numpy arrays, one for each Q index. If Q_index is an integer, returns a single numpy array for that Q index.

Raises:

Type Description
IndexError

If Q_index is not None and is out of bounds.

Source code in src/easydynamics/analysis/analysis.py
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
def calculate(
    self,
    Q_index: int | None = None,
) -> list[np.ndarray] | np.ndarray:
    """Calculate model data for a specific Q index. If Q_index is
    None, calculate for all Q indices and return a list of arrays.

    Args:
        Q_index (int or None): Index of the Q value to calculate
            for. If None, calculate for all Q values.

    Returns:
        list[np.ndarray] | np.ndarray: If Q_index is None, returns
            a list of numpy arrays, one for each Q index.
            If Q_index is an integer, returns a single numpy array
            for that Q index.

    Raises:
        IndexError: If Q_index is not None and is out of bounds.
    """

    if Q_index is None:
        return [analysis.calculate() for analysis in self.analysis_list]

    Q_index = self._verify_Q_index(Q_index)
    return self.analysis_list[Q_index].calculate()

fit(fit_method='independent', Q_index=None)

Fit the model to the experimental data.

Parameters:

Name Type Description Default
fit_method str

Method to use for fitting. Options are "independent" (fit each Q index independently, one after the other) or "simultaneous" (fit all Q indices simultaneously). Default is "independent".

'independent'
Q_index int or None

If fit_method is "independent", specify which Q index to fit. If None, fit all Q indices independently. Ignored if fit_method is "simultaneous". Default is None.

None

Returns:

Name Type Description
FitResults FitResults | list[FitResults]

a list of FitResults if fitting independently, or a single FitResults object if fitting simultaneously.

Raises:

Type Description
ValueError

If fit_method is not "independent" or "simultaneous"

IndexError

If fit_method is "independent" and Q_index is out of bounds.

Source code in src/easydynamics/analysis/analysis.py
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
def fit(
    self,
    fit_method: str = 'independent',
    Q_index: int | None = None,
) -> FitResults | list[FitResults]:
    """Fit the model to the experimental data.

    Args:
        fit_method (str): Method to use for fitting. Options are
            "independent" (fit each Q index independently, one after
            the other) or "simultaneous" (fit all Q indices
            simultaneously). Default is "independent".
        Q_index (int or None): If fit_method is "independent",
            specify which Q index to fit. If None, fit all Q indices
            independently. Ignored if fit_method is "simultaneous".
            Default is None.

    Returns:
        FitResults: a list of FitResults if fitting independently,
            or a single FitResults object if fitting simultaneously.

    Raises:
        ValueError: If fit_method is not "independent" or
            "simultaneous"
        IndexError: If fit_method is "independent" and Q_index is
            out of bounds.
    """

    if self.Q is None:
        raise ValueError(
            'No Q values available for fitting. Please check the experiment data.'
        )

    Q_index = self._verify_Q_index(Q_index)

    if fit_method == 'independent':
        if Q_index is not None:
            return self._fit_single_Q(Q_index)
        else:
            return self._fit_all_Q_independently()
    elif fit_method == 'simultaneous':
        return self._fit_all_Q_simultaneously()
    else:
        raise ValueError("Invalid fit method. Choose 'independent' or 'simultaneous'.")

get_fit_functions()

Get fit functions for all Q indices, which can be used for simultaneous fitting.

Returns:

Type Description
list[callable]

list[callable]: A list of fit functions, one for each Q index.

Source code in src/easydynamics/analysis/analysis.py
530
531
532
533
534
535
536
537
538
def get_fit_functions(self) -> list[callable]:
    """Get fit functions for all Q indices, which can be used for
    simultaneous fitting.

    Returns:
        list[callable]: A list of fit functions, one for each
            Q index.
    """
    return [analysis.as_fit_function() for analysis in self.analysis_list]

parameters_to_dataset()

Creates a scipp dataset with copies of the Parameters in the model.

Ensures unit consistency across Q.

Returns:

Type Description
Dataset

sc.Dataset: A dataset where each entry is a parameter, with

Dataset

dimensions "Q" and values corresponding to the parameter

Dataset

values.

Raises:

Type Description
UnitError

If there are inconsistent units for the same parameter across different Q values.

Source code in src/easydynamics/analysis/analysis.py
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
def parameters_to_dataset(self) -> sc.Dataset:
    """Creates a scipp dataset with copies of the Parameters in the
    model.

    Ensures unit consistency across Q.

    Returns:
        sc.Dataset: A dataset where each entry is a parameter, with
        dimensions "Q" and values corresponding to the parameter
        values.

    Raises:
        UnitError: If there are inconsistent units for the same
            parameter across different Q values.
    """

    ds = sc.Dataset(coords={'Q': self.Q})

    # Collect all parameter names
    all_names = {
        param.name
        for analysis in self.analysis_list
        for param in analysis.get_all_parameters()
    }

    # Storage
    values = {name: [] for name in all_names}
    variances = {name: [] for name in all_names}
    units = {}

    for analysis in self.analysis_list:
        pars = {p.name: p for p in analysis.get_all_parameters()}

        for name in all_names:
            if name in pars:
                p = pars[name]

                # Unit consistency check
                if name not in units:
                    units[name] = p.unit
                elif units[name] != p.unit:
                    try:
                        p.convert_unit(units[name])
                    except Exception as e:
                        raise UnitError(
                            f"Inconsistent units for parameter '{name}': "
                            f'{units[name]} vs {p.unit}'
                        ) from e

                values[name].append(p.value)
                variances[name].append(p.variance)
            else:
                values[name].append(np.nan)
                variances[name].append(np.nan)

    # Build dataset variables
    for name in all_names:
        ds[name] = sc.Variable(
            dims=['Q'],
            values=np.asarray(values[name], dtype=float),
            variances=np.asarray(variances[name], dtype=float),
            unit=units.get(name, None),
        )

    return ds

plot_data_and_model(Q_index=None, plot_components=True, add_background=True, **kwargs)

Plot the experimental data and the model prediction. Optionally also plot the individual components of the model.

Uses Plopp for plotting: https://scipp.github.io/plopp/

Parameters:

Name Type Description Default
Q_index int or None

Index of the Q value to plot. If None, plot all Q values. Default is None.

None
plot_components bool

Whether to plot the individual components. Default is True.

True
add_background bool

Whether to add background components to the sample model components when plotting. Default is True.

True
**kwargs Any

Additional keyword arguments passed to plopp for customizing the plot.

{}

Raises:

Type Description
ValueError

If Q_index is out of bounds, or if there is no data to plot, or if there are no Q values available for plotting.

RuntimeError

If not in a Jupyter notebook environment.

TypeError

If plot_components or add_background is not True or False.

Returns:

Name Type Description
InteractiveFigure InteractiveFigure

A Plopp InteractiveFigure containing the plot of the data and model.

Source code in src/easydynamics/analysis/analysis.py
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
def plot_data_and_model(
    self,
    Q_index: int | None = None,
    plot_components: bool = True,
    add_background: bool = True,
    **kwargs,
) -> InteractiveFigure:
    """Plot the experimental data and the model prediction.
    Optionally also plot the individual components of the model.

    Uses Plopp for plotting: https://scipp.github.io/plopp/

    Args:
        Q_index (int or None): Index of the Q value to plot. If
            None, plot all Q values. Default is None.
        plot_components (bool): Whether to plot the individual
            components. Default is True.
        add_background (bool): Whether to add background components
            to the sample model components when plotting. Default is
            True.
        **kwargs (Any): Additional keyword arguments passed to plopp
            for customizing the plot.

    Raises:
        ValueError: If Q_index is out of bounds, or if there is no
            data to plot, or if there are no Q values available for
            plotting.
        RuntimeError: If not in a Jupyter notebook environment.
        TypeError: If plot_components or add_background is not True
            or False.

    Returns:
        InteractiveFigure: A Plopp InteractiveFigure containing the
            plot of the data and model.
    """

    if Q_index is not None:
        Q_index = self._verify_Q_index(Q_index)
        return self.analysis_list[Q_index].plot_data_and_model(
            plot_components=plot_components,
            add_background=add_background,
            **kwargs,
        )

    if self.experiment.binned_data is None:
        raise ValueError('No data to plot. Please load data first.')

    if not _in_notebook():
        raise RuntimeError('plot_data() can only be used in a Jupyter notebook environment.')

    if self.Q is None:
        raise ValueError(
            'No Q values available for plotting. Please check the experiment data.'
        )

    if not isinstance(plot_components, bool):
        raise TypeError('plot_components must be True or False.')

    if not isinstance(add_background, bool):
        raise TypeError('add_background must be True or False.')

    import plopp as pp

    plot_kwargs_defaults = {
        'title': self.display_name,
        'linestyle': {'Data': 'none', 'Model': '-'},
        'marker': {'Data': 'o', 'Model': None},
        'color': {'Data': 'black', 'Model': 'red'},
        'markerfacecolor': {'Data': 'none', 'Model': 'none'},
        'keep': 'energy',
    }
    data_and_model = {
        'Data': self.experiment.binned_data,
        'Model': self._create_model_array(),
    }

    if plot_components:
        components = self._create_components_dataset(add_background=add_background)
        for key in components.keys():
            data_and_model[key] = components[key]
            plot_kwargs_defaults['linestyle'][key] = '--'
            plot_kwargs_defaults['marker'][key] = None

    # Overwrite defaults with any user-provided kwargs
    plot_kwargs_defaults.update(kwargs)

    fig = pp.slicer(
        data_and_model,
        **plot_kwargs_defaults,
    )
    return fig

plot_parameters(names=None, **kwargs)

Plot fitted parameters as a function of Q.

Parameters:

Name Type Description Default
names str | list[str] | None

Name(s) of the parameter(s) to plot. If None, plots all parameters.

None
kwargs Any

Additional keyword arguments passed to plopp.slicer for customizing the plot (e.g., title, linestyle, marker, color).

{}

Returns:

Name Type Description
InteractiveFigure InteractiveFigure

A Plopp InteractiveFigure containing the plot of the parameters.

Source code in src/easydynamics/analysis/analysis.py
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
def plot_parameters(
    self,
    names: str | list[str] | None = None,
    **kwargs,
) -> InteractiveFigure:
    """Plot fitted parameters as a function of Q.

    Args:
        names (str | list[str] | None): Name(s) of the parameter(s)
            to plot. If None, plots all parameters.
        kwargs (Any): Additional keyword arguments passed to
            plopp.slicer for customizing the plot (e.g., title,
            linestyle, marker, color).

    Returns:
        InteractiveFigure: A Plopp InteractiveFigure containing the
            plot of the parameters.
    """

    ds = self.parameters_to_dataset()

    if not names:
        names = list(ds.keys())

    if isinstance(names, str):
        names = [names]

    if not isinstance(names, list) or not all(isinstance(name, str) for name in names):
        raise TypeError('names must be a string or a list of strings.')

    for name in names:
        if name not in ds:
            raise ValueError(f"Parameter '{name}' not found in dataset.")

    data_to_plot = {name: ds[name] for name in names}
    plot_kwargs_defaults = {
        'linestyle': {name: 'none' for name in names},
        'marker': {name: 'o' for name in names},
        'markerfacecolor': {name: 'none' for name in names},
    }

    plot_kwargs_defaults.update(kwargs)

    import plopp as pp

    fig = pp.plot(
        data_to_plot,
        **plot_kwargs_defaults,
    )
    return fig

analysis

Analysis

Bases: AnalysisBase

For analysing two-dimensional data, i.e. intensity as function of energy and Q. Supports independent fits of each Q value and simultaneous fits of all Q.

Parameters:

Name Type Description Default
display_name str

Display name of the analysis.

'MyAnalysis'
unique_name str or None

Unique name of the analysis. If None, a unique name is automatically generated.

None
experiment Experiment | None

The Experiment associated with this Analysis. If None, a default Experiment is created.

None
sample_model SampleModel | None

The SampleModel associated with this Analysis. If None, a default SampleModel is created.

None
instrument_model InstrumentModel | None

The InstrumentModel associated with this Analysis. If None, a default InstrumentModel is created.

None
extra_parameters Parameter | list[Parameter] | None

Extra parameters to be included in the analysis for advanced users. If None, no extra parameters are added.

None

Attributes:

Name Type Description
experiment Experiment

The Experiment associated with this Analysis.

sample_model SampleModel

The SampleModel associated with this Analysis.

instrument_model InstrumentModel

The InstrumentModel associated with this Analysis.

Q Variable | None

The Q values from the associated Experiment, if available.

energy Variable | None

The energy values from the associated Experiment, if available.

temperature Parameter | None

The temperature from the associated SampleModel, if available.

extra_parameters list[Parameter]

The extra parameters included in this Analysis.

Source code in src/easydynamics/analysis/analysis.py
 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
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
class Analysis(AnalysisBase):
    """For analysing two-dimensional data, i.e. intensity as function of
    energy and Q. Supports independent fits of each Q value and
    simultaneous fits of all Q.

    Args:
        display_name (str): Display name of the analysis.
        unique_name (str or None): Unique name of the analysis. If None,
            a unique name is automatically generated.
        experiment (Experiment | None): The Experiment associated with
            this Analysis. If None, a default Experiment is created.
        sample_model (SampleModel | None): The SampleModel associated
            with this Analysis. If None, a default SampleModel is
            created.
        instrument_model (InstrumentModel | None): The InstrumentModel
            associated with this Analysis. If None, a default
            InstrumentModel is created.
        extra_parameters (Parameter | list[Parameter] | None): Extra
            parameters to be included in the analysis for advanced
            users. If None, no extra parameters are added.

    Attributes:
        experiment (Experiment): The Experiment associated with this
            Analysis.
        sample_model (SampleModel): The SampleModel associated with this
            Analysis.
        instrument_model (InstrumentModel): The InstrumentModel
            associated with this Analysis.
        Q (sc.Variable | None): The Q values from the associated
            Experiment, if available.
        energy (sc.Variable | None): The energy values from the
            associated Experiment, if available.
        temperature (Parameter | None): The temperature from the
            associated SampleModel, if available.
        extra_parameters (list[Parameter]): The extra parameters
            included in this Analysis.
    """

    def __init__(
        self,
        display_name: str = 'MyAnalysis',
        unique_name: str | None = None,
        experiment: Experiment | None = None,
        sample_model: SampleModel | None = None,
        instrument_model: InstrumentModel | None = None,
        extra_parameters: Parameter | list[Parameter] | None = None,
    ):
        """Initialize an Analysis object.

        Args:
            display_name (str): Display name of the analysis.
            unique_name (str or None): Unique name of the analysis. If
                None, a unique name is automatically generated.
            experiment (Experiment | None): The Experiment associated
                with this Analysis. If None, a default Experiment is
                created.
            sample_model (SampleModel | None): The SampleModel
                associated with this Analysis. If None, a default
                SampleModel is created.
            instrument_model (InstrumentModel | None): The
                InstrumentModel associated with this Analysis. If None,
                a default InstrumentModel is created.
            extra_parameters (Parameter | list[Parameter] | None): Extra
                parameters to be included in the analysis for advanced
                users. If None, no extra parameters are added.
        """

        # Avoid triggering updates before the object is fully
        # initialized
        self._call_updaters = False
        super().__init__(
            display_name=display_name,
            unique_name=unique_name,
            experiment=experiment,
            sample_model=sample_model,
            instrument_model=instrument_model,
            extra_parameters=extra_parameters,
        )

        self._analysis_list = []
        if self.Q is not None:
            for Q_index in range(len(self.Q)):
                analysis = Analysis1d(
                    display_name=f'{self.display_name}_Q{Q_index}',
                    unique_name=(f'{self.unique_name}_Q{Q_index}'),
                    experiment=self.experiment,
                    sample_model=self.sample_model,
                    instrument_model=self.instrument_model,
                    extra_parameters=self._extra_parameters,
                    Q_index=Q_index,
                )
                self._analysis_list.append(analysis)
        # Now we can allow updates to trigger recalculations
        self._call_updaters = True

    #############
    # Properties
    #############

    @property
    def analysis_list(self) -> list[Analysis1d]:
        """Get the Analysis1d objects associated with this Analysis.

        Returns:
            list[Analysis1d]: A list of Analysis1d objects, one for
                each Q index.
        """
        return self._analysis_list

    @analysis_list.setter
    def analysis_list(self, value: list[Analysis1d]) -> None:
        """analysis_list is read-only.

        To change the analysis list, modify the experiment, sample
        model, or instrument model.

        Raises:
            AttributeError: Always raised, since analysis_list is
                read-only.
        """

        raise AttributeError(
            'analysis_list is read-only. '
            'To change the analysis list, modify the experiment, sample model, '
            'or instrument model.'
        )

    #############
    # Other methods
    #############
    def calculate(
        self,
        Q_index: int | None = None,
    ) -> list[np.ndarray] | np.ndarray:
        """Calculate model data for a specific Q index. If Q_index is
        None, calculate for all Q indices and return a list of arrays.

        Args:
            Q_index (int or None): Index of the Q value to calculate
                for. If None, calculate for all Q values.

        Returns:
            list[np.ndarray] | np.ndarray: If Q_index is None, returns
                a list of numpy arrays, one for each Q index.
                If Q_index is an integer, returns a single numpy array
                for that Q index.

        Raises:
            IndexError: If Q_index is not None and is out of bounds.
        """

        if Q_index is None:
            return [analysis.calculate() for analysis in self.analysis_list]

        Q_index = self._verify_Q_index(Q_index)
        return self.analysis_list[Q_index].calculate()

    def fit(
        self,
        fit_method: str = 'independent',
        Q_index: int | None = None,
    ) -> FitResults | list[FitResults]:
        """Fit the model to the experimental data.

        Args:
            fit_method (str): Method to use for fitting. Options are
                "independent" (fit each Q index independently, one after
                the other) or "simultaneous" (fit all Q indices
                simultaneously). Default is "independent".
            Q_index (int or None): If fit_method is "independent",
                specify which Q index to fit. If None, fit all Q indices
                independently. Ignored if fit_method is "simultaneous".
                Default is None.

        Returns:
            FitResults: a list of FitResults if fitting independently,
                or a single FitResults object if fitting simultaneously.

        Raises:
            ValueError: If fit_method is not "independent" or
                "simultaneous"
            IndexError: If fit_method is "independent" and Q_index is
                out of bounds.
        """

        if self.Q is None:
            raise ValueError(
                'No Q values available for fitting. Please check the experiment data.'
            )

        Q_index = self._verify_Q_index(Q_index)

        if fit_method == 'independent':
            if Q_index is not None:
                return self._fit_single_Q(Q_index)
            else:
                return self._fit_all_Q_independently()
        elif fit_method == 'simultaneous':
            return self._fit_all_Q_simultaneously()
        else:
            raise ValueError("Invalid fit method. Choose 'independent' or 'simultaneous'.")

    def plot_data_and_model(
        self,
        Q_index: int | None = None,
        plot_components: bool = True,
        add_background: bool = True,
        **kwargs,
    ) -> InteractiveFigure:
        """Plot the experimental data and the model prediction.
        Optionally also plot the individual components of the model.

        Uses Plopp for plotting: https://scipp.github.io/plopp/

        Args:
            Q_index (int or None): Index of the Q value to plot. If
                None, plot all Q values. Default is None.
            plot_components (bool): Whether to plot the individual
                components. Default is True.
            add_background (bool): Whether to add background components
                to the sample model components when plotting. Default is
                True.
            **kwargs (Any): Additional keyword arguments passed to plopp
                for customizing the plot.

        Raises:
            ValueError: If Q_index is out of bounds, or if there is no
                data to plot, or if there are no Q values available for
                plotting.
            RuntimeError: If not in a Jupyter notebook environment.
            TypeError: If plot_components or add_background is not True
                or False.

        Returns:
            InteractiveFigure: A Plopp InteractiveFigure containing the
                plot of the data and model.
        """

        if Q_index is not None:
            Q_index = self._verify_Q_index(Q_index)
            return self.analysis_list[Q_index].plot_data_and_model(
                plot_components=plot_components,
                add_background=add_background,
                **kwargs,
            )

        if self.experiment.binned_data is None:
            raise ValueError('No data to plot. Please load data first.')

        if not _in_notebook():
            raise RuntimeError('plot_data() can only be used in a Jupyter notebook environment.')

        if self.Q is None:
            raise ValueError(
                'No Q values available for plotting. Please check the experiment data.'
            )

        if not isinstance(plot_components, bool):
            raise TypeError('plot_components must be True or False.')

        if not isinstance(add_background, bool):
            raise TypeError('add_background must be True or False.')

        import plopp as pp

        plot_kwargs_defaults = {
            'title': self.display_name,
            'linestyle': {'Data': 'none', 'Model': '-'},
            'marker': {'Data': 'o', 'Model': None},
            'color': {'Data': 'black', 'Model': 'red'},
            'markerfacecolor': {'Data': 'none', 'Model': 'none'},
            'keep': 'energy',
        }
        data_and_model = {
            'Data': self.experiment.binned_data,
            'Model': self._create_model_array(),
        }

        if plot_components:
            components = self._create_components_dataset(add_background=add_background)
            for key in components.keys():
                data_and_model[key] = components[key]
                plot_kwargs_defaults['linestyle'][key] = '--'
                plot_kwargs_defaults['marker'][key] = None

        # Overwrite defaults with any user-provided kwargs
        plot_kwargs_defaults.update(kwargs)

        fig = pp.slicer(
            data_and_model,
            **plot_kwargs_defaults,
        )
        return fig

    def parameters_to_dataset(self) -> sc.Dataset:
        """Creates a scipp dataset with copies of the Parameters in the
        model.

        Ensures unit consistency across Q.

        Returns:
            sc.Dataset: A dataset where each entry is a parameter, with
            dimensions "Q" and values corresponding to the parameter
            values.

        Raises:
            UnitError: If there are inconsistent units for the same
                parameter across different Q values.
        """

        ds = sc.Dataset(coords={'Q': self.Q})

        # Collect all parameter names
        all_names = {
            param.name
            for analysis in self.analysis_list
            for param in analysis.get_all_parameters()
        }

        # Storage
        values = {name: [] for name in all_names}
        variances = {name: [] for name in all_names}
        units = {}

        for analysis in self.analysis_list:
            pars = {p.name: p for p in analysis.get_all_parameters()}

            for name in all_names:
                if name in pars:
                    p = pars[name]

                    # Unit consistency check
                    if name not in units:
                        units[name] = p.unit
                    elif units[name] != p.unit:
                        try:
                            p.convert_unit(units[name])
                        except Exception as e:
                            raise UnitError(
                                f"Inconsistent units for parameter '{name}': "
                                f'{units[name]} vs {p.unit}'
                            ) from e

                    values[name].append(p.value)
                    variances[name].append(p.variance)
                else:
                    values[name].append(np.nan)
                    variances[name].append(np.nan)

        # Build dataset variables
        for name in all_names:
            ds[name] = sc.Variable(
                dims=['Q'],
                values=np.asarray(values[name], dtype=float),
                variances=np.asarray(variances[name], dtype=float),
                unit=units.get(name, None),
            )

        return ds

    def plot_parameters(
        self,
        names: str | list[str] | None = None,
        **kwargs,
    ) -> InteractiveFigure:
        """Plot fitted parameters as a function of Q.

        Args:
            names (str | list[str] | None): Name(s) of the parameter(s)
                to plot. If None, plots all parameters.
            kwargs (Any): Additional keyword arguments passed to
                plopp.slicer for customizing the plot (e.g., title,
                linestyle, marker, color).

        Returns:
            InteractiveFigure: A Plopp InteractiveFigure containing the
                plot of the parameters.
        """

        ds = self.parameters_to_dataset()

        if not names:
            names = list(ds.keys())

        if isinstance(names, str):
            names = [names]

        if not isinstance(names, list) or not all(isinstance(name, str) for name in names):
            raise TypeError('names must be a string or a list of strings.')

        for name in names:
            if name not in ds:
                raise ValueError(f"Parameter '{name}' not found in dataset.")

        data_to_plot = {name: ds[name] for name in names}
        plot_kwargs_defaults = {
            'linestyle': {name: 'none' for name in names},
            'marker': {name: 'o' for name in names},
            'markerfacecolor': {name: 'none' for name in names},
        }

        plot_kwargs_defaults.update(kwargs)

        import plopp as pp

        fig = pp.plot(
            data_to_plot,
            **plot_kwargs_defaults,
        )
        return fig

    #############
    # Private methods - updating models when things change
    #############

    def _on_experiment_changed(self) -> None:
        """Update the Q values in the sample and instrument models when
        the experiment changes.

        Also update all the Analysi1d objects with the new experiment.
        """
        if self._call_updaters:
            super()._on_experiment_changed()
            for analysis in self.analysis_list:
                analysis.experiment = self.experiment

    def _on_sample_model_changed(self) -> None:
        """Update the Q values in the sample model when the sample model
        changes.

        Also update all the Analysi1d objects with the new sample model.
        """
        if self._call_updaters:
            super()._on_sample_model_changed()
            for analysis in self.analysis_list:
                analysis.sample_model = self.sample_model

    def _on_instrument_model_changed(self) -> None:
        """Update the Q values in the instrument model when the
        instrument model changes.

        Also update all the Analysi1d objects with the new instrument
        model.
        """
        if self._call_updaters:
            super()._on_instrument_model_changed()
            for analysis in self.analysis_list:
                analysis.instrument_model = self.instrument_model

    #############
    # Private methods
    #############

    def _fit_single_Q(self, Q_index: int) -> FitResults:
        """Fit data for a single Q index.

        Args:
            Q_index (int): Index of the Q value to fit.

        Returns:
            FitResults: The results of the fit for the specified
                Q index.
        """

        Q_index = self._verify_Q_index(Q_index)

        return self.analysis_list[Q_index].fit()

    def _fit_all_Q_independently(self) -> list[FitResults]:
        """Fit data for all Q indices independently.

        Returns:
            list[FitResults]: A list of FitResults, one for each Q
                index.
        """
        return [analysis.fit() for analysis in self.analysis_list]

    def _fit_all_Q_simultaneously(self) -> FitResults:
        """Fit data for all Q indices simultaneously.

        Returns:
            FitResults: The results of the simultaneous fit across all
                Q indices.
        """

        xs = []
        ys = []
        ws = []

        for analysis in self.analysis_list:
            x, y, weight = self.experiment._extract_x_y_weights_only_finite(analysis.Q_index)
            xs.append(x)
            ys.append(y)
            ws.append(weight)

            # Make sure the convolver is up to date for this Q index
            analysis._convolver = analysis._create_convolver()

        mf = MultiFitter(
            fit_objects=self.analysis_list,
            fit_functions=self.get_fit_functions(),
        )

        results = mf.fit(
            x=xs,
            y=ys,
            weights=ws,
        )
        return results

    def get_fit_functions(self) -> list[callable]:
        """Get fit functions for all Q indices, which can be used for
        simultaneous fitting.

        Returns:
            list[callable]: A list of fit functions, one for each
                Q index.
        """
        return [analysis.as_fit_function() for analysis in self.analysis_list]

    def _create_model_array(self) -> sc.DataArray:
        """Create a scipp array for the model.

        Returns:
            sc.DataArray: A DataArray containing the model values, with
                dimensions "Q" and "energy".
        """

        model = sc.array(dims=['Q', 'energy'], values=self.calculate())
        model_data_array = sc.DataArray(
            data=model,
            coords={'Q': self.Q, 'energy': self.experiment.energy},
        )
        return model_data_array

    def _create_components_dataset(self, add_background: bool = True) -> sc.Dataset:
        """Create a scipp dataset containing the individual components
        of the model for plotting.

        Args:
            add_background (bool): Whether to add background components
                to the sample model components when creating the
                dataset. Default is True.

        Raises:
            TypeError: If add_background is not True or False.

        Returns:
            sc.Dataset: A scipp Dataset where each entry is a component
                of the model, with dimensions "Q".
        """
        if not isinstance(add_background, bool):
            raise TypeError('add_background must be True or False.')

        datasets = [
            analysis._create_components_dataset_single_Q(add_background=add_background)
            for analysis in self.analysis_list
        ]

        return sc.concat(datasets, dim='Q')

__init__(display_name='MyAnalysis', unique_name=None, experiment=None, sample_model=None, instrument_model=None, extra_parameters=None)

Initialize an Analysis object.

Parameters:

Name Type Description Default
display_name str

Display name of the analysis.

'MyAnalysis'
unique_name str or None

Unique name of the analysis. If None, a unique name is automatically generated.

None
experiment Experiment | None

The Experiment associated with this Analysis. If None, a default Experiment is created.

None
sample_model SampleModel | None

The SampleModel associated with this Analysis. If None, a default SampleModel is created.

None
instrument_model InstrumentModel | None

The InstrumentModel associated with this Analysis. If None, a default InstrumentModel is created.

None
extra_parameters Parameter | list[Parameter] | None

Extra parameters to be included in the analysis for advanced users. If None, no extra parameters are added.

None
Source code in src/easydynamics/analysis/analysis.py
 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
def __init__(
    self,
    display_name: str = 'MyAnalysis',
    unique_name: str | None = None,
    experiment: Experiment | None = None,
    sample_model: SampleModel | None = None,
    instrument_model: InstrumentModel | None = None,
    extra_parameters: Parameter | list[Parameter] | None = None,
):
    """Initialize an Analysis object.

    Args:
        display_name (str): Display name of the analysis.
        unique_name (str or None): Unique name of the analysis. If
            None, a unique name is automatically generated.
        experiment (Experiment | None): The Experiment associated
            with this Analysis. If None, a default Experiment is
            created.
        sample_model (SampleModel | None): The SampleModel
            associated with this Analysis. If None, a default
            SampleModel is created.
        instrument_model (InstrumentModel | None): The
            InstrumentModel associated with this Analysis. If None,
            a default InstrumentModel is created.
        extra_parameters (Parameter | list[Parameter] | None): Extra
            parameters to be included in the analysis for advanced
            users. If None, no extra parameters are added.
    """

    # Avoid triggering updates before the object is fully
    # initialized
    self._call_updaters = False
    super().__init__(
        display_name=display_name,
        unique_name=unique_name,
        experiment=experiment,
        sample_model=sample_model,
        instrument_model=instrument_model,
        extra_parameters=extra_parameters,
    )

    self._analysis_list = []
    if self.Q is not None:
        for Q_index in range(len(self.Q)):
            analysis = Analysis1d(
                display_name=f'{self.display_name}_Q{Q_index}',
                unique_name=(f'{self.unique_name}_Q{Q_index}'),
                experiment=self.experiment,
                sample_model=self.sample_model,
                instrument_model=self.instrument_model,
                extra_parameters=self._extra_parameters,
                Q_index=Q_index,
            )
            self._analysis_list.append(analysis)
    # Now we can allow updates to trigger recalculations
    self._call_updaters = True

analysis_list property writable

Get the Analysis1d objects associated with this Analysis.

Returns:

Type Description
list[Analysis1d]

list[Analysis1d]: A list of Analysis1d objects, one for each Q index.

calculate(Q_index=None)

Calculate model data for a specific Q index. If Q_index is None, calculate for all Q indices and return a list of arrays.

Parameters:

Name Type Description Default
Q_index int or None

Index of the Q value to calculate for. If None, calculate for all Q values.

None

Returns:

Type Description
list[ndarray] | ndarray

list[np.ndarray] | np.ndarray: If Q_index is None, returns a list of numpy arrays, one for each Q index. If Q_index is an integer, returns a single numpy array for that Q index.

Raises:

Type Description
IndexError

If Q_index is not None and is out of bounds.

Source code in src/easydynamics/analysis/analysis.py
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
def calculate(
    self,
    Q_index: int | None = None,
) -> list[np.ndarray] | np.ndarray:
    """Calculate model data for a specific Q index. If Q_index is
    None, calculate for all Q indices and return a list of arrays.

    Args:
        Q_index (int or None): Index of the Q value to calculate
            for. If None, calculate for all Q values.

    Returns:
        list[np.ndarray] | np.ndarray: If Q_index is None, returns
            a list of numpy arrays, one for each Q index.
            If Q_index is an integer, returns a single numpy array
            for that Q index.

    Raises:
        IndexError: If Q_index is not None and is out of bounds.
    """

    if Q_index is None:
        return [analysis.calculate() for analysis in self.analysis_list]

    Q_index = self._verify_Q_index(Q_index)
    return self.analysis_list[Q_index].calculate()

fit(fit_method='independent', Q_index=None)

Fit the model to the experimental data.

Parameters:

Name Type Description Default
fit_method str

Method to use for fitting. Options are "independent" (fit each Q index independently, one after the other) or "simultaneous" (fit all Q indices simultaneously). Default is "independent".

'independent'
Q_index int or None

If fit_method is "independent", specify which Q index to fit. If None, fit all Q indices independently. Ignored if fit_method is "simultaneous". Default is None.

None

Returns:

Name Type Description
FitResults FitResults | list[FitResults]

a list of FitResults if fitting independently, or a single FitResults object if fitting simultaneously.

Raises:

Type Description
ValueError

If fit_method is not "independent" or "simultaneous"

IndexError

If fit_method is "independent" and Q_index is out of bounds.

Source code in src/easydynamics/analysis/analysis.py
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
def fit(
    self,
    fit_method: str = 'independent',
    Q_index: int | None = None,
) -> FitResults | list[FitResults]:
    """Fit the model to the experimental data.

    Args:
        fit_method (str): Method to use for fitting. Options are
            "independent" (fit each Q index independently, one after
            the other) or "simultaneous" (fit all Q indices
            simultaneously). Default is "independent".
        Q_index (int or None): If fit_method is "independent",
            specify which Q index to fit. If None, fit all Q indices
            independently. Ignored if fit_method is "simultaneous".
            Default is None.

    Returns:
        FitResults: a list of FitResults if fitting independently,
            or a single FitResults object if fitting simultaneously.

    Raises:
        ValueError: If fit_method is not "independent" or
            "simultaneous"
        IndexError: If fit_method is "independent" and Q_index is
            out of bounds.
    """

    if self.Q is None:
        raise ValueError(
            'No Q values available for fitting. Please check the experiment data.'
        )

    Q_index = self._verify_Q_index(Q_index)

    if fit_method == 'independent':
        if Q_index is not None:
            return self._fit_single_Q(Q_index)
        else:
            return self._fit_all_Q_independently()
    elif fit_method == 'simultaneous':
        return self._fit_all_Q_simultaneously()
    else:
        raise ValueError("Invalid fit method. Choose 'independent' or 'simultaneous'.")

get_fit_functions()

Get fit functions for all Q indices, which can be used for simultaneous fitting.

Returns:

Type Description
list[callable]

list[callable]: A list of fit functions, one for each Q index.

Source code in src/easydynamics/analysis/analysis.py
530
531
532
533
534
535
536
537
538
def get_fit_functions(self) -> list[callable]:
    """Get fit functions for all Q indices, which can be used for
    simultaneous fitting.

    Returns:
        list[callable]: A list of fit functions, one for each
            Q index.
    """
    return [analysis.as_fit_function() for analysis in self.analysis_list]

parameters_to_dataset()

Creates a scipp dataset with copies of the Parameters in the model.

Ensures unit consistency across Q.

Returns:

Type Description
Dataset

sc.Dataset: A dataset where each entry is a parameter, with

Dataset

dimensions "Q" and values corresponding to the parameter

Dataset

values.

Raises:

Type Description
UnitError

If there are inconsistent units for the same parameter across different Q values.

Source code in src/easydynamics/analysis/analysis.py
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
def parameters_to_dataset(self) -> sc.Dataset:
    """Creates a scipp dataset with copies of the Parameters in the
    model.

    Ensures unit consistency across Q.

    Returns:
        sc.Dataset: A dataset where each entry is a parameter, with
        dimensions "Q" and values corresponding to the parameter
        values.

    Raises:
        UnitError: If there are inconsistent units for the same
            parameter across different Q values.
    """

    ds = sc.Dataset(coords={'Q': self.Q})

    # Collect all parameter names
    all_names = {
        param.name
        for analysis in self.analysis_list
        for param in analysis.get_all_parameters()
    }

    # Storage
    values = {name: [] for name in all_names}
    variances = {name: [] for name in all_names}
    units = {}

    for analysis in self.analysis_list:
        pars = {p.name: p for p in analysis.get_all_parameters()}

        for name in all_names:
            if name in pars:
                p = pars[name]

                # Unit consistency check
                if name not in units:
                    units[name] = p.unit
                elif units[name] != p.unit:
                    try:
                        p.convert_unit(units[name])
                    except Exception as e:
                        raise UnitError(
                            f"Inconsistent units for parameter '{name}': "
                            f'{units[name]} vs {p.unit}'
                        ) from e

                values[name].append(p.value)
                variances[name].append(p.variance)
            else:
                values[name].append(np.nan)
                variances[name].append(np.nan)

    # Build dataset variables
    for name in all_names:
        ds[name] = sc.Variable(
            dims=['Q'],
            values=np.asarray(values[name], dtype=float),
            variances=np.asarray(variances[name], dtype=float),
            unit=units.get(name, None),
        )

    return ds

plot_data_and_model(Q_index=None, plot_components=True, add_background=True, **kwargs)

Plot the experimental data and the model prediction. Optionally also plot the individual components of the model.

Uses Plopp for plotting: https://scipp.github.io/plopp/

Parameters:

Name Type Description Default
Q_index int or None

Index of the Q value to plot. If None, plot all Q values. Default is None.

None
plot_components bool

Whether to plot the individual components. Default is True.

True
add_background bool

Whether to add background components to the sample model components when plotting. Default is True.

True
**kwargs Any

Additional keyword arguments passed to plopp for customizing the plot.

{}

Raises:

Type Description
ValueError

If Q_index is out of bounds, or if there is no data to plot, or if there are no Q values available for plotting.

RuntimeError

If not in a Jupyter notebook environment.

TypeError

If plot_components or add_background is not True or False.

Returns:

Name Type Description
InteractiveFigure InteractiveFigure

A Plopp InteractiveFigure containing the plot of the data and model.

Source code in src/easydynamics/analysis/analysis.py
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
def plot_data_and_model(
    self,
    Q_index: int | None = None,
    plot_components: bool = True,
    add_background: bool = True,
    **kwargs,
) -> InteractiveFigure:
    """Plot the experimental data and the model prediction.
    Optionally also plot the individual components of the model.

    Uses Plopp for plotting: https://scipp.github.io/plopp/

    Args:
        Q_index (int or None): Index of the Q value to plot. If
            None, plot all Q values. Default is None.
        plot_components (bool): Whether to plot the individual
            components. Default is True.
        add_background (bool): Whether to add background components
            to the sample model components when plotting. Default is
            True.
        **kwargs (Any): Additional keyword arguments passed to plopp
            for customizing the plot.

    Raises:
        ValueError: If Q_index is out of bounds, or if there is no
            data to plot, or if there are no Q values available for
            plotting.
        RuntimeError: If not in a Jupyter notebook environment.
        TypeError: If plot_components or add_background is not True
            or False.

    Returns:
        InteractiveFigure: A Plopp InteractiveFigure containing the
            plot of the data and model.
    """

    if Q_index is not None:
        Q_index = self._verify_Q_index(Q_index)
        return self.analysis_list[Q_index].plot_data_and_model(
            plot_components=plot_components,
            add_background=add_background,
            **kwargs,
        )

    if self.experiment.binned_data is None:
        raise ValueError('No data to plot. Please load data first.')

    if not _in_notebook():
        raise RuntimeError('plot_data() can only be used in a Jupyter notebook environment.')

    if self.Q is None:
        raise ValueError(
            'No Q values available for plotting. Please check the experiment data.'
        )

    if not isinstance(plot_components, bool):
        raise TypeError('plot_components must be True or False.')

    if not isinstance(add_background, bool):
        raise TypeError('add_background must be True or False.')

    import plopp as pp

    plot_kwargs_defaults = {
        'title': self.display_name,
        'linestyle': {'Data': 'none', 'Model': '-'},
        'marker': {'Data': 'o', 'Model': None},
        'color': {'Data': 'black', 'Model': 'red'},
        'markerfacecolor': {'Data': 'none', 'Model': 'none'},
        'keep': 'energy',
    }
    data_and_model = {
        'Data': self.experiment.binned_data,
        'Model': self._create_model_array(),
    }

    if plot_components:
        components = self._create_components_dataset(add_background=add_background)
        for key in components.keys():
            data_and_model[key] = components[key]
            plot_kwargs_defaults['linestyle'][key] = '--'
            plot_kwargs_defaults['marker'][key] = None

    # Overwrite defaults with any user-provided kwargs
    plot_kwargs_defaults.update(kwargs)

    fig = pp.slicer(
        data_and_model,
        **plot_kwargs_defaults,
    )
    return fig

plot_parameters(names=None, **kwargs)

Plot fitted parameters as a function of Q.

Parameters:

Name Type Description Default
names str | list[str] | None

Name(s) of the parameter(s) to plot. If None, plots all parameters.

None
kwargs Any

Additional keyword arguments passed to plopp.slicer for customizing the plot (e.g., title, linestyle, marker, color).

{}

Returns:

Name Type Description
InteractiveFigure InteractiveFigure

A Plopp InteractiveFigure containing the plot of the parameters.

Source code in src/easydynamics/analysis/analysis.py
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
def plot_parameters(
    self,
    names: str | list[str] | None = None,
    **kwargs,
) -> InteractiveFigure:
    """Plot fitted parameters as a function of Q.

    Args:
        names (str | list[str] | None): Name(s) of the parameter(s)
            to plot. If None, plots all parameters.
        kwargs (Any): Additional keyword arguments passed to
            plopp.slicer for customizing the plot (e.g., title,
            linestyle, marker, color).

    Returns:
        InteractiveFigure: A Plopp InteractiveFigure containing the
            plot of the parameters.
    """

    ds = self.parameters_to_dataset()

    if not names:
        names = list(ds.keys())

    if isinstance(names, str):
        names = [names]

    if not isinstance(names, list) or not all(isinstance(name, str) for name in names):
        raise TypeError('names must be a string or a list of strings.')

    for name in names:
        if name not in ds:
            raise ValueError(f"Parameter '{name}' not found in dataset.")

    data_to_plot = {name: ds[name] for name in names}
    plot_kwargs_defaults = {
        'linestyle': {name: 'none' for name in names},
        'marker': {name: 'o' for name in names},
        'markerfacecolor': {name: 'none' for name in names},
    }

    plot_kwargs_defaults.update(kwargs)

    import plopp as pp

    fig = pp.plot(
        data_to_plot,
        **plot_kwargs_defaults,
    )
    return fig

analysis1d

Analysis1d

Bases: AnalysisBase

For analysing one-dimensional data, i.e. intensity as function of energy for a single Q index. Is used primarily in the Analysis class, but can also be used on its own for simpler analyses.

Parameters:

Name Type Description Default
display_name str

Display name of the analysis.

'MyAnalysis'
unique_name str or None

Unique name of the analysis. If None, a unique name is automatically generated.

None
experiment Experiment | None

The Experiment associated with this Analysis. If None, a default Experiment is created.

None
sample_model SampleModel | None

The SampleModel associated with this Analysis. If None, a default SampleModel is created.

None
instrument_model InstrumentModel | None

The InstrumentModel associated with this Analysis. If None, a default InstrumentModel is created.

None
Q_index int | None

The Q index to analyze. If None, the analysis will not be able to calculate or fit until a Q index is set.

None
extra_parameters Parameter | list[Parameter] | None

Extra parameters to be included in the analysis for advanced users. If None, no extra parameters are added.

None

Attributes:

Name Type Description
experiment Experiment

The Experiment associated with this Analysis.

sample_model SampleModel

The SampleModel associated with this Analysis.

instrument_model InstrumentModel

The InstrumentModel associated with this Analysis.

Q Variable | None

The Q values from the associated Experiment, if available.

energy Variable | None

The energy values from the associated Experiment, if available.

temperature Parameter | None

The temperature from the associated SampleModel, if available.

Q_index int | None

The Q index being analyzed.

extra_parameters list[Parameter]

The extra parameters included in this Analysis.

Source code in src/easydynamics/analysis/analysis1d.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
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
class Analysis1d(AnalysisBase):
    """For analysing one-dimensional data, i.e. intensity as function of
    energy for a single Q index. Is used primarily in the Analysis
    class, but can also be used on its own for simpler analyses.

    Args:
        display_name (str): Display name of the analysis.
        unique_name (str or None): Unique name of the analysis. If None,
            a unique name is automatically generated.
        experiment (Experiment | None): The Experiment associated with
            this Analysis. If None, a default Experiment is created.
        sample_model (SampleModel | None): The SampleModel associated
            with this Analysis. If None, a default SampleModel is
            created.
        instrument_model (InstrumentModel | None): The InstrumentModel
            associated with this Analysis. If None, a default
            InstrumentModel is created.
        Q_index (int | None): The Q index to analyze. If None, the
            analysis will not be able to calculate or fit until a
            Q index is set.
        extra_parameters (Parameter | list[Parameter] | None): Extra
            parameters to be included in the analysis for advanced
            users. If None, no extra parameters are added.

    Attributes:
        experiment (Experiment): The Experiment associated with this
            Analysis.
        sample_model (SampleModel): The SampleModel associated with this
            Analysis.
        instrument_model (InstrumentModel): The InstrumentModel
            associated with this Analysis.
        Q (sc.Variable | None): The Q values from the associated
            Experiment, if available.
        energy (sc.Variable | None): The energy values from the
            associated Experiment, if available.
        temperature (Parameter | None): The temperature from the
            associated SampleModel, if available.
        Q_index (int | None): The Q index being analyzed.
        extra_parameters (list[Parameter]): The extra parameters
            included in this Analysis.
    """

    def __init__(
        self,
        display_name: str = 'MyAnalysis',
        unique_name: str | None = None,
        experiment: Experiment | None = None,
        sample_model: SampleModel | None = None,
        instrument_model: InstrumentModel | None = None,
        Q_index: int | None = None,
        extra_parameters: Parameter | list[Parameter] | None = None,
    ):
        """Initialize a Analysis1d.

        Args:
            display_name (str): Display name of the analysis.
            unique_name (str or None): Unique name of the analysis. If
                None, a unique name is automatically generated.
            experiment (Experiment | None): The Experiment associated
                with this Analysis. If None, a default Experiment is
                created.
            sample_model (SampleModel | None): The SampleModel
                associated with this Analysis. If None, a default
                SampleModel is created.
            instrument_model (InstrumentModel | None): The
                InstrumentModel associated with this Analysis. If None,
                a default InstrumentModel is created.
            Q_index (int | None): The Q index to analyze. If None, the
                analysis will not be able to calculate or fit until a
                Q index is set.
            extra_parameters (Parameter | list[Parameter] | None): Extra
                parameters to be included in the analysis for advanced
                users. If None, no extra parameters are added.
        """
        super().__init__(
            display_name=display_name,
            unique_name=unique_name,
            experiment=experiment,
            sample_model=sample_model,
            instrument_model=instrument_model,
            extra_parameters=extra_parameters,
        )

        self._Q_index = self._verify_Q_index(Q_index)

        self._fit_result = None
        if self._Q_index is not None:
            self._convolver = self._create_convolver()
        else:
            self._convolver = None

    #############
    # Properties
    #############

    @property
    def Q_index(self) -> int | None:
        """Get the Q index associated with this Analysis.

        Returns:
            int | None: The Q index associated with this Analysis.
        """

        return self._Q_index

    @Q_index.setter
    def Q_index(self, value: int | None) -> None:
        """Set the Q index for single Q analysis.

        Args:
            index (int | None): The Q index.
        """

        self._Q_index = self._verify_Q_index(value)
        self._on_Q_index_changed()

    #############
    # Other methods
    #############

    def calculate(self) -> np.ndarray:
        """Calculate the model prediction for the chosen Q index. Makes
        sure the convolver is up to date before calculating.

        Returns:
            np.ndarray: The calculated model prediction.
        """

        self._convolver = self._create_convolver()

        return self._calculate()

    def _calculate(self) -> np.ndarray:
        """Calculate the model prediction for the chosen Q index. Does
        not check if the convolver is up to date.

        Returns:
            np.ndarray: The calculated model prediction.
        """

        sample_intensity = self._evaluate_sample()

        background_intensity = self._evaluate_background()

        sample_plus_background = sample_intensity + background_intensity

        return sample_plus_background

    def fit(self) -> FitResults:
        """Fit the model to the experimental data for the chosen Q
        index.

        The energy grid is fixed for the duration of the fit.
        Convolution objects are created once and reused during
        parameter optimization for performance reasons.

        Returns:
            FitResult: The result of the fit.

        Raises:
            ValueError: If no experiment is associated with this
                Analysis.

        Returns:
            FitResults: The result of the fit.
        """
        if self._experiment is None:
            raise ValueError('No experiment is associated with this Analysis.')

        # Create convolver once to reuse during fitting
        self._convolver = self._create_convolver()

        fitter = EasyScienceFitter(
            fit_object=self,
            fit_function=self.as_fit_function(),
        )

        x, y, weights = self.experiment._extract_x_y_weights_only_finite(
            Q_index=self._require_Q_index()
        )
        fit_result = fitter.fit(x=x, y=y, weights=weights)

        self._fit_result = fit_result

        return fit_result

    def as_fit_function(self, x=None, **kwargs) -> callable:
        """Return self._calculate as a fit function.

        The EasyScience fitter requires x as input, but
        self._calculate() already uses the correct energy from the
        experiment. So we ignore the x input and just return the
        calculated model.

        Args:
            x (Any): Ignored. The energy grid is taken from the
                experiment.
            kwargs (dict): Ignored. Included for compatibility with the
                EasyScience fitter.
        """

        def fit_function(x, **kwargs):
            return self._calculate()

        return fit_function

    def get_all_variables(self) -> list[DescriptorNumber]:
        """Get all variables used in the analysis.

        Returns:
            list[DescriptorNumber]: A list of all variables.
        """
        variables = self.sample_model.get_all_variables(Q_index=self.Q_index)

        variables.extend(self.instrument_model.get_all_variables(Q_index=self.Q_index))

        if self._extra_parameters:
            variables.extend(self._extra_parameters)

        return variables

    def plot_data_and_model(
        self,
        plot_components: bool = True,
        add_background=True,
        **kwargs,
    ) -> InteractiveFigure:
        """Plot the experimental data and the model prediction for the
        chosen Q index. Optionally also plot the individual components
        of the model.

        Uses Plopp for plotting: https://scipp.github.io/plopp/

        Args:
            plot_components (bool): Whether to plot the individual
                components of the model. Default is True.
            add_background (bool): Whether to add the background to the
                model prediction when plotting individual components.
            kwargs (dict): Keyword arguments to pass to the plotting
                function.

        Returns:
            InteractiveFigure: A plot of the data and model.
        """
        import plopp as pp

        if self.experiment.data is None:
            raise ValueError('No data to plot. Please load data first.')

        data = self.experiment.data['Q', self.Q_index]
        model_array = self._create_sample_scipp_array()

        component_dataset = self._create_components_dataset_single_Q(add_background=add_background)

        # Create a dataset containing the data, model, and individual
        # components for plotting.
        data_and_model = sc.Dataset({
            'Data': data,
            'Model': model_array,
        })

        data_and_model = sc.merge(data_and_model, component_dataset)
        plot_kwargs_defaults = {
            'title': self.display_name,
            'linestyle': {'Data': 'none', 'Model': '-'},
            'marker': {'Data': 'o', 'Model': 'none'},
            'color': {'Data': 'black', 'Model': 'red'},
            'markerfacecolor': {'Data': 'none', 'Model': 'none'},
        }

        if plot_components:
            for comp_name in component_dataset.keys():
                plot_kwargs_defaults['linestyle'][comp_name] = '--'
                plot_kwargs_defaults['marker'][comp_name] = None

        # Overwrite defaults with any user-provided kwargs
        plot_kwargs_defaults.update(kwargs)

        fig = pp.plot(
            data_and_model,
            **plot_kwargs_defaults,
        )
        return fig

    #############
    # Private methods: small utilities
    #############

    def _require_Q_index(self) -> int:
        """Get the Q index, ensuring it is set. Raises a ValueError if
        the Q index is not set.

        Returns:
            int: The Q index.

        Raises:
            ValueError: If the Q index is not set.
        """
        if self._Q_index is None:
            raise ValueError('Q_index must be set.')
        return self._Q_index

    def _on_Q_index_changed(self) -> None:
        """Handle changes to the Q index.

        This method is called whenever the Q index is changed. It
        updates the Convolution object for the new Q index.
        """
        self._convolver = self._create_convolver()

    #############
    # Private methods: evaluation
    #############

    def _evaluate_components(
        self,
        components: ComponentCollection | ModelComponent,
        convolver: Convolution | None = None,
        convolve: bool = True,
    ) -> np.ndarray:
        """Calculate the contribution of a set of components, optionally
        convolving with the resolution.

        If convolve is True and a
        Convolution object is provided (for full model evaluation), we
        use it to perform the convolution of the components with the
        resolution.
        If convolve is True but no Convolution object is
        provided, create a new Convolution object for the given
        components (for individual components).
        If convolve is False, evaluate the components directly without
        convolution (for background).

        Args:
            components (ComponentCollection | ModelComponent): The
                components to evaluate.
            convolver (Convolution | None): An optional Convolution
                object to use for convolution. If None, a new
                Convolution object will be created if convolve is True.
            convolve (bool): Whether to perform convolution with the
                resolution. Default is True.
        """

        Q_index = self._require_Q_index()
        energy = self.energy.values
        energy_offset = self.instrument_model.get_energy_offset_at_Q(Q_index)

        # If there are no components, return zero
        if isinstance(components, ComponentCollection) and components.is_empty:
            return np.zeros_like(energy)

        # No convolution
        if not convolve:
            return components.evaluate(energy - energy_offset.value)

        # If a convolver is provided, use it. This allows reusing the
        # same convolver for multiple evaluations during fitting for
        # performance reasons.
        if convolver is not None:
            return convolver.convolution()

        # If no convolver is provided, create a new one. This is for
        # evaluating individual components for plotting, where
        # performance is not important.

        # We don't create a convolver if the resolution is empty.
        resolution = self.instrument_model.resolution_model.get_component_collection(Q_index)
        if resolution.is_empty:
            return components.evaluate(energy - energy_offset.value)

        conv = Convolution(
            sample_components=components,
            resolution_components=resolution,
            energy=energy,
            temperature=self.temperature,
            energy_offset=energy_offset,
        )
        return conv.convolution()

    def _evaluate_sample(self) -> np.ndarray:
        """Evaluate the sample contribution for a given Q index.

        Assumes that self._convolver is up to date.

        Returns:
            np.ndarray: The evaluated sample contribution.
        """
        Q_index = self._require_Q_index()
        components = self.sample_model.get_component_collection(Q_index=Q_index)
        return self._evaluate_components(
            components=components,
            convolver=self._convolver,
            convolve=True,
        )

    def _evaluate_sample_component(
        self,
        component: ModelComponent,
    ) -> np.ndarray:
        """Evaluate a single sample component for the chosen Q index.

        Args:
            component (ModelComponent): The sample component to
                evaluate.

        Returns:
            np.ndarray: The evaluated sample component contribution.
        """
        return self._evaluate_components(
            components=component,
            convolver=None,
            convolve=True,
        )

    def _evaluate_background(self) -> np.ndarray:
        """Evaluate the background contribution for the chosen Q index.

        Returns:
            np.ndarray: The evaluated background contribution.
        """
        Q_index = self._require_Q_index()
        background_components = self.instrument_model.background_model.get_component_collection(
            Q_index=Q_index
        )
        return self._evaluate_components(
            components=background_components,
            convolver=None,
            convolve=False,
        )

    def _evaluate_background_component(
        self,
        component: ModelComponent,
    ) -> np.ndarray:
        """Evaluate a single background component for the chosen Q
        index.

        Args:
            component (ModelComponent): The background component to
                evaluate.

        Returns:
            np.ndarray: The evaluated background component contribution.
        """

        return self._evaluate_components(
            components=component,
            convolver=None,
            convolve=False,
        )

    def _create_convolver(self) -> Convolution | None:
        """Initialize and return a Convolution object for the chosen Q
        index. If the necessary components for convolution are not
        available, return None.

        Returns:
            Convolution | None: The initialized Convolution object or
                None if not available.
        """
        Q_index = self._require_Q_index()

        sample_components = self.sample_model.get_component_collection(Q_index)
        if sample_components.is_empty:
            return None

        resolution_components = self.instrument_model.resolution_model.get_component_collection(
            Q_index
        )
        if resolution_components.is_empty:
            return None
        energy = self.energy
        # TODO: allow convolution options to be set.
        convolver = Convolution(
            sample_components=sample_components,
            resolution_components=resolution_components,
            energy=energy,
            temperature=self.temperature,
            energy_offset=self.instrument_model.get_energy_offset_at_Q(Q_index),
        )
        return convolver

    #############
    # Private methods: create scipp arrays for plotting
    #############

    def _create_component_scipp_array(
        self,
        component: ModelComponent,
        background: np.ndarray | None = None,
    ) -> sc.DataArray:
        """Create a scipp DataArray for a single component. Adds the
        background if it is not None.

        Args:
            component (ModelComponent): The component to evaluate
            background (np.ndarray | None): Optional background to add
                to the component.

        Returns:
            sc.DataArray: The model calculation of the component.
        """

        values = self._evaluate_sample_component(component=component)
        if background is not None:
            values += background
        return self._to_scipp_array(values=values)

    def _create_background_component_scipp_array(
        self,
        component: ModelComponent,
    ) -> sc.DataArray:
        """Create a scipp DataArray for a single background component.

        Args:
            component (ModelComponent): The component to evaluate.

        Returns:
            sc.DataArray: The model calculation of the component.
        """

        values = self._evaluate_background_component(component=component)
        return self._to_scipp_array(values=values)

    def _create_sample_scipp_array(self) -> sc.DataArray:
        """Create a scipp DataArray for the full sample model including
        background.

        Returns:
            sc.DataArray: The model calculation of the full sample
                model.
        """
        values = self._calculate()
        return self._to_scipp_array(values=values)

    def _create_components_dataset_single_Q(
        self,
        add_background: bool = True,
    ) -> dict[str, sc.DataArray]:
        """Create sc.DataArrays for all sample and background
        components.

        Args:
            add_background (bool): Whether to add background components.

        Returns:
            dict[str, sc.DataArray]: A dictionary of component names to
                their corresponding sc.DataArrays.
        """

        scipp_arrays = {}
        sample_components = self.sample_model.get_component_collection(
            Q_index=self.Q_index
        ).components

        background_components = self.instrument_model.background_model.get_component_collection(
            Q_index=self.Q_index
        ).components
        background = self._evaluate_background() if add_background else None
        for component in sample_components:
            scipp_arrays[component.display_name] = self._create_component_scipp_array(
                component=component, background=background
            )
        for component in background_components:
            scipp_arrays[component.display_name] = self._create_background_component_scipp_array(
                component=component
            )
        return sc.Dataset(scipp_arrays)

    def _to_scipp_array(self, values: np.ndarray) -> sc.DataArray:
        """Convert a numpy array of values to a sc.DataArray with the
        correct coordinates for energy and Q.

        Args:
            values (np.ndarray): The values to convert.

        Returns:
            sc.DataArray: The converted sc.DataArray.
        """

        return sc.DataArray(
            data=sc.array(dims=['energy'], values=values),
            coords={
                'energy': self.energy,
                'Q': self.Q[self.Q_index],
            },
        )

Q_index property writable

Get the Q index associated with this Analysis.

Returns:

Type Description
int | None

int | None: The Q index associated with this Analysis.

__init__(display_name='MyAnalysis', unique_name=None, experiment=None, sample_model=None, instrument_model=None, Q_index=None, extra_parameters=None)

Initialize a Analysis1d.

Parameters:

Name Type Description Default
display_name str

Display name of the analysis.

'MyAnalysis'
unique_name str or None

Unique name of the analysis. If None, a unique name is automatically generated.

None
experiment Experiment | None

The Experiment associated with this Analysis. If None, a default Experiment is created.

None
sample_model SampleModel | None

The SampleModel associated with this Analysis. If None, a default SampleModel is created.

None
instrument_model InstrumentModel | None

The InstrumentModel associated with this Analysis. If None, a default InstrumentModel is created.

None
Q_index int | None

The Q index to analyze. If None, the analysis will not be able to calculate or fit until a Q index is set.

None
extra_parameters Parameter | list[Parameter] | None

Extra parameters to be included in the analysis for advanced users. If None, no extra parameters are added.

None
Source code in src/easydynamics/analysis/analysis1d.py
 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
def __init__(
    self,
    display_name: str = 'MyAnalysis',
    unique_name: str | None = None,
    experiment: Experiment | None = None,
    sample_model: SampleModel | None = None,
    instrument_model: InstrumentModel | None = None,
    Q_index: int | None = None,
    extra_parameters: Parameter | list[Parameter] | None = None,
):
    """Initialize a Analysis1d.

    Args:
        display_name (str): Display name of the analysis.
        unique_name (str or None): Unique name of the analysis. If
            None, a unique name is automatically generated.
        experiment (Experiment | None): The Experiment associated
            with this Analysis. If None, a default Experiment is
            created.
        sample_model (SampleModel | None): The SampleModel
            associated with this Analysis. If None, a default
            SampleModel is created.
        instrument_model (InstrumentModel | None): The
            InstrumentModel associated with this Analysis. If None,
            a default InstrumentModel is created.
        Q_index (int | None): The Q index to analyze. If None, the
            analysis will not be able to calculate or fit until a
            Q index is set.
        extra_parameters (Parameter | list[Parameter] | None): Extra
            parameters to be included in the analysis for advanced
            users. If None, no extra parameters are added.
    """
    super().__init__(
        display_name=display_name,
        unique_name=unique_name,
        experiment=experiment,
        sample_model=sample_model,
        instrument_model=instrument_model,
        extra_parameters=extra_parameters,
    )

    self._Q_index = self._verify_Q_index(Q_index)

    self._fit_result = None
    if self._Q_index is not None:
        self._convolver = self._create_convolver()
    else:
        self._convolver = None

as_fit_function(x=None, **kwargs)

Return self._calculate as a fit function.

The EasyScience fitter requires x as input, but self._calculate() already uses the correct energy from the experiment. So we ignore the x input and just return the calculated model.

Parameters:

Name Type Description Default
x Any

Ignored. The energy grid is taken from the experiment.

None
kwargs dict

Ignored. Included for compatibility with the EasyScience fitter.

{}
Source code in src/easydynamics/analysis/analysis1d.py
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
def as_fit_function(self, x=None, **kwargs) -> callable:
    """Return self._calculate as a fit function.

    The EasyScience fitter requires x as input, but
    self._calculate() already uses the correct energy from the
    experiment. So we ignore the x input and just return the
    calculated model.

    Args:
        x (Any): Ignored. The energy grid is taken from the
            experiment.
        kwargs (dict): Ignored. Included for compatibility with the
            EasyScience fitter.
    """

    def fit_function(x, **kwargs):
        return self._calculate()

    return fit_function

calculate()

Calculate the model prediction for the chosen Q index. Makes sure the convolver is up to date before calculating.

Returns:

Type Description
ndarray

np.ndarray: The calculated model prediction.

Source code in src/easydynamics/analysis/analysis1d.py
141
142
143
144
145
146
147
148
149
150
151
def calculate(self) -> np.ndarray:
    """Calculate the model prediction for the chosen Q index. Makes
    sure the convolver is up to date before calculating.

    Returns:
        np.ndarray: The calculated model prediction.
    """

    self._convolver = self._create_convolver()

    return self._calculate()

fit()

Fit the model to the experimental data for the chosen Q index.

The energy grid is fixed for the duration of the fit. Convolution objects are created once and reused during parameter optimization for performance reasons.

Returns:

Name Type Description
FitResult FitResults

The result of the fit.

Raises:

Type Description
ValueError

If no experiment is associated with this Analysis.

Returns:

Name Type Description
FitResults FitResults

The result of the fit.

Source code in src/easydynamics/analysis/analysis1d.py
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
def fit(self) -> FitResults:
    """Fit the model to the experimental data for the chosen Q
    index.

    The energy grid is fixed for the duration of the fit.
    Convolution objects are created once and reused during
    parameter optimization for performance reasons.

    Returns:
        FitResult: The result of the fit.

    Raises:
        ValueError: If no experiment is associated with this
            Analysis.

    Returns:
        FitResults: The result of the fit.
    """
    if self._experiment is None:
        raise ValueError('No experiment is associated with this Analysis.')

    # Create convolver once to reuse during fitting
    self._convolver = self._create_convolver()

    fitter = EasyScienceFitter(
        fit_object=self,
        fit_function=self.as_fit_function(),
    )

    x, y, weights = self.experiment._extract_x_y_weights_only_finite(
        Q_index=self._require_Q_index()
    )
    fit_result = fitter.fit(x=x, y=y, weights=weights)

    self._fit_result = fit_result

    return fit_result

get_all_variables()

Get all variables used in the analysis.

Returns:

Type Description
list[DescriptorNumber]

list[DescriptorNumber]: A list of all variables.

Source code in src/easydynamics/analysis/analysis1d.py
227
228
229
230
231
232
233
234
235
236
237
238
239
240
def get_all_variables(self) -> list[DescriptorNumber]:
    """Get all variables used in the analysis.

    Returns:
        list[DescriptorNumber]: A list of all variables.
    """
    variables = self.sample_model.get_all_variables(Q_index=self.Q_index)

    variables.extend(self.instrument_model.get_all_variables(Q_index=self.Q_index))

    if self._extra_parameters:
        variables.extend(self._extra_parameters)

    return variables

plot_data_and_model(plot_components=True, add_background=True, **kwargs)

Plot the experimental data and the model prediction for the chosen Q index. Optionally also plot the individual components of the model.

Uses Plopp for plotting: https://scipp.github.io/plopp/

Parameters:

Name Type Description Default
plot_components bool

Whether to plot the individual components of the model. Default is True.

True
add_background bool

Whether to add the background to the model prediction when plotting individual components.

True
kwargs dict

Keyword arguments to pass to the plotting function.

{}

Returns:

Name Type Description
InteractiveFigure InteractiveFigure

A plot of the data and model.

Source code in src/easydynamics/analysis/analysis1d.py
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
def plot_data_and_model(
    self,
    plot_components: bool = True,
    add_background=True,
    **kwargs,
) -> InteractiveFigure:
    """Plot the experimental data and the model prediction for the
    chosen Q index. Optionally also plot the individual components
    of the model.

    Uses Plopp for plotting: https://scipp.github.io/plopp/

    Args:
        plot_components (bool): Whether to plot the individual
            components of the model. Default is True.
        add_background (bool): Whether to add the background to the
            model prediction when plotting individual components.
        kwargs (dict): Keyword arguments to pass to the plotting
            function.

    Returns:
        InteractiveFigure: A plot of the data and model.
    """
    import plopp as pp

    if self.experiment.data is None:
        raise ValueError('No data to plot. Please load data first.')

    data = self.experiment.data['Q', self.Q_index]
    model_array = self._create_sample_scipp_array()

    component_dataset = self._create_components_dataset_single_Q(add_background=add_background)

    # Create a dataset containing the data, model, and individual
    # components for plotting.
    data_and_model = sc.Dataset({
        'Data': data,
        'Model': model_array,
    })

    data_and_model = sc.merge(data_and_model, component_dataset)
    plot_kwargs_defaults = {
        'title': self.display_name,
        'linestyle': {'Data': 'none', 'Model': '-'},
        'marker': {'Data': 'o', 'Model': 'none'},
        'color': {'Data': 'black', 'Model': 'red'},
        'markerfacecolor': {'Data': 'none', 'Model': 'none'},
    }

    if plot_components:
        for comp_name in component_dataset.keys():
            plot_kwargs_defaults['linestyle'][comp_name] = '--'
            plot_kwargs_defaults['marker'][comp_name] = None

    # Overwrite defaults with any user-provided kwargs
    plot_kwargs_defaults.update(kwargs)

    fig = pp.plot(
        data_and_model,
        **plot_kwargs_defaults,
    )
    return fig

analysis_base

AnalysisBase

Bases: ModelBase

Base class for analysis in EasyDynamics. This class is not meant to be used directly.

An Analysis consists of an Experiment, a SampleModel, and an InstrumentModel. The Experiment contains the data to be fitted, the SampleModel contains the model for the sample, and the InstrumentModel contains the model for the instrument, including background and resolution

Parameters:

Name Type Description Default
display_name str

Display name of the analysis.

'MyAnalysis'
unique_name str or None

Unique name of the analysis. If None, a unique name is automatically generated.

None
experiment Experiment | None

The Experiment associated with this Analysis. If None, a default Experiment is created.

None
sample_model SampleModel | None

The SampleModel associated with this Analysis. If None, a default SampleModel is created.

None
instrument_model InstrumentModel | None

The InstrumentModel associated with this Analysis. If None, a default InstrumentModel is created.

None
extra_parameters Parameter | list[Parameter] | None

Extra parameters to be included in the analysis for advanced users. If None, no extra parameters are added.

None

Attributes:

Name Type Description
experiment Experiment

The Experiment associated with this Analysis.

sample_model SampleModel

The SampleModel associated with this Analysis.

instrument_model InstrumentModel

The InstrumentModel associated with this Analysis.

Q Variable | None

The Q values from the associated Experiment, if available.

energy Variable | None

The energy values from the associated Experiment, if available.

temperature Parameter | None

The temperature from the associated SampleModel, if available.

extra_parameters list[Parameter]

The extra parameters included in this Analysis.

Source code in src/easydynamics/analysis/analysis_base.py
 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
 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
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
class AnalysisBase(EasyScienceModelBase):
    """Base class for analysis in EasyDynamics. This class is not meant
    to be used directly.

    An Analysis consists of an Experiment, a SampleModel, and an
    InstrumentModel. The Experiment contains the data to be fitted, the
    SampleModel contains the model for the sample, and the
    InstrumentModel contains the model for the instrument, including
    background and resolution

    Args:
        display_name (str): Display name of the analysis.
        unique_name (str or None): Unique name of the analysis. If None,
            a unique name is automatically generated.
        experiment (Experiment | None): The Experiment associated with
            this Analysis. If None, a default Experiment is created.
        sample_model (SampleModel | None): The SampleModel associated
            with this Analysis. If None, a default SampleModel is
            created.
        instrument_model (InstrumentModel | None): The InstrumentModel
            associated with this Analysis. If None, a default
            InstrumentModel is created.
        extra_parameters (Parameter | list[Parameter] | None): Extra
            parameters to be included in the analysis for advanced
            users. If None, no extra parameters are added.

    Attributes:
        experiment (Experiment): The Experiment associated with this
            Analysis.
        sample_model (SampleModel): The SampleModel associated with this
            Analysis.
        instrument_model (InstrumentModel): The InstrumentModel
            associated with this Analysis.
        Q (sc.Variable | None): The Q values from the associated
            Experiment, if available.
        energy (sc.Variable | None): The energy values from the
            associated Experiment, if available.
        temperature (Parameter | None): The temperature from the
            associated SampleModel, if available.
        extra_parameters (list[Parameter]): The extra parameters
            included in this Analysis.
    """

    def __init__(
        self,
        display_name: str = 'MyAnalysis',
        unique_name: str | None = None,
        experiment: Experiment | None = None,
        sample_model: SampleModel | None = None,
        instrument_model: InstrumentModel | None = None,
        extra_parameters: Parameter | list[Parameter] | None = None,
    ):
        """Initialize the AnalysisBase.

        Args:
            display_name (str): Display name of the analysis.
            unique_name (str or None): Unique name of the analysis. If
                None, a unique name is automatically generated.
            experiment (Experiment | None): The Experiment associated
                with this Analysis. If None, a default Experiment is
                created.
            sample_model (SampleModel | None): The SampleModel
                associated with this Analysis. If None, a default
                SampleModel is created.
            instrument_model (InstrumentModel | None): The
                InstrumentModel associated with this Analysis. If None,
                a default InstrumentModel is created.
            extra_parameters (Parameter | list[Parameter] | None): Extra
                parameters to be included in the analysis for advanced
                users. If None, no extra parameters are added.

        Raises:
            TypeError: If experiment is not an Experiment or None.
            TypeError: If sample_model is not a SampleModel or None.
            TypeError: If instrument_model is not an InstrumentModel or
                None.
            TypeError: If extra_parameters is not a Parameter, a list of
                Parameters, or None.
        """

        super().__init__(display_name=display_name, unique_name=unique_name)

        if experiment is None:
            self._experiment = Experiment()
        elif isinstance(experiment, Experiment):
            self._experiment = experiment
        else:
            raise TypeError('experiment must be an instance of Experiment or None.')

        if sample_model is None:
            self._sample_model = SampleModel()
        elif isinstance(sample_model, SampleModel):
            self._sample_model = sample_model
        else:
            raise TypeError('sample_model must be an instance of SampleModel or None.')

        if instrument_model is None:
            self._instrument_model = InstrumentModel()
        elif isinstance(instrument_model, InstrumentModel):
            self._instrument_model = instrument_model
        else:
            raise TypeError('instrument_model must be an instance of InstrumentModel or None.')

        if extra_parameters is not None:
            if isinstance(extra_parameters, Parameter):
                self._extra_parameters = [extra_parameters]
            elif isinstance(extra_parameters, list) and all(
                isinstance(p, Parameter) for p in extra_parameters
            ):
                self._extra_parameters = extra_parameters
            else:
                raise TypeError('extra_parameters must be a Parameter or a list of Parameters.')
        else:
            self._extra_parameters = []

        self._on_experiment_changed()

    #############
    # Properties
    #############

    @property
    def experiment(self) -> Experiment:
        """Get the Experiment associated with this Analysis.

        Returns:
            Experiment: The Experiment associated with this Analysis.
        """

        return self._experiment

    @experiment.setter
    def experiment(self, value: Experiment) -> None:
        """Set the Experiment for this Analysis.

        Raises:
            TypeError: if value is not an Experiment.
        """

        if not isinstance(value, Experiment):
            raise TypeError('experiment must be an instance of Experiment')
        self._experiment = value
        self._on_experiment_changed()

    @property
    def sample_model(self) -> SampleModel:
        """Get the SampleModel associated with this Analysis.

        Returns:
            SampleModel: The SampleModel associated with this Analysis.
        """

        return self._sample_model

    @sample_model.setter
    def sample_model(self, value: SampleModel) -> None:
        """Set the SampleModel for this Analysis.

        Raises:
            TypeError: if value is not a SampleModel.
        """
        if not isinstance(value, SampleModel):
            raise TypeError('sample_model must be an instance of SampleModel')
        self._sample_model = value
        self._on_sample_model_changed()

    @property
    def instrument_model(self) -> InstrumentModel:
        """Get the InstrumentModel associated with this Analysis.

        Returns:
            InstrumentModel: The InstrumentModel associated with this
                Analysis.
        """
        return self._instrument_model

    @instrument_model.setter
    def instrument_model(self, value: InstrumentModel) -> None:
        """Set the InstrumentModel for this Analysis.

        Raises:
            TypeError: if value is not an InstrumentModel.
        """
        if not isinstance(value, InstrumentModel):
            raise TypeError('instrument_model must be an instance of InstrumentModel')
        self._instrument_model = value
        self._on_instrument_model_changed()

    @property
    def Q(self) -> sc.Variable | None:
        """Get the Q values from the associated Experiment, if
        available.

        Returns:
            sc.Variable: The Q values from the associated Experiment,
                if available.
            None: If the Experiment does not have any data.
        """
        return self.experiment.Q

    @Q.setter
    def Q(self, value) -> None:
        """Q cannot be set, as it is a read-only property derived from
        the Experiment.

        Raises:
            AttributeError: If trying to set Q.
        """
        raise AttributeError('Q is a read-only property derived from the Experiment.')

    @property
    def energy(self) -> sc.Variable | None:
        """Get the energy values from the associated Experiment, if
        available.

        Returns:
            sc.Variable: The energy values from the associated
            Experiment, if available.
            None: If the Experiment does not have any data.
        """

        return self.experiment.energy

    @energy.setter
    def energy(self, value) -> None:
        """Energy cannot be set, as it is a read-only property derived
        from the Experiment.

        Raises:
            AttributeError: If trying to set energy.
        """

        raise AttributeError('energy is a read-only property derived from the Experiment.')

    @property
    def temperature(self) -> Parameter | None:
        """Get the temperature from the associated SampleModel, if
        available.

        Returns:
            Parameter: The temperature from the associated SampleModel,
            if available.
            None: If the SampleModel does not have a temperature.
        """

        return self.sample_model.temperature

    @temperature.setter
    def temperature(self, value) -> None:
        """Temperature cannot be set, as it is a read-only property
        derived from the SampleModel.

        Raises:
            AttributeError: If trying to set temperature.
        """

        raise AttributeError('temperature is a read-only property derived from the SampleModel.')

    @property
    def extra_parameters(self) -> list[Parameter]:
        """Get the extra parameters included in this Analysis.

        Returns:
            list[Parameter]: The extra parameters included in this
                Analysis.
        """
        return self._extra_parameters

    @extra_parameters.setter
    def extra_parameters(self, value: Parameter | list[Parameter]) -> None:
        """Set the extra parameters for this Analysis.

        Args:
            value (Parameter | list[Parameter]): The extra parameters to
                include in this Analysis.

        Raises:
            TypeError: If value is not a Parameter, a list of
            Parameters, or None.
        """
        if isinstance(value, Parameter):
            self._extra_parameters = [value]
        elif isinstance(value, list) and all(isinstance(p, Parameter) for p in value):
            self._extra_parameters = value
        elif value is None:
            self._extra_parameters = []
        else:
            raise TypeError('extra_parameters must be a Parameter, a list of Parameters, or None.')

    #############
    # Other methods
    #############

    #############
    # Private methods
    #############

    def _on_experiment_changed(self) -> None:
        """Update the Q values in the sample and instrument models when
        the experiment changes.
        """
        self.sample_model.Q = self.Q
        self.instrument_model.Q = self.Q

    def _on_sample_model_changed(self) -> None:
        """Update the Q values in the sample model when the sample model
        changes.
        """
        self.sample_model.Q = self.Q

    def _on_instrument_model_changed(self) -> None:
        """Update the Q values in the instrument model when the
        instrument model changes.
        """
        self.instrument_model.Q = self.Q

    def _verify_Q_index(self, Q_index: int | None) -> int | None:
        """Verify that the Q index is valid.

        Args:
            Q_index (int | None): The Q index to verify.

        Returns:
            int | None: The verified Q index.

        Raises:
            IndexError: If the Q index is not valid.
        """
        if Q_index is not None:
            if (
                not isinstance(Q_index, int)
                or Q_index < 0
                or (self.Q is not None and Q_index >= len(self.Q))
            ):
                raise IndexError('Q_index must be a valid index for the Q values.')
        return Q_index

    #############
    # Dunder methods
    #############

    def __repr__(self) -> str:
        """Return a string representation of the Analysis.

        Returns:
            str: A string representation of the Analysis.
        """
        return f' {self.__class__.__name__}  (display_name={self.display_name}, \
        unique_name={self.unique_name})'

Q property writable

Get the Q values from the associated Experiment, if available.

Returns:

Name Type Description
Variable | None

sc.Variable: The Q values from the associated Experiment, if available.

None Variable | None

If the Experiment does not have any data.

__init__(display_name='MyAnalysis', unique_name=None, experiment=None, sample_model=None, instrument_model=None, extra_parameters=None)

Initialize the AnalysisBase.

Parameters:

Name Type Description Default
display_name str

Display name of the analysis.

'MyAnalysis'
unique_name str or None

Unique name of the analysis. If None, a unique name is automatically generated.

None
experiment Experiment | None

The Experiment associated with this Analysis. If None, a default Experiment is created.

None
sample_model SampleModel | None

The SampleModel associated with this Analysis. If None, a default SampleModel is created.

None
instrument_model InstrumentModel | None

The InstrumentModel associated with this Analysis. If None, a default InstrumentModel is created.

None
extra_parameters Parameter | list[Parameter] | None

Extra parameters to be included in the analysis for advanced users. If None, no extra parameters are added.

None

Raises:

Type Description
TypeError

If experiment is not an Experiment or None.

TypeError

If sample_model is not a SampleModel or None.

TypeError

If instrument_model is not an InstrumentModel or None.

TypeError

If extra_parameters is not a Parameter, a list of Parameters, or None.

Source code in src/easydynamics/analysis/analysis_base.py
 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
def __init__(
    self,
    display_name: str = 'MyAnalysis',
    unique_name: str | None = None,
    experiment: Experiment | None = None,
    sample_model: SampleModel | None = None,
    instrument_model: InstrumentModel | None = None,
    extra_parameters: Parameter | list[Parameter] | None = None,
):
    """Initialize the AnalysisBase.

    Args:
        display_name (str): Display name of the analysis.
        unique_name (str or None): Unique name of the analysis. If
            None, a unique name is automatically generated.
        experiment (Experiment | None): The Experiment associated
            with this Analysis. If None, a default Experiment is
            created.
        sample_model (SampleModel | None): The SampleModel
            associated with this Analysis. If None, a default
            SampleModel is created.
        instrument_model (InstrumentModel | None): The
            InstrumentModel associated with this Analysis. If None,
            a default InstrumentModel is created.
        extra_parameters (Parameter | list[Parameter] | None): Extra
            parameters to be included in the analysis for advanced
            users. If None, no extra parameters are added.

    Raises:
        TypeError: If experiment is not an Experiment or None.
        TypeError: If sample_model is not a SampleModel or None.
        TypeError: If instrument_model is not an InstrumentModel or
            None.
        TypeError: If extra_parameters is not a Parameter, a list of
            Parameters, or None.
    """

    super().__init__(display_name=display_name, unique_name=unique_name)

    if experiment is None:
        self._experiment = Experiment()
    elif isinstance(experiment, Experiment):
        self._experiment = experiment
    else:
        raise TypeError('experiment must be an instance of Experiment or None.')

    if sample_model is None:
        self._sample_model = SampleModel()
    elif isinstance(sample_model, SampleModel):
        self._sample_model = sample_model
    else:
        raise TypeError('sample_model must be an instance of SampleModel or None.')

    if instrument_model is None:
        self._instrument_model = InstrumentModel()
    elif isinstance(instrument_model, InstrumentModel):
        self._instrument_model = instrument_model
    else:
        raise TypeError('instrument_model must be an instance of InstrumentModel or None.')

    if extra_parameters is not None:
        if isinstance(extra_parameters, Parameter):
            self._extra_parameters = [extra_parameters]
        elif isinstance(extra_parameters, list) and all(
            isinstance(p, Parameter) for p in extra_parameters
        ):
            self._extra_parameters = extra_parameters
        else:
            raise TypeError('extra_parameters must be a Parameter or a list of Parameters.')
    else:
        self._extra_parameters = []

    self._on_experiment_changed()

__repr__()

Return a string representation of the Analysis.

Returns:

Name Type Description
str str

A string representation of the Analysis.

Source code in src/easydynamics/analysis/analysis_base.py
354
355
356
357
358
359
360
361
def __repr__(self) -> str:
    """Return a string representation of the Analysis.

    Returns:
        str: A string representation of the Analysis.
    """
    return f' {self.__class__.__name__}  (display_name={self.display_name}, \
    unique_name={self.unique_name})'

energy property writable

Get the energy values from the associated Experiment, if available.

Returns:

Name Type Description
Variable | None

sc.Variable: The energy values from the associated

Variable | None

Experiment, if available.

None Variable | None

If the Experiment does not have any data.

experiment property writable

Get the Experiment associated with this Analysis.

Returns:

Name Type Description
Experiment Experiment

The Experiment associated with this Analysis.

extra_parameters property writable

Get the extra parameters included in this Analysis.

Returns:

Type Description
list[Parameter]

list[Parameter]: The extra parameters included in this Analysis.

instrument_model property writable

Get the InstrumentModel associated with this Analysis.

Returns:

Name Type Description
InstrumentModel InstrumentModel

The InstrumentModel associated with this Analysis.

sample_model property writable

Get the SampleModel associated with this Analysis.

Returns:

Name Type Description
SampleModel SampleModel

The SampleModel associated with this Analysis.

temperature property writable

Get the temperature from the associated SampleModel, if available.

Returns:

Name Type Description
Parameter Parameter | None

The temperature from the associated SampleModel,

Parameter | None

if available.

None Parameter | None

If the SampleModel does not have a temperature.