In [1]:
import os
os.environ["SAS_OPENCL"] = "cuda"   # use CUDA GPU backend for sasmodels

import escape as esc
import numpy as np
esc.require("0.9.8")
Loading material database from C:\dev\escape-core\python\src\escape\scattering\..\data\mdb\materials.db

SAXS. Form-factors. Cylinder (SasView-aligned)¶

A monodisperse right circular cylinder with uniform scattering length density contrast $\Delta\rho$ (cylinder minus solvent). Matches cylinder — SasView 6.1.3.

Reference: https://www.sasview.org/docs/user/models/cylinder.html

Parameters (SasView defaults)¶

Parameter Variable Value
Scale scale 1
Background (cm⁻¹) background 0.001
Contrast Δρ (10⁻⁶ Å⁻²) contrast 3 (= sld 4 − sld_solvent 1)
Radius (Å) radius 20
Length (Å) length 400
Theta (deg), 2D only theta 60
Phi (deg), 2D only phi 60

Form-factor (SasView cylinder.c)¶

The oriented amplitude at angle $\alpha$ between the cylinder axis and $\mathbf{q}$:

$$F(q,\alpha) = 2\,\Delta\rho\,V\;\mathrm{sinc}\!\left(\tfrac{L}{2}q\cos\alpha\right)\frac{J_1(R\,q\sin\alpha)}{R\,q\sin\alpha}, \quad H=L/2$$

Powder average over random orientations:

$$I(q) = \frac{\mathrm{scale}}{V}\int_0^{\pi/2} F^2(q,\alpha)\,\sin\alpha\,d\alpha + \mathrm{background}$$

In [2]:
# ── Variables ──────────────────────────────────────────────────────────────
q     = esc.var("Q")
alpha = esc.var("alpha")   # angle between cylinder axis and q

# ── Parameters ─────────────────────────────────────────────────────────────
scale      = esc.par("Scale",      1.0,  scale=1e8, fixed=True)
radius     = esc.par("Radius",    20.0,  units=esc.angstr)
length     = esc.par("Length",   400.0,  units=esc.angstr)
contrast   = esc.par("Contrast",   3.0,  scale=1e-6, units=f"{esc.angstr}^-2")
background = esc.par("Background", 0.001, userlim=[0.0, 0.03])

# ── Geometry ───────────────────────────────────────────────────────────────
half_length = 0.5 * length
volume      = np.pi * esc.pow(radius, 2) * length

# ── Oriented amplitude ─────────────────────────────────────────────────────
# q_axial  = q * cos(alpha): component along cylinder axis (sinc factor)
# q_radial = q * sin(alpha): component perpendicular to axis (J1 factor)
q_axial  = q * esc.cos(alpha)
q_radial = q * esc.sin(alpha)

# F = 2 * Δρ * V * sinc(H*q_axial) * J1(R*q_radial)/(R*q_radial)
# esc.sinc and esc.j1_over_x are numerically stable at zero
F = 2.0 * contrast * volume * esc.sinc(half_length * q_axial) * esc.j1_over_x(radius * q_radial)

# ── Powder average ─────────────────────────────────────────────────────────
i1d = (scale / volume
       * esc.integral(esc.pow(F, 2) * esc.sin(alpha),
                      alpha, 0.0, np.pi / 2.0,
                      numpoints=61, maxiter=5, epsabs=1e-5)
       + background)
In [3]:
i1d.device = "gpu"

qs = np.linspace(0.001, 1.0, 300)
i1d.show(coordinates=qs).config(
    title="Cylinder — powder average (1D)",
    xlog=True, ylog=True,
    xlabel=f"Q [{esc.angstr}^-1]", ylabel="I(q) [cm^-1]")
Out[3]:

2D oriented scattering (qx, qy)¶

For a fixed cylinder orientation $(\theta, \phi)$ the amplitude is evaluated directly at detector coordinates $(q_x, q_y)$. The cylinder axis unit vector is $\hat{\mathbf{u}} = (\sin\theta\cos\phi,\;\sin\theta\sin\phi,\;\cos\theta)$.

Decompose $\mathbf{q}$ into components parallel and perpendicular to the axis:

$$q_\parallel = \mathbf{q}\cdot\hat{\mathbf{u}}, \qquad q_\perp = \sqrt{|\mathbf{q}|^2 - q_\parallel^2}$$

$$I_{\mathrm{2D}}(q_x,q_y) = \frac{\mathrm{scale}}{V}\,F^2(q_\parallel, q_\perp) + \mathrm{background}$$

In [4]:
qx = esc.var("qx")
qy = esc.var("qy")

theta = esc.par("Theta", 60.0, userlim=[0.0, 180.0], units="deg")
phi   = esc.par("Phi",   60.0, userlim=[0.0, 360.0], units="deg")

deg = np.pi / 180.0

# Cylinder axis unit vector projected onto detector plane
sin_t = esc.sin(theta * deg)
ux = sin_t * esc.cos(phi * deg)
uy = sin_t * esc.sin(phi * deg)

# Parallel and perpendicular q components
q_sq      = esc.pow(qx, 2) + esc.pow(qy, 2)
q_par_2d  = qx * ux + qy * uy
q_perp_2d = esc.sqrt(q_sq - esc.pow(q_par_2d, 2))

F_2d = 2.0 * contrast * volume * esc.sinc(half_length * q_par_2d) * esc.j1_over_x(radius * q_perp_2d)
i2d  = scale / volume * esc.pow(F_2d, 2) + background

i2d.device = "gpu"

xs = np.linspace(-1.0, 1.0, 300); ys = np.linspace(-1.0, 1.0, 300)
xv, yv = np.meshgrid(xs, ys)
coords_2d = np.column_stack([xv.flatten(), yv.flatten()]).flatten()
i2d.show(coordinates=coords_2d).config(
    title="Cylinder — oriented 2D SAXS (qx, qy)",
    xlabel=f"qx [{esc.angstr}^-1]", ylabel=f"qy [{esc.angstr}^-1]",
    cblog=True, colorscale="jet")
Out[4]:

SasView reference model & comparison¶

ESCAPE parameter SasView parameter Notes
contrast * 1e-6 sld - sld_solvent contrast in Å⁻²
radius radius cylinder radius (Å)
length length cylinder length (Å)
In [5]:
import time
import matplotlib.pyplot as plt
from sasmodels.core import load_model
from sasmodels.data import empty_data1D
from sasmodels.direct_model import DirectModel

qs = np.linspace(0.001, 1.0, 300).copy()

# ── SasView model ───────────────────────────────────────────────────────────
kernel = load_model("cylinder")
f_sas  = DirectModel(empty_data1D(qs), kernel)
sas_pars = dict(scale=1.0, background=0.001, sld=4.0, sld_solvent=1.0,
                radius=20.0, length=400.0)

# ── Warm-up ─────────────────────────────────────────────────────────────────
f_sas(**sas_pars)
i1d.device = "gpu"; i1d(qs[:5])

# ── Timing helper ────────────────────────────────────────────────────────────
def timeit(fn, n=5):
    t0 = time.perf_counter()
    for _ in range(n): result = fn()
    return (time.perf_counter() - t0) / n * 1e3, result

# ── Evaluate ────────────────────────────────────────────────────────────────
t_sas, Iq_sas = timeit(lambda: f_sas(**sas_pars))

i1d.device = "gpu"
t_gpu, Iq_gpu = timeit(lambda: i1d(qs), n=3)
i1d.device = "cpu"
t_cpu, Iq_cpu = timeit(lambda: i1d(qs))
i1d.device = "gpu"

print(f"SASView GPU : {t_sas:.0f} ms")
print(f"ESCAPE GPU : {t_gpu:.0f} ms")
print(f"ESCAPE CPU : {t_cpu:.0f} ms  ({len(qs)} q-pts)")
rel = np.max(np.abs((Iq_gpu - Iq_sas) / Iq_sas)) * 100
print(f"Max relative diff vs SasView: {rel:.2f}%")


esc.overlay(Iq_sas, Iq_gpu, Iq_cpu, coordinates=qs).config(
    xlabel="Q (1/A)", ylabel="I(q) (1/cm)", 
    xlog=True, ylog=True,
    fig_title=f"Cylinder I(q) — {len(qs)} pts",
    labels=["SASView", "ESCAPE GPU", "ESCAPE CPU"],
    line_styles=["solid", "dash", "dot"],
    line_widths=[2, 3, 3]
)
SASView GPU : 10 ms
ESCAPE GPU : 0 ms
ESCAPE CPU : 3 ms  (300 q-pts)
Max relative diff vs SasView: 4.46%
C:\Users\User\AppData\Local\Temp\ipykernel_45760\2729306328.py:17: UserWarning:

Input array does not own its data (e.g. it is a view or slice); data will be copied

Out[5]:
In [ ]: