Sample

Handle data associated with a sample.

class sample.Sample(arr, errors=None, **kwargs)

Handle the measured data along with metadata.

This class is a subclass of the numpy.ndarray class with additional methods and attributes that are specific to neutron backscattering experiments.

It can handle various operations such as addition and subtraction of sample data or numpy array, scaling by a scalar or an array, indexing, broadcasting, reshaping, binning, sliding average or data cleaning.

Parameters:
  • input_arr (np.ndarray, list, tuple or scalar) – Input array corresponding to sample scattering data.
  • kwargs (dict (optional)) –

    Additional keyword arguments either for np.asarray() or for sample metadata. The metadata are:

    • filename, the name of the file used to extract the data.
    • errors, the errors associated with scattering data.
    • energies, the energy transfers associated with the data.
    • time, the experimental time.
    • wavelength, the wavelength of the incoming neutrons.
    • name, the name for the sample.
    • temperature, the temperature(s) used experimentally.
    • concentration, the concentration of the sample.
    • pressure, the pressure used experimentally.
    • buffer, a description of the buffer used experimentally.
    • q, the values for the momentum transfer q.
    • beamline, the name of the beamline used.
    • observable_name, the name of the observable variable.

Note

The errors metadata is special as it is updated for various operations that are performed on the data array such as indexing or for the use of universal functions. For instance, indexing of the data will be performed on errors as well if its shape is the same as for the data. Also, addition, subtraction and other universal functions will lead to automatic error propagation. Some other metadata might change as well, like q, but only for the use of methods specific of the Sample class and not for methods inherited from numpy.

Examples

A sample can be created using the following:

>>> s1 = Sample(
...     np.arange(5),
...     dtype='float32',
...     errors=np.array([0.1, 0.2, 0.12, 0.14, 0.15])
... )
>>> buffer = Sample(
...     [0., 0.2, 0.4, 0.3, 0.1],
...     dtype='float32',
...     errors=np.array([0.1, 0.2, 0.05, 0.1, 0.2])
... )

where my_data, my_errors and q_values are numpy arrays. A buffer subtraction can be performed using:

>>> s1 = s1 - buffer
Sample([0. , 0.80000001, 1.60000002, 2.70000005, 3.9000001], dtype=float32)

where buffer1 is another instance of Sample. The error propagation is automatically performed and the other attributes are taken from the first operand (here s1). Other operations such as scaling can be performed using:

>>> s1 = 0.8 * s1
Sample([0. , 0.80000001, 1.60000002, 2.4000001, 3.20000005], dtype=float32)

You can transform another Sample instance into a column vector and look how broadcasting and error propagation work:

>>> s2 = Sample(
...     np.arange(5, 10),
...     dtype='float32',
...     errors=np.array([0.1, 0.3, 0.05, 0.1, 0.2])
... )
>>> s2 = s2[:, np.newaxis]
>>> res = s1 * s2
>>> res.errors
array([[0.5       , 1.00498756, 0.63245553, 0.76157731, 0.85      ],
       [0.6       , 1.23693169, 0.93722996, 1.23109707, 1.5       ],
       [0.7       , 1.40089257, 0.84593144, 0.99141313, 1.06887792],
       [0.8       , 1.60312195, 0.98061205, 1.15948264, 1.26491106],
       [0.9       , 1.81107703, 1.1516944 , 1.3955644 , 1.56923548]])
T

Override the corresponding NumPy function to process axes too.

absorptionCorrection(ec, canType='tube', canScaling=0.9, neutron_wavelength=6.27, absco_kwargs=None, useModel=True)

Computes absorption Paalman-Pings coefficients

Can be used for sample in a flat or tubular can and apply corrections to data, for each q-value in data.qVals attribute.

Parameters:
  • ec (Sample) – The data corresponding to the empty can.
  • canType ({'tube', 'slab'}) – Type of can used, either ‘tube’ or ‘slab’. (default, ‘tube’)
  • canScaling (float) – Scaling factor for empty can contribution term, set it to 0 to use only correction of sample self-attenuation.
  • neutron_wavelength (float) – Incident neutrons wavelength.
  • absco_kwargs (dict) – Geometry arguments for absco library. from Joachim Wuttke [1].

References

[1]http://apps.jcns.fz-juelich.de/doku/sc/absco
bin(bin_size, axis=-1)

Bin data with the given bin size along specified axis.

Parameters:
  • bin_size (int) – The size of the bin (in number of data points).
  • axis (int, optional) – The axis over which the binning is to be performed. (default, -1 for energies)
Returns:

out_arr – A binned instance of Sample with the same metadata except for errors and the corresponding axis values, which are binned as well.

Return type:

Sample

discardData(indices, axis=0)

Discard data at given indices along the given axis.

Parameters:
  • indices (int, list) – The indices of the data to be discarded.
  • axis (int) – The index of the axis along which the data are discarded.
fit(model=None, cleanData='replace', res=None, ec=None, bkgd=None, volume_fraction_bkgd=0.95, **kwargs)

Fit the dataset using the model attribute.

Parameters:
  • model (Model instance) – The model to be used for fitting. If None, will look for a model instance in ‘model’ attribute of the class instance. If not None, will override the model attribute of the class instance.
  • cleanData ({'replace', 'omit'} or anything else for no, optional) – If set to ‘replace’ the locations of null or inf values in data are set to np.inf in weights prior to fitting. If set to ‘omit’ the locations of null or inf values in data are removed from data, weights and x prior to fitting. Else, nothing is done.
  • res (bool, optional) – If True, will use the attribute resData, fix the parameters, and convolve it with the data using: model = ConvolvedModel(self, resModel)
  • ec (bool, optional) – If True, will use the attribute ECData, fix the parameters, model by calling: ECModel = self.ECData.fixedModel and generate a new model by calling: model = self.model + ECModel
  • bkgd (bool, optional) – If True, will use the attribute D2OData to obtain the fixed model by calling: D2OModel = self.D2OData.fixedModel and generate a new model by calling: model = self.model + D2OModel
  • volume_fraction_bkgd (float [0, 1]) – Volume fraction for the D2O in the sample. (default 0.95)
  • kwargs (dict, optional) – Additional keyword arguments to pass to Model.fit method. It can override any parameters obtained from the dataset, which are passed to the fit function (‘data’, ‘errors’, ‘x’,…).
fit_best(**kwargs)

Return the fitted model.

Parameters:kwargs (dict) – Additional keyword arguments to pass to ModelResult.eval.
fit_components(**kwargs)

Return the fitted components.

Parameters:kwargs (dict) – Additional keyword arguments to pass to ModelResult.eval_components.
fit_result

Return the full result of the fit, if available.

getFixedOptParams(obsIdx)

Return the fixed optimal parameters

The parameters are return for the given observable value at index obsIdx or the first entry if there is only one observable.

get_energy_range(min, max)

Helper function to select a specific energy range.

The function assumes that time values correspond to the first dimension of the data set.

Parameters:
  • min (int) – The minimum value for time.
  • max (int) – The maximum value for time.
Returns:

out – A new instance of the class with the selected energy range.

Return type:

Sample

get_observable_range(min, max)

Helper function to select a specific observable range.

The function assumes that time values correspond to the first dimension of the data set.

Parameters:
  • min (int) – The minimum value for the observable.
  • max (int) – The maximum value for the observable.
Returns:

out – A new instance of the class with the selected observable range.

Return type:

Sample

get_q_range(min, max)

Helper function to select a specific momentum transfer range.

The function assumes that q values correspond to the last dimension of the data set.

Parameters:
  • min (int) – The minimum value for the momentum transfer q range.
  • max (int) – The maximum value for the momentum transfer q range.
Returns:

out – A new instance of the class with the selected q range.

Return type:

Sample

model

Return the model instance.

model_best

Return the model with the fitted parameters.

normalize(ref=None)

Normalize the data using sample intensities or reference sample.

The integration to get the normalization factor is performed along the energy axis.

Parameters:ref (Sample) – A reference sample that is used for as resolution function.
params

Return the best values and errors from the fit result.

plot(fig_ax=None, cb_ax=None, axis=-1, xlabel=None, ylabel='$\\rm S(q, \\hbar \\omega)$', label=None, yscale='log', plot_errors=True, plot_legend=True, max_lines=15, colormap='jet')

Helper function for quick plotting.

Parameters:
  • fig_ax (matplotlib Axis, optional) – An instance of Axis from matplotlib to be used for plotting. (default, None)
  • cb_ax (matplotlib Axis, optional) – An instance of Axis from matplotlib to be used for the colorbar if needed. (default, None, for 1D arrays)
  • axis (int) – The axis corresponding abscissa. (default, -1)
  • xlabel (str) – The label for the x-axis. (default None, will be guessed for axes attribute)
  • ylabel (str) – The label for the y-axis. (default ‘$rm S(q, hbar omega)$’)
  • label (str) – The label for curve. (default, the name attribute of the sample)
  • yscale (str) – The scale of the y-axis. (default, ‘log’)
  • plot_errors (bool) – If True, plot the error bars for each data point.
  • plot_legend (bool) – If True, add the legend to the plot.
  • max_lines (int) – For 2D data, maximum number of lines to be plotted.
  • colormap (str) – The colormap to be used for 2D data.
plot_3D(fig_ax=None, axis='observable', index=0, xlabel=None, ylabel=None, zlabel='$\\rm S(q, \\hbar \\omega)$', zscale='log', colormap='winter')

Helper function for quick plotting.

Parameters:
  • fig_ax (matplotlib axis) – An instance of Axis from matplotlib to be used for plotting. (default, None)
  • axis ({'observable', 'q', 'energies', 'time', 'temperature'}) – The axis along which the data are plotted. Valid for 3D arrays, has no effect for 2D arrays. (default, ‘observable’)
  • index (int) – The index on the axis given for plotting. Valid for 3D arrays. For 2D, the whole dataset is plotted.
  • xlabel (str) – The label for the x-axis. (default None, will be guessed for axes attribute)
  • ylabel (str) – The label for the y-axis. (default None, will be guessed for axes attribute)
  • zlabel (str) – The label for the z-axis. (default ‘$rm S(q, hbar omega)$’)
  • zscale (str) – The scale of the z-axis. (default, ‘linear’)
  • new_fig (bool) – If true, create a new figure instead of plotting on the existing one.
  • colormap (str) – The colormap to be used. (default, ‘winter’)
sliding_average(win_size, axis=0)

Performs a sliding average of data and errors along given axis.

Parameters:
  • win_size (int) –
  • axis (int, optional) – The axis over which the average is to be performed. (default, 0)
Returns:

out_arr – An averaged instance of Sample with the same metadata except for errors and the corresponding axis values, which are processed as well.

Return type:

Sample

squeeze(axis=None)

Override the corresponding NumPy function to process axes too.

swapaxes(axis1, axis2)

Override the corresponding NumPy function to process axes too.

take(indices, axis=None)

Override the corresponding NumPy function to process axes too.

transpose(*axes)

Override the corresponding NumPy function to process axes too.

sample.ensure_fit(func)

Ensures the class has a fitted model.

sample.implements(np_function)

Register an __array_function__ implementation for DiagonalArray objects.