(Top)

Simple fitting

Plot a data set. We will use data from MUSR00015189_cropped.nxs file.

Select the fitting tool button:

Right click on the plot to select a fitting function.

Choose ExpDecay.

Run Fit.

Examine the results.

(Top)

A more complex case

Activating the fitting tools

  • Open any data, here HRP39182.RAW and plot first spectrum
  • Zoom in on any peak, for example the peak near 93150 microseconds
  • Close to the zoom toolbar button, click on the Fit Function toolbar button


If this toolbar is not visible ensure that View->Toolbars...->Plot is ticked.

What you should now see is something similar to:

If the dashed-blue sliders do not show up in the plot window, is because they are outside the range of the view. Enter appropriate values in settings.StartX and settings.EndX to bring the sliders into view.

Three things happens when you click on the Fit Function toolbar button

  • The Fit Function toolbox, by default, will position itself on the left side of MantidPlot (if not already docked somewhere else)
  • Fit function items are adding to the plot, initially the two vertical dashed lines highlighted in red in the image above
  • Additional right click menu options becomes available on the plot window

Selecting the fitting range

The fitting range is the region of the data where you will attempt to do a fit.

This vertical dashed lines shows the fitting region of the data. These are in sync with the Fit Function setting properties: StartX and EndX values highlighted in green in the image above.

  • Use the mouse to adjust the vertical dashed lines and therefore the fitting range. Notice the StartX and EndX get updated in the Fit Function property browser.
  • Alternative adjust StartX and EndX in the Fit Function property browser which will adjust the positions of the vertical dashed lines

Other Fit Function Settings properties

In addition to StartX and EndX there are a number of other essential fit setting properties including:

  • Workspace and Workspace Index: what data to fit. Note typically you should not need to update these manually, these gets updated automatically as the Fit Function button is used to associate the Fit Function toolbox with different plots
  • Minimizer: Here you chose between a number of minimizer to search for better fit to a model
  • Cost function: The function used to specify the quality of a fit.
  • Plot Difference: When the result of a fit is displayed optionally the difference between the model and the fit can also be displayed

More documentation of these is available from Fit.

Setting up a fit model

Here start up with building up a model consisting of one peak and one background function.

This can in fact be done using just the Fit Function toolbox. However in practice it is advantageous to also use the fitting tools available on the plot and from the plot right click menu.

Select the right click plot menu option 'Add peak...'. This pops up a new window and in the combobox, select Gaussian. The mouse cursor then changes to a cross. Move this cross near the top of the peak and click any mouse button

Click on the red line and drag it sideways to set the initial width (FWHM) of the peak.

Now you can see 3 red lines - one solid line indicating peak's position and height, and two dashed ones representing the width of the peak. The dashed lines usually show the points of half peak's maximum. All three lines can be dragged within the plot to modify its centre, height or with parameters which is instantly reflected in the Fit Function browser.

Select the right click plot menu option 'Add background...'. This pops up a new window and in the combobox, select FlatBackground The result of this is

Note that a vertical line has appeared in the plot where the peak was positioned and two fit function entries have appeared in the Fit Function property browser called 'f0-Gaussian' and 'f1-FlatBackground'.

In summary from the Fit Function property browser you have created model consisting of a CompositeFunction which contains a Gaussian and a flat-background. The CompositeFunction part means that the model is sum of its parts, i.e. here the model is

'f0-Gaussian' + 'f1-FlatBackground'

Adjusting the fit function parameters for an educated initial guess

When you do fitting, the starting fit function parameter values can greatly affect both the speed and the result you obtain from fitting. This is specially true with complex models. In general, you want to use staring parameter that are a close as possible to the result you want to obtain.

Fit tools are available on the plot to help you with doing this. In doing this it can be helpful to turn on Plot Guess,

what this means does is to plot how the model you have created looks like compared to your data.

The aim is to have this plot and your data overlap reasonable well before you do the actual fit. Note this is not an absolute requirement but your chances of a successful fit increase this way.

Saving a model

If you have spend a considerable amount of type setting up a model you can save it and then load it later.

Tying and constraining fit parameters

Mantid fitting framework allows you to tie or constrain parameters during the fit. We define tying as setting a parameter equal to a result of an expression involving other parameters of the same function. The expression can be a constant (doesn't involve any parameters), in this case we call the tied parameter fixed.

By constraining we understand setting conditions on acceptable values of a parameter. For example limiting its value from below or above.

To set a constraint or a tie right click on a parameter name:

The menu offers three options:

  • Fix: tie this parameter to its current value.
  • Constraint: set a bounding constraining condition - define a lower or upper bound, or both.
  • Tie: tie this parameter to an arbitrary expression.

The tying expression can be as simple as a parameter name:

f0.Height

Note that parameter names of a model include prefixes such as "f0." which indicate the particular function they belong to.

A more interesting example is setting parameter f1.A0 from our earlier model to formula

20 - f0.Height
This will ensure that the maximum point is exactly 20 units above 0.

Execute your fit

After the model has been defined, its initial values are set, any ties and constraints defined we are ready to run a fit. It is done by selecting the Fit option from the Fit menu:

Inspecting a fit result

After a successful fit the results can be examined in three ways.

  • The Fit Function property browser will show the fitted parameters instead of their initial values.
  • A plot of the fitted model will be added to the graph along with the difference with the original data.
  • Output workspaces will be created and available via the workspace dock.

There are three output workspaces:

1 A TableWorkspace with the name suffixed with "_Parameters". It contains the fitting parameters and their corresponding errors.

2 A MatrixWorkspace with the name suffixed with "_Workspace". Its first three spectra are: the original data, the calculated model, and the difference.

3 A TableWorkspace with the name suffixed with "_NormalisedCovarianceMatrix". It contains the variance-covariance matrix normalized to 100.

(Top)

User custom fitting function

Mantid provides a user defined function called UserFunction. It has an attribute called "Formula" which accepts a text string with a mathematical formula. All variables in the formula are treated as parameters except for "x" which is the argument.

The formula can either be entered in the text editor in the Fit Function browser or constructed with the help of the User Function Dialog.

Edit your function in the text field, browse,and Add to your formula any built-in or saved function. The fitting parameters are extracted automatically and displayed in the Parameters read-only field. If the field is empty then your formula contains errors.

When finished click the Use button to insert the formula into the Fit Function browser.

The constructed formula can be saved permanently for future use. Click the Save button to see the dialog:

Now your function appears in the list of available functions:

Any unwanted function can be removed from the list using the Remove button.

(Top)

Tabulated function

A TabulatedFunction takes its values from a file or a workspace.

We will use this function when loading the instrument resolution in a workspace (Model: $R(Q,E) \otimes [I_{el}\delta(E) + S_{sim}(Q,E)]$)

(Top)

Exercises

(Top)

Fiting with a Gaussian plus a linear background

In this exercise we will fit a simple Gaussian on a linear background.

  • Start with loading the data set (GEM38370_Focussed).
  • Plot spectrum ID = 4.
  • Zoom into the peak around 5 angstroms.

  • Start the fitting tool.
  • Adjust the fitting range if needed.
  • Make sure the fitting model is empty in the Fit Function browser. If necessary clear it.

  • Add a background function. Select LinearBackground.

  • Add a peak. Select Gaussian.
  • Click at peak's maximum point to set initial values for the centre and the height.
  • Adjust the width.

  • Run the fit

(Top)

Fitting the Sassena output from the mPOSS simulation

We will fit the simulated $I(Q,t)$ from the mPOSS molecule with a model that will highlight the fundamentals of the physics involved in the caged diffusive motions of the hydrogens.

The trajectory of each of the hydrogens in a rotating methyl group is a circle

Not all angles are equally problable. There are three three preferred positions corresponding to the three minima of the dihedral potential governing the rotation of the methyl group. The picture below shows the minimum, when $\phi=60^o$

We use a diffusion model representing a particle jumping among three equivalent sites equally spaced on a circle:

For a rigid methyl group, parameter $r=1.04$ Angstroms from purely geometric calculations. The incoherent scattering function for this model is (from M. Bee, "Quasielastic Neutron Scattering")

$I(Q,t)=\frac{I}{3}[1+2\frac{sin(Qr\sqrt{3})}{Qr\sqrt{3}} ] + \frac{2I}{3}[1-\frac{sin(Qr\sqrt{3})}{Qr\sqrt{3}}]e^{-3|t|/\tau}$

The $t$-dependence of this model is a constant term ("flat background") and an exponential decay. This model has parameters $I, Q, r,$ and $\tau$.

  • Use algorithm LoadSassena to load file fqt_inc.h5 from your scratch area and save to workspace group "fqt".
  • Plot spectrum 8 from workspace fqt_fqt.Re. This spectrum corresponds to $I(Q=1.9A^{-1},t$).

The decay happens in a time scale much shorter than the simulation span. Let's zoom to a range around [-700,700].

  • Start the fitting tool and adjust the range to about [-700, 700]
  • We will define a UserFunction. The expression for the model is
    (1./3)*I*(1+2*sin(Q*r*sqrt(3))/(Q*r*sqrt(3))) + (2./3)*I*(1-sin(Q*r*sqrt(3))/(Q*r*sqrt(3)))*exp(-3*abs(x)/T)

In principle, we have the following fitting parameters:

  • $I$ Intensity, or I(Q,t=0)
  • $Q$ momentum transfer
  • $r$ radius of the circle
  • $T$ mean residence time in the potential energy minimum

However, we already know the values of $I$ and $Q$ ($Q=1.9A^{-1}$). The incoherent scattering length of each hydrogen $b^{(inc)}_H=25.272fm$ and there are 24 hydrogens in the mPOSS molecule. Thus $I=\sum_{i=1}^{24}|b^{(inc)}_H|^2=15328.2$. You can verify this number by looking at the contents of workspace fqt_fq0.

  • Fix parameters $I$ and $Q$ to the previous values

  • From geometric considerations and assuming a rigid rotor, $r=1.04$. Although stiff, the methyl group is not rigid due to angle and bond potentials. However, $r=1.04$ is a good starting initial guess. Enter this value in the parameter field.

  • Just by looking at the plot we see that $I(Q,t)$ plateaus after 100ps. Let's put an initial guess $T \sim 50$.

We are done with our initial guess. It only remains to plot it!

Now run the Fit

The fit is not all that spectacular. In fact, the optimized parameters barely moved from the initial guess.

Although our model is appropriate to describe the caged diffusive motions of the hydrogens, we have neglected to include the vibrational motions which happen on a much faster time scale (below 1ps). Due to the difference in time scales, we can assume vibrations and diffusive motions are uncorrelated, thus:

$I(Q,t)=I_{vibr}(Q,t) \cdot I_{diff}(Q,t)$

$I_{vibr}$ decays to a plateau in a time scale $<1ps$. Thus we can substitute $I_{vibr}(Q,t)$ with the plateau value, the so called Debye-Waller factor, and write our model as

$I(Q,t)=e^{-Q^2\langle u^2 \rangle}\cdot [\frac{I}{3}[1+2\frac{sin(Qr\sqrt{3})}{Qr\sqrt{3}} ] + \frac{2I}{3}[1-\frac{sin(Qr\sqrt{3})}{Qr\sqrt{3}}]e^{-3|t|/\tau}]$

Here $\langle u^2 \rangle$ is the temperature-averaged vibrational fluctuations of the hydrogen. Instead of explicitly including the Debye-Waller factor in our model, we will simply remove the tie that fixed parameter $I$. Now $I$ is a free fitting parameter:

Run the fit again:

The fit has improved markedly. Optimized radius $r=0.92A$ and mean residence time $\tau=85ps$. The intensity has decreased to $I=11980.1$. The ratio of this value to the value assuming no vibrations ($I_0=15328.2$) is the Debye-Waller factor:

$\frac{I}{I_0}=e^{-Q^2\langle u^2 \rangle}$

Solving for $\langle u^2 \rangle$ we obtain $\langle u^2 \rangle^{1/2}=0.26A$.

Finally, recalling that we set the heat bath of the simulation to $T=200K$, we can use the equipartition theorem to obtain a crude estimation for the time scale of the vibrational motions:

$\frac{3}{2}k_bT=\frac{1}{2}m_H \omega^2 \langle u^2 \rangle \rightarrow \omega^{-1} \simeq 0.044ps$ confirming $\omega^{-1} \ll ps$