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
7 changes: 6 additions & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,12 @@

Until the first release of the Python package, **all migration work is built
against and merged into `claude-python-app`**, not `master`. Start feature
branches from `origin/claude-python-app` and target pull requests at it.
branches from `origin/claude-python-app`.

When a piece of work is finished and pushed, **open the pull request
yourself, with base `claude-python-app`** (never `master`), so the owner
cannot merge into `master` by accident. Say in the PR description that it
targets `claude-python-app`.

## Plan and progress

Expand Down
18 changes: 18 additions & 0 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,24 @@
:members: two_theta, plot
```

## Single-crystal diffraction

```{eval-rst}
.. autofunction:: fourier

.. autoclass:: FourierMap
:members: hkl, plot, is_line
```

## Pair distribution function

```{eval-rst}
.. autofunction:: pdf

.. autoclass:: PDFPattern
:members: plot
```

## Running DISCUS directly

```{eval-rst}
Expand Down
3 changes: 3 additions & 0 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ import diffuse as dc
cr = dc.read_structure("anatase.cif", supercell=(10, 10, 4))
p = dc.powder(cr, qmin=0.5, qmax=10, dq=0.005, radiation="xray")
p.plot()

f = dc.fourier(cr, ll=(-4, -4, 0), lr=(4, -4, 0), ul=(-4, 4, 0)) # hk0 plane
g = dc.pdf(cr, rmax=20, qmax=25) # G(r)
```

```{toctree}
Expand Down
23 changes: 23 additions & 0 deletions migration/WP0_Test_Baseline.md
Original file line number Diff line number Diff line change
Expand Up @@ -413,3 +413,26 @@ explain the original CI failure of `04.sro3` (run 2). Needs its own
investigation: uninitialised memory or a race in the lots/NUFFT path are
candidates. Until then, CI keeps `--retry-mc 2`.

### Demo API: single-crystal Fourier and PDF

`diffuse.fourier()` (line or plane in reciprocal space, optional removal of
the average structure for diffuse scattering) and `diffuse.pdf()` (G(r),
periodic crystal or finite particle), with result objects `FourierMap` and
`PDFPattern`, plots, and two gallery examples (`fourier_demo.py`,
`pdf_demo.py`). Tests: `tests/python/test_fourier_pdf.py`.

Checked against independent references:

| Check | Result |
|---|---|
| `pdf()` vs the legacy `03.Pair_Distribution_Function/*.grcalc` (histogram, thermal, Qmax 30, Qdamp 0.02) | identical (R ≤ 1e-9). The reference files come from `water_hex.cell` (O only), although `pdf.mac`'s plot titles say nickel. |
| `fourier()` line vs `02.Calculation_Scattering/RESULTS/1d.inte` | R = 1.7e-7 |
| `fourier()` plane vs golden `02.2d` | identical |
| Orientation: a row of atoms along a, neutrons, no ADPs | intensity varies only along the first index (h), exactly constant along k |
| Finite particle (`particle_diameter`) | G(r) = 0 beyond the particle; a periodic crystal keeps its peaks |

**Bug found and fixed:** DISCUS's `cd` changes the working directory of the
whole Python process, so after any `diffuse` call, relative paths in the
user's script pointed somewhere else. `Session.run()` now restores the
caller's working directory (test `test_working_directory_kept`).

8 changes: 7 additions & 1 deletion python/README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
# DiffuseCode from Python

`python/diffuse/` is an early Python API for DISCUS. It currently covers a
small set of commands: reading a structure and calculating a powder pattern.
small set of commands: reading a structure, and calculating powder patterns,
single-crystal intensities (including diffuse scattering) and pair
distribution functions.
The results are NumPy arrays, so they can be plotted with matplotlib or any
other library.

Expand Down Expand Up @@ -61,6 +63,10 @@ import diffuse as dc
| `Crystal.atoms()`, `.positions()` | Atom names and fractional coordinates as arrays |
| `powder(crystal, qmin, qmax, dq, radiation, wavelength, method, temperature, lp_correction)` | Powder pattern on a Q grid. `radiation`: `"xray"`, `"neutron"`, `"electron"`; `method`: `"debye"` or `"complete"`. Returns a `PowderPattern`. |
| `PowderPattern.q`, `.intensity`, `.two_theta()`, `.plot()` | Results and a quick matplotlib plot |
| `fourier(crystal, ll, lr, ul=None, npoints, radiation, wavelength, temperature, subtract_average)` | Single-crystal intensities on a line (`ul` left out) or plane in reciprocal space; `subtract_average=100` leaves the diffuse scattering. Returns a `FourierMap`. |
| `FourierMap.intensity`, `.hkl()`, `.x`, `.y`, `.plot(log=...)` | Intensities (`[i, j]`: i along `ll`→`lr`, j along `ll`→`ul`), their (h, k, l), and an image or line plot |
| `pdf(crystal, rmax, dr, radiation, qmax, qdamp, qbroad, thermal, corrlin, corrquad, particle_diameter)` | Pair distribution function G(r), for a periodic crystal or a finite particle. Returns a `PDFPattern`. |
| `PDFPattern.r`, `.G`, `.plot()` | Results and a plot |
| `run_macro(text)` | Runs any DISCUS macro text, for commands that are not wrapped yet |
| `MacroError` | Raised when a DISCUS command fails; the message holds the `***` error lines |

Expand Down
7 changes: 5 additions & 2 deletions python/diffuse/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,14 @@

from ._session import DiffuseError, MacroError, Session, session
from .crystal import Crystal, read_structure
from .fourier import FourierMap, fourier
from .pdf import PDFPattern, pdf
from .powder import PowderPattern, powder

__all__ = [
"Crystal", "DiffuseError", "MacroError", "PowderPattern", "Session",
"powder", "read_structure", "run_macro", "session",
"Crystal", "DiffuseError", "FourierMap", "MacroError", "PDFPattern",
"PowderPattern", "Session",
"fourier", "pdf", "powder", "read_structure", "run_macro", "session",
]


Expand Down
12 changes: 9 additions & 3 deletions python/diffuse/_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,9 +151,15 @@ def run(self, commands: str, cwd: str | os.PathLike | None = None) -> str:
f"{FLAG} = 0\n"
f"{commands.strip()}\n"
f"{FLAG} = 1\n")
with self._capture() as cap:
self._s.execute_macro("@" + str(driver))
ok = self._s.get_value(FLAG) == 1.0
# DISCUS's "cd" changes the working directory of the whole process;
# give the caller theirs back afterwards.
caller_cwd = os.getcwd()
try:
with self._capture() as cap:
self._s.execute_macro("@" + str(driver))
ok = self._s.get_value(FLAG) == 1.0
finally:
os.chdir(caller_cwd)
self._show(cap.text)
if not ok:
errors = [line.strip() for line in cap.text.splitlines() if "***" in line]
Expand Down
260 changes: 260 additions & 0 deletions python/diffuse/fourier.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,260 @@
"""Single-crystal diffraction: intensities on a line or plane in reciprocal space."""

from __future__ import annotations

from dataclasses import dataclass, field

import numpy as np

from ._session import session
from .crystal import Crystal, _ensure_loaded

_RADIATION = {"xray": "xray", "x-ray": "xray", "neutron": "neutron", "electron": "electron"}
_HKL = "hkl"


@dataclass
class FourierMap:
"""Intensities on a line or plane in reciprocal space. See :func:`fourier`.

The points are ``ll + i/(na-1) * (lr - ll) + j/(no-1) * (ul - ll)`` for
``i < na`` along the abscissa and ``j < no`` along the ordinate.

Attributes
----------
intensity : numpy.ndarray
Shape ``(na, no)`` for a plane, ``(na,)`` for a line; index 0 runs
along the abscissa (``ll`` to ``lr``).
ll, lr, ul : numpy.ndarray
Corners in reciprocal-lattice units (h, k, l): lower left, lower
right, upper left.
x, y : numpy.ndarray
Axis values used for plotting: the Miller index that changes most
along each axis (named in ``x_label``, ``y_label``). ``y`` is empty
for a line.
settings : dict
The arguments the map was calculated with.
crystal : Crystal or None
The structure it was calculated for.
"""

intensity: np.ndarray
ll: np.ndarray
lr: np.ndarray
ul: np.ndarray
x: np.ndarray
y: np.ndarray
x_label: str
y_label: str
settings: dict = field(default_factory=dict)
crystal: Crystal | None = None

@property
def is_line(self) -> bool:
"""True for a 1-D line, False for a 2-D plane."""
return self.intensity.ndim == 1

def hkl(self) -> np.ndarray:
"""Reciprocal-space coordinates (h, k, l) of every point.

Returns
-------
numpy.ndarray
Shape ``(na, 3)`` for a line, ``(na, no, 3)`` for a plane.
"""
na = self.intensity.shape[0]
u = np.linspace(0, 1, na)
if self.is_line:
return self.ll + u[:, None] * (self.lr - self.ll)
no = self.intensity.shape[1]
v = np.linspace(0, 1, no)
return (self.ll + u[:, None, None] * (self.lr - self.ll)
+ v[None, :, None] * (self.ul - self.ll))

def plot(self, ax=None, *, log: bool = False, dynamic_range: float = 1e5,
cmap: str = "viridis", **kwargs):
"""Plot the map (image) or line with matplotlib.

Parameters
----------
ax : matplotlib.axes.Axes, optional
Axes to draw into. Default: a new figure.
log : bool
Logarithmic intensity scale (zero intensities are masked).
dynamic_range : float
With ``log``, show intensities down to ``max / dynamic_range``.
Finite crystals have fringes many decades below the peaks;
without a limit they would swamp the map.
cmap : str
Colour map for a plane.
**kwargs
Passed on to :meth:`~matplotlib.axes.Axes.imshow` (plane) or
:meth:`~matplotlib.axes.Axes.plot` (line).

Returns
-------
matplotlib.axes.Axes
"""
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm

if ax is None:
_, ax = plt.subplots(figsize=(6, 5) if not self.is_line else (8, 4.5))
if self.is_line:
kwargs.setdefault("lw", 1.0)
ax.plot(self.x, self.intensity, **kwargs)
ax.set_xlabel(self.x_label)
ax.set_ylabel("Intensity (arb. units)")
ax.set_xlim(self.x[0], self.x[-1])
if log:
ax.set_yscale("log")
top = float(self.intensity.max())
ax.set_ylim(top / dynamic_range, top * 2)
return ax
z = self.intensity.T # rows = ordinate for imshow
if log:
z = np.ma.masked_less_equal(z, 0)
top = float(z.max())
kwargs.setdefault("norm", LogNorm(vmin=top / dynamic_range, vmax=top))
im = ax.imshow(z, origin="lower", cmap=cmap, aspect="auto",
extent=(self.x[0], self.x[-1], self.y[0], self.y[-1]), **kwargs)
ax.set_xlabel(self.x_label)
ax.set_ylabel(self.y_label)
ax.figure.colorbar(im, ax=ax, label="Intensity")
return ax


def _axis_index(vector: np.ndarray, taken: int | None = None) -> int:
"""Miller index (0=h, 1=k, 2=l) that changes most along ``vector``."""
order = np.argsort(-np.abs(vector), kind="stable")
for i in order:
if i != taken:
return int(i)
return int(order[0])


def fourier(crystal: Crystal, *, ll, lr, ul=None, npoints=(201, 201),
radiation: str = "xray", wavelength: float | None = None,
temperature: bool = True, subtract_average: float = 0.0) -> FourierMap:
"""Calculate single-crystal intensities on a line or plane with DISCUS.

Parameters
----------
crystal : Crystal
The structure, from :func:`read_structure`.
ll, lr : sequence of 3 float
Lower-left and lower-right corner (h, k, l); the abscissa runs from
``ll`` to ``lr``.
ul : sequence of 3 float, optional
Upper-left corner; the ordinate runs from ``ll`` to ``ul``. Leave it
out for a line.
npoints : int or (int, int)
Number of points along the abscissa and the ordinate (a plain int
for a line, or the same along both axes of a plane).
radiation : {"xray", "neutron", "electron"}
Radiation type; selects the atomic form factors or scattering lengths.
wavelength : float, optional
Wavelength in Å. Default: DISCUS's current setting.
temperature : bool
Apply the atomic displacement parameters.
subtract_average : float
Percentage (0–100) of the average structure's scattering to subtract.
100 removes the Bragg peaks of the average structure and leaves the
diffuse scattering of a disordered crystal.

Returns
-------
FourierMap

Raises
------
ValueError
For an unknown ``radiation``, bad corners or point counts.
MacroError
If the calculation fails inside DISCUS.

Examples
--------
The hk0 plane from -3 to 3 in h and k:

>>> f = dc.fourier(cr, ll=(-3, -3, 0), lr=(3, -3, 0), ul=(-3, 3, 0),
... npoints=(301, 301)) # doctest: +SKIP
>>> f.plot(log=True) # doctest: +SKIP
"""
try:
rad = _RADIATION[radiation.lower()]
except KeyError:
raise ValueError(f"unknown radiation '{radiation}'; use {sorted(set(_RADIATION))}") from None
ll = np.asarray(ll, dtype=float)
lr = np.asarray(lr, dtype=float)
line = ul is None
ul = ll.copy() if line else np.asarray(ul, dtype=float)
if ll.shape != (3,) or lr.shape != (3,) or ul.shape != (3,):
raise ValueError("ll, lr and ul must each be three numbers (h, k, l)")
if np.allclose(lr, ll) or (not line and np.allclose(ul, ll)):
raise ValueError("lr (and ul for a plane) must differ from ll")
if line:
na, no = (int(npoints), 1) if np.ndim(npoints) == 0 else (int(npoints[0]), 1)
else:
na, no = (int(npoints),) * 2 if np.ndim(npoints) == 0 else map(int, npoints)
if na < 2 or (not line and no < 2):
raise ValueError("need at least 2 points along each axis")
if not 0.0 <= subtract_average <= 100.0:
raise ValueError("subtract_average is a percentage, 0 to 100")

ia = _axis_index(lr - ll)
io = _axis_index(ul - ll, taken=ia) if not line else (ia + 1) % 3

def vec(v):
return ", ".join(f"{c:.6g}" for c in v)

_ensure_loaded(crystal)
s = session()
out = s.workdir / "fourier.inte"
out.unlink(missing_ok=True)
wvle = f"\n wvle {wavelength}" if wavelength is not None else ""
s.run(f"""
discus
fourier
reset
{rad}
ll {vec(ll)}
lr {vec(lr)}
ul {vec(ul)}
na {na}
no {no}
abs {_HKL[ia]}
ord {_HKL[io]}
temp {"use" if temperature else "ign"}
disp off{wvle}
set aver, {subtract_average}
lots off
run
exit
output
outf {out.name}
value inte
form stan
run
exit
exit
kuplot
rese
load {"xy" if line else "ni"}, {out.name}
exit
""", cwd=s.workdir)
if line:
x, inte = s.dataset(1)
y = np.empty(0)
intensity = inte.astype(float)
else:
x, y, z = s.dataset_2d(1)
intensity = z.astype(float)
settings = dict(ll=tuple(ll), lr=tuple(lr), ul=None if line else tuple(ul),
npoints=(na,) if line else (na, no), radiation=rad,
wavelength=wavelength, temperature=temperature,
subtract_average=subtract_average)
return FourierMap(intensity=intensity, ll=ll, lr=lr, ul=ul,
x=np.asarray(x, dtype=float), y=np.asarray(y, dtype=float),
x_label=_HKL[ia], y_label="" if line else _HKL[io],
settings=settings, crystal=crystal)
Loading
Loading