Skip to main content

SANS Model Fitter

Tests Docs PyPI badge Docs badge Codacy Badge

A flexible, model-agnostic Python template for fitting Small-Angle Neutron Scattering (SANS) data using the SasModels library.

Features

  • Model-Agnostic Design: Works with any model from the SasModels library (cylinder, sphere, core_shell, etc.)
  • Multiple Fitting Engines: Supports both BUMPS (default) and LMFit optimization engines
  • Flexible Data Loading: Reads CSV, XML, and HDF5 formats via sasdata
  • Q-Range Restriction: Fit only a chosen [qmin, qmax] window (e.g. trim beam-stop or background-dominated points)
  • Dataset Arithmetic: Add, subtract, multiply, and divide datasets (or scale by constants) with propagated uncertainties via data_ops — e.g. background subtraction and transmission correction before fitting
  • User-Friendly Parameter Management: Easy-to-use interface for setting parameter values, bounds, and fitting flags
  • Interactive Visualization: Automatic plotting of data, fitted model, and residuals with Plotly
  • Bayesian Analysis: Posterior sampling with BUMPS DREAM (MCMC) plus corner, marginal, predictive-band, correlation, and trace plots
  • Result Export: Save fitted parameters and curves to CSV files

Installation

Option 1: Using pip (recommended for users)

# Clone the repository
git clone https://github.com/ai4se1dk/SANS-fitter.git
cd SANS-fitter

# Install the package
pip install -e .

# Or install with development dependencies
pip install -e ".[dev]"

Option 2: Using Pixi (recommended for development)

# Clone the repository
git clone https://github.com/ai4se1dk/SANS-fitter.git
cd SANS-fitter

# Install dependencies with Pixi
pixi install

# Run tests
pixi run test

# Run demo notebook
pixi run run-demo

Quick Start

from sans_fitter import SANSFitter

# Create fitter instance
fitter = SANSFitter()

# Load your data
fitter.load_data('my_sans_data.csv')

# Set the model (any model from SasModels!)
fitter.set_model('cylinder')

# Optionally restrict the Q range used for fitting
fitter.set_q_range(qmin=0.01, qmax=0.3)

# View initial parameter values
fitter.get_params()

# Configure parameters for fitting
fitter.set_param('radius', value=20, min=1, max=100, vary=True)
fitter.set_param('length', value=400, min=10, max=1000, vary=True)
fitter.set_param('scale', value=0.1, min=0, max=1, vary=True)
fitter.set_param('background', value=0.01, min=0, max=1, vary=True)

# View current parameters
fitter.get_params()

# Perform the fit (using BUMPS by default)
result = fitter.fit(engine='bumps', method='amoeba')

# Visualize results
fitter.plot_results(show_residuals=True)

# Save results
fitter.save_results('fit_results.csv')

Switching Models

The fitter is completely model-agnostic. Simply load a different model:

# Try with a sphere model instead
fitter.set_model('sphere')
fitter.get_params()  # See different parameters!

fitter.set_param('radius', value=25, min=5, max=100, vary=True)
result = fitter.fit()

Switching Fitting Engines

# Use BUMPS (default)
result = fitter.fit(engine='bumps', method='amoeba')

# Or use LMFit
result = fitter.fit(engine='lmfit', method='leastsq')

Working with Structure Factors

Combine any SasModels form factor with an interaction model to capture correlated systems.

fitter.set_model('sphere')

# Apply a structure factor (creates sphere@hardsphere product model)
fitter.set_structure_factor('hardsphere', radius_effective_mode='link_radius')

# Inspect linked parameters and run the fit as usual
fitter.get_params()
result = fitter.fit()

# Remove the structure factor to go back to the pure form factor
fitter.remove_structure_factor()
  • Supported structure factors: hardsphere, hayter_msa, squarewell, stickyhardsphere.
  • Radius handling: use radius_effective_mode='link_radius' to keep radius_effective equal to the form-factor radius, or leave the default unconstrained to fit it independently.
  • State helpers: get_structure_factor() returns the active structure factor so notebooks/scripts can branch as needed.

Bayesian Analysis

Sample the full posterior distribution of the varying parameters with the DREAM MCMC sampler (built into BUMPS — no extra dependencies):

fitter.set_model('sphere')
fitter.set_param('radius', value=50, min=10, max=200, vary=True)
fitter.set_param('scale', value=0.1, min=0.01, max=1.0, vary=True)

# Run the Bayesian fit (prints point estimates + credible intervals + diagnostics)
result = fitter.fit_bayesian(samples=10000, burn=200)

# Corner plot of the posterior
fitter.plot_posterior_pairs()

# More displays
fitter.plot_param_distribution('radius')      # marginal posterior
fitter.plot_posterior_predictive()            # 95% credible band over the data
fitter.plot_param_correlations()              # correlation heatmap
fitter.plot_trace()                           # MCMC chain traces

# Raw chain access / export
posterior = fitter.get_posterior()
posterior.save_posterior_csv('posterior_chain.csv')

See the User Guide for details.

Available Methods

BUMPS methods:

  • 'amoeba' - Nelder-Mead simplex (default, robust)
  • 'lm' - Levenberg-Marquardt
  • 'newton' - Newton's method
  • 'de' - Differential evolution

LMFit methods:

  • 'leastsq' - Levenberg-Marquardt (default)
  • 'least_squares' - Trust Region Reflective
  • 'differential_evolution' - Global optimizer
  • 'powell', 'nelder', etc.

Demo Notebooks

Design Philosophy

This implementation follows a template pattern where:

  1. The core fitting logic is abstracted into a reusable class
  2. Models are loaded dynamically from SasModels - no hardcoded model assumptions
  3. Parameters are discovered automatically from the model definition
  4. Multiple optimization engines are supported through a unified interface
  5. The user maintains full control over parameter initialization and bounds

Implementation Details

Engine Adapters

The fitter implements adapter patterns for both BUMPS and LMFit:

  • BUMPS: Uses native sasmodels.bumps_model integration
  • LMFit: Uses sasmodels.direct_model.DirectModel with a custom residual function

Parameter Management

Parameters are stored internally with:

  • value: Current/initial value
  • min, max: Bounds
  • vary: Fitting flag
  • description: From model metadata

This allows the fitter to work with any model without prior knowledge of its parameters.

License

BSD 3-Clause License. See LICENSE for the full text.

References

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

sans_fitter-0.2.0.tar.gz (54.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

sans_fitter-0.2.0-py3-none-any.whl (43.1 kB view details)

Uploaded Python 3

File details

Details for the file sans_fitter-0.2.0.tar.gz.

File metadata

  • Download URL: sans_fitter-0.2.0.tar.gz
  • Upload date:
  • Size: 54.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/7.0.0 CPython/3.13.14

File hashes

Hashes for sans_fitter-0.2.0.tar.gz
Algorithm Hash digest
SHA256 3962e96e9532e6b7f77c0018f62b34952c125bd0a890bea8f70cf80cb948af0e
MD5 40003c46d6f028782aea5e9c66b4652e
BLAKE2b-256 f316611c59c5ae8d1630034cf2ce0b1f514f2eb746dff21fcff88589e089d219

See more details on using hashes here.

Provenance

The following attestation bundles were made for sans_fitter-0.2.0.tar.gz:

Publisher: ci.yml on ai4se1dk/SANS-fitter

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file sans_fitter-0.2.0-py3-none-any.whl.

File metadata

  • Download URL: sans_fitter-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 43.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/7.0.0 CPython/3.13.14

File hashes

Hashes for sans_fitter-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 056fa058a1450492984581cd0db7176ee20e6d85f5716ab88fbfd36ee91ba9be
MD5 f9ab5246ee84a3fcfb6738b204c87759
BLAKE2b-256 a32e2d456a82ea66f29930380b659fb261823b8d9114c770a95bfa6d31479490

See more details on using hashes here.

Provenance

The following attestation bundles were made for sans_fitter-0.2.0-py3-none-any.whl:

Publisher: ci.yml on ai4se1dk/SANS-fitter

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Release history Release notifications | RSS feed

0.3.0

2 files

0.2.2

2 files

This release

0.2.0 This release

2 files

0.0.4

2 files

0.0.3

2 files

0.0.2

2 files

0.0.1

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page