<jupyter_start><jupyter_text>Disclaimer:     The main objective of the Jupyter notebooks is to show how to use the models of the QENS library by    - building a fitting model: composition of models, convolution with a resolution function  - setting and running the fit  - extracting and displaying information about the results  These steps have a minimizer-dependent syntax. That's one of the reasons why different minimizers have been used in the notebooks provided as examples.  But, the initial guessed parameters might not be optimal, resulting in a poor fit of the reference data. Chudley-Elliot diffusion with bumps Table of Contents- [Introduction](introduction)- [Import and install required libraries](Import-and-install-required-libraries) - [Setting of fitting](Setting-of-fitting)  - [Running the fit](Running-the-fit)- [Showing the results](Showing-the-results) [Top](Table-of-Contents) Introduction    The objective of this notebook is to show how to use the Chudley Elliot diffusion model to perform some fits using bumps . [Top](Table-of-Contents)  Import and install required libraries<jupyter_code># Imported required libraries
from __future__ import print_function
import numpy as np
import ipywidgets
# install bumps (if not already installed)
import sys
import os
import pkgutil
if not pkgutil.find_loader("bumps"):   
    bumpsY = ipywidgets.Button(description='Yes', button_style='success')
    bumpsN = ipywidgets.Button(description='No', button_style='danger')
    choice_installation = ipywidgets.VBox(
    [ipywidgets.Label("Do you want to install bumps?"), ipywidgets.HBox([bumpsY, bumpsN])],
    layout=ipywidgets.Layout(width='30%', height='80px'))

    display(choice_installation)
    
    def on_bumpsY_clicked(b):
        !{sys.executable} -m pip install bumps==0.7.12
    def on_bumpsN_clicked(b):
        print("You will not be able to run some of the remaining parts of this notebook")
        
    bumpsY.on_click(on_bumpsY_clicked)
    bumpsN.on_click(on_bumpsN_clicked)
import bumps

# check version of bumps installed
# Information message if installed version not recent enough
from distutils.version import StrictVersion
if StrictVersion(bumps.__version__) <= StrictVersion('0.7.6'):
    print("""The version of bumps installed is not recent 
    enough to run the examples. 
    Please update bumps. The minimum version required is 0.7.8""")
import bumps.names as bmp
from bumps.fitters import fit<jupyter_output><empty_output><jupyter_text>[Top](Table-of-Contents) Setting of fitting install QENSmodels (if not already installed)<jupyter_code>if not pkgutil.find_loader("QENSmodels"):
    buttonY = ipywidgets.Button(description='Yes', button_style='success')
    buttonN = ipywidgets.Button(description='No', button_style='danger')
    choice_installation = ipywidgets.VBox(
    [ipywidgets.Label("Do you want to install the QENSmodels' library?"), ipywidgets.HBox([buttonY, buttonN])],
    layout=ipywidgets.Layout(width='50%', height='80px'))
    display(choice_installation)
    
    def on_buttonY_clicked(b):
        !{sys.executable} -m pip install git+https://github.com/QENSlibrary/QENSmodels#egg=QENSmodels

    def on_buttonN_clicked(b):
        print("You will not be able to run some of the remaining parts of this notebook")
     
    buttonY.on_click(on_buttonY_clicked)
    buttonN.on_click(on_buttonN_clicked) 
import QENSmodels<jupyter_output><empty_output><jupyter_text>create reference data<jupyter_code>nb_points = 500
xx = np.linspace(-4, 4, nb_points)
q = np.linspace(0.2, 2, 10)
added_noise = 0.1 * np.random.normal(0, 1, nb_points)
chudley_elliot_noisy = QENSmodels.sqwChudleyElliotDiffusion(xx,
                                                            q,
                                                            scale=1.,
                                                            center=0.,
                                                            D=0.23,
                                                            L=1.) * (1. + added_noise) 
chudley_elliot_noisy += 0.1 * added_noise<jupyter_output><empty_output><jupyter_text>Physical unitsFor information about unit conversion, please refer to the jupyter notebook called `Convert_units.ipynb` in the `tools` folder.The dictionary of units defined in the cell below specify the units of the refined parameters adapted to the convention used in the experimental datafile.<jupyter_code># Units of parameters for selected QENS model and experimental data
dict_physical_units = {'omega': "1/ps",
                       'q': "1/Angstrom",
                       'D': "ps.Angstrom^2",
                       'L': "Angstrom",
                       'scale': "unit_of_signal/ps",
                       'center': "1/ps"}<jupyter_output><empty_output><jupyter_text>create fitting model<jupyter_code>M = []
for i in range(len(q)):
    # Bumps fitting model
    Mq = bmp.Curve(QENSmodels.sqwChudleyElliotDiffusion,
                   xx,
                   chudley_elliot_noisy[i],
                   q[i],
                   scale=1,
                   center=0,
                   D=0.2,
                   L=0.7)

    Mq.scale.range(0.1, 1e5)
    Mq.center.range(-0.1, 0.1)
    Mq.D.range(0.1, 1)
    Mq.L.range(0.1, 3)

    # Q-independent parameters
    if i == 0:
        QD = Mq.D
        QL = Mq.L
    else:
        Mq.D = QD
        Mq.L = QL

    M.append(Mq)

problem = bmp.FitProblem(M)<jupyter_output><empty_output><jupyter_text>Choice of minimizer for bumps<jupyter_code>options_dict={'Levenberg-Marquardt': "lm", 
             'Nelder-Mead Simplex': "amoeba", 
             'DREAM': "dream", 
             'Differential Evolution': "de", 
             'Quasi-Newton BFGS': "newton", 
             'Random Lines (experimental)': "rl", 
             'Particle Swarm (experimental)': "ps", 
             'Parallel Tempering (experimental)': "pt"}

w_choice_minimizer = ipywidgets.Dropdown(
    options=list(options_dict.keys()),
    value='Levenberg-Marquardt',
    description='Minimizer:',
    layout=ipywidgets.Layout(height='40px')
)
w_choice_minimizer<jupyter_output><empty_output><jupyter_text>Setting for running bumps<jupyter_code>steps_fitting = ipywidgets.IntText(
    value=100,
    description='Number of steps when fitting',
    style={'description_width': 'initial'})

steps_fitting
# Preview of the settings
print('Initial chisq', problem.chisq_str())
problem.plot()<jupyter_output><empty_output><jupyter_text>[Top](Table-of-Contents) Running the fitRun the fit using the *minimizer* defined above with a number of *steps* also specified above<jupyter_code>result = fit(problem,
             method=options_dict[w_choice_minimizer.value], 
             steps=int(steps_fitting.value), 
             verbose=True)<jupyter_output><empty_output><jupyter_text>[Top](Table-of-Contents) Showing the results<jupyter_code>problem.plot()
# Print chi**2 and parameters' values after fit
print("final chisq", problem.chisq_str())

for k, v, dv in zip(problem.labels(), result.x, result.dx):
    if k in dict_physical_units.keys():
        print(k, ":", v, dv, dict_physical_units[k])
    else:
        print(k, ":", v, dv)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10244648318042814, 'fraction_numerical': 0.010008340283569641, 'mean_word_length': 3.120847651775487, 'pattern_counts': {'":': 2, '<': 38, '<?xml version=': 0, '>': 37, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 10, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '9', 'dir': 'jupyter-structured-clean-dedup', 'id': '473589', 'license': 'MIT', 'n_tokens_mistral': 2286, 'n_tokens_neox': 2148, 'n_words': 569, 'path': 'docs/examples/bumps_ChudleyElliotDiff_fit.ipynb', 'repo_name': 'celinedurniak/test_nbsphinx', 'size': '7194'}