### Development setup commands Source: https://github.com/als-rsoxs/refloxide/blob/main/README.md Commands to clone the repository, install dependencies, and run tests. ```bash git clone https://github.com/ALS-RSOXS/refloxide.git cd refloxide make develop make test && make verify ``` -------------------------------- ### Print refloxide version Source: https://github.com/als-rsoxs/refloxide/blob/main/docs/index.md Quick start example to verify installation and print the version. ```python import refloxide print(refloxide.__version__) ``` -------------------------------- ### Clone and setup development environment Source: https://github.com/als-rsoxs/refloxide/blob/main/docs/index.md Clone the repository and install dependencies with uv, including dev group and plugin extra. ```bash git clone https://github.com/HarlanHeilman/refloxide.git cd refloxide uv sync --group dev --extra plugin ``` -------------------------------- ### Quick start: uniaxial_reflectivity Source: https://github.com/als-rsoxs/refloxide/blob/main/README.md Python example showing how to call uniaxial_reflectivity with CPU and GPU device options. ```python from refloxide.tmm import uniaxial_reflectivity refl, tran = uniaxial_reflectivity(q, layers, tensor, energy_ev, parallel=False) refl, tran = uniaxial_reflectivity( q, layers, tensor, energy_ev, parallel=False, device="gpu" ) ``` -------------------------------- ### Install refloxide with uv Source: https://github.com/als-rsoxs/refloxide/blob/main/docs/index.md Recommended installation using uv, with optional plugin extra. ```bash uv add refloxide uv add 'refloxide[plugin]' ``` -------------------------------- ### Install refloxide with pip and uv Source: https://github.com/als-rsoxs/refloxide/blob/main/README.md Installation commands for the core package and the plugin extra using pip and uv. ```bash pip install refloxide # core TMM (CPU + GPU feature) pip install 'refloxide[plugin]' # plus refnx modeling / fitting # or uv add refloxide uv add 'refloxide[plugin]' ``` -------------------------------- ### Install pre-commit hooks Source: https://github.com/als-rsoxs/refloxide/blob/main/docs/contributing.md Install pre-commit hooks using the prek command. ```bash prek install ``` -------------------------------- ### Fit setup output: constraints and seeds Source: https://github.com/als-rsoxs/refloxide/blob/main/examples/real_data_fit.ipynb Output from the initial fit setup showing constraints, varying parameters, bounds, and seed values for the DFT seed. ```text nc_constraint=False energies: 21, batches: 42 varying parameters k=101 (target 101 = full DFT free set) surface density bounds=(1.2, 1.8), interface density bounds=(0.1, 1) (capped below bulk=1.6385) rotation deg bounds — surface=[49.2, 53.2], interface=[43.2, 49.7] (magic=54.74 deg excluded) logl at DFT seed: -11721.979 interface dens seed = 1.0000 (DFT raw=1.8000) surface/interface rotation seed deg = 52.21 / 47.24 oxide density seed = 2.2627 (FREE=2.2627; DFT was 1.9212) si density seed = 2.3657 (FREE=2.3657; DFT was 2.5025) ``` -------------------------------- ### Install dependencies with uv Source: https://github.com/als-rsoxs/refloxide/blob/main/docs/contributing.md Install development tooling and the plugin modeling stack using uv sync with the dev group and plugin extra. ```bash uv sync --group dev --extra plugin ``` -------------------------------- ### Output of matched-k refinement setup Source: https://github.com/als-rsoxs/refloxide/blob/main/examples/real_data_fit_free.ipynb Shows the printed output from the setup code: nc_constraint is False, 21 energies, 42 batches, 347 varying parameters matching the target, and the log-likelihood at the free seed. ```text nc_constraint=False energies: 21, batches: 42 varying parameters k=347 (target 347) logl at free seed: -5937.749 ``` -------------------------------- ### Install refloxide with pip Source: https://github.com/als-rsoxs/refloxide/blob/main/docs/index.md Install the base package or include the plugin extra for refnx modeling/fitting stack. ```bash pip install refloxide pip install 'refloxide[plugin]' # refnx modeling / fitting stack ``` -------------------------------- ### Rust-only GPU checks and run Source: https://github.com/als-rsoxs/refloxide/blob/main/docs/guides/gpu.md Check the crate with the GPU feature and run the GPU recursive example. ```bash cargo check --features gpu cargo run --profile perf --no-default-features --features gpu --example gpu_recursive ``` -------------------------------- ### Setup and imports for UniTensor slab fit Source: https://github.com/als-rsoxs/refloxide/blob/main/examples/real_data_fit.ipynb Sets up the notebook environment with autoreload and imports required libraries (matplotlib, numpy, polars, refnx, refloxide). Disables POLARS_VERBOSE. ```python %matplotlib inline %load_ext autoreload %autoreload 2 from __future__ import annotations import json import os import pickle import time from pathlib import Path os.environ["POLARS_VERBOSE"] = "0" import matplotlib.pyplot as plt import numpy as np import polars as pl from refnx.analysis import CurveFitter, Transform from refloxide.data import OpticalConstants, ReflectDataset from refloxide.model import MaterialSLD, ReflectModel, UniTensorSLD from refloxide.objective import Objective, thread_workers ``` -------------------------------- ### Setup and imports for book-ended multi-energy fit Source: https://github.com/als-rsoxs/refloxide/blob/main/examples/bookended_real_data_fit.ipynb Initializes matplotlib inline, enables autoreload, and imports required libraries including refloxide's BookendedComponent, Objective, and bookended_from_three_slabs. Sets POLARS_VERBOSE to 0 to suppress verbose output. ```python %matplotlib inline %load_ext autoreload %autoreload 2 from __future__ import annotations import json import os import pickle from pathlib import Path os.environ["POLARS_VERBOSE"] = "0" import matplotlib.pyplot as plt import numpy as np import polars as pl from refnx.analysis import CurveFitter, Transform from refloxide.data import OpticalConstants, ReflectDataset from refloxide.model import BookendedComponent, MaterialSLD, ReflectModel, UniTensorSLD from refloxide.objective import Objective, thread_workers from refloxide.pxr.energy.bookended import bookended_from_three_slabs from refloxide.pxr.energy.ooc import OocAnchor ``` -------------------------------- ### Setup and imports for multi-energy free-tensor fit Source: https://github.com/als-rsoxs/refloxide/blob/main/examples/real_data_fit_free.ipynb Initializes the notebook environment: enables inline plotting, autoreload, and imports required libraries (json, os, pickle, time, pathlib, matplotlib, numpy, polars, refnx, and refloxide modules). Sets POLARS_VERBOSE to 0 to reduce logging. ```python %matplotlib inline %load_ext autoreload %autoreload 2 from __future__ import annotations import json import os import pickle import time from pathlib import Path os.environ["POLARS_VERBOSE"] = "0" import matplotlib.pyplot as plt import numpy as np import polars as pl from refnx.analysis import CurveFitter, Transform from refloxide.data import ReflectDataset from refloxide.model import FreeTensorSLD, MaterialSLD, ReflectModel from refloxide.objective import Objective, thread_workers ``` -------------------------------- ### Output: initial seed and stage 1 progress Source: https://github.com/als-rsoxs/refloxide/blob/main/examples/real_data_fit_free.ipynb Shows the starting bulk thickness and log-likelihood at the free seed, followed by the progress of stage 1 (L-BFGS-B instruments only) with 84 varying parameters. ```text bulk thick start = 180.55 logl at free seed: -5937.749 stage 1: L-BFGS-B instruments only: 84 varying parameters logl before: -5937.749 ``` -------------------------------- ### Output: stage 1 completion and stage 2 start Source: https://github.com/als-rsoxs/refloxide/blob/main/examples/real_data_fit_free.ipynb Shows the successful completion of stage 1 with logl=-193.434, and the start of stage 2 (DE geometry only) with 9 varying parameters. ```text L-BFGS-B maxiter=500: 16.09 s, success=True, logl=-193.434 stage 2: DE geometry only: 9 varying parameters logl before: -193.434 ``` -------------------------------- ### Setup imports and autoreload for bookended nonresonant fit Source: https://github.com/als-rsoxs/refloxide/blob/main/examples/bookended_nonres.ipynb Enables inline plotting and autoreload, then imports the libraries and refloxide modules needed for the fit. Uses refnx CurveFitter and Transform, and refloxide data/model/objective/energy components. ```python %matplotlib inline %load_ext autoreload %autoreload 2 from __future__ import annotations import json from pathlib import Path import matplotlib.pyplot as plt import numpy as np import polars as pl from refnx.analysis import CurveFitter, Transform from refloxide.data import ReflectDataset from refloxide.model import BookendedComponent, MaterialSLD, ReflectModel from refloxide.objective import Objective from refloxide.pxr.energy.bookended import BookendedOrientationProfile from refloxide.pxr.energy.ooc import OocAnchor ``` -------------------------------- ### Output: stage 3 completion and stage 4 start Source: https://github.com/als-rsoxs/refloxide/blob/main/examples/real_data_fit_free.ipynb Shows the completion of stage 3 with logl=421.588, and the start of stage 4 (L-BFGS-B polish) with 347 varying parameters. ```text DE maxiter=50 polish=False: 107.09 s, logl=421.588 stage 4: L-BFGS-B polish (full free set): 347 varying parameters logl before: 421.588 ``` -------------------------------- ### Define paths and load DFT/free summaries Source: https://github.com/als-rsoxs/refloxide/blob/main/examples/real_data_fit.ipynb Sets up file paths for DFT CSV, data parquet, and summary JSONs. Checks existence and raises FileNotFoundError if missing. Loads summaries and builds layer dictionaries. ```python ZNPC_DFT_CSV = Path.home() / "projects/refl-analysis/@models/optical/znpc/dft.csv" ZNPC_DATA = ( Path.home() / "projects/refl-analysis/@data/xrr/znpc/reflectivity_data.parquet" ) DFT_DIR = Path.home() / "projects/refl-analysis/@models/xrr/znpc/dft" FREE_DIR = Path.home() / "projects/refl-analysis/@models/xrr/znpc/free" DFT_SUMMARY_PATH = DFT_DIR / "dft_en_offset_new2_summary.json" FREE_SUMMARY_PATH = FREE_DIR / "free_en_offset_init_2_summary.json" for path in (ZNPC_DFT_CSV, ZNPC_DATA, DFT_SUMMARY_PATH, FREE_SUMMARY_PATH): if not path.exists(): raise FileNotFoundError( f"missing {path} -- expects sibling refl-analysis checkout, " "dft_en_offset_new2 extraction, and free_en_offset_init_2 extraction " "(summary mirrors free_en_offset_init_2.pkl without requiring pyref)" ) dft_summary = json.loads(DFT_SUMMARY_PATH.read_text()) free_summary = json.loads(FREE_SUMMARY_PATH.read_text()) dft_layers = {layer["name"]: layer for layer in dft_summary["layers"]} free_layers = {layer["name"]: layer for layer in free_summary["layers"]} surface_dft = dft_layers["Surface"] bulk_dft = dft_layers["ZnPc"] interface_dft = dft_layers["Contamination"] oxide_dft = dft_layers["Oxide"] substrate_dft = dft_layers["Substrate"] oxide_free = free_layers["Oxide"] substrate_free = free_layers["Substrate"] ``` -------------------------------- ### Create book-ended profile and build structure Source: https://github.com/als-rsoxs/refloxide/blob/main/examples/bookended_real_data_fit.ipynb Creates two book-ended profiles: one for fitting (energy=None) and one for plotting (energy=ANCHOR_ENERGY). Then builds a structure by combining vacuum, the profile, oxide, and substrate layers. The printed output shows the resulting total_thick and alpha_bulk values. ```python profile_fit = bookended_from_three_slabs( surface_slab, bulk_slab, interface_slab, znpc_anchor, energy=None, num_slabs=NUM_SLABS_FIT, mesh_constant=0.1, name="ZnPc", ) profile_plot = bookended_from_three_slabs( surface_slab, bulk_slab, interface_slab, znpc_anchor, energy=ANCHOR_ENERGY, num_slabs=NUM_SLABS_PLOT, mesh_constant=0.1, name="ZnPc", ) print( f"book-ended profile: total_thick={profile_fit.total_thick.value:.2f} A, " f"alpha_bulk={profile_fit.alpha_bulk.value:.3f} rad" ) def build_structure(profile): vacuum = MaterialSLD("", 0, name="vacuum")(0, 0) oxide = MaterialSLD("SiO2", density=oxide_layer["density"], name="oxide")( oxide_layer["thick"], oxide_layer["rough"] ) substrate = MaterialSLD("Si", density=substrate_layer["density"], name="substrate")( substrate_layer["thick"], substrate_layer["rough"] ) return vacuum | BookendedComponent(profile) | oxide | substrate structure_fit = build_structure(profile_fit) structure_plot = build_structure(profile_plot) ``` ```text Output: book-ended profile: total_thick=199.59 A, alpha_bulk=1.214 rad ``` -------------------------------- ### Output: stage 2 completion and stage 3 start Source: https://github.com/als-rsoxs/refloxide/blob/main/examples/real_data_fit_free.ipynb Shows the completion of stage 2 with logl=421.588, and the start of stage 3 (DE geometry + instruments) with 93 varying parameters. ```text DE maxiter=40 polish=False: 7.98 s, logl=421.588 stage 3: DE geometry + instruments: 93 varying parameters logl before: 421.588 ``` -------------------------------- ### Clone and enter the refloxide repository Source: https://github.com/als-rsoxs/refloxide/blob/main/docs/contributing.md Fork and clone the repository, then change into the project directory. ```bash git clone https://github.com/HarlanHeilman/refloxide.git cd refloxide ``` -------------------------------- ### Import Refloxide classes and initialize materials Source: https://github.com/als-rsoxs/refloxide/blob/main/docs/guides/building_structures/_preamble.md Imports model and profile classes from refloxide, then creates vacuum and silicon material instances and free uni-tensors for film layers. ```python from refloxide.model import MaterialSLD, FreeUniTensor, Mix, ReflectModel from refloxide.profiles import ( Diffusion, SecondOrderTransition, DepthProfile, Spline, Polynomial, CallableField, CallableDepthProfile, ) vac = MaterialSLD("", 0, name="vacuum")(0, 0) si = MaterialSLD("Si", 2.33, name="si")(0, 3.0) mat = FreeUniTensor(energies=[284.4], name="film") mat_a = FreeUniTensor(energies=[284.4], name="a") mat_b = FreeUniTensor(energies=[284.4], name="b") mat_c = FreeUniTensor(energies=[284.4], name="c") ``` -------------------------------- ### Load DFT-fit summary and data files Source: https://github.com/als-rsoxs/refloxide/blob/main/examples/bookended_real_data_fit.ipynb Sets up paths to the DFT-fit summary and data files, checks they exist, and loads the summary JSON. Prints the anchor energy and layer names. Requires the one-time extraction to have been run in the refl-analysis venv. ```python DFT_DIR = Path.home() / "projects/refl-analysis/@models/xrr/znpc/dft" SUMMARY_PATH = DFT_DIR / "dft_en_offset_new2_summary.json" DATA_PATH = DFT_DIR / "dft_en_offset_new2_data.parquet" for path in (SUMMARY_PATH, DATA_PATH): if not path.exists(): raise FileNotFoundError( f"missing {path} -- run the one-time extraction (in the " "refl-analysis venv, which has pyref) against " f"{DFT_DIR / 'dft_en_offset_new2.pkl'} first, or see " "dft_model_comparison_repl.py for the extraction story" ) summary = json.loads(SUMMARY_PATH.read_text()) ANCHOR_ENERGY = float(summary["anchor_energy"]) NUM_SLABS_FIT = 24 NUM_SLABS_PLOT = 100 SHOW_ENERGIES = (250.0, 283.7, 285.1) print( f"anchor energy: {ANCHOR_ENERGY} eV, " f"layers: {[layer['name'] for layer in summary['layers']]}" ) ``` -------------------------------- ### Regenerate figures with uv run Source: https://github.com/als-rsoxs/refloxide/blob/main/docs/guides/building_structures/index.md Command to regenerate the figures for the building structures guide. Run from the project root. ```bash uv run python docs/guides/builtin_slabs/build_figures.py ``` -------------------------------- ### Run L-BFGS-B fit with logging Source: https://github.com/als-rsoxs/refloxide/blob/main/examples/real_data_fit_free.ipynb Runs a CurveFitter fit using the L-BFGS-B method, printing the number of varying parameters, log-likelihood before, and fit success. Asserts the start is within bounds. ```python def run_lbfgsb(label: str, *, maxiter: int = 500) -> None: n_vary = len(objective.varying_parameters()) print(f"\n{label}: {n_vary} varying parameters") print(f" logl before: {float(objective.logl()):.3f}") assert np.isfinite(objective.logp()), f"{label}: start outside bounds" nudge_varying_inside_bounds(objective) t0 = time.perf_counter() res = CurveFitter(objective).fit( method="L-BFGS-B", options={"maxiter": maxiter}, ) print( f" L-BFGS-B maxiter={maxiter}: {time.perf_counter() - t0:.2f} s, " f"success={getattr(res, 'success', None)}, " f"logl={float(objective.logl()):.3f}" ) ``` -------------------------------- ### Run GPU backend benchmark Source: https://github.com/als-rsoxs/refloxide/blob/main/README.md Commands to sync dependencies and run the GPU backend benchmark script. ```bash uv sync --group dev --extra plugin uv run python examples/gpu_backend_bench.py --plot ``` -------------------------------- ### Build UniTensor stack with shared OpticalConstants and verify Source: https://github.com/als-rsoxs/refloxide/blob/main/examples/real_data_fit.ipynb Defines a build_structure() function that creates vacuum, ZnPc surface/bulk/interface (UniTensorSLD), oxide, and substrate layers, then builds a ReflectModel and asserts that the ZnPc layers share the same OpticalConstants and that Nevot-Croce is enforced for all except vacuum and substrate. Finally prints the structure and plots the optical constants and parameters. ```python znpc_ooc = OpticalConstants.from_file(ZNPC_DFT_CSV) def build_structure(): vacuum = MaterialSLD("", 0, name="vacuum")(0, 0) surface = UniTensorSLD( znpc_ooc, density=SURFACE["density"], rotation=SURFACE["rotation"], name="ZnPc_surface", )(SURFACE["thick"], SURFACE["rough"]) bulk = UniTensorSLD( znpc_ooc, density=BULK["density"], rotation=BULK["rotation"], name="ZnPc_bulk", )(BULK["thick"], BULK["rough"]) interface = UniTensorSLD( znpc_ooc, density=INTERFACE["density"], rotation=INTERFACE["rotation"], name="ZnPc_interface", )(INTERFACE["thick"], INTERFACE["rough"]) oxide = MaterialSLD("SiO2", density=OXIDE["density"], name="oxide")( OXIDE["thick"], OXIDE["rough"] ) substrate = MaterialSLD("Si", density=SUBSTRATE["density"], name="substrate")( 0, SUBSTRATE["rough"] ) return vacuum | surface | bulk | interface | oxide | substrate model = ReflectModel(build_structure(), energies=energies, parallel=False) structure = model.structure surface = structure.slab("ZnPc_surface") bulk = structure.slab("ZnPc_bulk") interface = structure.slab("ZnPc_interface") assert surface.sld.ooc is bulk.sld.ooc is interface.sld.ooc is znpc_ooc assert surface.enforce_nevot_croce and bulk.enforce_nevot_croce assert interface.enforce_nevot_croce and structure.slab("oxide").enforce_nevot_croce assert not structure.slab("vacuum").enforce_nevot_croce assert not structure.slab("substrate").enforce_nevot_croce print(structure) structure.plot.oc(283.7, difference=True) plt.show() structure.plot.param("density|orientation") plt.show() ``` -------------------------------- ### Define plot_data_vs_model function Source: https://github.com/als-rsoxs/refloxide/blob/main/examples/bookended_real_data_fit.ipynb Creates a figure with subplots for each energy and polarization ('s', 'p'). For each, it plots experimental data (with error bars) and the model prediction. Uses a log scale for the y-axis and labels axes with q and energy. The function is called with 'Starting model, all 21 energies'. ```python def plot_data_vs_model(model, title, show_energies=SHOW_ENERGIES): fig, axes = plt.subplots( len(show_energies), 2, figsize=(11, 3.2 * len(show_energies)) ) for row, energy in enumerate(show_energies): for col, pol in enumerate(("s", "p")): ax = axes[row, col] for e, p, indices in dataset.groups(): if e != energy or p != pol: continue q = dataset.q[indices] ax.errorbar( q, dataset.r[indices], yerr=dataset.r_err[indices], fmt=".", ms=2, lw=0.5, color="0.4", label="data", ) pred = model(q, energy) ax.plot( q, pred.s if pol == "s" else pred.p, color="C0", lw=1.5, label="fit" ) ax.set_yscale("log") ax.set_xlabel(r"$q$ ($\mathrm{\AA}^{-1}$)") ax.set_title(f"{energy:.1f} eV, {pol}-pol") if col == 0: ax.set_ylabel("Reflectivity") ax.legend(fontsize="x-small") fig.suptitle(title, y=1.01) fig.tight_layout() plt.show() plot_data_vs_model(model, "Starting model, all 21 energies") ``` -------------------------------- ### Snap initial thickness and roughness into bounds and disable parameter variation Source: https://github.com/als-rsoxs/refloxide/blob/main/examples/real_data_fit.ipynb Retrieves the oxide and substrate slabs, then snaps the initial thickness and roughness for surface, interface, and bulk into their respective bounds using snap_into_bounds. Finally, disables variation for all model parameters. ```python oxide = structure.slab("oxide") substrate = structure.slab("substrate") surface_thick0, surface_rough0 = snap_into_bounds( SURFACE["thick"], SURFACE["rough"], thick_bounds=SURFACE_THICK_BOUNDS, rough_bounds=SURFACE_ROUGH_BOUNDS, ) interface_thick0, interface_rough0 = snap_into_bounds( INTERFACE["thick"], INTERFACE["rough"], thick_bounds=INTERFACE_THICK_BOUNDS, rough_bounds=INTERFACE_ROUGH_BOUNDS, ) bulk_thick0, bulk_rough0 = snap_into_bounds( BULK["thick"], BULK["rough"], thick_bounds=BULK_THICK_BOUNDS, rough_bounds=BULK_ROUGH_BOUNDS, ) for param in model.parameters.flattened(): param.vary = False ``` -------------------------------- ### Material uniaxial tensor (rho, gamma) - UniTensorSLD Source: https://github.com/als-rsoxs/refloxide/blob/main/docs/guides/building_structures/homogeneous.md Builds a homogeneous slab using UniTensorSLD, which loads molecular indices from an optical-constants table, scales them by mass density rho, and rotates into the lab frame with polar angle gamma (API name: rotation). The example creates an OpticalConstants DataFrame and constructs the film with density=1.45 and rotation=0.65. ```python from refloxide.data import OpticalConstants from refloxide.model import UniTensorSLD import polars as pl import numpy as np ooc = OpticalConstants.from_source( pl.DataFrame( { "energy": np.linspace(250.0, 320.0, 20), "n_xx": np.full(20, 1.0e-3), "n_ixx": np.full(20, 3.0e-4), "n_zz": np.full(20, 2.0e-3), "n_izz": np.full(20, 6.0e-4), } ) ) film = UniTensorSLD(ooc, density=1.45, rotation=0.65, name="film") stack = vac | film(280.0, 2.0) | si model = ReflectModel(stack, energies=[284.4], parallel=False) ``` -------------------------------- ### Build and configure graded book-ended model Source: https://github.com/als-rsoxs/refloxide/blob/main/examples/bookended_nonres.ipynb Sets up a graded film model using BookendedOrientationProfile and BookendedComponent, with vacuum, oxide, and substrate slabs. Configures parameters for total thickness, roughness, densities, and tau values, then creates an Objective with a logY transform and nc_constraint. Prints free parameters and log-likelihood. ```python graded_film = BookendedOrientationProfile( ooc=ZNPC_OOC, energy=summary["energy"], num_slabs=summary["film"]["num_slabs"], mesh_constant=summary["film"]["mesh_constant"], name="ZnPc", **film_params, ) graded_structure = ( build_slab("Vacuum") | BookendedComponent(graded_film) | build_slab("Oxide", vary_rough=True, rough_bounds=BOUNDS["oxide_rough"]) | build_slab("Substrate") ) graded_model = ReflectModel(graded_structure, parallel=False) graded_film.total_thick.setp(value=150, vary=True, bounds=(100, 180)) graded_film.surface_roughness.setp( value=REFERENCE["surface_rough"], vary=False, bounds=BOUNDS["surface_roughness"] ) graded_film.tau_vac.setp(value=REFERENCE["surface_thick"], vary=False) graded_film.tau_si.setp(value=REFERENCE["interface_thick"], vary=False) graded_film.density_vac.setp(vary=True, bounds=BOUNDS["density_vac"]) graded_film.density_si.setp(vary=True, bounds=BOUNDS["density_si"]) graded_film.density_bulk.vary = False oxide_slab = graded_structure.slab("Oxide") oxide_slab.thick.setp(value=REFERENCE["oxide_thick"], vary=True, bounds=(5, 12.0)) oxide_slab.rough.setp(vary=True, bounds=(0, 12)) oxide_slab.sld.density.setp(value=REFERENCE["oxide_rho"], vary=False) substrate_slab = graded_structure.slab("Substrate") substrate_slab.rough.value = REFERENCE["substrate_rough"] substrate_slab.sld.density.value = REFERENCE["substrate_rho"] freeze_instrumentation(graded_model) graded_objective = Objective( graded_model, dataset, transform=Transform("logY"), nc_constraint=True ) print(f"free parameters: {len(graded_objective.varying_parameters())}") print(f"logl before fit: {graded_objective.logl():.3f}") print(graded_objective.varying_parameters()) ``` ```text Output: free parameters: 7 logl before fit: -5021032.282 ________________________________________________________________________________ Parameters: None ``` -------------------------------- ### Run GPU backend benchmark Source: https://github.com/als-rsoxs/refloxide/blob/main/docs/guides/gpu.md Regenerate the uniaxial backend benchmark with 1 slab and 10,000 film slabs, requiring the dev and plugin groups. ```bash uv sync --group dev --group plugin uv run python examples/gpu_backend_bench.py --plot ``` -------------------------------- ### Uniaxial vs biaxial diagonals - general_reflectivity Source: https://github.com/als-rsoxs/refloxide/blob/main/docs/guides/building_structures/homogeneous.md Computes reflectivity for a biaxial diagonal tensor after a 45-degree in-plane rotation using general_reflectivity. The example defines a diagonal tensor, rotates it, builds layers and tensor arrays, and extracts R_pp, R_sp, R_ps, R_ss from the 2x2 kernel. Kernel packing is [[R_pp, R_sp], [R_ps, R_ss]] with R_sp = s reflected from p incident (refl[:, 0, 1]) and R_ps = p reflected from s incident (refl[:, 1, 0]). ```python import numpy as np from refloxide.tmm import general_reflectivity n_xx = 0.80e-3 + 2.0e-4j n_yy = 2.20e-3 + 7.0e-4j n_zz = 1.50e-3 + 4.0e-4j t = 240.0 def diag(nx, ny, nz): m = np.zeros((3, 3), dtype=np.complex128) m[0, 0], m[1, 1], m[2, 2] = nx, ny, nz return m phi = np.deg2rad(45.0) c, s = np.cos(phi), np.sin(phi) rot_z = np.array([[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]]) t_lab = rot_z @ diag(n_xx, n_yy, n_zz) @ rot_z.T layers = np.array( [ [0.0, 0.0, 0.0, 0.0], [t, 0.5 * (t_lab[0, 0].real + t_lab[1, 1].real), 0.5 * (t_lab[0, 0].imag + t_lab[1, 1].imag), 2.0], [0.0, 7.5e-4, 1.2e-4, 3.0], ], dtype=np.float64, ) tensor = np.stack( [ diag(0j, 0j, 0j), t_lab, diag(7.5e-4 + 1.2e-4j, 7.5e-4 + 1.2e-4j, 7.5e-4 + 1.2e-4j), ] ) q = np.linspace(0.008, 0.275, 520) refl = general_reflectivity(q, layers, tensor, 284.4, parallel=False) # [[R_pp, R_sp], [R_ps, R_ss]]: R_sp = s<-p, R_ps = p<-s r_pp, r_sp = refl[:, 0, 0], refl[:, 0, 1] r_ps, r_ss = refl[:, 1, 0], refl[:, 1, 1] ``` -------------------------------- ### Compare oxide and substrate parameters against legacy free-tensor values Source: https://github.com/als-rsoxs/refloxide/blob/main/examples/real_data_fit_free.ipynb Prints thickness, roughness, and density for the oxide layer, and roughness and density for the substrate, comparing against legacy free-tensor values. The output is a formatted table with deltas. ```python for param, ours in ( ("thick", float(oxide.thick.value or 0.0)), ("rough", float(oxide.rough.value or 0.0)), ("density", float(oxide.sld.density.value or 0.0)), ): legacy_v = oxide_free[param] print( f"{'Oxide':<16}{param:<10}{ours:>12.4f}{legacy_v:>12.4f}" f"{ours - legacy_v:>12.4f}" ) for param, ours in ( ("rough", float(substrate.rough.value or 0.0)), ("density", float(substrate.sld.density.value or 0.0)), ): legacy_v = substrate_free[param] print( f"{'Substrate':<16}{param:<10}{ours:>12.4f}{legacy_v:>12.4f}" f"{ours - legacy_v:>12.4f}" ) ``` -------------------------------- ### Define substrate stack helpers, bounds, and seed geometry Source: https://github.com/als-rsoxs/refloxide/blob/main/examples/bookended_nonres.ipynb Defines BKG_ESTIMATE, a build_slab function to create MaterialSLD slabs with frozen thickness and density, and freeze_instrumentation to set scale_s/theta_offset_s vary and fix bkg. Sets oxide roughness upper bound from Nevot-Croce ceiling and REFERENCE seed values for total thickness. ```python BKG_ESTIMATE = 0.0 layers = {layer["name"]: layer for layer in summary["layers"]} def build_slab( name: str, *, vary_rough: bool = False, rough_bounds: tuple[float, float] = (0.0, 30.0), ): layer = layers[name] sld = MaterialSLD(layer["formula"], density=layer["density"], name=name) slab = sld(layer["thick"], layer["rough"]) slab.thick.vary = False sld.density.vary = False if vary_rough: slab.rough.setp(vary=True, bounds=rough_bounds) else: slab.rough.vary = False return slab def freeze_instrumentation(model: ReflectModel) -> None: """Open scale_s/theta_offset_s; fix bkg at the measured floor. Call after the first per-energy channel exists (after ReflectModel construction). Newly created channels default scale_p/theta_offset_p to vary=True with infinite bounds, which breaks differential_evolution. """ model.scale_s.at(ENERGY_EV).setp(vary=True, bounds=(0.8, 1.2)) model.theta_offset_s.at(ENERGY_EV).setp(vary=True, bounds=(-0.8, 0.8)) model.bkg.at(ENERGY_EV).value = BKG_ESTIMATE model.bkg.at(ENERGY_EV).vary = False model.scale_p.at(ENERGY_EV).vary = False model.theta_offset_p.at(ENERGY_EV).vary = False _oxide_thick = layers["Oxide"]["thick"] _oxide_rough_ceiling = float(np.sqrt(2.0 * np.pi) * _oxide_thick / 2.0) BOUNDS = { "surface_roughness": (3.0, 20.0), "oxide_rough": (0.0, _oxide_rough_ceiling), "density_vac": (1.5, 2.5), "density_si": (0.0, 1.3), } REFERENCE = { "surface_thick": 7.89151, "surface_rough": 6.28961, "bulk_thick": 125.596, "interface_thick": 18.2626, "oxide_thick": 9.84672, "oxide_rho": 2.0692, "substrate_rough": 0.5, "substrate_rho": 2.21255, } REFERENCE_TOTAL_THICK = ( REFERENCE["surface_thick"] + REFERENCE["bulk_thick"] + REFERENCE["interface_thick"] ) print(f"REFERENCE_TOTAL_THICK = {REFERENCE_TOTAL_THICK:.2f} A") print(f"oxide rough NC ceiling = {_oxide_rough_ceiling:.2f} A") ``` ```text Output: REFERENCE_TOTAL_THICK = 151.75 A oxide rough NC ceiling = 8.62 A ``` -------------------------------- ### Rebuild extension with make develop Source: https://github.com/als-rsoxs/refloxide/blob/main/docs/guides/gpu.md Rebuild the extension after pulling GPU changes. ```bash make develop ``` -------------------------------- ### Set bulk, surface, and interface parameter bounds Source: https://github.com/als-rsoxs/refloxide/blob/main/examples/real_data_fit_free.ipynb Sets thickness and roughness bounds for bulk, surface, and interface layers using the computed initial values. ```python bulk.thick.setp(value=bulk_thick0, vary=True, bounds=BULK_THICK_BOUNDS) bulk.rough.setp(value=bulk_rough0, vary=True, bounds=BULK_ROUGH_BOUNDS) surface.thick.setp(value=surface_thick0, vary=True, bounds=SURFACE_THICK_BOUNDS) surface.rough.setp(value=surface_rough0, vary=True, bounds=SURFACE_ROUGH_BOUNDS) interface.thick.setp(value=interface_thick0, vary=True, bounds=INTERFACE_THICK_BOUNDS) interface.rough.setp(value=interface_rough0, vary=True, bounds=INTERFACE_ROUGH_BOUNDS) ``` -------------------------------- ### Create a Diffusion depth profile (couple or exponential) Source: https://github.com/als-rsoxs/refloxide/blob/main/docs/guides/building_structures/diffusion.md Shows how to create a DepthProfile with a Diffusion field, using either kind='couple' or kind='exponential'. The commented alternative shows the exponential parameters. The profile is then placed in a stack with vacuum and silicon. ```python phi = Diffusion(thickness=160.0, left=1.0, right=0.0, length=20.0, kind="couple") # or: Diffusion(..., kind="exponential", edge=1.0, base=0.0, length=20.0) layer = DepthProfile( material=Mix([mat_a, mat_b], rule="linear"), thickness=160.0, roughness=1.0, phi=phi, ) stack = vac | layer | si ```