Package API

diffpy.structure

The top-level diffpy.structure module provides the following objects.

Functions

loadStructure(filename, fmt='auto', **kw)

Load new structure object from the specified file.

Parameters:
  • filename (str) – Path to the file to be loaded.
  • fmt (str, optional) – Format of the structure file such as ‘cif’ or ‘xyz’. Must be one of the formats listed by the parsers.inputFormats function. When ‘auto’, all supported formats are tried in a sequence.
  • kw (misc, optional) – Extra keyword arguments that are passed to parsers.getParser function. These configure the dedicated Parser object that is used to read content in filename.
Returns:

stru (Structure, PDFFitStructure) – The new Structure object loaded from the specified file. Return a more specific PDFFitStructure type for ‘pdffit’ and ‘discus’ formats.

Classes

Atom
describes one atom site in the structure - its type, position, displacement parameters and so forth.
Lattice
depicts general coordinate system and associated operations.
Structure
collection of Atom objects that form the structure together with associated Lattice.

Exceptions

class StructureFormatError

Exception for failed IO from Structure file

class LatticeError

Exception for impossible lattice parameters.

class SymmetryError

Exception raised for invalid symmetry operations.

diffpy.structure.spacegroups

Space group classes and definitions from mmLib and sgtbx.

GetSpaceGroup(sgid)

Returns the SpaceGroup instance for the given identifier.

sgid – space group symbol, either short_name or pdb_name,
whatever it means in mmlib. Can be also an integer.

Return space group instance. Raise ValueError when not found.

IsSpaceGroupIdentifier(sgid)

Check if identifier can be used as an argument to GetSpaceGroup.

Return bool.

FindSpaceGroup(symops, shuffle=False)

Lookup SpaceGroup from a given list of symmetry operations.

Parameters:
  • symops (list) – The list of SymOp objects for which to find SpaceGroup.
  • shuffle (bool, optional) – Flag for allowing different order of symops in the returned SpaceGroup. The default is False.
Returns:

SpaceGroup – The SpaceGroup object with equivalent list of symmetry operations. Return predefined SpaceGroup instance when symmetry operations have the same order or when the shuffle flag is set.

Raises:

ValueError – When symops do not match any known SpaceGroup.

diffpy.structure.structureerrors

Exceptions used in Structure package.

exception StructureFormatError

Bases: Exception

Exception for failed IO from Structure file

exception LatticeError

Bases: Exception

Exception for impossible lattice parameters.

exception SymmetryError

Bases: Exception

Exception raised for invalid symmetry operations.

diffpy.structure.symmetryutilities

Symmetry utility functions such as expansion of asymmetric unit, and generation of positional constraints.

isSpaceGroupLatPar(spacegroup, a, b, c, alpha, beta, gamma)

Check if space group allows passed lattice parameters.

spacegroup – instance of SpaceGroup a, b, c, alpha, beta, gamma – lattice parameters

Return bool.

isconstantFormula(s)

Check if formula string is constant. True when argument is a floating point number or a fraction of float with integer.

s – formula string

Return bool.

positionDifference(xyz0, xyz1)

Smallest difference between two coordinates in periodic lattice.

xyz0, xyz1 – fractional coordinates

Return dxyz, a numpy.array dxyz with 0 <= dxyz <= 0.5.

nearestSiteIndex(sites, xyz)

Index of the nearest site to a specified position.

sites – list of coordinates or a 2-dimensional numpy.array xyz – single position

Return integer.

equalPositions(xyz0, xyz1, eps)

Equality of two coordinates with optional tolerance.

xyz0, xyz1 – fractional coordinates eps – tolerance for equality of coordinates

Return bool.

expandPosition(spacegroup, xyz, sgoffset=[0, 0, 0], eps=None)

Obtain unique equivalent positions and corresponding operations.

spacegroup – instance of SpaceGroup xyz – position to be expanded sgoffset – offset of space group origin [0, 0, 0] eps – cutoff for equal positions

Return a tuple with (list of unique equivalent positions, nested list of SpaceGroups.SymOp instances, site multiplicity).

nullSpace(A)

Null space of matrix A.

class GeneratorSite(spacegroup, xyz, Uij=array([[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]]), sgoffset=[0, 0, 0], eps=None)

Bases: object

Storage of data related to a generator positions.

Data members:

xyz – fractional coordinates of generator site Uij – anisotropic thermal displacement at generator site sgoffset – offset of space group origin [0, 0, 0] eps – cutoff for equal positions eqxyz – list of equivalent positions eqUij – list of displacement matrices at equivalent positions symops – nested list of operations per each eqxyz multiplicity – generator site multiplicity Uisotropy – bool flag for isotropic thermal factors invariants – list of invariant operations for generator site null_space – null space of all possible differences of invariant

rotational matrices, this is a base of symmetry allowed shifts.

Uspace – 3D array of independent components of U matrices. pparameters – list of (xyz symbol, value) pairs Uparameters – list of (U symbol, value) pairs

Ucomponents = array([[[1., 0., 0.], [0., 0., 0.], [0., 0., 0.]], [[0., 0., 0.], [0., 1., 0.], [0., 0., 0.]], [[0., 0., 0.], [0., 0., 0.], [0., 0., 1.]], [[0., 1., 0.], [1., 0., 0.], [0., 0., 0.]], [[0., 0., 1.], [0., 0., 0.], [1., 0., 0.]], [[0., 0., 0.], [0., 0., 1.], [0., 1., 0.]]])
idx2Usymbol = {0: 'U11', 1: 'U12', 2: 'U13', 3: 'U12', 4: 'U22', 5: 'U23', 6: 'U13', 7: 'U23', 8: 'U33'}
signedRatStr(x)

Convert floating point number to signed rational representation. Possible fractional are multiples of 1/3, 1/6, 1/7, 1/9, if these are not close, return “%+g” format.

Return string.

positionFormula(pos, xyzsymbols=('x', 'y', 'z'))

Formula of equivalent position with respect to generator site

pos – fractional coordinates of possibly equivalent site xyzsymbols – symbols for parametrized coordinates

Return position formulas in a dictionary with keys equal (“x”, “y”, “z”) or an empty dictionary when pos is not equivalent to generator. Formulas are formatted as “[[-][%g*]{x|y|z}] [{+|-}%g]”, for example “-x”, “z +0.5”, “0.25”.

UFormula(pos, Usymbols=['U11', 'U22', 'U33', 'U12', 'U13', 'U23'])

List of atom displacement formulas with custom parameter symbols.

pos – fractional coordinates of possibly equivalent site Usymbols – 6 symbols for possible U matrix parameters

Return U element formulas in a dictionary where keys are from (‘U11’,’U22’,’U33’,’U12’,’U13’,’U23’) or empty dictionary when pos is not equivalent to generator.

eqIndex(pos)

Index of the nearest generator equivalent site

pos – fractional coordinates

Return integer.

class ExpandAsymmetricUnit(spacegroup, corepos, coreUijs=None, sgoffset=[0, 0, 0], eps=None)

Bases: object

Expand asymmetric unit and anisotropic thermal displacement

Data members:

spacegroup – instance of SpaceGroup corepos – list of positions in asymmetric unit,

it may contain duplicates

coreUijs – thermal factors for corepos (defaults to zeros) sgoffset – optional offset of space group origin [0, 0, 0] eps – cutoff for equivalent positions

Calculated data members:
multiplicity – multiplicity of each site in corepos Uisotropy – bool flags for isotropic sites in corepos expandedpos – list of equivalent positions per each site in corepos expandedUijs – list of thermal factors per each site in corepos
pruneFormulaDictionary(eqdict)

Remove constant items from formula dictionary.

eqdict – formula dictionary which maps standard variable symbols
(“x”, “U11”) to string formulas (“0”, “-x3”, “z7 +0.5”)

Return pruned formula dictionary.

class SymmetryConstraints(spacegroup, positions, Uijs=None, sgoffset=[0, 0, 0], eps=None)

Bases: object

Generate symmetry constraints for specified positions

Data members:
spacegroup – instance of SpaceGroup positions – all positions to be constrained Uijs – thermal factors for all positions (defaults to zeros) sgoffset – optional offset of space group origin [0, 0, 0] eps – cutoff for equivalent positions
Calculated data members:

corepos – list of of positions in the asymmetric unit coremap – dictionary mapping indices of asymmetric core positions

to indices of all symmetry related positions
poseqns – list of coordinate formula dictionaries per each site.
Formula dictionary keys are from (“x”, “y”, “z”) and the values are formatted as [[-]{x|y|z}%i] [{+|-}%g], for example: “x0”, “-x3”, “z7 +0.5”, “0.25”.

pospars – list of (xyz symbol, value) pairs Ueqns – list of anisotropic atomic displacement formula

dictionaries per each position. Formula dictionary keys are from (‘U11’,’U22’,’U33’,’U12’,’U13’,’U23’) and the values are formatted as {[%g*][Uij%i]|0}, for example: “U110”, “0.5*U2213”, “0”

Upars – list of (U symbol, value) pairs Uisotropy – list of bool flags for isotropic thermal displacements

posparSymbols()

Return list of standard position parameter symbols.

posparValues()

Return list of position parameters values.

positionFormulas(xyzsymbols=None)

List of position formulas with custom parameter symbols.

xyzsymbols – list of custom symbols used in formula strings

Return list of coordinate formulas dictionaries. Formulas dictionary keys are from (“x”, “y”, “z”) and the values are formatted as [[-]{symbol}] [{+|-}%g], for example: “x0”, “-sym”, “@7 +0.5”, “0.25”.

positionFormulasPruned(xyzsymbols=None)

List of position formula dictionaries with constant items removed. See also positionFormulas().

xyzsymbols – list of custom symbols used in formula strings

Return list of coordinate formula dictionaries.

UparSymbols()

Return list of standard atom displacement parameter symbols.

UparValues()

Return list of atom displacement parameters values.

UFormulas(Usymbols=None)

List of atom displacement formulas with custom parameter symbols.

Usymbols – list of custom symbols used in formula strings

Return list of atom displacement formula dictionaries per each site. Formula dictionary keys are from (‘U11’,’U22’,’U33’,’U12’,’U13’,’U23’) and the values are formatted as {[%g*][Usymbol]|0}, for example: “U11”, “0.5*@37”, “0”.

UFormulasPruned(Usymbols=None)

List of atom displacement formula dictionaries with constant items removed. See also UFormulas().

Usymbols – list of custom symbols used in formula strings

Return list of atom displacement formulas in tuples of (U11, U22, U33, U12, U13, U23).

diffpy.structure.mmlibspacegroups

Space groups defined as a part of the pymmlib.

diffpy.structure.pdffitstructure

definition of PDFFitStructure class derived from Structure

class PDFFitStructure(*args, **kwargs)

Bases: diffpy.structure.structure.Structure

PDFFitStructure –> Structure with extra pdffit member

Data members:
pdffit – dictionary for storing following extra parameters from
PDFFit structure files:
‘scale’, ‘delta1’, ‘delta2’, ‘sratio’, ‘rcut’, ‘spcgr’, ‘dcell’, ‘ncell’
read(filename, format='auto')

Same as Structure.read, but update spcgr value in self.pdffit when parser can get spacegroup.

Return instance of StructureParser used to load the data. See Structure.read() for more info.

readStr(s, format='auto')

Same as Structure.readStr, but update spcgr value in self.pdffit when parser can get spacegroup.

Return instance of StructureParser used to load the data. See Structure.readStr() for more info.

diffpy.structure.sgtbxspacegroups

Extra space group representations generated using sgtbx module from cctbx. Import of this module extends the SpaceGroupList in the SpaceGroups module. Notable variables:

sgtbxSpaceGroupList – list of space group instances defined in this module

diffpy.structure.structure

This module defines class Structure.

class Structure(atoms=None, lattice=None, title=None, filename=None, format=None)

Bases: list

Structure –> group of atoms

Structure class is inherited from Python list. It contains a list of Atom instances. Structure overloads setitem and setslice methods so that the lattice attribute of atoms get set to lattice.

Data members:
title – structure description lattice – coordinate system (instance of Lattice) pdffit – None or a dictionary of PDFFit-related metadata
pdffit = None
title = ''
copy()

Return a copy of this Structure object.

addNewAtom(*args, **kwargs)

Add new Atom instance to the end of this Structure.

All arguments are forwarded to Atom constructor.

No return value.

getLastAtom()

Return Reference to the last Atom in this structure.

assignUniqueLabels()

Set a unique label string for each atom in this structure. The label strings are formatted as “%(baresymbol)s%(index)i”, where baresymbol is the element right-stripped of “[0-9][+-]”.

No return value.

distance(aid0, aid1)

Distance between 2 atoms, no periodic boundary conditions.

aid0 – zero based index of the first atom or a string label
such as “Na1”

aid1 – zero based index or string label of the second atom.

Return float. Raise IndexError for invalid arguments.

angle(aid0, aid1, aid2)

The bond angle at the second of three atoms in degrees.

aid0 – zero based index of the first atom or a string label
such as “Na1”
aid1 – index or string label for the second atom,
where the angle is formed

aid2 – index or string label for the third atom

Return float. Raise IndexError for invalid arguments.

placeInLattice(new_lattice)

place structure into new_lattice coordinate system

sets lattice to new_lattice and recalculate fractional coordinates of all atoms so their absolute positions remain the same

return self

read(filename, format='auto')

Load structure from a file, any original data become lost.

filename – file to be loaded format – all structure formats are defined in parsers submodule,

when format == ‘auto’ all parsers are tried one by one

Return instance of data Parser used to process file. This can be inspected for information related to particular format.

readStr(s, format='auto')

Load structure from a string, any original data become lost.

s – string with structure definition format – all structure formats are defined in parsers submodule,

when format == ‘auto’ all parsers are tried one by one

Return instance of data Parser used to process input string. This can be inspected for information related to particular format.

write(filename, format)

Save structure to file in the specified format

No return value.

Note: available structure formats can be obtained by:
from parsers import formats
writeStr(format)

return string representation of the structure in specified format

Note: available structure formats can be obtained by:
from parsers import formats
tolist()

Return atoms in this Structure as a standard Python list.

append(a, copy=True)

Append atom to a structure and update its lattice attribute.

a – instance of Atom copy – flag for appending a copy of a.

When False, append a and update a.lattice.

No return value.

insert(idx, a, copy=True)

Insert atom a before position idx in this Structure.

idx – position in atom list a – instance of Atom copy – flag for inserting a copy of a.

When False, append a and update a.lattice.

No return value.

extend(atoms, copy=None)

Extend Structure with an iterable of atoms.

Update the lattice attribute of all added atoms.

Parameters:
  • atoms (iterable) – The Atom objects to be appended to this Structure.
  • copy (bool, optional) – Flag for adding copies of Atom objects. Make copies when True, append Atoms unchanged when False. The default behavior is to make copies when Atoms are of Structure type or if new atoms introduce repeated objects.
lattice

Coordinate system for this Structure.

composition

Dictionary of chemical symbols and their total occupancies.

element

Character array of atom types. Assignment updates the element attribute of the respective atoms.

xyz

Array of fractional coordinates of all atoms. Assignment updates xyz attribute of all atoms.

x

Array of all fractional coordinates x. Assignment updates xyz attribute of all atoms.

y

Array of all fractional coordinates y. Assignment updates xyz attribute of all atoms.

z

Array of all fractional coordinates z. Assignment updates xyz attribute of all atoms.

label

Character array of atom names. Assignment updates the label attribute of all atoms.

occupancy

Array of atom occupancies. Assignment updates the occupancy attribute of all atoms.

xyz_cartn

Array of absolute Cartesian coordinates of all atoms. Assignment updates the xyz attribute of all atoms.

anisotropy

Boolean array for anisotropic thermal displacement flags. Assignment updates the anisotropy attribute of all atoms.

U

Array of anisotropic thermal displacement tensors. Assignment updates the U and anisotropy attributes of all atoms.

Uisoequiv

Array of isotropic thermal displacement or equivalent values. Assignment updates the U attribute of all atoms.

U11

Array of U11 elements of the anisotropic displacement tensors. Assignment updates the U and anisotropy attributes of all atoms.

U22

Array of U22 elements of the anisotropic displacement tensors. Assignment updates the U and anisotropy attributes of all atoms.

U33

Array of U33 elements of the anisotropic displacement tensors. Assignment updates the U and anisotropy attributes of all atoms.

U12

Array of U12 elements of the anisotropic displacement tensors. Assignment updates the U and anisotropy attributes of all atoms.

U13

Array of U13 elements of the anisotropic displacement tensors. Assignment updates the U and anisotropy attributes of all atoms.

U23

Array of U23 elements of the anisotropic displacement tensors. Assignment updates the U and anisotropy attributes of all atoms.

Bisoequiv

Array of Debye-Waller isotropic thermal displacement or equivalent values. Assignment updates the U attribute of all atoms.

B11

Array of B11 elements of the Debye-Waller displacement tensors. Assignment updates the U and anisotropy attributes of all atoms.

B22

Array of B22 elements of the Debye-Waller displacement tensors. Assignment updates the U and anisotropy attributes of all atoms.

B33

Array of B33 elements of the Debye-Waller displacement tensors. Assignment updates the U and anisotropy attributes of all atoms.

B12

Array of B12 elements of the Debye-Waller displacement tensors. Assignment updates the U and anisotropy attributes of all atoms.

B13

Array of B13 elements of the Debye-Waller displacement tensors. Assignment updates the U and anisotropy attributes of all atoms.

B23

Array of B23 elements of the Debye-Waller displacement tensors. Assignment updates the U and anisotropy attributes of all atoms.

diffpy.structure.utils

Small shared functions.

isiterable(obj)

True if argument is iterable.

isfloat(s)

True if argument can be converted to float

atomBareSymbol(smbl)

Remove atom type string stripped of isotope and ion charge symbols. This removes blank and leading [0-9-] or trailing [1-9][+-] characters.

smbl – atom type string such as “Cl-”, “Ca2+” or “12-C”.

Return bare element symbol.

diffpy.structure.version

Definition of __version__, __date__, __timestamp__, __git_commit__.

Notes

Variable __gitsha__ is deprecated as of version 3.0. Use __git_commit__ instead.