Skip to content
D-sudoasdPublic

About

Absolute-intensity calibration for SAXS with a Python API, CLI, and desktop workbench. Tracks correction history and supports canSAS and NXcanSAS export.

Topics

Resources

Code of conduct

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

91 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Conceptual illustration of SAXS absolute-intensity calibration; this artwork is not an experimental measurement.

AbsSAXS

Traceable 1D & 2D Absolute-Intensity Calibration System for Small-Angle X-Ray Scattering
将相对 SAXS 强度标定为绝对强度(cm−1),全程保留监测计数、透射率、厚度、不确定度与可复用标定溯源记录。

CI Python 3.10+ Version 2.0.0 unreleased BSD-3-Clause License Zenodo Concept DOI

Principle · Architecture · 1D vs 2D · Installation · Quick Start · Workflows · Workbench · 2D Example · 中文快速开始 · Citation


AbsSAXS (saxsabs) is a reusable, fail-closed 1D and 2D SAXS absolute-intensity calibration system uniting a pure-Python scientific core, smart dataset discovery and reference pairing, portable calibration profiles, a headless CLI, the bilingual SAXSAbs Workbench desktop GUI, and a strict BL19B2 synchrotron campaign runner. Every exported profile carries explicit intensity-state metadata, correction history, units (q in Å⁻¹, I(q) in cm⁻¹), and traceable uncertainty status.

Scientific transparency: Measured calibration requires consistent normalization, transmission, thickness, and detector geometry supplied by the researcher. Input intensity states gate incompatible operations, and unknown uncertainty components remain explicitly NaN rather than silently zero-filled.


Principle schematic

Reference-based SAXS absolute-intensity calibration — conceptual schematic / 概念示意图

A reference standard sets the scalar calibration factor K over a shared q range; thickness, monitor, and transmission provenance accompany every absolute-intensity profile. Curves are conceptual.
参考标准与相对强度在共同 q 区间比较确定标定因子 K;厚度、监测计数与透射信息随绝对强度输出保留。曲线仅作原理示意。
View full-size schematic / 查看完整示意图


System architecture

AbsSAXS 1D and 2D reusable absolute-intensity calibration architecture: entry points, smart discovery and reference pairing, CalibrationSession and CalibrationProfile engine with asset caching, fail-closed safety gates, and traceable 1D/2D exports.

AbsSAXS separates deterministic scientific computation from interactive UI and optional detector libraries (pyFAI, FabIO, h5py, matplotlib, sv-ttk remain lazy/optional on import saxsabs):

  • Smart discovery & reference pairing (saxsabs.core.discovery) — Automatically scans beamtime directories, classifies detector frames, standards, backgrounds, darks, geometries (.poni / Pydidas Cali.yaml), masks, flats, and 1D profiles, clusters acquisition sessions by timestamp gap, and pairs each sample with instrument-consistent background and dark references.
  • Reusable calibration profiles & asset caching (saxsabs.core.calibration_profile) — Persists portable saxsabs.calibration_profile.v1 JSON recipes with canonical SHA-256 fingerprints, imports existing Workbench calibration records, and caches stat-keyed detector frames, pre-normalized backgrounds, pyFAI integrators, and digests in a thread-safe CalibrationAssetCache.
  • Unified 1D & 2D batch engine (saxsabs.core.calibration_engine) — CalibrationSession provides fail-closed preflight checks (preflight_1d, preflight_2d) and deterministic single- or multi-worker batch processing (calibrate_1d_batch, calibrate_2d_batch) with per-item QC summaries and structured provenance manifests.
  • Fail-closed scientific safety gates — Explicitly distinguishes raw_counts, relative, absolute_cm^-1, and ambiguous intensity states; prevents double-scaling; enforces NIST SRM 3600 / water / custom reference compatibility; and keeps partial/unknown uncertainties explicit (NaN).

Positioning in the SAXS ecosystem

Related tools address complementary stages of SAXS data reduction and analysis: pyFAI provides detector geometry and azimuthal integration; FabIO handles detector image I/O; SasView and Irena support structural modeling and fitting; BioXTAS RAW focuses on BioSAXS reduction and scaling against water or glassy carbon. AbsSAXS focuses specifically on traceable 1D and 2D absolute-intensity calibration, reusable calibration profiles, fail-closed state/provenance gates, and the strict BL19B2 detector workflow, exporting standards-compliant profiles ready for downstream analysis.


1D and 2D capabilities

Capability 1D External Profile Calibration 2D Detector Batch Calibration Strict BL19B2 Campaign Runner
Inputs CSV, TSV, DAT, CHI, canSAS1d XML, NXcanSAS HDF5 2D frames (TIFF/EDF/CBF via FabIO), .poni, mask, flat, BG/Dark libraries Explicit BL19B2 folder layout, .poni or Pydidas Cali.yaml, --include-manifest, thickness derivation JSON
Discovery & Pairing Batch file queues with unit & column validation discover_dataset role classification, session clustering, same-session & instrument-consistent BG/Dark pairing Explicit reference contracts & source-snapshot SHA-256 verification
Calibration & Scaling Robust median/MAD K (SRM 3600, water, custom); K/d or provenance-verified K-only Exposure-matched dark & NIST-blank subtraction, monitor norm (rate / integrated), cached pyFAI integration, fixed d or μ Schema v4 K/QC contract, exposure-matched dark, NIST blank, joint BG-monitor covariance propagation
Post-Processing Absolute-scale buffer subtraction (α, u(α)) & opt-in 1D fluorescence (constant, high_q_mean, high_q_median, measured) Optional opt-in 1D fluorescence subtraction after integration; optional calibrated 2D EDF/mask/PONI export Dedicated downstream CSR 1D integration (5500-pt q), directory matrices, mean/SD tables, optional 1D fluorescence
Safety & Provenance Fail-closed intensity-state gate (relative required before K; refuses raw_counts, absolute_cm^-1, ambiguous) Preflight gate (READY / CAUTION / BLOCKED), profile SHA-256 fingerprint, deterministic --workers execution Transactional 2D publication, OS file locks, journaled interruption recovery, explicit partial uncertainty budget
Outputs CSV, TSV, canSAS1d XML, optional NXcanSAS HDF5, batch summary JSON Absolute 1D profiles (CSV/TSV/XML/HDF5), optional calibrated 2D packages, batch QC manifest Calibrated 2D HDF5/EDF/PNG packages, checksums, 1D integration bundle, reproducible rerun command
Entry Points CalibrationSession.calibrate_1d_batch, saxsabs calibrate-1d-batch, saxsabs estimate-k, Workbench Tab 3 CalibrationSession.calibrate_2d_batch, saxsabs calibrate-2d-batch, Workbench Tabs 1–2 saxsabs bl19b2-abs2d, saxsabs bl19b2-abs2d-v1-legacy

Installation

Python 3.10 or later is required. The lightweight core package depends only on NumPy, pandas, and xraydb:

git clone https://github.com/D-sudoasd/AbsSAXS.git
cd AbsSAXS
python -m pip install -e .
saxsabs --version

The current source tree reports version 2.0.0, an unreleased candidate prepared for JOSS review. The latest archived release is v1.1.1.

Install optional extras only when needed:

Extra Installs Use it for
gui pyFAI, fabio, matplotlib, sv-ttk SAXSAbs Desktop Workbench, 2D calibration/integration, publication figure export
io fabio Headless 2D detector-image I/O (TIFF/EDF/CBF)
hdf5 h5py NXcanSAS HDF5 writing and HDF5 calibrated-2D packages
bl19b2 fabio, h5py, matplotlib, Pillow, pyFAI, tifffile Full strict BL19B2 2D batch & 1D integration workflows
dev pytest, ruff, matplotlib, psutil, PyYAML, build tools Automated testing, linting, and engineering benchmarks
# Desktop Workbench + 2D detector integration
python -m pip install -e ".[gui]"

# Add NXcanSAS HDF5 export support
python -m pip install -e ".[gui,hdf5]"

# Full strict BL19B2 detector workflow stack
python -m pip install -e ".[bl19b2]"

Note (Linux): The Workbench uses Tk (tkinter), which is bundled with standard Windows and macOS Python installers. On Linux, install your distribution's Tk package (typically python3-tk) if python -m tkinter is unavailable. The CLI and Python API run headlessly without a display server.


Example usage

1. Monitor normalization & K-factor estimation (CLI)

In rate mode, MON is a beam-monitor count rate in counts/s and exp is exposure time in seconds (exp * MON * T). In integrated mode, MON is the integrated monitor count for the exposure (MON * T). Detector images contain accumulated counts in both modes.

# Rate mode: MON = 100,000 counts/s, exposure = 1.0 s, transmission = 0.8
saxsabs norm-factor --mode rate --exp 1.0 --mon 100000 --trans 0.8
# 80000.0

# Integrated mode: MON = 100,000 accumulated monitor counts, transmission = 0.8
saxsabs norm-factor --mode integrated --mon 100000 --trans 0.8
# 80000.0

# Estimate K from the bundled synthetic example profiles (expected k_factor: 2.0)
saxsabs estimate-k --meas examples/k_measured.csv --ref examples/k_reference.csv --qmin 0.01 --qmax 0.2

For estimate-k, the measured profile must already be reduced to relative intensity (dark/background subtracted and monitor/transmission normalized), with thickness applied in the profile or passed via --thickness-cm. The bundled k_measured.csv declares intensity_state=relative and k_reference.csv declares absolute_cm^-1, yielding k_factor: 2.0; these are synthetic demonstration curves, not beamline measurements.

2. Smart discovery, reusable profiles & batch calibration (CLI)

# 1. Scan a beamtime directory to classify samples, standards, BG/Dark, geometry, and sessions
saxsabs discover --root path/to/beamtime --session-gap-minutes 90 --json-out discovery.json

# 2. Inspect and verify a saved CalibrationProfile JSON (or Workbench calibration record)
saxsabs profile-inspect --profile calibration_profile.json --verify-files

# 3. Batch-calibrate external 1D profiles (with optional buffer/fluorescence subtraction & workers)
saxsabs calibrate-1d-batch \
  --profile calibration_profile.json \
  --inputs sample_01.csv sample_02.csv \
  --output-dir outputs/calibrated_1d \
  --thickness-cm 0.10 \
  --formats csv,cansas_xml \
  --workers 4

# 4. Batch-calibrate 2D detector frames with cached pyFAI integration & smart BG/Dark pairing
saxsabs calibrate-2d-batch \
  --profile calibration_profile.json \
  --inputs sample_01.tif sample_02.tif \
  --output-dir outputs/calibrated_2d \
  --thickness-cm 0.10 \
  --formats csv,cansas_xml \
  --workers 4

3. Reusable calibration system (Python API)

from saxsabs import CalibrationSession, compute_norm_factor

# Low-level normalization helper
factor = compute_norm_factor(1.0, 100000.0, 0.8, "rate")  # 80000.0

# High-level reusable session: auto-discover, calibrate K, save profile, preflight & batch run
session, summary = CalibrationSession.from_directory(
    "path/to/beamtime",
    monitor_mode="rate",
    standard_key="SRM3600",
)
k_result = session.calibrate_2d()
session.save_profile("calibration_profile.json", overwrite=True)

# Fail-closed preflight check followed by deterministic cached batch processing
gate, reports = session.preflight_2d(summary.samples, sample_thickness_cm=0.10)
if not gate.is_blocked:
    batch = session.calibrate_2d_batch(
        summary.samples,
        output_dir="outputs/calibrated_2d",
        sample_thickness_cm=0.10,
        output_formats=("csv", "cansas_xml"),
        workers=4,
    )
    print(batch.succeeded, batch.elapsed_seconds, batch.cache_stats)

See the API and command-line reference for all 12 CLI subcommands, complete function signatures, supported formats, and scientific boundaries.


Workflows

Choose the interface that matches your measurement workflow:

Route Best suited for Start here
Python API (CalibrationSession & core/io) Embedding discovery, cached calibration, subtraction, and standards-compliant writers in analysis pipelines API reference
Headless CLI (saxsabs) Scripted discovery, profile verification, 1D/2D batch calibration, normalization, and subtraction saxsabs --help
SAXSAbs Workbench Interactive K calibration, guided 2D/1D batch processing, visual QC, and publication figure export Install .[gui], run saxsabs-workbench --lang en
Strict BL19B2 Runner Unattended synchrotron campaigns requiring schema-v4 provenance, manifest controls, and journaled recovery BL19B2 batch runbook

Measured BL19B2 batch engineering evidence

For the strict BL19B2 delivery pipeline (saxsabs bl19b2-abs2d + downstream 1D integration), measured end-to-end workstation engineering benchmarks on a 19-frame Pilatus 2M (1679 × 1475 px) beamtime selection are documented in docs/bl19b2-performance.md:

Measured metric (19-frame Pilatus 2M selection, 2 runs/variant) Baseline (722d606) Optimized (c374339) Notes
Fresh complete delivery (mean / range) 54.43 s (51.33–57.52 s) 47.44 s (43.71–51.18 s) 1.15× (−12.8% wait); shared workstation
Full verified resume (mean / range) 17.38 s (16.75–18.00 s) 13.38 s (12.38–14.38 s) 1.30× (−23.0% wait)
Peak resident memory (fresh run mean) 1506.19 MiB 1103.86 MiB ~27% lower peak RSS via streaming variance accumulation
Scientific numerical agreement Reference Bitwise identical All 209 HDF5 arrays (517.6M scalars), max error 0
Interrupted-run recovery (killed after 5 frames) Refused incomplete set Recovered all 19 frames Reused 5 committed frames, completed remaining 14 bit-for-bit

Scope note: These figures document measured software engineering delivery on one shared workstation (not cold-cache isolated timing or a full historical campaign); numerical agreement does not resolve the experiment's explicitly reported partial uncertainty budget.


Workbench

The SAXSAbs Workbench provides a redesigned, modern bilingual (English / 中文) desktop interface with harmonized Light and Dark themes, guided workflow steppers across Tabs 1–3, live active-K status badges, 4-tile calibration KPI cards, smart folder auto-detection, reusable saxsabs.calibration_profile.v1 profile save/load, sticky bottom preflight docks (PREFLIGHT NEEDED / READY / CAUTION / BLOCKED), and publication-grade matplotlib figure export.

python -m pip install -e ".[gui]"
saxsabs-workbench --lang en   # or --lang zh for Chinese

Redesigned SAXSAbs Workbench Tab 1 (K-Factor Calibration, Light theme) showing guided calibration stepper, smart Auto-detect folder button, 4-tile KPI strip, Profiles toolbar, and clean empty-state plot canvas without experimental data.

More Workbench views: 2D Detector Batch Processing & Dark Theme
SAXSAbs Workbench Tab 2 (Detector processing, Light theme) showing the 4-step Batch Workflow stepper, Sample Queue with Detect groups, fixed-thickness strategy, and sticky Preflight dock.
Tab 2 · 2D Detector Batch Processing — guided stepper, session grouping, fixed-thickness gate, and sticky preflight dock
SAXSAbs Workbench Tab 1 (K-Factor Calibration, Dark theme) with harmonized dark surfaces, accent primary button, and theme-synced empty plot canvas.
Harmonized Dark Theme — high-contrast dark surfaces with non-mutating publication-white figure export

Ownership boundary: The Workbench is an interactive desktop interface. For unattended multi-folder synchrotron campaigns, use the strict saxsabs bl19b2-abs2d runner and its documented input contract.


Reproducible 2D example

Run the deterministic synthetic end-to-end software check without private beamline files:

python examples/minimal_2d/run_minimal_2d_pipeline.py

This script generates separate synthetic dark, blank, standard, and sample frames on a 9×9 array, runs detector-space NIST-blank subtraction and a small, homemade integer-bin radial average (not pyFAI integration, not a BL19B2 campaign test, and not experimental beamline validation), recovers the planted K and sample profile within the acceptance tolerances recorded in summary.json, and writes labeled CSV, TSV, and canSAS1d XML outputs (plus NXcanSAS HDF5 when h5py is installed). See examples/minimal_2d/README.md for expected outputs.

Synthetic calibration demonstration showing a supplied NIST SRM 3600 reference curve, a rescaled synthetic profile, inlier ratios, rejected outliers, and the robust median/MAD estimate K = 0.0350.

Synthetic K-factor estimation demonstration (planted K = 0.035) illustrating robust median/MAD outlier rejection. This figure is software illustration, not beamline validation; see asset provenance for regeneration steps.


Scope and validation

  • Explicit units & monitor conventions: Scattering vector q is canonicalized to Å⁻¹ and calibrated intensity to cm⁻¹. Thickness is specified in cm in the CLI/Python API and in mm in Workbench Tab 1/Tab 2 inputs. Monitor normalization distinguishes rate (counts/s × s × T) from integrated (counts × T) while detector arrays always hold accumulated counts.
  • Explicit intensity-state & correction ledger: Every 1D profile is classified as raw_counts, relative, absolute_cm^-1, or ambiguous. Contradictory metadata or missing provenance fail closed before scaling, buffer subtraction, or fluorescence subtraction.
  • Explicit missingness & partial uncertainty: Combined uncertainties are propagated only from supplied, documented sources; missing terms leave combined uncertainty explicitly NaN (and BL19B2 unquantified shared raw-count/dark covariance keeps the budget explicitly partial).
  • Verification boundary: Automated unit/integration tests and the manual verification checklist establish reproducible software engineering behavior without proprietary beamline files; users remain responsible for experiment-specific reference standards, geometry, transmission, and thickness accuracy.

Documentation and support

Document Contents
API and command-line reference Python API signatures, reusable CalibrationSession/CalibrationProfile guide, and all 12 CLI subcommands
Architecture and safety contracts Package layers, release-safety gates, preflight/provenance rules, and known boundaries
BL19B2 batch runbook Input layout, correction formulas, manifest/thickness contracts, and strict campaign commands
BL19B2 performance & recovery evidence Measured 19-frame Pilatus 2M delivery timing, memory, bitwise agreement, and crash-recovery tests
Minimal synthetic 2D example Deterministic 9×9 raw-frame reproducibility script and acceptance criteria
Manual verification checklist Step-by-step reviewer verification commands and Workbench UI check instructions
Reviewer FAQ Scope boundaries, fluorescence vs blank/buffer definitions, and offline schema-check notes
Changelog Detailed release and development history

Report reproducible bugs or request features via the issue tracker using anonymized, portable inputs (never upload private beamline data, credentials, or large generated outputs). Community guidelines and development workflows are documented in CONTRIBUTING.md and CODE_OF_CONDUCT.md.


中文快速开始

AbsSAXS(Python 包与命令行名称 saxsabs)是一套面向 1D 与 2D SAXS 绝对强度标定的可复用系统,提供自动数据集发现与参考配对、可复用标定配置文件(saxsabs.calibration_profile.v1)、失败即阻断的强度状态门控、无头命令行与双语桌面工作台。

核心安装与基础验证

py -m pip install -e .
saxsabs norm-factor --mode rate --exp 1.0 --mon 100000 --trans 0.8
saxsabs estimate-k --meas examples/k_measured.csv --ref examples/k_reference.csv --qmin 0.01 --qmax 0.2
  • 上述 estimate-k 使用仓库自带的合成示例曲线,预期 k_factor 为 2.0,仅用于软件功能验证,并非同步辐射束线实测结果。
  • rate 模式下 MON 为监测计数率(counts/s),exp 为曝光秒数;integrated 模式下 MON 为该次曝光累计监测计数。两种模式中探测器帧均为累计计数。

批量发现与可复用标定工作流

# 自动扫描束线目录中的样品、标样、背景、暗场、几何与机时分组
saxsabs discover --root path/to/beamtime --json-out discovery.json

# 校验已保存的 CalibrationProfile 或工作台标定记录
saxsabs profile-inspect --profile calibration_profile.json --verify-files

# 使用同一套可复用标定配置批量标定 1D 或 2D 数据
saxsabs calibrate-1d-batch --profile calibration_profile.json --inputs sample1.csv sample2.csv --output-dir out_1d --thickness-cm 0.10 --formats csv,cansas_xml
saxsabs calibrate-2d-batch --profile calibration_profile.json --inputs sample1.tif sample2.tif --output-dir out_2d --thickness-cm 0.10 --workers 4

启动全新桌面工作台(中文界面)

py -m pip install -e ".[gui]"
saxsabs-workbench --lang zh

完整参数说明、API 签名与科学边界请参阅命令行与 API 说明及架构与安全边界说明。


Citation

Machine-readable citation metadata is provided in CITATION.cff. The Zenodo badge at the top of this page points to the project-level Concept DOI (10.5281/zenodo.19687103); when citing a specific archived software release, please use that release's version-specific DOI.

License

AbsSAXS is distributed under the BSD-3-Clause license.

About

Absolute-intensity calibration for SAXS with a Python API, CLI, and desktop workbench. Tracks correction history and supports canSAS and NXcanSAS export.

Topics

Resources

Code of conduct

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages