### Install Dependencies Source: https://lmfitxps.readthedocs.io/en/latest/about.html Install all project dependencies using pip by running this command in your terminal. ```bash pip install -r requirements.txt ``` -------------------------------- ### Install lmfitxps development version Source: https://lmfitxps.readthedocs.io/en/latest/_sources/introduction.rst.txt Clone the GitHub repository to install the development version or contribute to the project. ```sh git clone https://github.com/Julian-Hochhaus/lmfitxps.git ``` -------------------------------- ### Example: ConvGaussianDoniachSinglett with ShirleyBG Model Source: https://lmfitxps.readthedocs.io/en/latest/_sources/introduction.rst.txt This Python script demonstrates fitting a ConvGaussianDoniachSinglett model with a ShirleyBG background. It is used for spectral fitting. ```python from lmfitxps.models import ConvGaussianDoniachSinglett, ShirleyBG # Initialize the model with ShirleyBG background model = ConvGaussianDoniachSinglett(background=ShirleyBG, prefix='singlett_') # Define initial parameters for the model params = model.make_params(center=10, sigma=1, amplitude=10) # Fit the model to the data result = model.fit(y, params, x=x) # Access the fit results print(result.fit_report()) ``` -------------------------------- ### Example: FermiEdgeModel fitting Source: https://lmfitxps.readthedocs.io/en/latest/_sources/introduction.rst.txt This Python script is an example for fitting the FermiEdgeModel. It is used in conjunction with the FermiModel. ```python from lmfitxps.models import FermiEdgeModel # Initialize the model model = FermiEdgeModel(prefix='fermi_') # Define initial parameters for the model params = model.make_params(center=10, sigma=1) # Fit the model to the data result = model.fit(y, params, x=x) # Access the fit results print(result.fit_report()) ``` -------------------------------- ### Fit XPS Data with ConvGaussianDoniachDublett and TougaardBG Source: https://lmfitxps.readthedocs.io/en/latest/introduction.html This example demonstrates fitting XPS data using a combination of ConvGaussianDoniachDublett and TougaardBG models. It includes data loading, model definition, parameter initialization, fitting, and plotting the results. Ensure data is in CSV format and adjust paths as needed. ```python import numpy as np import matplotlib.pyplot as plt import lmfit import sys import os sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../src'))) from lmfitxps import models import matplotlib as mpl exec_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) dublett = models.ConvGaussianDoniachDublett(prefix='dublett_', independent_vars=["x"]) bg=models.TougaardBG(independent_vars=["x","y"], prefix='tougaard_') fit_model=dublett+bg data = np.genfromtxt(exec_dir + '/examples/clean_Au_4f.csv', delimiter=',', skip_header=0) x = data[:, 0] y = data[:, 1] output_dir = os.path.join(exec_dir, 'examples/', 'plots') os.makedirs(output_dir, exist_ok=True) fig, (ax1, ax2) = plt.subplots(nrows=2,gridspec_kw={'height_ratios': [1, 1]}, sharex=True) fig.patch.set_facecolor('#FCFCFC') params = lmfit.Parameters() params.add('tougaard_B', value=148.969) params.add('tougaard_C', value=144.506, vary=False) params.add('tougaard_D', value=268.598, vary=False) params.add('tougaard_C_d', value=0.281, vary=False) params.add('tougaard_extend', value=30) params.add('dublett_amplitude', value=np.max(y)) params.add('dublett_sigma', value=0.2126) params.add('dublett_gamma', value=0.04) params.add('dublett_gaussian_sigma', value=0.0892) params.add('dublett_center', value=92.2273) params.add('dublett_soc', value=3.67127) params.add('dublett_height_ratio', value=0.7) params.add('dublett_fct_coster_kronig', value=1.04) result = fit_model.fit(y, params, y=y, x=x, weights=1 /(np.sqrt(y))) comps = result.eval_components(x=x, y=y) print(result.fit_report()) cmap = mpl.colormaps['tab20'] ax1.plot(x, result.best_fit, label='Best Fit', color=cmap(0)) ax1.plot(x, y, 'x', markersize=4, label='Data Points', color=cmap(2)) ax1.plot(x, comps['tougaard_'], label='Tougaard background', color='black') ax1.plot(x, comps['dublett_'] + comps['tougaard_'], color=cmap(4), label="Doniach-Dublett") ax1.fill_between(x, comps['dublett_'] + comps['tougaard_'], comps['tougaard_'], alpha=0.5,color=cmap(5)) ax1.legend() ax1.set_xlabel('bin. energy in eV') ax1.set_ylabel('intensity in arb. units') # Set ticks only inside ax1.tick_params(axis='x', which='both',top=True, direction='in') ax1.tick_params(axis='y', which='both', right=True,direction='in') ax2.tick_params(axis='x', which='both',top=True, direction='in') ax2.tick_params(axis='y', which='both', right=True, direction='in') ax1.set_yticklabels([]) ax1.set_title(f'ConvGaussian DoniachDublett using kin. energy scale') fig.subplots_adjust(hspace=0) ax1.set_xlim(np.min(x), np.max(x)) ``` -------------------------------- ### Install required packages for lmfitxps Source: https://lmfitxps.readthedocs.io/en/latest/introduction.html If required packages are not automatically installed, use this command to install them. Ensure you have pip installed. ```bash lmfit>=1.1.0 matplotlib>=3.6 numpy>=1.19 scipy>=1.6 ``` -------------------------------- ### Example: ConvGaussianDoniachDublett with TougaardBG Model Source: https://lmfitxps.readthedocs.io/en/latest/_sources/introduction.rst.txt This Python script shows how to fit a ConvGaussianDoniachDublett model using the TougaardBG background. This is useful for analyzing doublet peaks in XPS data. ```python from lmfitxps.models import ConvGaussianDoniachDublett, TougaardBG # Initialize the model with TougaardBG background model = ConvGaussianDoniachDublett(background=TougaardBG, prefix='dublett_') # Define initial parameters for the model params = model.make_params(center=10, sigma=1, amplitude=10) # Fit the model to the data result = model.fit(y, params, x=x) # Access the fit results print(result.fit_report()) ``` -------------------------------- ### Install lmfitxps using pip Source: https://lmfitxps.readthedocs.io/en/latest/introduction.html Use this command to install the stable version of the lmfitxps package. Ensure you have pip installed. ```bash $ pip install lmfitxps ``` -------------------------------- ### Install lmfitxps using pip Source: https://lmfitxps.readthedocs.io/en/latest/_sources/introduction.rst.txt Use this command to install the stable version of lmfitxps. Ensure required packages are present. ```bash pip install lmfitxps ``` -------------------------------- ### Clone lmfitxps repository for development Source: https://lmfitxps.readthedocs.io/en/latest/introduction.html Clone the GitHub repository to install the development version or contribute to lmfitxps. Ensure you have git installed. ```bash $ git clone https://github.com/Julian-Hochhaus/lmfitxps.git ``` -------------------------------- ### Fit Background Spectra with lmfit Source: https://lmfitxps.readthedocs.io/en/latest/backgrounds.html This code snippet demonstrates fitting a complex background model to XPS data using lmfit. It includes parameter initialization, model definition, fitting, and component evaluation. Ensure lmfit, numpy, and matplotlib are installed. ```python data = np.genfromtxt(exec_dir + '/examples/clean_Au_4f.csv', delimiter=',', skip_header=1) x = 180-data[:, 0] y = data[:, 1] output_dir = os.path.join(exec_dir, 'docs/src/', 'plots') os.makedirs(output_dir, exist_ok=True) params = lmfit.Parameters() params.add('tougaard_B', value= 197.643926) params.add('tougaard_C', value=144.506, vary=False) params.add('tougaard_C_d', value=0.281, vary=False) params.add('tougaard_D', value=268.598, vary=False) params.add('tougaard_extend', value=0) params.add('d1_amplitude', value=71980) params.add('d1_sigma', value=0.21) params.add('d1_gamma', value=0.01) params.add('d1_gaussian_sigma', value=0.0892) params.add('d1_center', value=180-92.2273) params.add('d1_soc', value=3.67127) params.add('d1_height_ratio', value=0.7) params.add('d1_fct_coster_kronig', value=1.04, vary=False) params.add('d2_amplitude', value=43966) params.add('d2_sigma', value=0.2, expr='d1_sigma') params.add('d2_gamma', value=0.0, expr='d1_gamma') params.add('d2_gaussian_sigma', value=0.14, expr='d1_gaussian_sigma') params.add('diff', value=-0.31165) params.add('d2_center', value=180-92.4, expr='d1_center+diff') params.add('d2_soc', value=-3.67, expr="d1_soc") params.add('d2_height_ratio', value=0.7, expr='d1_height_ratio') params.add('d2_fct_coster_kronig', value=1, expr='d1_fct_coster_kronig') params.add('const_c', value=2677.97771) fit_model = tougaard_model + d1+d2 + const result = fit_model.fit(y, params, y=y, x=x, weights=1 /(np.sqrt(y))) ``` -------------------------------- ### Fit Fermi-Edge Model with lmfitxps Source: https://lmfitxps.readthedocs.io/en/latest/introduction.html Example of fitting a Fermi-Edge model combined with a constant background to experimental data. Includes data loading, parameter initialization, fitting, and plotting of results and residuals. ```python import numpy as np import matplotlib.pyplot as plt import lmfit import sys import os sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../src'))) from lmfitxps import models import matplotlib as mpl exec_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) fermi = models.FermiEdgeModel(prefix='fermi_', independent_vars=["x"]) const = lmfit.models.ConstantModel(prefix='const_') fit_model=fermi+const data = np.genfromtxt(exec_dir + '/examples/FermiEdge.csv', delimiter=',', skip_header=1) x = data[:, 0] y = data[:, 1] output_dir = os.path.join(exec_dir, 'examples/', 'plots') os.makedirs(output_dir, exist_ok=True) fig, (ax1, ax2) = plt.subplots(nrows=2,gridspec_kw={'height_ratios': [1, 1]}, sharex=True) fig.patch.set_facecolor('#FCFCFC') params = lmfit.Parameters() params.add('fermi_amplitude', value=232) params.add('fermi_sigma', value=0.2126) params.add('fermi_kt', value=0.0026, vary=False) params.add('fermi_center', value=236) params.add('const_c', value=np.min(y)) result = fit_model.fit(y, params, y=y, x=x, weights=1 /(np.sqrt(y))) comps = result.eval_components(x=x, y=y) print(result.fit_report()) cmap = mpl.colormaps['tab20'] ax1.plot(x, result.best_fit, label='Best Fit', color=cmap(0)) ax1.plot(x, y, 'x', markersize=4, label='Data Points', color=cmap(2)) ax1.plot(x, comps['const_'], label='const. background', color='black') ax1.plot(x, comps['fermi_'] + comps['const_'], color=cmap(4), label="fermi-edge") ax1.fill_between(x, comps['fermi_'] + comps['const_'], comps['const_'], alpha=0.5,color=cmap(5)) ax1.legend() ax1.set_xlabel('kin. energy in eV') ax1.set_ylabel('intensity in arb. units') # Set ticks only inside ax1.tick_params(axis='x', which='both',top=True, direction='in') ax1.tick_params(axis='y', which='both', right=True,direction='in') ax2.tick_params(axis='x', which='both',top=True, direction='in') ax2.tick_params(axis='y', which='both', right=True, direction='in') ax1.set_yticklabels([]) ax1.set_title(f'FermiEdgeModel using kin. energy scale') fig.subplots_adjust(hspace=0) ax1.set_xlim(np.min(x), np.max(x)) # Residual plot residual = result.residual ax2.plot(x, residual) ax2.set_xlabel('kin. energy in eV') ax2.set_ylabel('Residual') plot_filename = os.path.join(output_dir, f'plot_fermi_kin.png') fig.savefig(plot_filename, dpi=300) plt.close(fig) ``` -------------------------------- ### Fit Fermi-Edge Model with Reversed Energy Scale Source: https://lmfitxps.readthedocs.io/en/latest/introduction.html Example of fitting a Fermi-Edge model with a reversed energy scale. Demonstrates parameter constraints (min/max) and plotting of fit results and residuals. ```python fermi = models.FermiEdgeModel(prefix='fermi_', independent_vars=["x"]) const = lmfit.models.ConstantModel(prefix='const_') fit_model=fermi+const data = np.genfromtxt(exec_dir + '/examples/FermiEdge.csv', delimiter=',', skip_header=1) x = 240-data[:, 0] y = data[:, 1] output_dir = os.path.join(exec_dir, 'examples/', 'plots') os.makedirs(output_dir, exist_ok=True) fig2, (ax21, ax22) = plt.subplots(nrows=2,gridspec_kw={'height_ratios': [1, 1]}, sharex=True) fig2.patch.set_facecolor('#FCFCFC') params = lmfit.Parameters() params.add('fermi_amplitude', value=232, min=220, max=240) params.add('fermi_sigma', value=0.15, min=0.12,max=0.17) params.add('fermi_kt', value=0.0026, vary=False) params.add('fermi_center', value=3.5, min=3, max=4) params.add('const_c', value=np.min(y), min=np.min(y), max=np.mean(y)) result = fit_model.fit(y, params, y=y, x=x, weights=1 /(np.sqrt(y))) comps = result.eval_components(x=x, y=y) print(result.fit_report()) cmap = mpl.colormaps['tab20'] ax21.plot(x, result.best_fit, label='Best Fit', color=cmap(0)) ax21.plot(x, y, 'x', markersize=4, label='Data Points', color=cmap(2)) ax21.plot(x, comps['const_'], label='const. background', color='black') ax21.plot(x, comps['fermi_'] + comps['const_'], color=cmap(4), label="fermi-edge") ax21.fill_between(x, comps['fermi_'] + comps['const_'], comps['const_'], alpha=0.5,color=cmap(5)) ax21.legend() ax21.set_xlabel('bin. energy in eV') ax21.set_ylabel('intensity in arb. units') ``` -------------------------------- ### Setting up XPS Fitting Models Source: https://lmfitxps.readthedocs.io/en/latest/backgrounds.html This code initializes TougaardBG and ConvGaussianDoniachDublett models for XPS analysis. It sets up parameters for background and peak fitting, including fixed and variable parameters. ```python exec_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) tougaard_model = models.TougaardBG(prefix='tougaard_', independent_vars=['y', 'x']) d1 = models.ConvGaussianDoniachDublett(prefix='d1_') d2 = models.ConvGaussianDoniachDublett(prefix='d2_') const = lmfit.models.ConstantModel(prefix='const_') data = np.genfromtxt(exec_dir + '/examples/clean_Au_4f.csv', delimiter=',', skip_header=1) x = data[:, 0] y = data[:, 1] guess_extend(x,y,156.969,144.506,0.281,268.598) output_dir = os.path.join(exec_dir, 'docs/src/', 'plots') os.makedirs(output_dir, exist_ok=True) combined_fig, (combined_ax1, combined_ax2) = plt.subplots(nrows=2,gridspec_kw={'height_ratios': [1, 1]}, sharex=True) combined_fig.patch.set_facecolor('#FCFCFC') residual_fig, residual_ax = plt.subplots(figsize=(6, 4)) residual_fig.patch.set_facecolor('#FCFCFC') combined2_fig, combined2_ax = plt.subplots(figsize=(6, 4)) combined2_fig.patch.set_facecolor('#FCFCFC') tg_bgs=[] tg_res=[] for j in [0]+[i for i in range(27,35,1)]: params = lmfit.Parameters() params.add('tougaard_B', value=148.969) params.add('tougaard_C', value=144.506, vary=False) params.add('tougaard_C_d', value=0.281, vary=False) params.add('tougaard_D', value=268.598, vary=False) params.add('tougaard_extend', value=j) params.add('d1_amplitude', value=71980, vary=False) params.add('d1_sigma', value=0.2126, vary=False) params.add('d1_gamma', value=0.01, vary=False) params.add('d1_gaussian_sigma', value=0.0892, vary=False) params.add('d1_center', value=92.2273, vary=False) params.add('d1_soc', value=3.67127, vary=False) params.add('d1_height_ratio', value=0.7, vary=False) params.add('d1_fct_coster_kronig', value=1.04, vary=False) params.add('d2_amplitude', value=43966, vary=False) params.add('d2_sigma', value=0.2, expr='d1_sigma') params.add('d2_gamma', value=0.0, expr='d1_gamma') params.add('d2_gaussian_sigma', value=0.14, expr='d1_gaussian_sigma') params.add('diff', value=0.31) ``` -------------------------------- ### ConvGaussianDoniachDublett Initialization and Parameter Hints Source: https://lmfitxps.readthedocs.io/en/latest/_modules/lmfitxps/models.html Details the initialization of the ConvGaussianDoniachDublett model and the parameter hints set for its components, including amplitude, sigma, gamma, and broadening factors. ```APIDOC ## ConvGaussianDoniachDublett ### Description Initializes the ConvGaussianDoniachDublett model, inheriting from `lmfit.model.Model`. It sets default parameter hints for various components of the Doniach-Sunjic lineshape and a Gaussian broadening. ### Method ```python def __init__(self, *args, **kwargs): super().__init__(dublett, *args, **kwargs) self._set_paramhints_prefix() ``` ### Parameters - **amplitude** (:obj:`float`) - Amplitude of the larger peak (P1) of the dublett. - **sigma** (:obj:`float`) - Doniach-broadening of the larger peak (P1) of the dublett. - **gamma** (:obj:`float`) - Asymmetry of the larger peak (P1) of the dublett. - **center** (:obj:`float`) - Center of peak P1. - **soc** (:obj:`float`) - Distance (energy) between the two peaks. - **height_ratio** (:obj:`float`) - Ratio of the amplitude of the smaller peak with respect to the larger one. - **fct_coster_kronig** (:obj:`float`) - Factor that scales P2's broadening with respect to P1 (Coster-Kronig effect). - **gaussian_sigma** (:obj:`float`) - Broadening of the gaussian kernel. ### Parameter Hints - **amplitude**: value=100, min=0 - **sigma**: value=0.2, min=0 - **gamma**: value=0.02 - **gaussian_sigma**: value=0.2, min=0 - **center**: value=285 - **soc**: value=2.0 - **height_ratio**: value=0.75, min=0 - **fct_coster_kronig**: value=1, min=0 - **gaussian_fwhm**: expr='2*{pre:s}gaussian_sigma*1.1774' - **lorentzian_fwhm_p1**: expr='{pre:s}sigma*(2+{pre:s}gamma*2.5135+({pre:s}gamma*3.6398)**4)' - **lorentzian_fwhm_p2**: expr='{pre:s}sigma*(2+{pre:s}gamma*2.5135+({pre:s}gamma*3.6398)**4)*{pre:s}fct_coster_kronig' ``` -------------------------------- ### Set TougaardBG Parameter Hints Source: https://lmfitxps.readthedocs.io/en/latest/_modules/lmfitxps/models.html Sets initial values and constraints for the TougaardBG model parameters: 'B', 'C', 'C_d', 'D', and 'extend'. ```python def _set_paramhints_prefix(self): """ Sets parameter hints for the model. The method sets initial values and constraints for the parameters 'B', 'C', 'C_d', 'D', and 'extend'. """ self.set_param_hint('B', value=2886) self.set_param_hint('C', value=1643) self.set_param_hint('C_d', value=1) self.set_param_hint('D', value=1) self.set_param_hint('extend', value=0, vary=False) ``` -------------------------------- ### General workflow for predefined models in lmfitxps Source: https://lmfitxps.readthedocs.io/en/latest/_sources/introduction.rst.txt This Python script demonstrates the typical workflow for using predefined models in lmfitxps. It includes importing data, initializing a model, defining parameters, fitting the model to the data, and printing the fit report. ```python import numpy as np from lmfitxps.models import ChoosenModel # Import your data, ensuring that energy (x) and intensity (y) values are stored in arrays x = np.array([...]) # Replace with your energy data y = np.array([...]) # Replace with your intensity data # Initialize the model model = ChoosenModel(prefix='choosen_model_') # Model parameters will have the specified prefix # Define initial parameters for the model params = model.make_params(param1=10, param2=40) # Fit the model to the data result = model.fit(y, params, x=x) # Access the fit results print(result.fit_report()) ``` -------------------------------- ### General Workflow for Predefined Models in lmfitxps Source: https://lmfitxps.readthedocs.io/en/latest/introduction.html This schematic demonstrates the typical workflow for using predefined models in lmfitxps. It involves importing data, initializing a chosen model, defining initial parameters, and fitting the model to the data. ```python import numpy as np from lmfitxps.models import ChoosenModel # Import your data, ensuring that energy (x) and intensity (y) values are stored in arrays x = np.array([...]) # Replace with your energy data y = np.array([...]) # Replace with your intensity data # Initialize the model model = ChoosenModel(prefix='choosen_model_') # Model parameters will have the specified prefix # Define initial parameters for the model params = model.make_params(param1=10, param2=40) # Fit the model to the data result = model.fit(y, params, x=x) ``` -------------------------------- ### ConvGaussianDoniachSinglett Source: https://lmfitxps.readthedocs.io/en/latest/_modules/lmfitxps/models.html A model representing a convolution of a Gaussian and a Doniach-Sunjic profile, suitable for fitting XPS signals with asymmetry. It combines experimental setup influences (Gaussian) with sample physics (Doniach-Sunjic). ```APIDOC ## ConvGaussianDoniachSinglett ### Description A model based on a convolution of a Gaussian and a Doniach-Sunjic profile. The model is designed for fitting XPS signals with asymmetry. The Gaussian thereby represents the gaussian-like influences of the experimental setup and the Doniach-Sunjic represents the sample's physics. The implementation is based on the `Gaussian `_ and `Doniach `_ lineshapes of the LMFIT package. The convolution is calculated using the FFT-Convolution implemented in `scipy.signal.fftconvolve `_. The Convolution is, in analogy to the Voigt profile given by: .. math:: (DS * G)(E, A, \mu, \gamma, \alpha, \sigma) = A \cdot \int_{-\infty}^{\infty} DS(E', \mu,\gamma,\alpha) G(E - E', \sigma)\, dE' The Doniach-Sunjic profile (:math:`DS`) is convolved with the Gaussian kernel (:math:`G`). Thereby: - :math:`A` is the amplitude of the peak profile, - :math:`\mu` is the center of the peak, - :math:`\gamma` represents the broadening of the Doniach-Sunjic lineshape, - :math:`\alpha` is the asymmetry of the Doniach-Sunjic lineshape, - :math:`\sigma` is the broadening parameter of the Gaussian kernel. ### Parameters #### Model Parameters - **amplitude** (float) - Amplitude :math:`A` of the peak profile - **sigma** (float) - Broadening of the Doniach-Sunjic. - **gamma** (float) - Asymmetry of the Doniach-Sunjic. - **center** (float) - Center of the peak profile. - **gaussian_sigma** (float) - Broadening of the gaussian kernel. #### Inherited Parameters (from lmfit.model.Model) - **x** (array) - 1D-array containing the x-values (energies) of the spectrum. - **y** (array) - 1D-array containing the y-values (intensities) of the spectrum. ### Usage ```python from lmfitxps.models import ConvGaussianDoniachSinglett # Instantiate the model model = ConvGaussianDoniachSinglett() # Fit the model to data (example) # params = model.make_params() # result = model.fit(data, params, x=x_values) # print(result.fit_report()) ``` ### Notes The `ConvGaussianDoniachSinglett` class inherits from `lmfit.model.Model` and only extends it. Therefore, the `lmfit.model.Model` class parameters are inherited as well. ``` -------------------------------- ### Set Parameter Hints for ConvGaussianDoniachDublett Source: https://lmfitxps.readthedocs.io/en/latest/_modules/lmfitxps/models.html Sets default parameter hints including values, minimums, and expressions for peak amplitudes, broadening, and ratios. ```python def _set_paramhints_prefix(self): self.set_param_hint('amplitude', value=100, min=0) self.set_param_hint('sigma', value=0.2, min=0) self.set_param_hint('gamma', value=0.02) self.set_param_hint('gaussian_sigma', value=0.2, min=0) self.set_param_hint('center', value=285) self.set_param_hint('soc', value=2.0) self.set_param_hint('height_ratio', value=0.75, min=0) self.set_param_hint('fct_coster_kronig', value=1, min=0) g_fwhm_expr = '2*{pre:s}gaussian_sigma*1.1774' self.set_param_hint('gaussian_fwhm', expr=g_fwhm_expr.format(pre=self.prefix)) l_p1_fwhm_expr = '{pre:s}sigma*(2+{pre:s}gamma*2.5135+({pre:s}gamma*3.6398)**4)' l_p2_fwhm_expr = '{pre:s}sigma*(2+{pre:s}gamma*2.5135+({pre:s}gamma*3.6398)**4)*{pre:s}fct_coster_kronig' self.set_param_hint('lorentzian_fwhm_p1', expr=l_p1_fwhm_expr.format(pre=self.prefix)) self.set_param_hint('lorentzian_fwhm_p2', expr=l_p2_fwhm_expr.format(pre=self.prefix)) ``` -------------------------------- ### Set Parameter Hints for a Model Source: https://lmfitxps.readthedocs.io/en/latest/_modules/lmfitxps/models.html Sets default values, minimum, and maximum constraints for model parameters like 'center', 'kt', 'amplitude', and 'sigma'. Useful for initializing model fitting. ```python kb = scipy.constants.physical_constants['Boltzmann constant in eV/K'][0] self.set_param_hint('center', value=np.mean(x), min=min(x), max=max(x)) self.set_param_hint('kt', value=kb * 300, min=0, max=kb * 1500) self.set_param_hint('amplitude', value=(max(data) - min(data)) / 10, min=0, max=(max(data) - min(data))) self.set_param_hint('sigma', value=(max(x) - min(x)) / len(x), min=0, max=2) params = self.make_params() return lmfit.models.update_param_vals(params, self.prefix, **kwargs) ``` -------------------------------- ### ConvGaussianDoniachSinglett Class Source: https://lmfitxps.readthedocs.io/en/latest/peaks.html The ConvGaussianDoniachSinglett class is a model designed for fitting XPS signals with asymmetry. It convolves a Gaussian profile (representing experimental setup influences) with a Doniach-Sunjic profile (representing sample physics). The convolution is computed using FFT-Convolution. ```APIDOC ## `ConvGaussianDoniachSinglett` ### Description A model based on a convolution of a Gaussian and a Doniach-Sunjic profile. The model is designed for fitting XPS signals with asymmetry. The Gaussian thereby represents the gaussian-like influences of the experimental setup and the Doniach-Sunjic represents the sample’s physics. ### Mathematical Basis The convolution is, in analogy to the Voigt profile given by: (DS∗G)(E,A,μ,γ,α,σ)=A⋅∫−∞∞DS(E′,μ,γ,α)G(E−E′,σ)dE′ Where DS is the Doniach-Sunjic profile and G is the Gaussian kernel. ### Parameters #### Model-specific Parameters - **x** (array) - 1D-array containing the x-values (energies) of the spectrum. - **y** (array) - 1D-array containing the y-values (intensities) of the spectrum. - **amplitude** (float) - Amplitude A of the peak profile. - **sigma** (float) - Broadening of the Doniach-Sunjic. - **gamma** (float) - Asymmetry of the Doniach-Sunjic. - **center** (float) - Center of the peak profile. - **gaussian_sigma** (float) - Broadening of the gaussian kernel. #### Inherited Parameters from `lmfit.model.Model` - **independent_vars** (list of str, optional) - Arguments to the model function that are independent variables (default is ['x']). - **prefix** (str, optional) - String to prepend to parameter names, needed to add two Models that have parameter names in common. - **nan_policy** ({'raise', 'propagate', 'omit'}, optional) - How to handle NaN and missing values in data. Options are: - 'raise': raise a ValueError (default) - 'propagate': do nothing - 'omit': drop missing data - **kwargs** (optional) - Keyword arguments to pass to `Model`. ``` -------------------------------- ### Fit ConvGaussianDoniachSinglett with ShirleyBG Model Source: https://lmfitxps.readthedocs.io/en/latest/introduction.html This snippet demonstrates fitting a combined model of ConvGaussianDoniachSinglett and ShirleyBG to XPS data. It includes data loading, parameter initialization, model fitting, and plotting of the best fit, data points, Shirley background, and the combined peak. Residuals are also plotted. Ensure the 'clean_Au_4f.csv' file is available and the 'src' directory is in the Python path. ```python import numpy as np import matplotlib.pyplot as plt import lmfit import sys import os sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../src'))) from lmfitxps import models import matplotlib as mpl exec_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) singlett = models.ConvGaussianDoniachSinglett(prefix='singlett_', independent_vars=["x"]) bg=models.ShirleyBG(independent_vars=["y"], prefix='shirley_') fit_model=singlett+bg data = np.genfromtxt(exec_dir + '/examples/clean_Au_4f.csv', delimiter=',', skip_header=0) x = data[150:, 0] y = data[150:, 1] output_dir = os.path.join(exec_dir, 'examples/', 'plots') os.makedirs(output_dir, exist_ok=True) fig, (ax1, ax2) = plt.subplots(nrows=2,gridspec_kw={'height_ratios': [1, 1]}, sharex=True) fig.patch.set_facecolor('#FCFCFC') params = lmfit.Parameters() params.add('shirley_k', value=0.002) params.add('shirley_const', value=100) params.add('singlett_amplitude', value=np.max(y)) params.add('singlett_sigma', value=0.2126) params.add('singlett_gamma', value=0.0, vary=False) params.add('singlett_gaussian_sigma', value=0.0892) params.add('singlett_center', value=92) result = fit_model.fit(y, params, y=y, x=x, weights=1 /(np.sqrt(y))) comps = result.eval_components(x=x, y=y) print(result.fit_report()) cmap = mpl.colormaps['tab20'] ax1.plot(x, result.best_fit, label='Best Fit', color=cmap(0)) ax1.plot(x, y, 'x', markersize=4, label='Data Points', color=cmap(2)) ax1.plot(x, comps['shirley_'], label='Shirley background', color='black') ax1.plot(x, comps['singlett_'] + comps['shirley_'], color=cmap(4), label="Doniach-Peak") ax1.fill_between(x, comps['singlett_'] + comps['shirley_'], comps['shirley_'], alpha=0.5,color=cmap(5)) ax1.legend() ax1.set_xlabel('bin. energy (eV)') ax1.set_ylabel('intensity in arb. units') # Set ticks only inside ax1.tick_params(axis='x', which='both',top=True, direction='in') ax1.tick_params(axis='y', which='both', right=True,direction='in') ax2.tick_params(axis='x', which='both',top=True, direction='in') ax2.tick_params(axis='y', which='both', right=True, direction='in') ax1.set_yticklabels([]) ax1.set_title(f'ConvGaussianDoniachSinglett using kin. energy scale') fig.subplots_adjust(hspace=0) ax1.set_xlim(np.min(x), np.max(x)) # Residual plot residual = result.residual ax2.plot(x, residual) ax2.set_xlabel('kin. energy in eV') ax2.set_ylabel('Residual') plot_filename = os.path.join(output_dir, f'plot_singlett_kin.png') fig.savefig(plot_filename, dpi=300) plt.close(fig) ``` ```python singlett = models.ConvGaussianDoniachSinglett(prefix='singlett_', independent_vars=["x"]) bg=models.ShirleyBG(independent_vars=["y"], prefix='shirley_') fit_model=singlett+bg data = np.genfromtxt(exec_dir + '/examples/clean_Au_4f.csv', delimiter=',', skip_header=0) x = 180-data[150:, 0] y = data[150:, 1] output_dir = os.path.join(exec_dir, 'examples/', 'plots') os.makedirs(output_dir, exist_ok=True) fig2, (ax21, ax22) = plt.subplots(nrows=2,gridspec_kw={'height_ratios': [1, 1]}, sharex=True) fig2.patch.set_facecolor('#FCFCFC') params = lmfit.Parameters() params.add('shirley_k', value=0.002) params.add('shirley_const', value=3000) params.add('singlett_amplitude', value=np.max(y)) params.add('singlett_sigma', value=0.15) params.add('singlett_gamma', value=0.0, vary=False) params.add('singlett_gaussian_sigma', value=0.15) params.add('singlett_center', value=87) result = fit_model.fit(y, params, y=y, x=x, weights=1 /(np.sqrt(y))) comps = result.eval_components(x=x, y=y) print(result.fit_report()) cmap = mpl.colormaps['tab20'] ax21.plot(x, result.best_fit, label='Best Fit', color=cmap(0)) ax21.plot(x, y, 'x', markersize=4, label='Data Points', color=cmap(2)) ax21.plot(x, comps['shirley_'], label='Shirley background', color='black') ax21.plot(x, comps['singlett_'] + comps['shirley_'], color=cmap(4), label="Doniach-Peak") ax21.fill_between(x, comps['singlett_'] + comps['shirley_'], comps['shirley_'], alpha=0.5,color=cmap(5)) ax21.legend() ax21.set_xlabel('bin. energy (eV)') ax21.set_ylabel('intensity in arb. units') ``` -------------------------------- ### Define and Fit a ConvGaussianDoniachDublettModel with TougaardBG Source: https://lmfitxps.readthedocs.io/en/latest/introduction.html This snippet demonstrates defining a composite model, initializing parameters, loading data, performing a fit, and printing the fit report. Ensure necessary libraries like lmfit, numpy, and matplotlib are imported. ```python dublett = models.ConvGaussianDoniachDublett(prefix='dublett_', independent_vars=["x"]) bg=models.TougaardBG(independent_vars=["x","y"], prefix='tougaard_') fit_model=dublett+bg data = np.genfromtxt(exec_dir + '/examples/clean_Au_4f.csv', delimiter=',', skip_header=0) x = 180-data[:, 0] y = data[:, 1] output_dir = os.path.join(exec_dir, 'examples/', 'plots') os.makedirs(output_dir, exist_ok=True) params = lmfit.Parameters() params.add('tougaard_B', value=148.969) params.add('tougaard_C', value=144.506, vary=False) params.add('tougaard_D', value=268.598, vary=False) params.add('tougaard_C_d', value=0.281, vary=False) params.add('tougaard_extend', value=30) params.add('dublett_amplitude', value=np.max(y)) params.add('dublett_sigma', value=0.2126) params.add('dublett_gamma', value=0.04, min=0) params.add('dublett_gaussian_sigma', value=0.0892) params.add('dublett_center', value=87.663) params.add('dublett_soc', value=3.67127) params.add('dublett_height_ratio', value=0.7) params.add('dublett_fct_coster_kronig', value=1.04) result = fit_model.fit(y, params, y=y, x=x, weights=1 /(np.sqrt(y))) ``` -------------------------------- ### Set Parameter Hints for XPS Models Source: https://lmfitxps.readthedocs.io/en/latest/_modules/lmfitxps/models.html Defines default parameter hints for XPS spectral components like amplitude, sigma, and center. Includes expressions for derived parameters such as Gaussian and Lorentzian FWHM. ```python self._set_paramhints_prefix() def _set_paramhints_prefix(self): self.set_param_hint('amplitude', value=100, min=0) self.set_param_hint('sigma', value=0.2, min=0) self.set_param_hint('gamma', value=0.02) self.set_param_hint('gaussian_sigma', value=0.2, min=0) self.set_param_hint('center', value=100, min=0) g_fwhm_expr = '2*{pre:s}gaussian_sigma*1.1774' self.set_param_hint('gaussian_fwhm', expr=g_fwhm_expr.format(pre=self.prefix)) l_fwhm_expr = '{pre:s}sigma*(2+{pre:s}gamma*2.5135+({pre:s}gamma*3.6398)**4)' self.set_param_hint('lorentzian_fwhm', expr=l_fwhm_expr.format(pre=self.prefix)) ``` -------------------------------- ### Set ShirleyBG Parameter Hints Source: https://lmfitxps.readthedocs.io/en/latest/_modules/lmfitxps/models.html Sets parameter hints for the ShirleyBG model, providing initial values for 'k' and 'const'. ```python def _set_paramhints_prefix(self): """ Sets parameter hints for the model. The method sets initial values and constraints for the parameters :math:`k` and :math: `const`. """ self.set_param_hint('k', value=0.03) self.set_param_hint('const', value=1000) ``` -------------------------------- ### Initialize TougaardBG Model Source: https://lmfitxps.readthedocs.io/en/latest/_modules/lmfitxps/models.html Initializes the TougaardBG model instance, inheriting parameters from lmfit.model.Model. ```python def __init__(self, *args, **kwargs): """ Initializes the TougaardBG model instance. """ super().__init__(tougaard, *args, **kwargs) self._set_paramhints_prefix() ``` -------------------------------- ### Combine TougaardBG with ConstantModel Source: https://lmfitxps.readthedocs.io/en/latest/backgrounds.html Use TougaardBG with 'extend' set to 0 and combine it with an additional ConstantModel for accurate background approximation when dealing with substantial peak asymmetry. ```python import lmfit import lmfitxps tougaard_bg=lmfitxps.models.TougaardBG(prefix='tougaard_', independent_vars=['y', 'x']) const_bg=lmfit.models.ConstantModel(prefix='const_') bg_model=tougaard_bg+const_bg params = lmfit.Parameters() params.add('tougaard_extend', value=0) ``` -------------------------------- ### Set Parameter Hints for SlopeBG Source: https://lmfitxps.readthedocs.io/en/latest/_modules/lmfitxps/models.html Sets parameter hints for the SlopeBG model, specifically providing an initial value for the 'k' parameter. ```python def _set_paramhints_prefix(self): """ Sets parameter hints for the model. The method sets an initial value for the parameter 'k'. """ self.set_param_hint('k', value=0.01) ``` -------------------------------- ### Clone lmfitxps Repository Source: https://lmfitxps.readthedocs.io/en/latest/about.html Use this command to clone the lmfitxps repository to your local machine. Replace with your GitHub username. ```bash git clone https://github.com//lmfitxps.git ``` -------------------------------- ### Combine TougaardBG and ConstantModel Source: https://lmfitxps.readthedocs.io/en/latest/_sources/backgrounds.rst.txt Use TougaardBG with 'extend' set to 0 and combine it with lmfit's ConstantModel to approximate background, particularly when dealing with asymmetric peaks. Ensure 'independent_vars' are correctly set for both models. ```python import lmfit import lmfitxps tougaard_bg=lmfitxps.models.TougaardBG(prefix='tougaard_', independent_vars=['y', 'x']) const_bg=lmfit.models.ConstantModel(prefix='const_') bg_model=tougaard_bg+const_bg params = lmfit.Parameters() params.add('tougaard_extend', value=0) # Set all other parameters ``` -------------------------------- ### Initialize ShirleyBG Model Source: https://lmfitxps.readthedocs.io/en/latest/_modules/lmfitxps/models.html Initializes the ShirleyBG model instance. It inherits parameters from lmfit.model.Model and sets parameter hints for 'k' and 'const'. ```python def __init__(self, *args, **kwargs): """ Initializes the ShirleyBG model instance. """ super().__init__(shirley, *args, **kwargs) self._set_paramhints_prefix() ```