Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ sim = de.MasterPatternSimulator(
npx=500,
dmin=0.05,
bethe=de.BetheParameters(),
# backend="bloch_prism" is the default: the batched dynamical solve.
# backend="bloch_smatrix" is the default: the batched dynamical solve.
# "bloch" is the one-direction-at-a-time float64 reference it reproduces.
)

Expand Down
2 changes: 1 addition & 1 deletion docs/dev/algorithm.rst
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ The master pattern is computed as in EMsoft's ``EMEBSDmaster``
positive), and ``L_gh = conj(C) I C^T``. ``lambda_E(z)`` is the Monte Carlo
exit-depth fraction times ``exp(+2 pi z / x_gp)``, which cancels the normal
absorption already in the eigenvalues; the depth limit is the 99 % histogram
depth. ``bloch_prism`` evaluates the same integral through the scattering
depth. ``bloch_smatrix`` evaluates the same integral through the scattering
matrix instead of an eigendecomposition.

7. **S_gh weighting.** Per asymmetric-unit site,
Expand Down
14 changes: 11 additions & 3 deletions docs/dev/architecture.rst
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ Every intensity model sits behind one seam,
then ``intensities(directions)`` in chunks. The simulator owns gridding,
chunking and assembly; backends own the physics.

``bloch_prism`` (the default)
``bloch_smatrix`` (the default)
Replaces the eigendecomposition with the physically equivalent scattering
matrix ``exp(2 pi i A z / (2 k_n))`` (batched ``torch.linalg.matrix_exp``,
pure matrix products) followed by a depth recurrence. Everything is batched:
Expand All @@ -70,11 +70,19 @@ chunking and assembly; backends own the physics.
bucketed by strong-beam count so each batch is a uniform ``[B, S, S]``. It
reproduces ``bloch`` to about 1e-13 in float64 and 1e-4 in float32.

The scattering-matrix form of dynamical diffraction is Sturkey's (Proc.
Phys. Soc. 80, 321, 1962); with Bethe potentials it is Wang and De Graef's
(Ultramicroscopy 160, 35, 2016) and on GPUs Singh and De Graef's (Microsc.
Microanal. 24 S1, 222, 2018). Before 0.6 it was called ``bloch_prism``, but
it is not Ophus's PRISM (Adv. Struct. Chem. Imaging 3, 13, 2017), which
interpolates a STEM scattering matrix in Fourier space: nothing here is
interpolated, and the result equals ``bloch``.

``bloch``
The float64 reference, one direction at a time. A non-Hermitian
eigendecomposition neither batches nor accelerates on a GPU (cuSOLVER has no
batched general-eigenvalue kernel), so this backend is CPU-bound and exists
to validate ``bloch_prism``, not for production.
to validate ``bloch_smatrix``, not for production.

Symmetry reduction is independent of the backend: only the point group's
fundamental sector is sampled and the result is replicated, which is exact (the
Expand All @@ -101,7 +109,7 @@ Differentiability
=================

Gradients flow end to end from crystal parameters to intensity. The
``bloch_prism`` path is torch-native (``matrix_exp``, a depth recurrence and
``bloch_smatrix`` path is torch-native (``matrix_exp``, a depth recurrence and
``S_gh``), so gradients pass through the non-Hermitian complex solve back to
``U_g``. ``differentiable_ucg_lut`` assembles ``U_g`` in torch, and
``scattering_torch.wk_scattering_factor_torch`` ports the full
Expand Down
2 changes: 1 addition & 1 deletion docs/dev/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ not done when it runs -- it is done when it still reproduces the oracle:

.. code-block:: shell

uv run python scripts/validate_master_pattern.py --material ni --backend bloch_prism
uv run python scripts/validate_master_pattern.py --material ni --backend bloch_smatrix

Nickel uses kikuchipy's bundled master pattern and needs no external files.
Silicon needs a local EMsoft ``Si_MC.h5`` run, which is not redistributed here;
Expand Down
2 changes: 1 addition & 1 deletion examples/cif_to_master_pattern.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -445,7 +445,7 @@
"source": [
"## 2. Set up the simulation\n",
"\n",
"The default `backend=\"bloch_prism\"` is the batched dynamical solver; `\"bloch\"` is the\n",
"The default `backend=\"bloch_smatrix\"` is the batched dynamical solver; `\"bloch\"` is the\n",
"one-direction-at-a-time float64 reference it reproduces.\n",
"\n",
"`npx` and `dmin` are the accuracy/cost knobs: `npx` sets the Lambert grid\n",
Expand Down
2 changes: 1 addition & 1 deletion examples/indexing/dictionary_indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@
npx=100,
dmin=0.05,
monte_carlo=depth,
backend="bloch_prism",
backend="bloch_smatrix",
)
master = sim.compute(device=device, dtype=torch.float32)
print(master)
Expand Down
2 changes: 1 addition & 1 deletion examples/indexing/spherical_indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@
npx=100,
dmin=0.05,
monte_carlo=depth,
backend="bloch_prism",
backend="bloch_smatrix",
)
master = sim.compute(device=device, dtype=torch.float32)
symmetry = phase_from_crystal(crystal).point_group
Expand Down
2 changes: 1 addition & 1 deletion examples/simulation/cif_to_detector.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@
npx=100,
dmin=0.05,
monte_carlo=depth,
backend="bloch_prism",
backend="bloch_smatrix",
)
sim.structure_factors().show(n=12)

Expand Down
2 changes: 1 addition & 1 deletion examples/simulation/compare_emsoft.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@
dmin=dmin,
bethe=bethe,
monte_carlo=depth,
backend="bloch_prism",
backend="bloch_smatrix",
)
started = perf_counter()
simulated = simulator.compute(device=device, dtype=torch.float64, chunk_size=512).to("cpu")
Expand Down
2 changes: 1 addition & 1 deletion examples/simulation/energy_resolved_simulation.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@
npx=100,
dmin=0.05,
monte_carlo=depth,
backend="bloch_prism",
backend="bloch_smatrix",
)
master = sim.compute(device=device, dtype=torch.float64, energy_resolved=True, chunk_size=512)
assert master.data.shape == (3, 2, 2 * sim.npx + 1, 2 * sim.npx + 1)
Expand Down
6 changes: 3 additions & 3 deletions examples/simulation/resolution_and_backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@
#
# These are normal-depth integration slices, not crystal layers or a simulated
# electron trajectory. The stored exponential is sampled at z = j * dz;
# PRISM evaluates the propagated wave at (j + 1) * dz. Both solvers use the
# The scattering matrix evaluates the propagated wave at (j + 1) * dz. Both solvers use the
# absorption-corrected weights internally; this viewer shows uncorrected exit
# statistics, so it does not mistake an increasing correction for deeper yield.

Expand All @@ -115,7 +115,7 @@
npx=100,
dmin=0.05,
monte_carlo=depth,
backend="bloch_prism",
backend="bloch_smatrix",
)
coarse_sim.structure_factors()
fine_sim = coarse_sim.refine(npx=200)
Expand Down Expand Up @@ -180,7 +180,7 @@
scale = reference.data.abs().max().clamp_min(1e-30)
relative_max = (coarse.data - reference.data).abs().max() / scale
assert torch.isfinite(relative_max) and relative_max < 1e-7
print(f"PRISM versus Bloch maximum relative difference: {relative_max.item():.3e}")
print(f"Scattering matrix vs eigendecomposition, max relative diff: {relative_max.item():.3e}")

# %%
# Continue a convergence study
Expand Down
6 changes: 3 additions & 3 deletions scripts/validate_master_pattern.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@

Usage::

uv run python scripts/validate_master_pattern.py --material ni --backend bloch_prism
uv run python scripts/validate_master_pattern.py --material si --backend bloch_prism \\
uv run python scripts/validate_master_pattern.py --material ni --backend bloch_smatrix
uv run python scripts/validate_master_pattern.py --material si --backend bloch_smatrix \\
--mc /path/to/Si_MC.h5 --device cuda
"""

Expand Down Expand Up @@ -126,7 +126,7 @@ def main() -> None:
"--dmin", type=float, default=None, help="dmin in nm (default: the reference run's value)"
)
parser.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu")
parser.add_argument("--backend", default="bloch_prism")
parser.add_argument("--backend", default="bloch_smatrix")
parser.add_argument(
"--mc",
default=None,
Expand Down
14 changes: 12 additions & 2 deletions src/de_ebsd/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
from de_ebsd.crystal import AtomSite, Crystal
from de_ebsd.diffraction import (
BetheParameters,
BlochPrismBackend,
BlochScatteringMatrixBackend,
BlochWaveBackend,
MasterPatternBackend,
)
Expand All @@ -45,7 +45,7 @@
__all__ = [
"AtomSite",
"BetheParameters",
"BlochPrismBackend",
"BlochScatteringMatrixBackend",
"BlochWaveBackend",
"Crystal",
"CrystalExplorer",
Expand All @@ -72,6 +72,16 @@


def __getattr__(name: str):
if name == "BlochPrismBackend": # the scattering-matrix backend's old name
import warnings

warnings.warn(
"BlochPrismBackend is now BlochScatteringMatrixBackend; "
"the old name goes in a later release",
DeprecationWarning,
stacklevel=2,
)
return BlochScatteringMatrixBackend
module = _LAZY.get(name)
if module is None:
raise AttributeError(f"module 'de_ebsd' has no attribute {name!r}")
Expand Down
2 changes: 1 addition & 1 deletion src/de_ebsd/crystal/structure_factors.py
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,7 @@ def differentiable_ucg_lut(

When ``debye_waller`` is None the amplitudes are evaluated in numpy and held
constant (positions/occupancy gradients only). Feed the result to a torch
backend (``bloch_prism``) as its ``u_lut`` for end-to-end
backend (``bloch_smatrix``) as its ``u_lut`` for end-to-end
``d(intensity)/d(crystal parameter)``. Lattice gradients (through ``g``)
remain a further step.
"""
Expand Down
19 changes: 17 additions & 2 deletions src/de_ebsd/diffraction/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,18 @@
reduce_to_fundamental_sector,
sample_incident_directions,
)
from de_ebsd.diffraction.prism import BlochPrismBackend
from de_ebsd.diffraction.reflections import (
ReflectionList,
candidate_reflections,
excitation_errors,
master_reflection_list,
partition_strong_weak,
)
from de_ebsd.diffraction.smatrix import BlochScatteringMatrixBackend

__all__ = [
"BetheParameters",
"BlochPrismBackend",
"BlochScatteringMatrixBackend",
"BlochWaveBackend",
"DynamicalMatrix",
"KVectorGrid",
Expand All @@ -43,3 +43,18 @@
"resolve_backend",
"sample_incident_directions",
]


def __getattr__(name: str):
# The scattering-matrix backend's old name, kept a release with a warning.
if name == "BlochPrismBackend":
import warnings

warnings.warn(
"BlochPrismBackend is now BlochScatteringMatrixBackend; "
"the old name goes in a later release",
DeprecationWarning,
stacklevel=2,
)
return BlochScatteringMatrixBackend
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
21 changes: 16 additions & 5 deletions src/de_ebsd/diffraction/backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@

:class:`BlochWaveBackend` is the dynamical solver (Bethe-perturbed dynamical
matrix, eigen-decomposition, depth integration) in float64, one direction at a
time; :class:`~de_ebsd.diffraction.prism.BlochPrismBackend` is its batched GPU
equivalent. The dynamical matrix, depth integration and ``S_gh`` weighting port
EMsoft's ``GetDynMat``, ``CalcLgh`` and ``preCalcSgh``.
time; :class:`~de_ebsd.diffraction.smatrix.BlochScatteringMatrixBackend` is its
batched GPU equivalent, by the scattering matrix. The dynamical matrix, depth
integration and ``S_gh`` weighting port EMsoft's ``GetDynMat``, ``CalcLgh`` and
``preCalcSgh``.
"""

from __future__ import annotations
Expand Down Expand Up @@ -303,12 +304,22 @@ def resolve_backend(backend: str | MasterPatternBackend) -> MasterPatternBackend
"""Map a backend name to an instance; pass instances through."""
if isinstance(backend, MasterPatternBackend):
return backend
from de_ebsd.diffraction.prism import BlochPrismBackend # deferred: prism imports this module
# deferred: smatrix imports this module
from de_ebsd.diffraction.smatrix import BlochScatteringMatrixBackend

named = {
"bloch": BlochWaveBackend,
"bloch_prism": BlochPrismBackend,
"bloch_smatrix": BlochScatteringMatrixBackend,
}
if backend == "bloch_prism": # the old name, kept a release with a warning
import warnings

warnings.warn(
'backend "bloch_prism" is now "bloch_smatrix"; the old name goes in a later release',
DeprecationWarning,
stacklevel=2,
)
backend = "bloch_smatrix"
try:
return named[backend]()
except KeyError:
Expand Down
Loading
Loading