### Simple Feffit Fit Example Source: https://github.com/xraypy/xraylarch/blob/master/doc/xafs_feffit.rst Demonstrates a basic Feffit fit using a single Feff Path. This example covers parameter definition, Feff Path creation, transform setup, dataset creation, running the fit, and generating a report. ```python import xray.xafs.feffit from xray.xafs.feffit import feffit, feffit_report, feffit_dataset, feffit_transform, feffpath from xray.xafs.feffit.parameters import _math pars = xray.xafs.feffit.parameters.Parameters() pars.add_param("amp", "amp", "amplitude", guess=1.0, min=0.0, max=2.0) pars.add_param("en", "en", "energy", guess=20.0, min=10.0, max=30.0) pars.add_param("s02", "s02", "s02", guess=0.8, min=0.0, max=1.0) pars.add_param("degen", "degen", "degeneracy", guess=1.0, min=0.0, max=2.0) pars.add_param("r0", "r0", "r0", guess=1.8, min=1.0, max=3.0) pars.add_param("dr0", "dr0", "dr0", guess=0.0, min=-0.5, max=0.5) pars.add_param("sigma2", "sigma2", "sigma2", guess=0.005, min=0.0, max=0.02) pars.add_param("dsigma2", "dsigma2", "dsigma2", guess=0.0, min=-0.005, max=0.005) path = feffpath(pars.amp, pars.en, pars.s02, pars.degen, pars.r0, pars.dr0, pars.sigma2, pars.dsigma2) transform = feffit_transform(rmin=1.0, rmax=5.0) dataset = feffit_dataset("data/doc_feffit1.lar", transform=transform, pathlist=[path]) fit_result = feffit(dataset, pars) print(feffit_report(fit_result)) # Plotting commands (omitted for brevity, refer to source for full details) # xray.xafs.feffit.plot(dataset, fit_result, "k") # xray.xafs.feffit.plot(dataset, fit_result, "r") ``` -------------------------------- ### Install X-ray Larch with Documentation Tools Source: https://github.com/xraypy/xraylarch/blob/master/doc/installation.rst Installs xraylarch and the necessary tools to build the project's documentation. This is useful for contributors who want to update or review the documentation. ```bash pip install "xraylarch[doc]" ``` -------------------------------- ### Run GetLarch.bat on Windows Source: https://github.com/xraypy/xraylarch/blob/master/doc/installation.rst Execute this command in the Windows command prompt to start the Larch installation process using the GetLarch.bat script. Ensure you are in the directory where the script was downloaded. ```bash cd C:\Users\\Downloads GetLarch ``` -------------------------------- ### Example: Deconvolve XAFS Spectrum (Fe2O3) Source: https://github.com/xraypy/xraylarch/blob/master/doc/xafs_preedge.rst An example demonstrating the deconvolution of a XAFS spectrum for Fe2O3. ```python xas_deconvolve(energy, norm=norm) ``` -------------------------------- ### Install Basic Xraylarch with Pip Source: https://github.com/xraypy/xraylarch/blob/master/doc/installation.rst Installs the core xraylarch library from PyPI. This provides the basic functionality without GUI-related packages. ```bash pip install xraylarch ``` -------------------------------- ### Run GetLarch.sh on Linux/macOS Source: https://github.com/xraypy/xraylarch/blob/master/doc/installation.rst Execute this command in a Linux or macOS terminal to start the Larch installation process using the GetLarch.sh script. Navigate to the directory where the script was downloaded before running. ```bash cd Downloads sh GetLarch.sh ``` -------------------------------- ### Install X-ray Larch with Development Packages Source: https://github.com/xraypy/xraylarch/blob/master/doc/installation.rst Installs xraylarch along with packages needed for development and testing. Use this if you plan to contribute to the project or test new features. ```bash pip install "xraylarch[dev]" ``` -------------------------------- ### Pre-Edge Subtraction Example Source: https://github.com/xraypy/xraylarch/blob/master/doc/xafs_preedge.rst A simple example demonstrating how to perform pre-edge subtraction using the pre_edge function. ```APIDOC ## Pre-Edge Subtraction Example A simple example of pre-edge subtraction: .. code:: python # Larch fname = 'fe2o3_rt1.xmu' dat = read_ascii(fname, labels='energy mu i0') pre_edge(dat, group=dat) plot_mu(dat, show_pre=True, show_post=True) or in plain Python: .. code:: python from larch.io import read_ascii from larch.xafs import pre_edge from wxmplot.interactive import plot fname = 'fe2o3_rt1.xmu' dat = read_ascii(fname, labels='energy mu i0') pre_edge(dat, group=dat) ``` -------------------------------- ### Larch Interpreter Startup Source: https://github.com/xraypy/xraylarch/blob/master/doc/larchlang/start.rst This shows the typical output when starting the Larch interpreter, including version information and loaded libraries. ```text C:> larch =========================================================================== Larch 0.9.46 (2019-Sep-12) M. Newville, M. Koker, B. Ravel, and others Python 3.7.0 (default, Jun 28 2018, 07:39:16) numpy 1.16.4, scipy 1.3.0, matplotlib 3.1.0, lmfit 0.9.14, wx 4.0.6 =========================================================================== ``` -------------------------------- ### Install X-ray Larch from Source Source: https://github.com/xraypy/xraylarch/blob/master/doc/installation.rst Installs xraylarch in editable mode from a cloned source repository, including all optional packages. This is for developers who are actively working on the codebase. ```bash pip install -e ".[all]" ``` -------------------------------- ### Procedure Operation Examples Source: https://github.com/xraypy/xraylarch/blob/master/doc/larchlang/procedures.rst Demonstrates the behavior of the 'operate' procedure with different operation types and verbosity settings. ```larch larch> operate(3, 2, op='mul', verbose=True) op == mul ``` ```larch larch> operate(3, 2, op='xxx', verbose=True) op == xxx unsupported operation! ``` ```larch larch> operate(3, 2, op='xxx', debug=False) op == xxx ``` -------------------------------- ### Example: Applying Cauchy Wavelet Transform Source: https://github.com/xraypy/xraylarch/blob/master/doc/xafs_wavelets.rst This example demonstrates how to apply the Cauchy wavelet transform to Fe K-edge data of FeO. It requires the 'wavelet_example.lar' script to be available. ```lar .. literalinclude:: ../examples/xafs/wavelet_example.lar ``` -------------------------------- ### Load and Fit Data Example Source: https://github.com/xraypy/xraylarch/blob/master/doc/fitting_confidence.rst This script loads data, defines a model, and performs a fit using the minimize function. It's a prerequisite for generating confidence intervals. ```python from xraylarch.fitting import minimize, fit_report from xraylarch.fitting import confidence_intervals, confidence_report from xraylarch.fitting import f_test # Load data and define model (omitted for brevity) # ... # Perform the fit params = minimize(model, data=data, guesses=guesses, method='leastsq') print(fit_report(params)) ``` -------------------------------- ### Larch Script for Fitting Example Source: https://github.com/xraypy/xraylarch/blob/master/doc/fitting_confidence.rst This Larch script demonstrates a basic data fitting process, likely used as a precursor to confidence interval calculations. ```larch import xraylarch.fitting def gaussian(p, x): return p.amp * xraylarch.math.exp(-(x-p.cen)**2/(2*p.wid**2)) + p.off # Load data (omitted for brevity) # ... params = xraylarch.fitting.minimize(gaussian, data=data, guesses=guesses, method='leastsq') print(xraylarch.fitting.fit_report(params)) ``` -------------------------------- ### Larch ZeroDivisionError Example Source: https://github.com/xraypy/xraylarch/blob/master/doc/larchlang/errors.rst Demonstrates a runtime exception when attempting to divide by zero in Larch. ```larch larch> n = 1 larch> print(4.0 / ( n - 1)) ZeroDivisionError('float division') print(4.0/(n-1)) ^^^ ``` -------------------------------- ### Larch Try-Except for ZeroDivisionError Source: https://github.com/xraypy/xraylarch/blob/master/doc/larchlang/errors.rst A basic example of using try-except to handle a ZeroDivisionError in Larch. ```larch try: x = a/b except ZeroDivisionError: print('saw a divide by zero!) x = 0 #endtry ``` -------------------------------- ### Larch Script Example Source: https://github.com/xraypy/xraylarch/blob/master/doc/larchlang/modules.rst Define a Larch script with print statements, variable assignments, and a loop. This script can be executed directly. ```larch # file myscript.lar print('hello from myscript.lar!') name = 'Fred' phi = (sqrt(5)+1)/2 for i in range(5): print(i, sqrt(i)) #endfor # end of file myscript.lar ``` -------------------------------- ### FEFFit: Fitting in 'q' Space Source: https://github.com/xraypy/xraylarch/blob/master/doc/xafs_feffit.rst This example shows the output of a FEFFit analysis performed in 'q' space, which is the backtransformed k-space. The results are compared to fits in other spaces. ```text Fe-O path: amplitude: 0.785 +/- 0.020 distance: 1.981 +/- 0.003 sigma: 0.0070 +/- 0.0003 Fe-Fe path: amplitude: 0.785 +/- 0.020 distance: 3.401 +/- 0.001 sigma: 0.0101 +/- 0.0001 Fit statistics: chi2: 1.1987 dof: 10 r-factor: 0.009 ``` -------------------------------- ### Load Athena Project and Data Source: https://github.com/xraypy/xraylarch/blob/master/examples/Jupyter/XANES_PCA_example.ipynb Imports necessary Larch modules and reads an Athena project file. Ensure the 'athena' library is installed and the project file path is correct. ```python from pathlib import Path from larch.io import read_athena from larch.xafs import pre_edge from larch.math import pca_train, pca_fit from larch.plot.plotly_xafsplots import plot_mu, plot_pca_components, plot_pca_weights, plot_pca_fit filename = Path('..', 'pca', 'cyanobacteria.prj') prj = read_athena(filename) ``` -------------------------------- ### Call Larch Procedure with Unspecified Keyword Arguments Source: https://github.com/xraypy/xraylarch/blob/master/doc/larchlang/procedures.rst Demonstrates calling a procedure defined with '**options', showing how to pass and use various keyword arguments to control its behavior. ```larch larch> operate(3, 2, op='add') 5 larch> operate(3, 2, op='add', verbose=True) op == add ``` -------------------------------- ### Initialize and Display RixsMainWindow Source: https://github.com/xraypy/xraylarch/blob/master/doc/qtrixs.rst Create an instance of RixsMainWindow to manage and display RIXS data. The main window must be explicitly shown. ```python from larch.qtrixs.plotrixs import RixsMainWindow main_win = RixsMainWindow() main_win.show() ``` -------------------------------- ### Call Larch Procedure with Keyword Arguments Source: https://github.com/xraypy/xraylarch/blob/master/doc/larchlang/procedures.rst Illustrates calling a procedure with keyword arguments, demonstrating how to override default values and use named parameters. ```larch larch> xlog(16) 2.7725887222397811 larch> xlog(16, base=10) 1.2041199826559246 larch> xlog(16, base=2) 4.0 ``` -------------------------------- ### Plotting Subgroups from Athena Project Source: https://github.com/xraypy/xraylarch/blob/master/examples/Jupyter/Iteration_of_Group.ipynb Plots the energy and mu data for all subgroups within an Athena project file. This example requires matplotlib to be installed. The legend is placed outside the plot area for clarity. ```python # plotting all the subgroups in the athena project file import matplotlib.pyplot as plt for key, group in aprj.items(): plt.plot(group.energy, group.mu, label=key) plt.xlabel('Energy (eV)') plt.ylabel('mu') plt.legend(loc='upper left', bbox_to_anchor=(1, 1)) plt.plot() ``` -------------------------------- ### Install All Optional Packages for X-ray Larch Source: https://github.com/xraypy/xraylarch/blob/master/doc/installation.rst Installs xraylarch along with all available optional packages, including Larix, development tools, documentation tools, and Epics support. This provides a comprehensive installation. ```bash pip install "xraylarch[all]" ``` -------------------------------- ### Create and group parameters Source: https://github.com/xraypy/xraylarch/blob/master/doc/fitting_parameters.rst Demonstrates creating individual parameters with different configurations and then grouping them using the `group` function. Parameters can be added to an existing group later. ```python # create some Parameters c1 = param(0.75) # a constant (non-varying) parameter a1 = param(1.0, min=0, max=5, vary=True) # a bounded variable parameter a2 = guess(10., min=0) # a semi-bounded variable parameter # create a group of parameters, either from existing parameters # or ones created right here params = group(a1 = a1, a2 = a2, centroid = param(99, vary=False) ) # add more parameters to the group: params.c1 = c1 # add a constrained parameter: dependent on other parameters in the group params.e1 = param(expr='a1 - c1*sqrt(a2)') ``` -------------------------------- ### sum(sequence[, start]) Source: https://github.com/xraypy/xraylarch/blob/master/doc/larchlang/builtins.rst Calculates the sum of items in a sequence, optionally starting from an initial value. ```APIDOC ## sum(sequence[, start]) ### Description Calculate the sum of items in a sequence, optionally starting from an initial value. ### Parameters * **sequence** (iterable) - The sequence of numbers to sum. * **start** (number, optional) - The initial value to add to the sum. Defaults to 0. ``` -------------------------------- ### Run Feffit and report results Source: https://github.com/xraypy/xraylarch/blob/master/examples/Jupyter/feffit_basic_znse_wxmplot.ipynb Sets up a Feffit dataset combining the experimental data, Feff paths, and transform parameters, then performs the fit and prints a detailed report of the results. ```python # step 6: run and view the fit # now that we have data, a set of paths, and Fourier transform values, we can # set up a "Feffit Dataset" and then fit that with the group of Parameters # define dataset to include data, pathlist, transform dset = feffit_dataset(data=data, pathlist=[path_znse], transform=trans) # do the fit... result = feffit(pars, dset) # print out the fit report print(feffit_report(result)) ``` -------------------------------- ### Accessing Procedure Documentation Source: https://github.com/xraypy/xraylarch/blob/master/doc/larchlang/procedures.rst Illustrates how to access the documentation string of a defined procedure using the 'help' command in Larch. ```larch larch> help(safe_sqrt) safe sqrt function: returns sqrt(abs(x)) ``` -------------------------------- ### Initialize and Plot with wxmplot Source: https://github.com/xraypy/xraylarch/blob/master/examples/Jupyter/wxmplot_simple.ipynb Use this snippet to create an initial plot with custom labels and theme. Ensure numpy and wxmplot.interactive are imported. ```python # this example demonstrates using wxmpot from a Jupyter notebook import numpy as np x = np.linspace(-10, 10, 251) y = np.sin(x) + x/100 import wxmplot.interactive as wi wi.plot(x, y, label='sin+x', theme='dark', xlabel=r'$x\, (\mathrm{{\mu}m})$', new=True) ``` -------------------------------- ### Install Optional Packages with Conda Source: https://github.com/xraypy/xraylarch/blob/master/doc/installation.rst Installs additional optional packages such as openbabel and tomopy from the conda-forge channel into the active Conda environment. ```bash conda install -y -c conda-forge openbabel tomopy ``` -------------------------------- ### Symbol Name Nesting Example Source: https://github.com/xraypy/xraylarch/blob/master/doc/larchlang/notpython.rst Provides examples of nested symbol names using dot notation, common in Larch for organizing data and code. ```python cu_01.data.chi cu_02.path1.chi cu_03.model.chi ``` -------------------------------- ### Run Feffit and generate report Source: https://github.com/xraypy/xraylarch/blob/master/examples/Jupyter/feffit_basic_znse_bokeh.ipynb Sets up a Feffit dataset combining the experimental data, Feff paths, and transform parameters. It then executes the fit using the defined parameters and displays the results. ```python # step 6: run and view the fit # now that we have data, a set of paths, and Fourier transform values, we can # set up a "Feffit Dataset" and then fit that with the group of Parameters # define dataset to include data, pathlist, transform dset = feffit_dataset(data=data, pathlist=[path_znse], transform=trans) # do the fit... result = feffit(pars, dset) ``` -------------------------------- ### Set up Feffit Parameters Source: https://github.com/xraypy/xraylarch/blob/master/examples/Jupyter/ReadingLarixSessions.ipynb Initializes a parameter group for feffit with predefined parameters and their variations. This is used to define the fitting space and initial parameter values. ```python _feffit_params = param_group(reff=-1.0) _feffit_params.s02 = param(1.0, vary=True) _feffit_params.e0 = param(0.001, vary=True) _feffit_params.delr_Se245 = param(0.001, min=-0.75, max=0.75, vary=True) _feffit_params.sigma2_Se245 = param(0.0078, min=0.0, max=1.0, vary=True) _feffit_params.delr_Zn401 = param(0.001, min=-0.75, max=0.75, vary=True) _feffit_params.sigma2_Zn401 = param(0.01, min=0.0, max=1.0, vary=True) ``` -------------------------------- ### Install Development Version of X-ray Larch Source: https://github.com/xraypy/xraylarch/blob/master/doc/installation.rst Installs the latest nightly build of the development version of xraylarch. This is for users who want to test the most recent code, but it may be unstable. ```bash larch -n ``` -------------------------------- ### Create a directory Source: https://github.com/xraypy/xraylarch/blob/master/doc/larchlang/builtins.rst Creates a directory with the specified name, including any intermediate subdirectories. The `mode` option sets the permission mask. ```larch larch> mkdir(directory_name[, mode=0777]) ``` -------------------------------- ### Install X-ray Larch with Epics Controls System Support Source: https://github.com/xraypy/xraylarch/blob/master/doc/installation.rst Installs xraylarch and packages required for integration with the Epics controls system. This is for users who need to interface with Epics. ```bash pip install "xraylarch[epics]" ``` -------------------------------- ### Create Desktop Shortcuts for Larch Applications Source: https://github.com/xraypy/xraylarch/blob/master/doc/installation.rst Generates a 'Larch' folder on the desktop containing shortcuts to launch GUI applications. This command may require specifying the path to Python or Larch explicitly. ```bash larch -m ``` ```bash $HOME/xraylarch/bin/larch -m ``` ```bash %APPDATA%\Local\xraylarch\Scripts\larch.exe -m ``` -------------------------------- ### Run Feff fit and view results Source: https://github.com/xraypy/xraylarch/blob/master/examples/Jupyter/feffit_cu_3paths.ipynb Sets up a Feffit dataset combining the experimental data, Feff paths, and transform parameters. It then executes the Feff fit using the defined parameters and dataset. ```python # step 6: run and view the fit # now that we have data, a set of paths, and Fourier transform values, we can # set up a "Feffit Dataset" and then fit that with the group of Parameters # define dataset to include data, pathlist, transform dset = feffit_dataset(data=cu_data, pathlist=[path1], transform=trans) # do the fit... result = feffit(pars, dset) ``` -------------------------------- ### run Source: https://github.com/xraypy/xraylarch/blob/master/doc/larchlang/builtins.rst Executes Larch code from a specified file. ```APIDOC ## run(filename[, printall=True]) ### Description Executes the Larch text in a file as Larch code. ### Parameters #### Path Parameters - **filename** (string) - Required - The path to the Larch file to execute. #### Keyword Arguments - **printall** (boolean) - Optional - Whether to print all output (default: True). ``` -------------------------------- ### Larch Try-Except-Else for File Handling Source: https://github.com/xraypy/xraylarch/blob/master/doc/larchlang/errors.rst Shows how to use try-except-else to safely open, read, and close a file, handling potential IOErrors in Larch. ```larch try: fh = open(filename, 'r') except IOError: print('cannot open file %s!' % filename) datalines = [] else: datalines = fh.readlines() fh.close() #endtry ``` -------------------------------- ### open(name[, mode[, buffering]]) Source: https://github.com/xraypy/xraylarch/blob/master/doc/larchlang/builtins.rst Opens a file and returns a file object with specified mode and buffering. ```APIDOC ## open(name[, mode[, buffering]]) ### Description Open a file, returning a file object. ### Parameters * **name** (str) - The name of the file to open. * **mode** (str, optional) - The mode to open the file in ('r', 'w', 'a', 'b', '+', 'U'). Defaults to 'r'. * **buffering** (int, optional) - The buffering policy (0 for unbuffered, 1 for line buffered, or buffer size). ``` -------------------------------- ### Get Epics Process Variable Value with caget Source: https://github.com/xraypy/xraylarch/blob/master/doc/data.rst Retrieve the current value of an Epics Process Variable (PV) using `caget`. Set `as_string=True` to get the value as a string. ```larch caget(PV_name, as_string=False) ``` -------------------------------- ### Update X-ray Larch Installation Source: https://github.com/xraypy/xraylarch/blob/master/doc/installation.rst Upgrades an existing xraylarch installation to the latest version available on PyPI, including the Larix add-on. It is recommended to perform updates from the Jupyter Lab Terminal. ```bash pip install --upgrade "xraylarch[larix]" ``` -------------------------------- ### Fit Gaussian + Background with fit_peak Source: https://github.com/xraypy/xraylarch/blob/master/doc/fitting_fitpeaks.rst This example demonstrates fitting a Gaussian function with a linear background to noisy mock data using the fit_peak function. It requires creating mock data first. ```lar import xray_larch.math as lm import numpy # create mock data x = numpy.linspace(0, 10, 100) y = 100 * numpy.exp(-(x-5)**2/(2*1**2)) + 0.1*x + 5 + numpy.random.normal(size=x.size) dy = numpy.ones(x.size) * 2 # fit Gaussian + linear background result = lm.fit_peak(x, y, model='gaussian', dy=dy, background='linear') # print fit parameters print(result.params) # plot fit import matplotlib.pyplot as plt plt.plot(result.x, result.y, 'o', label='data') plt.plot(result.x, result.fit, '-', label='fit') plt.plot(result.x, result.bkg, '--', label='background') plt.legend() plt.show() ``` -------------------------------- ### Install Xraylarch with Larix Support via Pip Source: https://github.com/xraypy/xraylarch/blob/master/doc/installation.rst Installs the xraylarch package along with the 'larix' extra, which includes dependencies required for GUI functionalities like wxPython and Jupyter libraries. ```bash pip install "xraylarch[larix]" ``` -------------------------------- ### Install Core and GUI Packages with Conda Source: https://github.com/xraypy/xraylarch/blob/master/doc/installation.rst Installs essential scientific packages (numpy, scipy, matplotlib, h5py) and wxPython for GUI applications into the active Conda environment from the conda-forge channel. ```bash conda install -y -c conda-forge numpy scipy matplotlib h5py>=3.10 wxpython>=4.2.2 mkl_fft ``` -------------------------------- ### mkdir Source: https://github.com/xraypy/xraylarch/blob/master/doc/larchlang/builtins.rst Creates a directory with the specified name and optional permissions. ```APIDOC ## mkdir(directory_name[, mode=0777]) ### Description Creates a directory (and any intermediate subdirectories) with the specified name. The ``mode`` option sets the permission mask to use for creating the directory (default=0777). ### Parameters #### Path Parameters - **directory_name** (string) - Required - The name of the directory to create. #### Keyword Arguments - **mode** (integer) - Optional - The permission mask for the new directory (default: 0777). ``` -------------------------------- ### Get X-ray Absorption Edge Data Source: https://context7.com/xraypy/xraylarch/llms.txt Retrieve energy, fluorescence yield, and edge jump ratio for a specific element and edge from the xraydb database. Use `xray_edges` to get all edges for an element. ```python from larch.xray import xray_edge, xray_edges # Single edge edge = xray_edge('Fe', 'K') print(f"Fe K edge: {edge.energy:.1f} eV, yield={edge.fluorescence_yield:.4f}") # All edges for an element for name, edge in xray_edges('Cu').items(): print(f"Cu {name}: {edge.energy:.1f} eV") ``` -------------------------------- ### get Source: https://github.com/xraypy/xraylarch/blob/master/doc/larchlang/builtins.rst Retrieves an object from the symbol table by its name. ```APIDOC ## get(name) ### Description Retrieves an object from the symbol table by its name. This function uses only the name of the object, unlike ``getattr``. ### Parameters #### Path Parameters - **name** (string) - Required - The name of the object to retrieve. ``` -------------------------------- ### Get absolute value Source: https://github.com/xraypy/xraylarch/blob/master/doc/larchlang/builtins.rst Returns the absolute value of the argument. ```python abs(value) ``` -------------------------------- ### String Splitting Methods in Larch Source: https://github.com/xraypy/xraylarch/blob/master/doc/larchlang/datatypes.rst Demonstrates the split() method for strings, showing default whitespace splitting and splitting by a specified delimiter. ```larch 'Here is a String'.split() ``` ```larch 'Here is a String'.split('i') ``` -------------------------------- ### Pre-edge Subtraction Example (Plain Python) Source: https://github.com/xraypy/xraylarch/blob/master/doc/xafs_preedge.rst Demonstrates pre-edge subtraction and normalization using Larch functions within a standard Python script. Ensure necessary imports from `larch.io`, `larch.xafs`, and `wxmplot.interactive` are included. ```python from larch.io import read_ascii from larch.xafs import pre_edge from wxmplot.interactive import plot fname = 'fe2o3_rt1.xmu' dat = read_ascii(fname, labels='energy mu i0') pre_edge(dat, group=dat) ``` -------------------------------- ### Get subgroups of a group Source: https://github.com/xraypy/xraylarch/blob/master/doc/larchlang/builtins.rst Returns a list of subgroups of a given group. ```larch larch> subgroups(group) ``` -------------------------------- ### slice([start,] stop[, step]) Source: https://github.com/xraypy/xraylarch/blob/master/doc/larchlang/builtins.rst Creates a slice object for extended slicing. ```APIDOC ## slice([start,] stop[, step]) ### Description Create a slice object. This is used for extended slicing (e.g. a[0:10:2]). ### Parameters * **start** (any, optional) - The start index of the slice. * **stop** (any) - The stop index of the slice. * **step** (any, optional) - The step of the slice. ``` -------------------------------- ### Define Larch Procedure with Unspecified Keyword Arguments Source: https://github.com/xraypy/xraylarch/blob/master/doc/larchlang/procedures.rst Illustrates using '**options' to capture an arbitrary number of keyword arguments passed to a procedure. These arguments are stored in a dictionary named 'options'. ```larch def operate(a, b, **options): """perform operation on a and b""" debug = options.get('debug', True) verbose = options.get('verbose', False) op = options.get('op', 'add') if verbose: print('op == %s ' % op) #endif if op == 'add': return a + b elif op == 'sub': return a - b elif op == 'mul': return a * b elif op == 'div': return a / b else: if debug: print('unsupported operation!') #endif #enddef ``` -------------------------------- ### range([start,] stop[, step]) Source: https://github.com/xraypy/xraylarch/blob/master/doc/larchlang/builtins.rst Generates a list of numbers in an arithmetic progression. ```APIDOC ## range([start,] stop[, step]) ### Description Return a list containing an arithmetic progression of integers. range(i, j) returns [i, i+1, i+2, ..., j-1]. ### Parameters * **start** (int, optional) - The starting number. Defaults to 0. * **stop** (int) - The end number (exclusive). * **step** (int, optional) - The increment or decrement. Defaults to 1. ``` -------------------------------- ### Get binary representation Source: https://github.com/xraypy/xraylarch/blob/master/doc/larchlang/builtins.rst Returns the binary representation of an integer or long integer. ```python bin(number) ``` -------------------------------- ### Initialize Larch Interpreter for Python Interface Source: https://github.com/xraypy/xraylarch/blob/master/doc/python.rst Demonstrates the initialization of a Larch interpreter instance, which was historically required or recommended for passing as a 'session instance' to many Larch functions in the Python interface. ```python from larch import Interreter from larch.io import read_xdi _larch = Interpreter() ``` -------------------------------- ### Larch TypeError Example Source: https://github.com/xraypy/xraylarch/blob/master/doc/larchlang/errors.rst Illustrates a TypeError when attempting to add an integer and a string in Larch. ```larch larch> 4 + 'a' TypeError("unsupported operand type(s) for +: 'int' and 'str'") 4 + 'a' ``` -------------------------------- ### Create and Access a Dictionary in Larch Source: https://github.com/xraypy/xraylarch/blob/master/doc/larchlang/datatypes.rst Illustrates the creation of a dictionary with key-value pairs and accessing elements by their keys. ```larch atomic_weight = {'H': 1.008, 'He': 4.0026, 'Li': 6.9, 'Be': 9.012} print(atomic_weight['He']) ``` -------------------------------- ### Larch IOError Example Source: https://github.com/xraypy/xraylarch/blob/master/doc/larchlang/errors.rst Shows an IOError that occurs when trying to open a non-existent file in Larch. ```larch larch> fh = open('foo', 'r') Error running IOError(2, 'No such file or directory') fh = open('foo', 'r') ^^^ ``` -------------------------------- ### Get help for linspace function Source: https://github.com/xraypy/xraylarch/blob/master/doc/larchlang/arrays.rst Access the documentation for Larch functions, including underlying numpy functions, using the `help()` command. This provides detailed information on parameters and usage. ```larch larch> help(linspace) Return evenly spaced numbers over a specified interval. Returns `num` evenly spaced samples, calculated over the interval [`start`, `stop` ]. The endpoint of the interval can optionally be excluded. Parameters ---------- start : scalar The starting value of the sequence. stop : scalar The end value of the sequence, unless `endpoint` is set to False. In that case, the sequence consists of all but the last of ``num + 1`` evenly spaced samples, so that `stop` is excluded. Note that the step size changes when `endpoint` is False. num : int, optional ``` -------------------------------- ### Larch Syntax Error Example Source: https://github.com/xraypy/xraylarch/blob/master/doc/larchlang/errors.rst Illustrates a basic syntax error in Larch where an incomplete expression is provided. ```larch larch> x = 3 + SyntaxError: invalid syntax x = 3 + x = 3 + ```