# Examples on BornAgain

file:///usr/share/doc/bornagain/html/ref/fit/ex/index.html Recent content in Examples on BornAgain Hugo en-us

# Fitting with masks

file:///usr/share/doc/bornagain/html/ref/fit/ex/fit-with-masks.html Mon, 01 Jan 0001 00:00:00 +0000 file:///usr/share/doc/bornagain/html/ref/fit/ex/fit-with-masks.html <h2 id="fitting-with-masks">Fitting with masks</h2> <p>In this example we demonstrate how to mask certain areas on the detector image to exclude their influence on the fitting procedure. This can be done by invoking the method <code>addMask</code> on a simulation object.</p> <pre tabindex="0"><code>simulation = ScatteringSimulation() simulation.addMask(Rectangle(x1, y1, x2, y2), mask_value) </code></pre><p>where <code>Rectangle</code> is related to the shape of the mask in detector coordinates, <code>mask_value</code> can be either <code>True</code> (area is excluded from the simulation and fit) or <code>False</code> (area will stay in the simulation and will be taken into account in $\chi^2$ calculations during the fit). There can be an arbitrary number of masks of various shapes added to the simulation one after another. Each subsequent mask overrides the previously defined <code>mask_value</code> in the given area.</p>

# Custom objective function

file:///usr/share/doc/bornagain/html/ref/fit/ex/custom-objective-function.html Mon, 01 Jan 0001 00:00:00 +0000 file:///usr/share/doc/bornagain/html/ref/fit/ex/custom-objective-function.html <h2 id="custom-objective-function">Custom objective function</h2> <p>The BornAgain fitting API allows users to define a custom objective function to for the minimization engine.</p> <p>In this example we are going to construct a vector of residuals calculated between the experimental and simulated intensity values after applying an additional $sqrt$ function to the amplitudes.</p> <p>$$ residuals = [r_{0}, r_{1}, &hellip; , r_{n-1}], ~~~ r_{i} = \sqrt{e_{i}} - \sqrt{s_{i}} $$</p> <p>The length of vector <code>n</code> corresponds to the total number of <em>non-masked</em> detector channels.</p>

# Fitting along slices

file:///usr/share/doc/bornagain/html/ref/fit/ex/fit-along-slices.html Mon, 01 Jan 0001 00:00:00 +0000 file:///usr/share/doc/bornagain/html/ref/fit/ex/fit-along-slices.html <h2 id="fitting-along-slices">Fitting along slices</h2> <p>Here we demonstrate how to fit along slices. The idea is that the user defines the positions of vertical and horizontal lines crossing the detector plane in regions of most interest (Yoneda wings, Bragg peaks, etc.) and then finds the sample parameters which fits those regions best.</p> <p>Such an approach uses much less CPU while still giving a chance to find the optimal sample parameters. In general, however, it is arguable whether fitting along slices makes more sense than fitting using the whole detector image.</p>

# GISAS 2D fits

file:///usr/share/doc/bornagain/html/ref/fit/ex/gisas-fit2d.html Mon, 01 Jan 0001 00:00:00 +0000 file:///usr/share/doc/bornagain/html/ref/fit/ex/gisas-fit2d.html <h1 id="fitting-gisas-in-2d">Fitting GISAS in 2D</h1> <p>This example demonstrates fitting of 2D GISAS data.</p> <h2 id="faked-experimental-data">Faked experimental data</h2> <p>The sample and instrument model is basically the same as in our <a href="file:///usr/share/doc/bornagain/html/ref/sim/class/scattering/ex/gisas">basic GISAS simulation example</a>, except that it depends on four external parameters: beam intensity, detector background, radius and height of the cylindrical nanoparticles.</p> <p>Faked experimental data have been generated by the script <a href="https://jugit.fz-juelich.de/mlz/bornagain/-/tree/r23/devtools/fakeData/fake-gisas1.py">devtools/fakeData/fake-gisas1.py</a>.</p> <p>The intensity for each detector pixel has been drawn at random from a Poisson distribution, with rate basically given by the fit model except for some imperfections that have been introduced on purpose to make the subsequent fitting more difficult and more realistic:</p>

# Experiment at GALAXI

file:///usr/share/doc/bornagain/html/ref/fit/ex/galaxi.html Mon, 01 Jan 0001 00:00:00 +0000 file:///usr/share/doc/bornagain/html/ref/fit/ex/galaxi.html <h2 id="experiment-at-galaxi">Experiment at GALAXI</h2> <p>This is an example of a real data fit. We use our own measurements performed at the laboratory diffractometer <a href="https://www.fz-juelich.de/en/jcns/jcns-2/expertise/in-house-x-ray/galaxi">GALAXI</a> in Forschungszentrum Jülich.</p> <div class="galleryscg "> <div class="row justify-content-center align-items-center"> <figure > <a href="file:///usr/share/doc/bornagain/html/img/draw/FitGALAXIData_setup.jpg"> <img src="file:///usr/share/doc/bornagain/html/img/draw/FitGALAXIData_setup.jpg" width="350px"> </a> <figcaption> <p>Real-space model</p> </figcaption> </figure> <figure > <a href="file:///usr/share/doc/bornagain/html/img/draw/FitGALAXIData.png"> <img src="file:///usr/share/doc/bornagain/html/img/draw/FitGALAXIData.png" width="350px"> </a> <figcaption> <p>Fit window</p> </figcaption> </figure> </div> </div> <ul> <li>The sample represents a 4 layer system (substrate, teflon, hmdso and air) with Ag nanoparticles placed inside the hmdso layer on top of the teflon layer.</li> <li>The sample is generated with the help of a <code>SampleBuilder</code>, which is able to create samples depending on parameters defined in the constructor and passed through to the <code>create_sample</code> method.</li> <li>The nanoparticles have a broad log-normal size distribution.</li> <li>The detector is created to represent the PILATUS detector from the experiment (line 19).</li> <li>In the simulation settings the beam is initialized and the detector is assigned to the simulation. A region of interest is assigned at line 39 to simulate only a small rectangular window. Additionally, a rectangular mask is added to exclude the reflected beam from the analysis (line 40).</li> <li>The real data is loaded from a tiff file into a histogram representing the detector&rsquo;s channels.</li> <li>The <code>run_fitting()</code> function contains the initialization of the fitting kernel: loading experimental data, assignment of fit pair, fit parameters selection (line 62).</li> </ul> <h2 id="experiment-description">Experiment description</h2> <p>To successfully simulate and fit results of some real experiment it is important to have</p>

# Find background

file:///usr/share/doc/bornagain/html/ref/fit/ex/find-background.html Mon, 01 Jan 0001 00:00:00 +0000 file:///usr/share/doc/bornagain/html/ref/fit/ex/find-background.html <h2 id="find-background">Find background</h2> <p>This example demonstrates how to introduce a background in the simulation and fit its value. Here we are simulating cylinders on top of a substrate without interference. The function <code>get_simulation</code> requires 4 parameters:</p> <ul> <li>the height of the cylinders</li> <li>the radius of the cylinders</li> <li>the value of the constant background</li> <li>a scale factor for the beam&rsquo;s intensity</li> </ul> <p>The radius and height of the cylinders are passed to the function constructing the multi layer while the scale and background values are used to initialize the instrument.</p>

# Minimizer settings

file:///usr/share/doc/bornagain/html/ref/fit/ex/minimizer-settings.html Mon, 01 Jan 0001 00:00:00 +0000 file:///usr/share/doc/bornagain/html/ref/fit/ex/minimizer-settings.html <h2 id="minimizer-settings">Minimizer settings</h2> <p>This example demonstrates how to change the minimizer algorithm and some of its settings. For example, the following lines</p> <div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="n">minimizer</span> <span class="o">=</span> <span class="n">ba</span><span class="o">.</span><span class="n">Minimizer</span><span class="p">()</span> </span></span><span class="line"><span class="cl"><span class="n">minimizer</span><span class="o">.</span><span class="n">setMinimizer</span><span class="p">(</span><span class="s2">&#34;Minuit2&#34;</span><span class="p">,</span> <span class="s2">&#34;Migrad&#34;</span><span class="p">,</span> <span class="s2">&#34;MaxFunctionCalls=500;Strategy=2&#34;</span><span class="p">)</span> </span></span></code></pre></div><p>will set the internal minimizer to &ldquo;Minuit2&rdquo;, its internal algorithm to &ldquo;Migrad&rdquo; and then pass additional options, limiting the maximum number of calls and an internal minimization strategy.</p> <p>The list of available minimizers and their options can be seen with</p> <div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="nb">print</span><span class="p">(</span><span class="n">ba</span><span class="o">.</span><span class="n">MinimizerFactory</span><span class="p">()</span><span class="o">.</span><span class="n">catalogueDetailsToString</span><span class="p">())</span> </span></span></code></pre></div><p>For more information, see the <a href="file:///usr/share/doc/bornagain/html/ref/fit/minimizers">minimizer settings tutorial</a>.</p>

# Bayesian Sampling

file:///usr/share/doc/bornagain/html/ref/fit/ex/bayesian.html Mon, 01 Jan 0001 00:00:00 +0000 file:///usr/share/doc/bornagain/html/ref/fit/ex/bayesian.html <h2 id="bayesian-sampling">Bayesian sampling</h2> <p>Bayesian sampling of reflectometry models is a common tool in the analysis of specular reflectometry data. The Python programming language has a powerful infrastructure for this modelling, including packages such as <a href="https://docs.pymc.io">PyMC3</a> and <a href="https://pystan.readthedocs.io/en/latest/">PyStan</a>. Here, we will show how the <a href="https://emcee.readthedocs.io/en/stable/">emcee</a> Python may be used to enable Bayesian sampling in BornAgain and the differential evoulation optimisation algorithm from the <a href="https://docs.scipy.org/doc/scipy/">scipy</a>.</p> <h3 id="example-script">Example script</h3> <p>To generate these images of the probability distributions of the parameters and the maximum likelihood reflectometry profile</p>

# Consecutive fitting

file:///usr/share/doc/bornagain/html/ref/fit/ex/consecutive-fitting.html Mon, 01 Jan 0001 00:00:00 +0000 file:///usr/share/doc/bornagain/html/ref/fit/ex/consecutive-fitting.html <h2 id="consecutive-fitting">Consecutive fitting</h2> <p>This example demonstrates how to run two fits one after the other using different minimizer settings and starting values of the fit parameters.</p> <ul> <li>In this example we are looking for the <code>radius</code> and <code>height</code> of cylindrical nano particles randomly distributed on a surface.</li> <li>During the first (started at line 101) fit we are setting the initial values of the fit parameters to be quite far from the expected values and use a genetic minimizer to explore a large parameter space.</li> <li>The second fit at line 112 starts from the best parameter values found in the previous step and uses one of the gradient descent algorithms to find the precise location of the minimum.</li> </ul> <div class="highlight"><div class="chroma"> <table class="lntable"><tr><td class="lntd"> <pre tabindex="0" class="chroma"><code></code></pre></td> <td class="lntd"> <pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"></code></pre></td></tr></table> </div> </div> <a class="linktofile" href="https://jugit.fz-juelich.de/mlz/bornagain/-/tree/r23/auto/Examples/fit/scatter2d/consecutive_fitting.py"/>auto/Examples/fit/scatter2d/consecutive_fitting.py</a>

# Considering uncertainties

file:///usr/share/doc/bornagain/html/ref/fit/ex/fit-with-uncertainties.html Mon, 01 Jan 0001 00:00:00 +0000 file:///usr/share/doc/bornagain/html/ref/fit/ex/fit-with-uncertainties.html <h2 id="taking-uncertainties-into-account">Taking uncertainties into account</h2> <p>In this example we are demonstrating how to allow for uncertainties during a Reflectometry fitting job. The sample to fit consists of twenty Titanium-Nickel bilayers. Assuming that all Titanium layers have the same thickness, the goal is to find that thickness.</p> <p>The reference data was generated with GENX, setting the thickness of the Ti layers equal to 3 nm.</p> <p>The main points to focus on here are the following:</p>

# External minimizer

file:///usr/share/doc/bornagain/html/ref/fit/ex/external-minimizer.html Mon, 01 Jan 0001 00:00:00 +0000 file:///usr/share/doc/bornagain/html/ref/fit/ex/external-minimizer.html <h2 id="external-minimizer">External minimizer</h2> <p>In this example we are demonstrating how to run a typical fitting task in BornAgain using a third party minimizer.</p> <p>The BornAgain fit parameters and minimizer interface were developed with the idea to simplify the switch between our own minimization engines and other, possibly more advanced minimization libraries. Particularly, we have been inspired by the <a href="https://lmfit.github.io/lmfit-py/">lmfit Python package</a>.</p> <p>This makes the switch between the BornAgain and <code>lmfit</code> minimizers very easy.</p>

# External minimizer: plotting

file:///usr/share/doc/bornagain/html/ref/fit/ex/external-minimizer-with-plotting.html Mon, 01 Jan 0001 00:00:00 +0000 file:///usr/share/doc/bornagain/html/ref/fit/ex/external-minimizer-with-plotting.html <h2 id="external-minimizers-plotting-fit-progress">External Minimizers: Plotting Fit Progress</h2> <p>In this example we are demonstrating how to run a typical fitting task in BornAgain using a third party minimizer while plotting the results. As in our <a href="file:///usr/share/doc/bornagain/html/ref/fit/ex/external-minimizer">previous example</a>, we use lmfit for sake of illustration.</p> <p>To plot the fit progress, it is needed to use the lmfit iteration callback function. It will come handy to define the plotting callback function as a specialized class:</p> <div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">class</span> <span class="nc">Plotter</span><span class="p">:</span> </span></span><span class="line"><span class="cl"> <span class="s2">&#34;&#34;&#34; </span></span></span><span class="line"><span class="cl"><span class="s2"> Adapts standard plotter for lmfit minimizer. </span></span></span><span class="line"><span class="cl"><span class="s2"> &#34;&#34;&#34;</span> </span></span><span class="line"><span class="cl"> <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">fit_objective</span><span class="p">,</span> <span class="n">every_nth</span> <span class="o">=</span> <span class="mi">10</span><span class="p">):</span> </span></span><span class="line"><span class="cl"> <span class="bp">self</span><span class="o">.</span><span class="n">fit_objective</span> <span class="o">=</span> <span class="n">fit_objective</span> </span></span><span class="line"><span class="cl"> <span class="bp">self</span><span class="o">.</span><span class="n">plotter_gisas</span> <span class="o">=</span> <span class="n">ba</span><span class="o">.</span><span class="n">PlotterGISAS</span><span class="p">()</span> </span></span><span class="line"><span class="cl"> <span class="bp">self</span><span class="o">.</span><span class="n">every_nth</span> <span class="o">=</span> <span class="n">every_nth</span> </span></span><span class="line"><span class="cl"> </span></span><span class="line"><span class="cl"> <span class="k">def</span> <span class="fm">__call__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">params</span><span class="p">,</span> <span class="nb">iter</span><span class="p">,</span> <span class="n">resid</span><span class="p">):</span> </span></span><span class="line"><span class="cl"> <span class="k">if</span> <span class="nb">iter</span><span class="o">%</span><span class="bp">self</span><span class="o">.</span><span class="n">every_nth</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span> </span></span><span class="line"><span class="cl"> <span class="bp">self</span><span class="o">.</span><span class="n">plotter_gisas</span><span class="o">.</span><span class="n">plot</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">fit_objective</span><span class="p">)</span> </span></span></code></pre></div><p>An instance of this class is then passed to the lmfit minimization function:</p>

# Simultaneous fit of two datasets

file:///usr/share/doc/bornagain/html/ref/fit/ex/multiple-datasets.html Mon, 01 Jan 0001 00:00:00 +0000 file:///usr/share/doc/bornagain/html/ref/fit/ex/multiple-datasets.html <h2 id="simultaneous-fit-of-two-datasets">Simultaneous fit of two datasets</h2> <p>In this example we demonstrate how to fit two datasets simultaneously.</p> <p>Suppose that we have a sample measured twice for two different incident angles. We are going to fit both datasets simultaneously to find the unknown sample parameters.</p> <p>To do this, we define one dataset (a pair of real data and corresponding simulation builder) for the first incidence angle and another pair for the second incidence angle. We add both pairs to the <code>FitObjective</code> and run the fit as usual.</p>

# Spin asymmetry fit example

file:///usr/share/doc/bornagain/html/ref/fit/ex/polarized-spinasymmetry-fit.html Mon, 01 Jan 0001 00:00:00 +0000 file:///usr/share/doc/bornagain/html/ref/fit/ex/polarized-spinasymmetry-fit.html <h3 id="fitting-the-spin-asymmetry-example-from-nist">Fitting the spin-asymmetry example from NIST</h3> <p>This example shows how to fit the parameters in the <a href="file:///usr/share/doc/bornagain/html/ref/instr/pol/polarized-spinasymmetry">spin-asymmetry example</a>.</p> <p>For this demonstration, we choose initial parameters that are not too far from the fitting results. In particular, the magnetization is initially set to zero, such that the spin asymmetry identically vanishes.</p> <p>With the initial parameters, we obtain the following reflectivity and spin-asymmetry curves:</p> <div class="galleryscg "> <div class="row justify-content-center align-items-center"> <figure > <a href="file:///usr/share/doc/bornagain/html/files/fitted/SpinAsymmetryInitial1.png"> <img src="file:///usr/share/doc/bornagain/html/files/fitted/SpinAsymmetryInitial1.png" width="350px"> </a> <figcaption> <p>Reflectivity</p> </figcaption> </figure> <figure > <a href="file:///usr/share/doc/bornagain/html/files/fitted/SpinAsymmetryInitial2.png"> <img src="file:///usr/share/doc/bornagain/html/files/fitted/SpinAsymmetryInitial2.png" width="350px"> </a> <figcaption> <p>Spin Asymmetry</p> </figcaption> </figure> </div> </div> <h4 id="setup-of-the-fit">Setup of the Fit</h4> <p>For fitting of reflectometry data covering several orders of magnitude we use the $\chi^2$ metric</p>

# Reflectometry: Fit Pt layer

file:///usr/share/doc/bornagain/html/ref/fit/ex/reflectometry-pt-layer.html Mon, 01 Jan 0001 00:00:00 +0000 file:///usr/share/doc/bornagain/html/ref/fit/ex/reflectometry-pt-layer.html <h3 id="reflectometry-fit-pt-layer">Reflectometry: Fit Pt layer</h3> <p>In this example, we want to demonstrate how to fit experimental reflectivity data that was obtained by a time-of-flight experiment with unpolarized neutrons. Experimental data is available for a sample of a roughly 50 nm thick platinum layer on top of a silicon substrate that is published in <a href="https://doi.org/10.5281/zenodo.4072376">this repository</a>.</p> <p>The mesaurements were made by Timothy Charlton, Haile Ambaye and Michael Fitzsimmons (ORNL) on a sample provided by Eric Fullerton (UCSD).</p>

# Reflectometry: Fit honeycomb

file:///usr/share/doc/bornagain/html/ref/fit/ex/reflectometry-honeycomb.html Mon, 01 Jan 0001 00:00:00 +0000 file:///usr/share/doc/bornagain/html/ref/fit/ex/reflectometry-honeycomb.html <h3 id="reflectometry-fit-honeycomb-lattice">Reflectometry: Fit honeycomb lattice</h3> <p>In this example, we want to demonstrate how to fit a more complex sample. For this purpose, we utilize the reflectometry data of an artificial magnetic honeycomb lattice published by A. Glavic et al., in <a href="https://doi.org/10.1002/advs.201700856">this paper</a></p> <p>The experiment was performed with polarized neutrons, but without polarization analysis. Since the magnetization of the sample was parallel to the neutron spin, there is no spin flip and we apply the scalar theory to this problem. This is primarily done to speed up computations: when the polarized computational engine is utilized the fitting procedure takes roughly three times as long.</p>