Crystals#

class pyemaps.crystals.DW(value)#

Bases: Enum

Debye-Waller (thermal) factor types that pyEMAPS supports.

  • iso: isotropic Debye-Waller factor B

  • bij: anisotropic temperature factors

  • uij: anisotropic displacement factors

iso = 1#
bij = 2#
uij = 3#
class pyemaps.crystals.Cell(data=None)#

Bases: object

Unit cell constants: the lengths a, b and c (Å) and the angles alpha, beta and gamma (degrees). Each value must be a number or a string that converts to one.

From a dictionary:

from pyemaps import Cell

data_dict = {
    "a": "5.4307",
    "b": "5.4307",
    "c": "5.4307",
    "alpha": "90.0",
    "beta": "90.0",
    "gamma": "90.0"
}
si_cell = Cell(data=data_dict)

From a list, in the order a, b, c, alpha, beta, gamma:

from pyemaps import Cell

si_cell = Cell(data=[5.4307, 5.4307, 5.4307, 90.0, 90.0, 90.0])
# strings work too: ["5.4307", "5.4307", "5.4307", "90.0", "90.0", "90.0"]

Or by setting the attributes one at a time:

from pyemaps import Cell

si_cell = Cell()        # every value starts at 0.0
si_cell.a = 5.4307
si_cell.b = 5.4307
si_cell.c = 5.4307
si_cell.alpha = 90.0
si_cell.beta = 90.0
si_cell.gamma = 90.0
__init__(data=None)#
Parameters:

data (dict or list, optional) – the six cell constants, either as a dictionary with the keys a, b, c, alpha, beta and gamma, or as a list in that order. If omitted, all six values are 0.0.

Raises:
  • CellDataError – if data doesn’t have exactly six values, has an unknown key, or is neither a dictionary nor a list.

  • CellValueError – if a value isn’t a number or a numeric string.

property a#

Cell length a, in Å.

property b#

Cell length b, in Å.

property c#

Cell length c, in Å.

property alpha#

Cell angle alpha, in degrees.

property beta#

Cell angle beta, in degrees.

property gamma#

Cell angle gamma, in degrees.

property session_controls#

Microscope controls attached to the cell, an EMControl. Set it by calling the cell with the controls, cell(emc), and clear it with cell(). It’s None until set. pyEMAPS doesn’t use it.

prepare()#

Return the cell constants as a Fortran-ordered array of six floats, in the order a, b, c, alpha, beta, gamma, for the simulation backend. Used internally.

Raises:

CellDataError – if a cell constant is missing.

class pyemaps.crystals.Atom(a_type=iso.value, sym='', data=None)#

Bases: object

One atom in a crystal: its element symbol, fractional position (x, y, z), thermal factor(s) and occupancy.

From a dictionary, for an isotropic atom:

from pyemaps import Atom

data_dict = {
    "x": "0.125",
    "y": "0.125",
    "z": "0.125",
    "d-w": "0.4668",
    "occ": "1.00"
}
si_atom = Atom(sym='Si', data=data_dict)

From a list:

from pyemaps import Atom

si_atom = Atom(sym='Si', data=[0.125, 0.125, 0.125, 0.4668, 1.00])

Warning

A list must give the values in this order:

['x', 'y', 'z', 'd-w', 'occ']                                    # isotropic (iso)
['x', 'y', 'z', 'b11', 'b22', 'b33', 'b12', 'b13', 'b23', 'occ']  # anisotropic (bij, uij)

Note

The occupancy occ can be left out of a list or dictionary; it then defaults to 1.0.

Or by setting the attributes one at a time:

from pyemaps import Atom

si_atom = Atom()
si_atom.symb = 'Si'
si_atom.loc = [0.125, 0.125, 0.125, 0.4668, 1.00]
__init__(a_type=iso.value, sym='', data=None)#
Parameters:
  • a_type (int, optional) – thermal factor type: 1 (iso), 2 (bij) or 3 (uij).

  • sym (str, optional) – element symbol, up to 10 characters.

  • data (dict or list, optional) – position, thermal factor(s) and optional occupancy. A dictionary needs the keys x, y, z and d-w for an isotropic atom, or x, y, z, b11, b22, b33, b12, b13 and b23 for an anisotropic one, plus an optional occ. A list gives the same values in that order.

Raises:

UCError – if data isn’t a dictionary or list, has the wrong number of values or is missing a key, or if a_type or sym is invalid.

property atype#

Thermal factor type: 1 (iso), 2 (bij) or 3 (uij).

property symb#

Element symbol.

property loc#

Position, thermal factor(s) and occupancy, as a list: [x, y, z, d-w, occ] for an isotropic atom, or [x, y, z, b11, b22, b33, b12, b13, b23, occ] for an anisotropic one.

isISO()#

Return True if the atom has an isotropic thermal factor.

prepare()#

Return the position, thermal factor(s) and occupancy as a list of floats, for the simulation backend. Used internally.

class pyemaps.crystals.SPG(data=None)#

Bases: object

Space group: its number in the International Tables for Crystallography and its setting.

From a dictionary:

from pyemaps import SPG

spg_dict = {
    "number": "227",    # International Tables number
    "setting": "2"      # space group setting
}
si_spg = SPG(data=spg_dict)

From a list [number, setting]:

from pyemaps import SPG

si_spg = SPG(data=[227, 2])     # or ["227", "2"]

Or by setting the attributes:

from pyemaps import SPG

si_spg = SPG()
si_spg.number = 227
si_spg.setting = 2
__init__(data=None)#
Parameters:

data (dict or list, optional) – the space group number and setting, as a dictionary with the keys number and setting, or as a list [number, setting]. If omitted, both are 0.

Raises:

SPGInvalidDataInputError – if data isn’t a two-item list or a dictionary with exactly those two keys, or if a value isn’t an integer.

property number#

International Tables number of the space group.

property setting#

Space group setting.

prepare()#

Check that the number and setting form a valid space group, and return them as a Fortran-ordered integer array for the simulation backend. Used internally.

Raises:

SPGInvalidDataInputError – if the space group number and setting aren’t valid.

class pyemaps.crystals.Crystal(name='Diamond', data=None)#

Bases: object

A crystal: its name, unit cell, atoms, space group and thermal factor type. All pyEMAPS simulations and calculations are methods of this class.

  • name: crystal name

  • cell: unit cell constants, a Cell

  • atoms: the atoms, a list of Atom

  • spg: space group, an SPG

  • dw: Debye-Waller (thermal) factor type, see DW

Ways to create a crystal:

  1. Crystal(name, data), from a dictionary.

  2. from_builtin(), from the pyEMAPS built-in crystal database.

  3. from_xtl(), from a pyEMAPS XTL crystal file.

  4. from_cif(), from a Crystallographic Information File (CIF).

  5. from_json(), from a JSON file.

  6. from_dict(), from a dictionary that includes the name.

  7. From its parts: Cell, Atom and SPG objects.

From a dictionary:

from pyemaps import Crystal

c_dict = {
    'cell': {                       # cell constants
        'a': '5.4307', 'b': '5.4307', 'c': '5.4307',
        'alpha': '90.0', 'beta': '90.0', 'gamma': '90.0'
    },
    'atoms': [                      # one dictionary per atom
        {'symb': 'si',              # element symbol
         'x': '0.125',              # fractional coordinates
         'y': '0.125',
         'z': '0.125',
         'd-w': '0.4668',           # Debye-Waller factor
         'occ': 1.00}               # occupancy
    ],
    'spg': {                        # space group
        'number': '227',            # International Tables number
        'setting': '2'              # setting
    },
    'dw': 'iso'                     # Debye-Waller factor type
}

si = Crystal(name='Silicon', data=c_dict)

From the built-in crystal database:

from pyemaps import Crystal

si = Crystal.from_builtin('Silicon')

Note

For the names of all built-in crystals, call list_all_builtin_crystals().

From its parts:

from pyemaps import Cell, Atom, SPG, Crystal

si = Crystal(name='Silicon')
si.cell = Cell(data=[5.4307, 5.4307, 5.4307, 90.0, 90.0, 90.0])
si.atoms = [Atom(sym='Si', data=[0.125, 0.125, 0.125, 0.4668, 1.00])]
si.spg = SPG(data=[227, 2])
si.dw = 'iso'

Note

All atoms in a crystal must have the same thermal factor type as the crystal.

__init__(name='Diamond', data=None)#
Parameters:
  • name (str, optional) – crystal name.

  • data (dict, optional) – the crystal data, as a dictionary with the keys cell, atoms, spg and dw (see the example below). If omitted, the crystal starts empty: a zero cell, no atoms, space group 0 and isotropic thermal factors.

Raises:

CrystalClassError – if data isn’t a dictionary, a required key is missing, or an atom has no symb. Validation errors from the cell, atoms and space group, such as CellDataError and UCError, are raised as they are.

The dictionary for Silicon:

{
    'cell': {'a': '5.4307', 'b': '5.4307', 'c': '5.4307',
             'alpha': '90.0', 'beta': '90.0', 'gamma': '90.0'},
    'atoms': [{'symb': 'si', 'x': '0.125', 'y': '0.125', 'z': '0.125',
               'd-w': '0.4668', 'occ': 1.00}],
    'spg': {'number': '227', 'setting': '2'},
    'dw': 'iso'
}
angle(v1=(1.0, 0.0, 0.0), v2=(0.0, 0.0, 1.0), ty=0)#

Calculate the angle between two vectors, both in real space or both in reciprocal space.

Parameters:
  • v1 (tuple of float, optional) – the first vector.

  • v2 (tuple of float, optional) – the second vector.

  • ty (int, optional) – 0 for real-space vectors, 1 for reciprocal-space vectors.

Returns:

the angle, in degrees.

Return type:

float

Raises:

ValueError – if either vector is zero.

beginBloch(aperture=DEF_APERTURE, omega=DEF_OMEGA, sampling=DEF_SAMPLING, dbsize=DEF_CBED_DSIZE, em_controls=None)#

Start a dynamic diffraction (Bloch wave) simulation session.

The results stay in the backend until endBloch(). Between the two calls you can retrieve them with:

  1. getBlochImages(): the diffraction images, for one or more sample thicknesses;

  2. getSCMatrix(): the scattering matrix, eigenvalues and diffracted beams at one sampling point;

  3. getIBDetails(): the sampling points and their beam tilts;

  4. getCalculatedBeams(): the diffracted beams used in the calculation.

To get images in one call, use generateBloch() instead.

Parameters:
  • aperture (float, optional) – objective aperture. Defaults to DEF_APERTURE (1.0).

  • omega (int, optional) – diagonalization cutoff. Defaults to DEF_OMEGA (10).

  • sampling (int, optional) – number of sampling points along the disk radius. Defaults to DEF_SAMPLING (8).

  • dbsize (float, optional) – diffracted beam (disk) size, within DEF_DSIZE_LIMITS (0.01 to 1.0). Defaults to DEF_CBED_DSIZE (0.16).

  • em_controls (EMControl, optional) – microscope and simulation controls. Defaults to a camera length of 200 mm, gmax 1.0 and excitation error limits (0.3, 1.0). The object is updated with the settings used and kept as the crystal’s session controls.

Returns:

(n, points): the number of sampling points, and the points as a list of (i, j) tuples.

Return type:

tuple

Raises:

BlochError – if an input is invalid, the backend’s resource limit is reached, or the simulation fails.

cleanCSF()#

Free the memory used by the structure factor calculation, and unload the crystal from the simulation backend. generateCSF() calls this itself.

d2r(v=(0.0, 0.0, 0.0))#

Transform a vector from real space to reciprocal space, using the crystal’s metric tensor.

Parameters:

v (tuple of float, optional) – the vector’s three components.

Returns:

the transformed vector.

Return type:

tuple of float

endBloch()#

End the dynamic diffraction session started by beginBloch(), and free the backend’s memory for it.

generateBloch(aperture=DEF_APERTURE, omega=DEF_OMEGA, sampling=DEF_SAMPLING, pix_size=DEF_PIXSIZE, det_size=DEF_DETSIZE, disk_size=DEF_CBED_DSIZE, sample_thickness=DEF_THICKNESS, em_controls=None, nType=TY_NORMAL, bSave=False)#

Simulate dynamic diffraction (Bloch wave) images in one call. It’s the same as calling beginBloch(), getBlochImages() and endBloch().

Parameters:
  • aperture (float, optional) – objective aperture. Defaults to DEF_APERTURE (1.0).

  • omega (int, optional) – diagonalization cutoff. Defaults to DEF_OMEGA (10).

  • sampling (int, optional) – number of sampling points along the disk radius. Defaults to DEF_SAMPLING (8).

  • pix_size (int, optional) – detector pixel size, in µm. Defaults to DEF_PIXSIZE (25).

  • det_size (int, optional) – detector size in pixels; each image is det_size × det_size. Defaults to DEF_DETSIZE (512).

  • disk_size (float, optional) – diffracted beam (disk) size, within DEF_DSIZE_LIMITS (0.01 to 1.0). Defaults to DEF_CBED_DSIZE (0.16).

  • sample_thickness (tuple of int, optional) – (start, end, step), in Å: one image at start, start + step, … below end, and at end. Defaults to DEF_THICKNESS, (200, 200, 100).

  • em_controls (EMControl, optional) – microscope and simulation controls. Defaults to a camera length of 200 mm, gmax 1.0 and excitation error limits (0.3, 1.0).

  • nType (int, optional) – TY_NORMAL (0) for normal images, or TY_LACBED (1) for large-angle CBED images, one per thickness and calculated beam.

  • bSave (bool, optional) – if True, also save the images to a raw .im3 file in the bloch folder of the pyEMAPS data folder.

Returns:

the images, each with the controls and thickness it was made with.

Return type:

BlochImgs

Raises:
  • BlochError – if an input is invalid or the simulation fails.

  • BlochListError – if sample_thickness, pix_size or det_size is invalid.

Warning

Dynamic diffraction needs a lot of memory, and large-angle CBED (nType = TY_LACBED) needs much more than normal images. To reduce it, lower:

  • the detector size det_size: 256 instead of the default 512, for example, uses a quarter of the image memory;

  • the number of sampling points sampling.

generateCSF(kv=100, smax=0.5, sftype=1, aptype=0)#

Calculate the crystal’s structure factors.

Parameters:
  • kv (int or float, optional) – accelerating voltage, in kV. Used for the electron structure factors.

  • smax (int or float, optional) – largest sin(θ)/λ to include, in 1/Å.

  • sftype (int, optional) –

    the structure factor type:

    1. X-ray (the default)

    2. electron, in volts

    3. electron, in 1/Ų

    4. electron absorption, in 1/Ų

  • aptype (int, optional) – the output format: 0 for real and imaginary parts (the default), or 1 for amplitude and phase (in degrees).

Returns:

a list of dictionaries. The first holds the inputs: kv, smax, sftype and aptype. Each one after it is one reflection:

{
    'hkl': (h, k, l),     # Miller indices
    'sw': s,              # sin(theta)/lambda, 1/Å
    'ds': d,              # d-spacing, Å
    'amp_re': ar,         # amplitude, or real part
    'phase_im': ph        # phase in degrees, or imaginary part
}

Return type:

list of dict

Raises:

CSFError – if the calculation fails, sftype is invalid, or there are more reflections within smax than the backend can handle; in that case, lower smax.

To print the result as a table, pass it to printCSF().

generateDP(mode=None, dsize=None, em_controls=None)#

Simulate a kinematic diffraction pattern.

Parameters:
  • mode (int, optional) – 1 for normal diffraction or 2 for convergent beam (CBED). Defaults to 1.

  • dsize (float, optional) – diffracted beam (disk) size, used only in CBED mode. Defaults to DEF_CBED_DSIZE (0.16).

  • em_controls (EMControl, optional) – microscope and simulation controls. Defaults to EMC().

Returns:

(emc, dp): the controls used and the diffraction pattern, a diffPattern. emc is the same object as em_controls, updated with the mode, the disk size (CBED) and the x-axis the backend calculated if none was set.

Return type:

tuple

Raises:
  • EMCError – if mode isn’t 1 or 2, dsize isn’t numeric, or a control is missing.

  • DPError – if the simulation fails.

generateDPDB(emc=None, xa=DEF_XAXIS, res=LOW_RES, vertices=DEF_VERTMAT)#

Generate a database of kinematic diffraction patterns for this crystal, over a range of orientations, and save it to a .bin file. 4D-STEM pattern indexing (indexImage()) uses it. This is a licensed feature.

The file is saved in the dpdb folder of the pyEMAPS data folder; see Environment Variables.

Parameters:
  • emc (EMControl, optional) – microscope and simulation controls. Its accelerating voltage, zone axis and simulation controls are used.

  • xa (tuple of int, optional) – the crystal’s horizontal axis, as three integers. Defaults to (0, 0, 0), which lets the backend choose it.

  • res (int, optional) – resolution of the stereographic projection map: the number of sampling points along its radius, from 100 to 500. Higher resolutions put more patterns in the database. Defaults to 100.

  • vertices (list of list of int, optional) – three or four zone axes, each [h, k, l], that enclose the orientation range to cover (see the figure below). Defaults to [[0,0,1], [1,1,1], [0,1,1]], the standard triangle for a cubic crystal.

Returns:

(status, file_name): 0 and the database file’s path on success, or -1 and None (or the intended path) on failure. A message is printed either way.

Return type:

tuple

https://github.com/emlab-solutions/imagepypy/raw/main/stereoprojectionmap.png
generateDif(mode=None, dsize=None, em_controls=None)#

Simulate a kinematic diffraction pattern and return it in a list.

Deprecated since version Use: generateDP(), which returns the pattern and its controls directly.

Parameters:
  • mode (int, optional) – 1 for normal diffraction or 2 for convergent beam (CBED). Defaults to 1.

  • dsize (float, optional) – diffracted beam (disk) size, used only in CBED mode.

  • em_controls (EMControl, optional) – microscope and simulation controls.

Returns:

a list holding the one pattern, with its controls.

Return type:

DPList

Raises:

CrystalClassError – if the simulation fails.

generateMxtal(trMatrix=ID_MATRIX, trShift=DEF_TRSHIFT, cellbox=DEF_CELLBOX, xz=DEF_XZ, orShift=DEF_ORSHIFT, locASpace=DEF_LOCASPACE, bound=None)#

Build a block of the crystal’s atomic structure (a supercell) from its unit cell.

Parameters:
  • trMatrix (list or array, optional) – 3 × 3 matrix that transforms the unit cell into the new cell. Defaults to the identity matrix.

  • trShift (list or array, optional) – origin shift of the transformation, three numbers. Defaults to [0, 0, 0].

  • cellbox (list or array, optional) – the range of cells to fill, as [[x0, y0, z0], [x1, y1, z1]] in cell units. Defaults to [[0, 0, 0], [3, 3, 3]].

  • xz (list or array, optional) – two real-space directions, [x_direction, z_direction], to align with the output’s x and z axes. Defaults to [[1, 0, 0], [0, 0, 1]].

  • orShift (list or array, optional) – shift added to the atom positions in cell coordinates, before they’re oriented. Defaults to [0, 0, 0].

  • locASpace (list or array, optional) – shift added to the final atom positions, in Å. Defaults to [0, 0, 0].

  • bound (float, optional) – if given, also include atoms up to this distance, in Å, outside the cell range.

Returns:

the atomic structure.

Return type:

Xtal

Raises:

MxtalError – if the structure can’t be built or retrieved.

To print or save the result, use printXYZ() or writeXYZ().

generatePowder(kv=100, t2max=0.05, smax=1.0, eta=1.0, gamma=0.001, absp=0, bg=False, bamp=0.35, bgamma=0.001, bmfact=0.02)#

Calculate the crystal’s electron powder diffraction profile.

Parameters:
  • kv (int or float, optional) – accelerating voltage, in kV.

  • t2max (float, optional) – largest scattering angle 2θ, in radians.

  • smax (float, optional) – largest sin(θ)/λ, in 1/Å.

  • eta (float, optional) – mixing coefficient of the pseudo-Voigt peak shape, from 0 to 1: eta * Lorentzian + (1 - eta) * Gaussian. 1 is purely Lorentzian, 0 purely Gaussian.

  • gamma (float, optional) – peak full width at half maximum, in radians.

  • absp (int, optional) – 1 to include absorption structure factors, 0 (the default) not to.

  • bg (bool, optional) – add a background.

  • bamp (float, optional) – background amplitude.

  • bgamma (float, optional) – background width.

  • bmfact (float, optional) – background exponential damping factor.

Returns:

a 2 × 1000 array: the first row holds the scattering angles 2θ (radians), the second the intensities. If the calculation fails, a message is printed and the array is all zeros.

Return type:

numpy.ndarray

To plot the result, pass it to plotPowder().

generateStereo(xa=(0, 2, 0), tilt=(0.0, 0.0), zone=(0, 0, 1))#

Calculate the crystal’s stereographic projection (stereodiagram).

Parameters:
  • xa (tuple of int, optional) – the crystal’s horizontal axis in reciprocal space, as three integers.

  • tilt (tuple of float, optional) – sample tilt (x, y).

  • zone (tuple of int, optional) – zone axis, as three integers.

Returns:

the projected poles, one dictionary each:

{
    'c': (x, y),          # center
    'r': r,               # radius
    'idx': (h, k, l)      # Miller indices
}

Return type:

list of dict

Raises:

StereodiagramError – if the calculation fails.

To display the result, use showStereo().

getBlochImages(sample_thickness=DEF_THICKNESS, pix_size=DEF_PIXSIZE, det_size=DEF_DETSIZE, nType=TY_NORMAL, bSave=False)#

Get the dynamic diffraction images from the session started by beginBloch(): one image per sample thickness, or, for large-angle CBED, one per thickness and calculated beam.

Parameters:
  • sample_thickness (tuple of int, optional) – (start, end, step), in Å. Images are made at start, start + step, … below end, and at end. At most MAX_DEPTH (200) thicknesses. Defaults to DEF_THICKNESS, (200, 200, 100): one image at 200 Å.

  • pix_size (int, optional) – detector pixel size, in µm. Defaults to DEF_PIXSIZE (25).

  • det_size (int, optional) – detector size in pixels; each image is det_size × det_size. Defaults to DEF_DETSIZE (512).

  • nType (int, optional) – TY_NORMAL (0) for normal images, or TY_LACBED (1) for large-angle CBED images.

  • bSave (bool, optional) – if True, also save the images to a raw .im3 file in the bloch folder of the pyEMAPS data folder; see Environment Variables.

Returns:

the images, each with the controls and thickness it was made with.

Return type:

BlochImgs

Raises:
  • BlochListError – if sample_thickness, pix_size or det_size is invalid, or there are too many thicknesses.

  • BlochError – if the images can’t be made or the file can’t be written.

Warning

Dynamic diffraction needs a lot of memory, and large-angle CBED (nType = TY_LACBED) needs much more than normal images. To reduce it, lower:

  • the detector size det_size: 256 instead of the default 512, for example, uses a quarter of the image memory;

  • the number of sampling points sampling.

getCalculatedBeams(bPrint=False)#

Get the diffracted beams used in the session started by beginBloch().

Parameters:

bPrint (bool, optional) – also print them.

Returns:

(n, beams): the number of beams, and their Miller indices as an n × 3 array.

Return type:

tuple

Raises:

BlochError – if the beams can’t be retrieved.

getIBDetails(bPrint=True)#

Get the sampling points of the session started by beginBloch(), with the incident beam tilt at each one.

Parameters:

bPrint (bool, optional) – also print them.

Returns:

(n, details): the number of sampling points, and a list of dictionaries with the keys ib, the point as an (i, j) tuple, and tilt, the beam tilt in reciprocal space as three numbers.

Return type:

tuple

Raises:

BlochError – if the session has no sampling points or they can’t be retrieved.

getSCMatrix(ib_coords=(0, 0), sample_thickness=DEF_THICKNESS[0], rvec=(0.0, 0.0, 0.0))#

Get the scattering matrix at one sampling point of the session started by beginBloch(), with its eigenvalues and diffracted beams. For the session’s sampling points, call getIBDetails().

Parameters:
  • ib_coords (tuple, optional) – the sampling point, as an (i, j) tuple of integers.

  • sample_thickness (int, optional) – sample thickness, in Å. Defaults to 200.

  • rvec (tuple of float, optional) – the R vector, three numbers between 0.0 and 1.0, that shifts the atom positions in the crystal.

Returns:

(n, scm, ev, beams): the matrix dimension; the n × n complex scattering matrix; the n complex eigenvalues; and the diffracted beams’ Miller indices as an n × 3 array.

Return type:

tuple

Raises:

BlochError – if an input is invalid, or there’s no scattering matrix for that point.

Example eigenvalues:

[ 0.04684002-0.00218389j -0.2064669 -0.00147516j -0.30446348+0.00055009j
 -0.27657617+0.00023512j -0.2765751 +0.00023515j  0.00539041-0.00382443j
 ...]
load(cty=0)#

Load the crystal’s data into the simulation backend.

The data stays in the backend’s memory until unload() is called or another crystal is loaded. The backend holds one crystal at a time for the whole process: using one crystal after another is fine, since each loads itself again when it’s used next, but running simulations for different crystals concurrently in one process gives wrong results; use separate processes instead.

Parameters:

cty (int, optional) – 0 for simulations, 1 for the crystal constructor (generateMxtal()).

Raises:

CrystalClassError – if an atom symbol is longer than 10 characters, or the backend can’t load the crystal.

Note

The simulation methods call this themselves, and skip it when the crystal is already loaded, so you don’t need to call it directly.

plotPowder(pw)#

Plot a powder diffraction profile from generatePowder().

Parameters:

pw (numpy.ndarray, required) – the profile: a 2 × N array of scattering angles and intensities.

Raises:

ValueError – if pw doesn’t have two rows.

printCSF(sfs)#

Print structure factors from generateCSF() as a table.

Parameters:

sfs (list of dict, required) – the list returned by generateCSF().

Example output, X-ray structure factors of Silicon as amplitude and phase:

-----X-ray Structure Factors-----
     crystal            : Silicon
     h k l              : Miller Index
     s-w                : Sin(theta)/Wavelength <= 0.5
     d-s                : D-Spacing

 h   k   l        s-w             d-s          amplitude         phase

 1   1   1    0.1594684869    3.1354157925    58.89618        180.000000
 0   0   2    0.1841383278    2.7153499126    1.171896e-06    180.000000
 ...
static printXYZ(mx)#

Print a crystal structure from generateMxtal() in XYZ format. See XYZ format.

Parameters:

mx (Xtal, required) – the crystal structure.

Raises:

MxtalError – if mx isn’t an Xtal.

Example output for Silicon:

216
    50.0 50.0 50.0 90.0 90.0 90.0
SI           0.6788375000   0.6788375000   0.6788375000
SI           3.3941875000   3.3941875000   0.6788375000
SI           4.7518625000   2.0365125000   2.0365125000
...
r2d(v=(0.0, 0.0, 0.0))#

Transform a vector from reciprocal space to real space, using the crystal’s reciprocal metric tensor.

Parameters:

v (tuple of float, optional) – the vector’s three components.

Returns:

the transformed vector.

Return type:

tuple of float

set_sim_controls(simc=None)#

Send the simulation controls to the backend. Values left at their defaults aren’t sent, since the backend already has them.

Parameters:

simc (SIMControl, optional) – simulation controls. If omitted, the backend defaults are used.

Note

The simulation methods call this themselves; you don’t need to call it directly.

unload()#

Remove the crystal’s data from the simulation backend’s memory. It does nothing if another crystal has been loaded since, so the other crystal’s data stays.

vlen(v=(1.0, 0.0, 0.0), ty=0)#

Calculate the length of a real-space or reciprocal-space vector.

Parameters:
  • v (tuple of float, optional) – the vector’s three components.

  • ty (int, optional) – 0 for a real-space vector (length in Å), 1 for a reciprocal-space vector (length in 1/Å).

Returns:

the vector’s length.

Return type:

float

static wavelength(kv=100)#

Calculate the relativistic electron wavelength for an accelerating voltage.

Parameters:

kv (float or int, optional) – accelerating voltage, in kV.

Returns:

the wavelength, in Å.

Return type:

float

Raises:

ValueError – if kv isn’t positive.

writeXYZ(mx, fn=None)#

Save a crystal structure from generateMxtal() to an XYZ file, which tools such as Jmol can open.

Parameters:
  • mx (Xtal, required) – the crystal structure.

  • fn (str, optional) – file name, without the .xyz extension, which is added. If omitted, a name is composed from the crystal name. Without a directory, the file goes in the mxtal folder of the pyEMAPS data folder; see Environment Variables.

Returns:

0 on success, -1 if the file can’t be written.

Return type:

int

Raises:

MxtalError – if mx isn’t an Xtal.

property cell#

Unit cell constants, a Cell.

property dw#

Debye-Waller (thermal) factor type: 1 (iso), 2 (bij) or 3 (uij). It can be set with the number or the name; 'par' is accepted for iso.

property name#

Crystal name.

property atoms#

The atoms, a list of Atom.

property spg#

Space group, an SPG.

isISO()#

Return True if the crystal has isotropic thermal factors.

loaded()#

Return whether the crystal’s data is loaded into the simulation backend.

Returns:

True if loaded, otherwise False.

Return type:

bool

classmethod from_builtin(cn='Diamond')#

Create a crystal from the pyEMAPS built-in crystal database.

Parameters:

cn (str, optional) – name of a built-in crystal, such as 'Silicon'.

Returns:

the crystal.

Return type:

Crystal

Raises:

CrystalClassError – if there’s no built-in crystal with that name, or its data doesn’t validate.

Note

For the names of all built-in crystals, call list_all_builtin_crystals().

classmethod from_xtl(fn)#

Create a crystal from a pyEMAPS XTL crystal file.

Parameters:

fn (str, required) – XTL file name.

Returns:

the crystal.

Return type:

Crystal

Raises:

CrystalClassError – if the file isn’t found, or its data doesn’t validate.

XTL format example:

crystal Aluminium: dw = iso
cell 4.0493 4.0493 4.0493 90.0000 90.0000 90.0000
atom al 0.000000 0.000000 0.000000 0.7806 1.000000
spg 225 1

Fields:

  1. crystal: the crystal name, then the Debye-Waller factor type after dw =: iso (the default), bij or uij.

  2. cell: the six cell constants a, b, c (Å) and alpha, beta, gamma (degrees).

  3. atom: one line per atom: the element symbol, then its values.

  4. spg: the space group number and setting.

Atom values:

  • iso: at least 4 numbers, x, y, z and d-w, then optionally occ (default 1.0).

  • bij or uij: at least 9 numbers, x, y, z, b11, b22, b33, b12, b13 and b23, then optionally occ.

Where the file is looked for:

  1. fn as given: a full path, or a path relative to the current directory.

  2. The crystals folder in the pyEMAPS data folder.

See Environment Variables for how the data folder is set.

classmethod from_cif(fn)#

Create a crystal from a Crystallographic Information File (CIF).

Parameters:

fn (str, required) – CIF file name. It’s looked for as given (a full path or a path relative to the current directory), then in the crystals folder of the pyEMAPS data folder.

Returns:

the crystal.

Return type:

Crystal

Raises:

CrystalClassError – if the file isn’t found, or its cell, atoms or space group don’t validate.

classmethod from_json(jfn)#

Create a crystal from a JSON file.

Parameters:

jfn (str, required) – JSON file name. It’s looked for as given (a full path or a path relative to the current directory), then in the crystals folder of the pyEMAPS data folder.

Returns:

the crystal.

Return type:

Crystal

Raises:

CrystalClassError – if the file isn’t found or can’t be read, has no name, or its data doesn’t validate.

Example file:

{
    "cell": {
        "a": "5.4307", "b": "5.4307", "c": "5.4307",
        "alpha": "90.0", "beta": "90.0", "gamma": "90.0"
    },
    "atoms": [
        {"symb": "si", "x": "0.125", "y": "0.125", "z": "0.125",
         "d-w": "0.4668", "occ": "1.00"}
    ],
    "spg": {"number": "227", "setting": "2"},
    "dw": "iso",
    "name": "Silicon"
}
classmethod from_dict(cdict)#

Create a crystal from a dictionary that includes its name.

Parameters:

cdict (dict, required) – the crystal data: the keys name, cell, atoms, spg and dw.

Returns:

the crystal.

Return type:

Crystal

Raises:

CrystalClassError – if cdict has no name, or its data doesn’t validate.

Example:

{
    "cell": {"a": "5.4307", "b": "5.4307", "c": "5.4307",
             "alpha": "90.0", "beta": "90.0", "gamma": "90.0"},
    "atoms": [{"symb": "si", "x": "0.125", "y": "0.125", "z": "0.125",
               "d-w": "0.4668", "occ": "1.00"}],
    "spg": {"number": "227", "setting": "2"},
    "dw": "iso",
    "name": "Silicon"
}
static list_all_builtin_crystals()#

List the names of all crystals in the pyEMAPS built-in crystal database, for use with from_builtin().

Returns:

crystal names, such as 'Silicon'.

Return type:

list of str