## Fitting in the GUI

This tutorial gives a brief overview of the fitting functionality in the GUI.

As a first example, this tutorial will focus on fitting data simulated with BornAgain itself. More complex fitting examples will be addressed in coming releases. This tutorial is organized as follows:

- Preparing the data for fitting
- Simulating the model
- Importing “experimental” data in BornAgain
- Performing a fit

Although this tutorial consideres GISAS data fitting, the steps described are equally applicable to fitting reflectometry or off-specular data (after choosing the appropriate type of instrument).

### 1. Preparing the data for fitting

First, as explained in the GUI Overview chapter, create a project and select and instrument (here, GISAS).

Then switch to Sample View and construct a simple sample - a two-layer system (vacuum, substrate), with cylindrical particles sitting on top of the substrate. The height and radius of the cylindrical particles are both assumed to be 5 nm.

To represent the cylindrical particles in vacuum, create a new layer with the “Add layer” button. The layer is named `Layer 0`.

Set the layer material to “Vacuum” via the “Material Editor”, accessible via the button on the right-hand side of the layer.

To represent the cylindrical particles, create a particle layout via the “Add partice layout” button. Set the total particle density (here, 0.005/nm^2). Select the interference function (here, “None”).

Select the particle type via the “Add particle” button (here, `Hard particles->Cylinder`). Set the corresponding radius and height (here, both are 5 nm).

Add a second layer to represent the substrate (named `Layer 1`).

Choose the corresponding material to be “Substrate”.

### 2. Simulating the model

Switch to the Simulation View and run the simulation by clicking on the “Run Simulation” button.

As soon as the simulation is complete, the interface automatically switches to Job View, which displays the simulated intensity map. This result can be saved as a file, in several formats; e.g., `experimental_data.int` in BornAgain ASCII format (`*.int`). This file can be later used as an “experimental data” to be imported for fitting.

### 3. Importing the “experimental” data

Switch to the Data View. At the beginning it is empty since there are no real data samples loaded yet. Click the import button corresponding to the 2D Data and select the experimental data file (here, `experimental_data.int` which was created earlier).

The data will be loaded into BornAgain and presented in the Import Data view as shown below.

Remember to set the instrument linked to the data (here, “GISAS”).

### 4. Performing a fit

#### 4.1 Preparation for fitting

To setup the fitting job, switch back to the Simulation View. In the “Real Data” field, select the name of the real (experimental) dataset which was imported. Now, the data selection box states, as shown below, that an instrument “GISAS” will be used together with the sample “Sample”, which represents the sample with cylinders that was constructed in section 1, in order to fit the dataset “experimental_data”. Click on the “Run Simulation” button to start the simulation.

Once the simulation is complete, the display is once again switched to the Job View. Our current job is now ready for fitting. Switch to “Fitting Activity” via the menu `View->Fitting Activity`. By default, when real data has been selected in Simulation view, the current view will already be switched to the Fitting Activity.

In the Fitting Activity view (below) the following elements are visible:

- (1) An intensity map of the selected “Real Data”.
- (2) A simulated intensity map of the job itself
- (3) A relative difference map between (1) and (2)
- (4) A plot showing how the fit is progressing
- (5) A sample parameter tuning widget
- (6) A window to display fitting parameters

Furthermore, the presentation selector drop-down button allows to switch quickly between views from current “Fit Data” to standard “Heat Map”.

As you may see, the relative difference map (3) shows that there is actually no difference between “experimental” and “simulated” data, except for floating-point errors. This is normal, since our “experimental” data was generated using the same sample/instrument settings as the simulation. Or, in other words, at this point no fitting is required - our sample parameters perfectly describe the “experimental” data. In the following paragraph we are going to change that.

#### 4.2 Varying parameters to emulate a certain initial condition

Using the parameter tuning widget on the right we set new values for two sample parameters: the cylinder radius and the cylinder height. This leads to an automatic re-simulation and update of the views: the simulated intensity map has changed and does not coincide with the “experimental” data map anymore. The relative difference map also shows this difference.

These will be the initial conditions of our fitting. The real data was simulated using values for the cylinder’s `height = radius = 5 nm`. The simulated intensity map is obtained for the cylinder’s `height = radius = 10 nm`. We are going to define two fit parameters for the cylinder’s radius and height. Our final goal is to find the original values; i.e., `height = radius = 5 nm`.

#### 4.3 Defining and executing the fit

To create the fit parameters, drag-and-drop “radius” and “height” from the parameter tuning widget to the fit parameters widget below (indicated in the figure below).

Every fit parameter has the following fields

- Fit parameter name
- Fit parameter type (limited, free, fixed, etc.)
- Fit parameter starting value
- Fit parameter limits
- A long string showing to which sample parameter the given fit parameter is linked

Define the fit parameter limits: `min = 3 nm`, `max = 15 nm` and `starting value = 10 nm`.

Push the “Run” button at the bottom of the “Fit Parameters” view. The fitting should start. Using the slider at the bottom area one can change the rate of updating the plot. The plot below shows the view after the fitting was completed. The green histogram in the lower right corner shows how $\chi^2$ evolves as a function of the number of fit iterations. The resulting messages are printed in the Message panel.

- Introduction
  - Functionality overview
  - Architectural overview

- Install or build
  - Install Python
    - Python on Linux
    - Python on Windows
    - Python on Mac
    - Python modules
  - Install BornAgain
    - Linux
    - Windows
    - MacOS
    - Development snapshot
  - Build BornAgain
    - Unix
      - Install third-party software
      - Get the source
      - Build and install BornAgain
      - Run a first simulation
    - Windows

- Graphical user interface
  - Quick Start
  - GUI overview
  - Fitting in the GUI

- Python scripting
  - Run a script
  - Understand the syntax
  - Fitting
  - Upgrading

- Reference
  - Simulation model
    - Simulation classes
      - Specular
        - Example
      - Scattering
        - Examples
          - GISAS
          - without DWBA terms
          - with specular peak
          - SAS
          - Polarized SANS
          - Monte-Carlo
      - Off-specular
        - Off-specular
      - Depth probe
        - Examples
          - Thin film
          - Transmitted modulus
          - Resonator
    - Common settings
      - Background
      - Options
        - Monte-Carlo
        - # threads
        - Average materials
        - Include specular
      - Progress monitor
  - Instrument model
    - Beam
      - Footprint
      - Beam divergence
    - Scan
      - TOF reflectometry
      - TOF resolution
      - Beam Angular Spread
      - Beam Wavelength Spread
    - Detectors
      - SphericalDetector
      - 2d detector resolution
      - Offspec detector
    - Neutron polarization
      - Spin asymmetry example
    - Examples
      - 2D detector resolution
      - Neutron polarization
        - Magnetic layer
        - Ditto, realistic instrument
        - Polarized scattering
  - Sample model
    - Materials
      - Magnetization
    - Sample
      - Layer
      - LayerStack
      - Layout
    - Roughness
      - Interface model
      - Transient
      - Cross-correlation
      - Examples
        - GISAS
        - Reflectivity
    - Particles
      - Form factor
        - Hard particles
          - Bipyramid4
          - Box
          - CantellatedCube
          - Cone
          - Cylinder
          - Dodecahedron
          - EllipsoidalCylinder
          - HemiEllipsoid
          - HorizontalCylinder
          - Icosahedron
          - PlatonicOctahedron
          - PlatonicTetrahedron
          - Prism3
          - Prism6
          - Pyramid2
          - Pyramid3
          - Pyramid4
          - Pyramid6
          - Sphere
          - SphericalSegment
          - Spheroid
          - SpheroidalSegment
          - TruncatedCube
        - Ripples
          - Bar ripple
          - Cosine ripple
          - Sawtooth ripple
        - Soft particles
          - FuzzySphere
          - Gauss
        - Custom formfactor
      - Composite particles
        - Core and shell
        - Compound particle
        - Mesocrystal
      - Examples
        - Compound particle
        - Core and shell
        - Crossing an interface
        - Mesocrystal
        - Rotation example
        - Dense cylinders
        - Dense hemispheres
        - Uncorrelated mixture
        - Polydispersity
    - Particle assemblies
      - Grating
        - 1D lattice
        - Cosine ripples in a lattice
        - Triangular ripples in a lattice
      - 2D lattice
        - Square lattice
        - Lattice orientation distribution
        - Finite square lattice
        - Lattice with basis
        - Multi-layer lattice
        - Position variance
      - Radial paracrystal
      - 2D paracrystal
      - Others
        - Size-distribution model: decoupling approximation
        - Size-distribution model: local monodisperse approximation
        - Size-distribution model: size-spacing coupling approximation
  - Model modifiers
    - Rotation
    - Distributions
  - Data types
    - Class Datafield
      - Export
      - Find intensity peaks
    - SLD profile
      - SLD profile with rough interfaces
      - SLD profile with a sliced particle layer
  - Plotting
    - Functions
    - Configuration
    - Heat map
    - LaTeX markup
    - Export
    - Plot axes in different units
  - Fitting
    - Data import
      - TIFF
    - Minimizer settings
    - Multiple datasets
    - Examples
      - Fitting with masks
      - Custom objective function
      - Fitting along slices
      - GISAS 2D fits
      - Experiment at GALAXI
      - Find background
      - Minimizer settings
      - Bayesian Sampling
      - Consecutive fitting
      - Considering uncertainties
      - External minimizer
      - External minimizer: plotting
      - Simultaneous fit of two datasets
      - Spin asymmetry fit example
      - Reflectometry: Fit Pt layer
      - Reflectometry: Fit honeycomb

- Literature
  - Babonneau2010
  - Babonneau2013
  - Croset2021
  - Lazzari2002
  - Lazzari2006
  - Pospelov2020
  - Renaud2009
  - Sears1992
  - Wuttke2021

- How to
  - Get announcements
  - Solve known problems
    - Set Python environmental variables under Windows
  - Request help or report bugs
  - Cite BornAgain

- Developers' corner
  - Configure
    - Build
    - Pyenv
  - Develop
    - Manual checks
    - Debug
    - Webdoc
    - Code analyses
  - Release
    - Manual GUI test