API reference#

Structures#

diffuse.read_structure(path, supercell=None)[source]#

Read a structure file into DISCUS.

Parameters:
  • path (str or os.PathLike) – A .cif or .cell file (an asymmetric unit: DISCUS applies the space group) or a .stru file (a whole crystal).

  • supercell (int or tuple of 3 int, optional) – Number of unit cells along a, b and c; an int means the same along all three. Default: 1 x 1 x 1 for .cif/.cell, and a .stru file is read as it is.

Returns:

Crystal – The structure, now held by DISCUS.

Raises:
Return type:

Crystal

Examples

>>> import diffuse as dc
>>> cr = dc.read_structure("anatase.cif", supercell=(10, 10, 4))
>>> cr.natoms
4800
class diffuse.Crystal(path, supercell, natoms, lattice, _atoms=None)[source]#

A structure loaded into DISCUS. Create it with read_structure().

DISCUS holds one structure at a time. A Crystal remembers how it was made, so a calculation on an older Crystal reads it in again first.

Parameters:
path#

The structure file it was read from.

Type:

pathlib.Path

supercell#

Number of unit cells along a, b and c, or None for a .stru file read as it is.

Type:

tuple of int or None

natoms#

Number of atoms in the whole crystal.

Type:

int

lattice#

(a, b, c, alpha, beta, gamma) in Å and degrees.

Type:

tuple of float

property a: float#

Lattice parameter a in Å.

property volume: float#

Volume of one unit cell in Å^3.

atoms()[source]#

Atom names and fractional coordinates.

Returns:

  • names (numpy.ndarray of str, shape (natoms,)) – Atom names as DISCUS uses them, for example "TI4+".

  • xyz (numpy.ndarray of float, shape (natoms, 3)) – Fractional coordinates in units of the unit cell.

Return type:

tuple[ndarray, ndarray]

Notes

DISCUS saves the crystal to a .stru file, which is read back. The result is cached on the Crystal.

positions()[source]#

Fractional coordinates, shape (natoms, 3). See atoms().

Return type:

ndarray

Powder diffraction#

diffuse.powder(crystal, *, qmin=0.5, qmax=10.0, dq=0.005, radiation='xray', wavelength=0.2, method='debye', temperature=True, lp_correction='none')[source]#

Calculate the powder pattern of a crystal with DISCUS.

Parameters:
  • crystal (Crystal) – The structure, from read_structure().

  • qmin (float) – Q range and step in Å⁻¹.

  • qmax (float) – Q range and step in Å⁻¹.

  • dq (float) – Q range and step in Å⁻¹.

  • radiation ({"xray", "neutron", "electron"}) – Radiation type; selects the atomic form factors or scattering lengths.

  • wavelength (float) – Wavelength in Å, used for the Lorentz-polarisation factor and for PowderPattern.two_theta().

  • method ({"debye", "complete"}) – "debye": Debye equation, for any structure, including finite particles. "complete": Fourier transform on a reciprocal-space grid, for periodic crystals.

  • temperature (bool) – Apply the atomic displacement parameters.

  • lp_correction ({"none", "bragg", "neutron"}) – Lorentz-polarisation correction.

Returns:

PowderPattern

Raises:
  • ValueError – For an unknown radiation or method, or an invalid Q range.

  • MacroError – If the calculation fails inside DISCUS.

Return type:

PowderPattern

Examples

>>> p = dc.powder(cr, qmin=0.5, qmax=10, dq=0.005, radiation="neutron")
>>> p.plot()
class diffuse.PowderPattern(q, intensity, settings=<factory>, crystal=None)[source]#

A calculated powder pattern on an evenly spaced Q grid. See powder().

Parameters:
q#

Momentum transfer Q in Å⁻¹.

Type:

numpy.ndarray

intensity#

Intensity at each Q, arbitrary units.

Type:

numpy.ndarray

settings#

The arguments the pattern was calculated with.

Type:

dict

crystal#

The structure it was calculated for.

Type:

Crystal or None

two_theta(wavelength=None)[source]#

Scattering angle 2θ in degrees.

Parameters:

wavelength (float, optional) – Wavelength in Å. Default: the one the pattern was calculated with.

Return type:

ndarray

plot(ax=None, *, x='q', **kwargs)[source]#

Plot the pattern with matplotlib.

Parameters:
Returns:

matplotlib.axes.Axes

Single-crystal diffraction#

diffuse.fourier(crystal, *, ll, lr, ul=None, npoints=(201, 201), radiation='xray', wavelength=None, temperature=True, subtract_average=0.0)[source]#

Calculate single-crystal intensities on a line or plane with DISCUS.

Parameters:
  • crystal (Crystal) – The structure, from read_structure().

  • ll (sequence of 3 float) – Lower-left and lower-right corner (h, k, l); the abscissa runs from ll to lr.

  • 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.

Return type:

FourierMap

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))
>>> f.plot(log=True)
class diffuse.FourierMap(intensity, ll, lr, ul, x, y, x_label, y_label, settings=<factory>, crystal=None)[source]#

Intensities on a line or plane in reciprocal space. See 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.

Parameters:
intensity#

Shape (na, no) for a plane, (na,) for a line; index 0 runs along the abscissa (ll to lr).

Type:

numpy.ndarray

ll, lr, ul

Corners in reciprocal-lattice units (h, k, l): lower left, lower right, upper left.

Type:

numpy.ndarray

x, y

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.

Type:

numpy.ndarray

settings#

The arguments the map was calculated with.

Type:

dict

crystal#

The structure it was calculated for.

Type:

Crystal or None

property is_line: bool#

True for a 1-D line, False for a 2-D plane.

hkl()[source]#

Reciprocal-space coordinates (h, k, l) of every point.

Returns:

numpy.ndarray – Shape (na, 3) for a line, (na, no, 3) for a plane.

Return type:

ndarray

plot(ax=None, *, log=False, dynamic_range=100000.0, cmap='viridis', **kwargs)[source]#

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 imshow() (plane) or plot() (line).

Returns:

matplotlib.axes.Axes

Pair distribution function#

diffuse.pdf(crystal, *, rmax=20.0, dr=0.01, radiation='xray', qmax=0.0, qdamp=0.0, qbroad=0.0, thermal=True, corrlin=0.0, corrquad=0.0, particle_diameter=None)[source]#

Calculate the pair distribution function G(r) of a crystal with DISCUS.

Parameters:
  • crystal (Crystal) – The structure, from read_structure().

  • rmax (float) – Largest distance and step in Å.

  • dr (float) – Largest distance and step in Å.

  • radiation ({"xray", "neutron", "electron"}) – Weights the atom pairs by scattering power.

  • qmax (float) – Qmax in Å⁻¹ of the termination ripples to include; 0 means none.

  • qdamp (float) – Instrumental damping and resolution broadening (as in PDFgui).

  • qbroad (float) – Instrumental damping and resolution broadening (as in PDFgui).

  • thermal (bool) – Broaden each pair by a Gaussian from the displacement parameters. False gives sharp, histogram-like peaks.

  • corrlin (float) – Linear and quadratic correlated-motion corrections (peak sharpening at small r); only with thermal=True.

  • corrquad (float) – Linear and quadratic correlated-motion corrections (peak sharpening at small r); only with thermal=True.

  • particle_diameter (float, optional) – Treat the crystal as a finite spherical particle of this diameter in Å (no periodic boundaries; the -4πρ₀r baseline is corrected for a sphere). Default: an infinite crystal with periodic boundaries.

Returns:

PDFPattern

Raises:
  • ValueError – For an unknown radiation or invalid ranges.

  • MacroError – If the calculation fails inside DISCUS.

Return type:

PDFPattern

Examples

>>> g = dc.pdf(cr, rmax=20, dr=0.01, qmax=25)
>>> g.plot()
class diffuse.PDFPattern(r, G, settings=<factory>, crystal=None)[source]#

A calculated pair distribution function. See pdf().

Parameters:
r#

Distance r in Å.

Type:

numpy.ndarray

G#

G(r) = 4πr(ρ(r) − ρ₀) in Å⁻².

Type:

numpy.ndarray

settings#

The arguments it was calculated with.

Type:

dict

crystal#

The structure it was calculated for.

Type:

Crystal or None

plot(ax=None, **kwargs)[source]#

Plot G(r) with matplotlib.

Parameters:
Returns:

matplotlib.axes.Axes

Running DISCUS directly#

diffuse.run_macro(commands, cwd=None)[source]#

Run DISCUS macro text (escape hatch for commands not wrapped yet).

Parameters:

commands (str)

Return type:

str

diffuse.session(echo=None)[source]#

The process-wide Session (created on first use).

Parameters:

echo (bool | None)

Return type:

Session

class diffuse.Session(echo=None)[source]#

Wrapper around the in-process DISCUS suite. Use diffuse.session().

Parameters:

echo (bool | None)

property workdir: Path#

Scratch folder for files written by DISCUS.

run(commands, cwd=None)[source]#

Run macro text with cwd as working directory; return the output.

Raises MacroError if a command error stopped the macro.

Parameters:
Return type:

str

value(expression)[source]#

Value of a DISCUS expression, e.g. n[1] or lat[1].

Parameters:

expression (str)

Return type:

float

dataset(ik)[source]#

KUPLOT data set ik (1-based) as float32 arrays (x, y).

Parameters:

ik (int)

Return type:

tuple[ndarray, ndarray]

dataset_2d(ik)[source]#

KUPLOT grid data set ik as (x[nx], y[ny], z[nx, ny]).

Parameters:

ik (int)

Return type:

tuple[ndarray, ndarray, ndarray]

Errors#

exception diffuse.DiffuseError[source]#

Base class for errors raised by the diffuse package.

exception diffuse.MacroError(message, output='')[source]#

A command failed inside DISCUS.

The message holds DISCUS’s *** error lines; output holds all the text DISCUS wrote during the failed call.

Parameters: