pyemaps package

Submodules

pyemaps.crystals module

Crystals module contains python classes and methods for creating, importing and loading crystal data from various sources. It also provides the core interfaces to the backend diffraction simulations and calculations.

class pyemaps.crystals.DW(value)

Bases: Enum

Enumerated thermal property of crystal supported by pyemaps

  • iso: Isotropic Debye-Waller Factor B (short for Isotropic)

  • bij: Anisotropic Temperature Factor

  • uij: Anisotropic Displacement Factor

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

Bases: object

Cell constant data class create and validate crystal unit cell lengths (a, b, c) and angles (alpha, beta, gamma).

To create a Cell object using the following python dict object:

{
    "a": "5.4307",
    "b": "5.4307",
    "c": "5.4307",
    "alpha": "90.0",
    "beta": "90.0",
    "gamma": "90.0"
}
from pyemaps import Cell

si_cell = Cell(data = data_dict)

To create a Cell object using the following python list:

from pyemaps import Cell

data_list = ["5.4307", "5.4307", "5.4307", "90.0", "90.0", "90.0"]
# or
data_list = [5.4307, 5.4307, 5.4307, 90.0, 90.0, 90.0]

si_cell = Cell(data = data_list)

To create a Cell class object by setting individual attributes:

from pyemaps import Cell

# create a Cell object with all defaults values (0.0).
si_cell = Cell()

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

Validation of a Cell object data fails if input value for each arribute is:

  1. not numberal or numberal string.

  2. length of input data is less than 6.

__init__(data=None)

This Cell constructor allows Cell construction with python dict and list object, as well as customization.

Parameters:

data (dict or list, optional) – Cell constant python dictionary or list

Raises:

CellValueError – if cell data validations fail.

property a

a cell length

property b

b cell length

property c

c cell length

property alpha

alpha cell angle

property beta

beta cell angle

property gamma

gamma cell angle

property session_controls
prepare()

Prepare cell constant data for loading into backend simulation modules

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

Bases: object

Crystal atom descriptor class. Depending on the thermal types, its data include atom symbol, positional data (x, y, z) and thermal coefficients as well as its occupancy.

To create an isotropic Atom object with a python dict object:

{
    "symb": "Si",
    "x": "0.125",
    "y": "0.125",
    "z": "0.125",
    "d-w": "0.4668",
    "occ": "1.00" 
}
from pyemaps import Atom

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

To create an isotropic Atom object with a python list object:

from pyemaps import Atom
data_list = ["0.125", "0.125", "0.125", "0.4668", "1.00"]
# or
data_list = [0.125, 0.125, 0.125, 0.4668, 1.00]

si_atom = Atom(data = data_list)

Warning

When atom positional data is entered as a python list object the order of the elements must match their corresponding keys:

['x','y','z','d-w','occ']       # for isotropic atom type
['x','y','z','b11','b22','b33','b12','b13','b23','occ']   #for anisotropic atome types

Note

The list input for atom positional data can have ‘occ’ data missing. In which case pyemaps will default its occupancy data to 1.0

To create an Atom class object by setting individual attributes:

from pyemaps import Atom
# create an Atom object with all defaults to its data members.

si_at = Atom()

si_at.symb = 'Si'
si_at.loc = [0.125, 0.125, 0.125, 0.4668, 1.00]
__init__(a_type=iso.value, sym='', data=None)

Internal representation of single atom in a crystal object.

Parameters:
  • a_type (int, optional) – Atom thermal factor type.

  • data (dict or list, optional) – Atoms positional and other data input.

Raises:

UCError – if data validation fails.

property atype

Atom symbol

property symb

Atom symbol

property loc

atomic position, thermal factor or coefficients, occupacy information

isISO()

Check to see if this Atom thermal type is isotropic

prepare()

Format Atom data and prepare it for loading into backend simulation module.

class pyemaps.crystals.SPG(data=None)

Bases: object

Space Group class. This class includes:

  1. Symmetry International Tables Number, and

  2. Symmetry Space Group Setting

It is part of Crystal objects.

To create a space group object with a python dictionary object:

from pyemaps import SPG

spg_dict = {
    "number": "227", #<---Symmetry International Tables Number
    "setting": "2"   #<---Symmetry Space Group Setting  
}

si_spg = SPG(data = spg_dict)

To create a space group object with a python integer list:

from pyemaps import SPG

spg_list = ["227", "2"] 
# or
spg_list = [227, 2]

si_spg = SPG(data = spg_list)

To create a space group object with custom data:

from pyemaps import SPG
si_spg = SPG()
si_spg.number = 227
si_spg.setting = 2
__init__(data=None)

SPG object constructor.

Parameters:

data (dict or list, optional) – Space group data input.

Raises:

SPGInvalidDataInputError – if cell data validations fail.

property number

Symmetry International Tables Number

property setting

Symmetry Space Group Setting

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

Bases: object

This class is defined to capture and to validate crystal data. It is composed of the following data:

  • cell: Cell object

  • atoms: list of Atom objects

  • spg: Space Group SPG object

  • dw: Debye-waller factor type

  • name: Crystal name

Crystal class constructors include:

  1. Crystal(name, data): python dictionary object (default)

  2. From pyemaps built-in crystal database: from_builtin;

  3. From a pyemaps proprietory crystal data file: from_xtl;

  4. From Crystallographic Information File (CIF): from_cif;

  5. From .JSON File: from_json;

  6. From a python dict object: from_dict;

  7. Custom from individual components such as Cell, Atom objects

To create a Crystal object using a python dictionary object:

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':                                        #atomic info.
                [
                    {'symb': 'si',                          #atom symbol
                    'x': '0.125',                           #atom coordinates
                    'y': '0.125',  
                    'z': '0.125',
                    'd-w': '0.4668',                        #Debye-waller factor
                    'occ': 1.00},                           #occupancy
                ],
            'spg':                                          #space group info
                {'number': '227'                            #symmetry international table(IT) number
                'setting': '2'                              #symmetry space group setting
                },
            'dw': 
                'iso'                                       #Debye-waller factor
            'name', 
                'Silicon'                                   #crystal name
        }

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

To create a Crystal object using pyemaps builtin crystal database:

from pyemaps import Crystal
si = Crystal.from('Silicon') 

Note

For a list of builtin crystal names, call:

Crystal.list_all_builtin_crystals()

To create a Crystal object with custom Cell, SPG and Atom objects:

from pyemaps import Cell, Atom, SPG, Crystal
cell = Cell(data = [5.4307, 5.4307, 5.4307, 90.0, 90.0, 90.0])
atom = Atom(data = [0.125, 0.125, 0.125, 0.4668, 1.00])
spg = SPG(data = [227, 2])
si = Crystal()

si.cell = cell
si.atoms = [atom,]
si.spg = spg
si.dw = iso.value
si.name = 'Silicon' 

Note

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

__init__(name='Diamond', data=None)

Default constructor for crystal object

Parameters:
  • name (string, optional) – Name of the crystal or default to ‘Diamond’

  • data (dict, optional) – Other data of the crystal.

Raises:

CrystalClassError – If data validations fail.

The dictionary object example 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)

Calculates angle between two real space vectors or two reciprocal space vectors

Parameters:
  • v1 (tuple, optional) – A vector of float coordinates

  • v2 (tuple, optional) – A vector of float coordinates

  • ty (int, optional) – 0 real space, 1 reciprocal space

Returns:

an angle between v1 and v2.

Return type:

float

beginBloch(aperture=DEF_APERTURE, omega=DEF_OMEGA, sampling=DEF_SAMPLING, dbsize=DEF_CBED_DSIZE, em_controls=EMC(cl=200, simc=SIMC(gmax=1.0, excitation=(0.3, 1.0))))

Begins a dynamic diffraction (Bloch) simulation session. The simulation results are retained in the session between this and endBloch call.

Parameters:
  • aperture (float) – Optional. Objective aperture

  • omega (float) – Optional. Diagnization cutoff value

  • sampling (int) – Optional. Number of sampling points

  • dbsize (float, optional) – Diffracted beams size.

  • em_controls (pyemaps.EMC) – Optional. electron microscope control object.

Returns:

a tuple (n, ns) where ns is a list of sampling points; n is the number of sampling points

Return type:

tuple

Default values:

DEF_APERTURE = 1.0
DEF_OMEGA = 10
DEF_SAMPLING = 8
DEF_CBED_DSIZE - 0.16
DEF_DSIZE_LIMITS =(0.01, 0.5)

Note

During the simulation session, results are retained in pyemaps bloch module. The following methods are used to retrieve the result before the end of session:

  1. getBlochimages. Retrieve a list of bloch images

  2. getSCMatrix. Retrieve a scattering matrix at a sampling point

Note

Other information available during the session:

  1. List of sampling points, diffraction beams tilts etc with printIBDetails;

  2. getEigen function is folded into getSCMatrix call starting from Stable verion 1.0.3

  3. Diagnization Miller indexes at each sampling point: getBeams;

cleanCSF()

Cleans up memories used by structure factor calculation. This also includes the crystal data loaded into pyemaps’ backend simulation module.

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

Transform vector from real to recriprocal space

Parameters:

v (tuple, optional) – A vector of float coordinates

Returns:

a transformed vector

Return type:

tuple

endBloch()
Clean up Bloch module. This function follows

beginBloch

to mark the end of a dynamic simulation session.

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=EMC(cl=200, simc=SIMC(gmax=1.0, excitation=(0.3, 1.0))), nType=TY_NORMAL, bSave=False)

Generates dynamic diffraction (Bloch) image(s). This function is equivalent to calling :

  1. beginBloch

  2. getBlockImages

  3. endBloch

Parameters:
  • aperture (float, optional) – Objective aperture.

  • omega (float, optional) – Diagnization cutoff value, defaults to 10.

  • sampling (int, optional) – Number of sampling points

  • pix_size (int, optional) – Detector pixel size in microns

  • det_size (int, optional) – Detector size or output image size

  • disk_size (float, optional) – Diffracted beams size in range

  • sample_thickness (tuple of int, optional) – Sample thickness in (start, end, step) tuple

  • nType (int, optional. defaults to 0) – type of bloch images generated. 0 for normal or 1 for large angle CBED images

  • em_controls – Microscope controls object

  • bSave (bool, optional) – True - save the output to a raw image file (ext: im3)

Returns:

BImgList object

Return type:

BImgList

Default values:

DEF_APERTURE = 1.0
DEF_OMEGA = 10
DEF_SAMPLING = 8
DEF_CBED_DSIZE = 0.16
DEF_DSIZE_LIMITS =(0.01, 0.5)
DEF_PIXSIZE = 25
DEF_DETSIZE = 512
DEF_THICKNESS = (200, 200, 100)

Note

There will be one slice of image generated for each sample thickness specified by sample_thickness = (start, end, step) arguement:

start, start+step … start+N*step, end

Warning

Dynamic diffraction pattern generation or Bloch has an extensive memory requirement for regular image generation:

nType = TY_NORMAL

Even more so for a large angle CBED generation when nType = TY_LACBED.

To reduce the memory needed, it is recommended to lower input parameters, particularly:

  • The detector size det_size. A reduction of the default value of 512 to 218 for example can reduce memory usage in pyemaps without losing accuracies of the results.

  • The number of sampling points in sampling. With less available memory on the system where pyemaps is running, decreased sampling points in sampling parameter can make a big difference in pyemaps performance.

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

Calculates structure factors.

:param kv:Accelaration Voltage in Kilo-Volts, default value 100 :type kv: int or float, optional

Parameters:
  • smax (int or float, optional) – Limit of Sin(theta)/Wave length, default value 0.5

  • sftype (, int, optional) – Structure factor types to be generated, default value 1 - x-ray

  • aptype (, int, optional) – Output format type, default value 0 - amplitude and phase

Returns:

a dict object with structure factor data

Return type:

dict

Note

sftype has the following value representing:

  1. x-ray structure factor (default)

  2. electron structure factor in volts (KV)

  3. electron structure factor in 1/angstrom^2 in (KV)

  4. electron absorption structure factor in 1/angstrom^2 (KV)

Note

aptype has the following value representing structure factor format:

0: amplitude and phase 1: real and imaginary

The return of an array of structure factors in the following python dictionary format:

{
    'hkl': (h,k,l),         # Miller Indices 
    'sw': s,                # Sin(theta)/Wave length
    'ds': d,                # d-spacing value
    'amp_re': ar            # amplitude or real part 
    'phase_im': ph          # phase or imaginary part
}
generateDP(mode=None, dsize=None, em_controls=None)

Kinematic diffraction simulation.

Parameters:
  • mode (int, optional) – Mode of kinemetic diffraction - normal(1) or CBED(2).

  • dsize (float, optional) – diffractted beam size, only applied to CBED mode.

  • em_controls (pyemaps.EMC, optional) –

    Microscope control object.

Returns:

A tuple (emc, dp) where emc is the microscope control and dp is a diffPattern object .

Return type:

tuple.

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

Generate a list diffraction patterns and save them in proprietory binary formatted database file with extension .bin.

The database created will be used for diffraction pattern indexing and matchig functions in pyemaps EDIOM module.

The generated database file is saved to directory pointed by environment variable PYEMAPS_DATA or in current working directory if PYEMAPS_DATA is not set.

Parameters:
  • emc (EMControls, optional) – Control parameters

  • xa (three integer tuple.) – x-axis, optional

  • res (integer, defaults to 100, optional.) – resolution of stereo projection map, ranging from *LOW_RES*=100 to *HIGH_RES*=300 that is the number of sampling points along the radius. The higher the resolution, the more diffraction patterns are generated in the database file.

  • vertices (three integer tuple, optional) – an array of 3 or 4 zone axis indexes that form an enclosed orientation surface area within which the diffraction patterns are generated. See the following graphic illustration of the vertices input.

Returns:

a tuple of a status code and database file name

Return type:

tuple of an integer and a string

Input zone axis indexes define the vertices of the stereo projection map. The default for a cubic crystal is DEF_VERTMAT = [[0,0,1],[1,1,1],[0,1,1]].

https://github.com/emlab-solutions/imagepypy/raw/main/stereoprojectionmap.png

The diffraction patterns database file produced will be consumed by pyemaps ediom module for experimental diffraction pattern serach and indexing.

generateDif(mode=None, dsize=None, em_controls=None)

Another kinematic diffraction simulation method to be deprecated in stabel production soon. Its replacement is: generateDP.

Parameters:
  • mode (int) – mode of kinemetic diffraction - normal(1) or CBED(2).

  • dsize (float) – diffractted beam size, only applied to CBED mode.

  • em_controls (pyemaps.EMC) – electron microscope controls object.

Returns:

myDif.

Return type:

pyemaps.DPList.

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

Generate the crystal atomic structure data in .xyz format.

Parameters:
  • trMatrix (array, optional) – Transformation matrix

  • trShift (array, optional) – Transformation shift

  • cellbox (array, optional) – Locate atoms inside a box defined.

  • xz (array, optional) – X and Z orientations in real space.

  • orShift (float, optional) – Origin shift.

  • locASpace (array, optional) – Locate atoms inside a box defined.

  • bound (float, optional) – Location in A Space.

Returns:

a python dictionary object of cell constants and 3D coordinates of atoms

Return type:

dict

Example of the .xyz data in python dictionary object:

{
    xyz: [(x1, y1, z1)...(xn, yn, zn)]
    cell: [...] #transformed cell constants
}
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)

Generates powder diffraction.

Parameters:
  • kv (int or float, optional) – Accelaration voltage in kilo-volts.

  • t2max (float, optional) – Maximum scattering angle.

  • smax (float, optional) – Maximum Sin(theta)/Wavelength.

  • smax – Maximum Sin(theta)/Wavelength.

  • eta (float, optional) – the mixing coefficient between gaussian and lorentzian in a pseudo-Voight peak function.

  • gamma (float, optional) – Diffraction peaks half maximum half width.

  • absp (int, optional) – With Absoption structure factor (1 -default) or not (0).

  • isbgdon (int, optional) – Background on or not (default no background).

  • bamp (float, optional) – Background amplitude.

  • bgamma (float, optional) – Background width.

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

Returns:

an array of 2 x 1000 with the first row representing the scattering angle 2theta and the second the intensity

Return type:

array

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

Generate stereodiagram.

Parameters:
  • xa (tuple of 3 integers, optional) – Crystal horizontal axis in reciprical space

  • tilt (tuple, optional) – Sample tilts in (x,y)

  • zone (tuple, optional) – Zone axis

Returns:

A list of stereodiagram elements represented by dict object

Return type:

list of dict object

Example of the stereodiagram output:

[
    {
        "c": (x,y),              # center
        "r": rad,                # radius
        "idx": (h, k, l),        # Miller Index
    }
]    

To display the resulting stereodiagram, use showStereo.

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

Retrieves a set of dynamic diffraction image from the simulation sessiom marked by:

beginBloch. and endBloch.

Parameters:
  • thickness (int, optional) – sample thickness range and step in tuple of three integers (th_start, th_end, th_step)

  • pix_size (int, optional) – Detector pixel size in microns

  • det_size (int, optional) – Detector size or output image size

  • nType (int, optional. defaults to 0) – type of bloch images generated. 0 for normal or 1 for large angle CBED images

  • bSave (bool, optional) – True - save the output to a raw image file with extension of ‘im3’

Returns:

BImgList object

Return type:

BImgList

Default values:

DEF_PIXSIZE = 25
DEF_DETSIZE = 512
DEF_THICKNESS = (200, 200, 100)

Warning

Dynamic diffraction pattern generation or Bloch has an extensive memory requirement for regular image generation:

nType = TY_NORMAL

Even more so for a large angle CBED generation when nType = TY_LACBED.

To reduce the memory needed, it is recommended to lower input parameters, particularly:

  • The detector size det_size. A reduction of the default value of 512 to 218 for example can reduce memory usage in pyemaps without losing accuracies of the results.

  • The number of sampling points in sampling. With less available memory on the system where pyemaps is running, decreased sampling points in sampling parameter can make a big difference in pyemaps performance.

getCalculatedBeams(bPrint=False)

Retieves and/or prints calculated beams for current dynamic diffraction simulation session marked by beginBloch and endBloch.

This information is available right after beginBloch call.

Parameters:

bPrint (bool, optional, default False) – whether to print selected diffracted beams info on standard output

Returns:

The number of selected beams and the selected beams list in Miller indexes.

Return type:

a python tuple.

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

Obtains scattering matrix at a given sampling point. To get a list of sampling points used in this dynamic simulation session, call printIBDetails after beginBloch. In addition to the scattering matrix, it also generates associated eigen values and diffracted beams.

This call must be made during a dynamic simulation session marked by beginBloch and endBloch.

Parameters:
  • ib_coords (tuple, optional, defaults to (0, 0)) – Sampling point coordinates tuple.

  • thickness (int, optional, defaults to 200) – Sample thickness.

  • rvec (tuple of 3 floats, optional, defaults to (0.0,0.0,0.0)) – R vector shifting atom coordinates in crystal, each value between 0.0 and 1.0.

Returns:

scattering matrix size; scattering matrix; eigen values; diffracted beams.

Return type:

a tuple.

Default values for sample_thickness:

DEF_THICKNESS[0] = 200

Example of the eigen vales:

Eigen values at: (0, 0):
[ 0.04684002-0.00218389j -0.2064669 -0.00147516j -0.30446348+0.00055009j
-0.27657617+0.00023512j -0.2765751 +0.00023515j  0.00539041-0.00382443j
-0.535879  -0.00023585j -0.5612881 +0.00045343j -0.55369247+0.00026236j
-0.55368818+0.00026249j -0.19093572+0.00066419j -0.1550311 +0.00045471j
-0.15503166+0.00045471j -0.58842399-0.00202841j -0.67850191+0.00042728j
-0.72713566+0.00060655j -0.70972681+0.00052279j -0.72092338+0.0005903j
-0.72093237+0.00059052j -0.64608335-0.0001983j  -0.64607544-0.00019853j]
load(cty=0)

Prepare and load crystal data into backend simulation module.

Once loaded into simulation modules, the crystal data will be in backend module’s memory until unload() method is called or another crystal object calls this method.

Since all crystal objects use this method to load its data into the shared silmulation modules, data races need to be avoided.

One way to prevent data races is to guard all simulations for one crystal object between its load() and unload() methods.

Parameters:

cty (int, optional) – 0 - normal crystal loading, 1 - loading for crystal constructor

Note

This routine is designed to minimize trips to the backend simulation modules and therefore miximizing the performance. Users do not need to handle this calls directly.

plotPowder(pw)

Show powder diffraction created from generatePowder.

Parameters:

pw (array, required) – Powder diffraction data

printCSF(sfs)

Formats and prints structure factors to standard output.

Parameters:

sfs (dict, required) – structure factor data generated from generateCSF.

Example of the output for a X-Ray Structure Factor for Silicon:

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

h   k   l        s-w             d-s          amplitude         phase

1   1   1    0.1594684670    3.1354161069    58.89618        180.000000
0   0   2    0.1841383247    2.7153500000    6.565563e-31    0.000000
0   2   2    0.2604109162    1.9200423983    67.56880        180.000000
1   1   3    0.3053588663    1.6374176590    44.24472        180.000000
2   2   2    0.3189369340    1.5677080534    8.151511e-14    180.000000
...
printIBDetails()

Prints a dynamic diffraction simulation details during a session marked by beginBloch. and endBloch.

Information regarding the simulation session include sampling points and their associated diffracted beam directions etc.

The information is available right after beginBloch call.

printXYZ(xyzdict)

Print mxtal data in .xyz format in standard output. Refer to XYZ format for its definition and usage.

Parameters:

xyzdict (dict, required) – Crystal structure data.

Note

An example of Silicon atomic structure by pyemaps:

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 
SI           2.0365125000   4.7518625000   2.0365125000 
SI           3.3941875000   0.6788375000   3.3941875000 
...
r2d(v=(0.0, 0.0, 0.0))

Transform vector from recriprocal to real space

Parameters:

v (tuple, optional) – A vector of float coordinates

Returns:

Tranformed vector

Return type:

tuple of floats

set_sim_controls(simc=None)

Sets simulation controls in the backend.

This method also tries to minimize the trip to the backend simulation module by skipping the call to the backend if default values are given.

Parameters:

simc (pyemaps.SIMC, optional) – Simulation control objects

Note

*pyemaps” assumes that attributes in sim_control class are rarely changed.

unload()

Remove crystal data from the memory in the backend simulation modules.

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

Calculates vector length real space vectors or in reciprocal space vectors.

Parameters:
  • v (tuple, optional) – A vector of float coordinates

  • ty (int, optional) – 0 real space, 1 reciprocal space

Returns:

vector length in reciprical space or in reciprocal space

Return type:

float

static wavelength(kv=100)

Calculates electron wavelength.

Parameters:

kv (float or int, optional) – High voltage

return: wave length rtype: float

writeXYZ(xyzdict, fn=None)

Save mxtal data generated by pyemaps to a .xyz file <fn> File path is composed by pyemaps depending on whether PYEMAP_DATA environment variable is set. For details how pyemaps compose the file name see Environment Variables for details.

The file can be imported into external tool such as Jmole to view its content.

property cell

Cell constants

property dw

Debye-Waller factor or thermal factor

property name

crystal name

property atoms

atom list

property spg

Space group

isISO()

Check if crystal thermal type is Isotropic or not

loaded()

Check to see if crystal data is loaded into simulation module or not.

Returns:

True - loaded; otherwise False

Return type:

bool

classmethod from_builtin(cn='Diamond')

Create a crystal by importing data from pyemaps build-in crystal database

Parameters:

cn (string, optional) – Name of the crystal in pyemaps’s builtin database.

Raises:

CrystalClassError – If reading database fails or any of its components fail to validate.

Note

For a list of pyemaps builtin crystal names, call: Crystal.list_all_builtin_crystals() method

classmethod from_xtl(fn)

To create a crystal object by importing data from xtl formtted file.

Parameters:

fn (string, required) – Crystal data file name in pyemaps propietory format.

Raises:

CrystalClassError – file reading fails or any of its components fail to 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

Required Fields:

  1. dw = iso by default, other values: uij, bij

  2. name: crystal name.

  3. cell constants: six floating point values defining crystal cell.

  4. atoms: one or two lines of atoms positions along with element symbol

  5. spg: space group data. Two positive digits: [number, setting]

Validation:

  • if dw == iso, atoms line must have at least 4 floating numbers in of (x,y,x,d-w,occ) where occ defaults to 1.00 if not provided.

  • if dw == uij,bij, each atom data must have at least 9 floating points like (x,y,z,b11,b22,b33,b12,b13,b23,occ)

Input File Name Search:

  • Full path and exists.

  • Current working directory.

  • PYEMAPSHOME/crystals directory, where PYEMAPSHOME is an environment variable pointing to pyemaps data home directory.

For detals how pyemaps look for crystal files, See Environment Variables.

classmethod from_cif(fn)

import crystal data from a cif (Crystallographic Information File).

Parameters:

fn (string, required) – Crystal data file name in JSON format.

Raises:

CrystalClassError – If file reading fails or any of its components (cell, atoms, spg) fail to validate.

classmethod from_json(jfn)

Import crystal data from a .json file.

Parameters:

jfn (string, required) – Crystal data file name in JSON format.

Raises:

CrystalClassError – If file reading fails or any of its components fail to validate.

An example of a json file content:

{
    "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)

Import crystal data from a python dictionary object.

Parameters:

cdict (dict, required) – Crystal data file name in as a python dictionary object.

Raises:

CrystalClassError – If any of its components import fails.

An example of a json file content:

{
    "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()

To list all builtin crystals available in pyemaps built-in crystal database, use this routine to determine the name of the crystal to load using from_builtin.

pyemaps.ddiffs module

Simple wrapper for dynamic simulation images.

class pyemaps.ddiffs.BlochImgs(name)

Bases: object

list of Bloch image objects and its associated controls

__init__(name)
property name
property blochList
add(emc, b)
sort()

Sort the bloch simulation results by controls

pyemaps.display module

Display is provided as a helper module. It serves as demonstration purpose only. It is implemented for a list of pyemaps simulation objects and multiprocess and pipe python objects. Currently this rendering functions may not be best fit for single display.

Check Visualisation for examples of customizing your own visualization methods rendering pyemaps simulations results.

class pyemaps.display.DifPlotter

Bases: object

__init__()
savePlot()
terminate()
plotKDif()
plotDDif()
plotControls(emc, ax)
plotStereo()
call_back()
showImage()
position_fig(x, y)
class pyemaps.display.NBPlot(type=TY_DIF, n=1, name='', bSave=False, cShow=True, bClose=False, layout='individual')

Bases: object

__init__(type=TY_DIF, n=1, name='', bSave=False, cShow=True, bClose=False, layout='individual')
plot(data=(), finished=False)
pyemaps.display.showDif(dpl=None, cShow=True, kShow=True, iShow=True, layout='individual', bSave=False, bClose=False)

Render kinematic diffraction pattern generated by pyemaps.

Parameters:
  • dpl (DPList) – Kinematic difraction pattern object list DPList

  • cShow (bool, optional) – Plot control annotation. True (default): plot the control parameters on lower left corner; False do not plot.

  • kShow (bool) – Whether to display Kikuchi lines.

  • iShow (bool) – Whether to display Miller indexes.

  • layout (str, optional) – layout format. individual (default): plotting one by one, table: plotting in a table of 3 columns

  • bSave (bool) – Whether to save the diplay into a .png image file.

  • bClose (bool, optional) – Whether to close plotting window when finished. Default: False - users must close it.

pyemaps.display.showBloch(bimgs, cShow=True, bColor=False, layout='individual', bSave=False, bClose=False)

Render dynamic diffraction pattern generated by pyemaps.

Parameters:
  • bimgs (BlochImgs) –

    Optional. Dynamic difraction pattern object list BImgList

  • cShow (bool, optional) – Plot control annotation. True (default): plot the control parameters on lower left corner; False do not plot.

  • bColor (bool) – Optional. Whether to display the image in predefined color map.

  • layout (str, optional) – layout format. individual (default): plotting one by one, table: plotting in a table of 3 columns

  • bSave (bool) – Optional. Whether to save the image into a .im3 image file.

  • bClose (bool, optional) – Whether to close plotting window when finished. Default: False - users must close it.

pyemaps.display.showStereo(slist, name, cShow=True, iShow=False, zLimit=2, layout='individual', bSave=False, bClose=False)

Render stereodiagram generated by pyemaps.

Parameters:
  • slist (list, required) – Stereodiagram output from generateStereo.

  • cShow (bool, optional) – Plot control annotation. True (default): plot the control parameters on lower left corner; False do not plot.

  • iShow (bool, optional) – Whether to display Miller indexes or not.

  • zLimit (int, optional) – Miller indexes cutoff number.

  • layout (str, optional) – layout format. individual (default): plotting one by one in sequence, table: plotting in a table of 3 columns

  • bSave (bool, optional) – Whether to save the image into a .png image file.

  • bClose (bool, optional) – Whether to close plotting window when finished. Default: False - users must close it.

Note

When zlimit is set at 2, it is applied to all elements of each Miller index. For example, (3, 1, 0) will not be rendered.

pyemaps.display.normalizeImage(img)
pyemaps.display.displayXImage(img, fsize=(0, 0), bColor=False, isMask=False, bIndexed=False, iShow=False, ds=None, suptitle='')

Internal ediom helper function displaying image.

Returns:

Return type:

None

pyemaps.emcontrols module

There are two controls classes this module defines: microscope controls and simulations controls.

Since the latter changes much less frequently than the former, simulation control is embedded as a member of a microscope controls class.

Simulation Control Constants and Default Values:

pyemaps.emcontrols.DEF_EXCITATION = (0.3, 2.0)
pyemaps.emcontrols.DEF_GMAX = 3.5
pyemaps.emcontrols.DEF_BMIN = 0.1
pyemaps.emcontrols.DEF_INTENSITY = (0.0, 5)
pyemaps.emcontrols.DEF_GCTL = 6.0
pyemaps.emcontrols.DEF_ZCTL = 5.0
pyemaps.emcontrols.DEF_OMEGA = 10
pyemaps.emcontrols.DEF_SAMPLING = 8
pyemaps.emcontrols.SAMPLE_THICKNESS = (200, 200, 100)

Microscope Control Constants and Default Values:

pyemaps.emcontrols.DEF_TILT = (0.0, 0.0)
pyemaps.emcontrols.DEF_ZONE = (0, 0, 1)
pyemaps.emcontrols.DEF_DEFL = (0.0, 0.0)
pyemaps.emcontrols.DEF_KV = 200.0
pyemaps.emcontrols.DEF_CL = 1000.0
pyemaps.emcontrols.DEF_APERTURE = 1.0
pyemaps.emcontrols.DEF_XAXIS = (0, 0, 0)
pyemaps.emcontrols.DEF_PIXSIZE = 25
pyemaps.emcontrols.DEF_DETSIZE = 512
pyemaps.emcontrols.DEF_MODE = 1
pyemaps.emcontrols.DEF_CBED_DSIZE = 0.16 
pyemaps.emcontrols.doc_dec_simc(k)
class pyemaps.emcontrols.SIMControl(excitation=DEF_SIMC['excitation'], gmax=DEF_SIMC['gmax'], bmin=DEF_SIMC['bmin'], intensity=DEF_SIMC['intensity'], gctl=DEF_SIMC['gctl'], zctl=DEF_SIMC['zctl'])

Bases: object

Simulation controls, to be embedded in EMControl

__init__(excitation=DEF_SIMC['excitation'], gmax=DEF_SIMC['gmax'], bmin=DEF_SIMC['bmin'], intensity=DEF_SIMC['intensity'], gctl=DEF_SIMC['gctl'], zctl=DEF_SIMC['zctl'])
property excitation

Excitation error range in (min, max)

property gmax

Maximum recipricol vector length

property bmin

Beta perturbation cutoff

property intensity

Kinematic diffraction intensity cutoff level and scale in (level, scale)

property gctl

Maximum index number for g-list

property zctl

Maximum zone or Miller index number

property omega

Diagnization cutoff value

property sampling

Number of sampling points

property sth

Samples thickness

plot_format()

Format simulation controls in builtin display functions Only plot those parameter that are not defaults

classmethod from_random()

For backward compatibility only

pyemaps.emcontrols.doc_dec(k)
class pyemaps.emcontrols.EMControl(tilt=DEF_TILT, zone=DEF_ZONE, defl=DEF_DEFL, vt=DEF_KV, cl=DEF_CL, simc=SIMControl())

Bases: object

Microscope and sample property controls class. Its attributes include:

  • tilt: sample tilt in x and y directory (x,y)

  • zone: starting zone axis

  • defl: shifts in x and y direction (x, y)

  • cl: cameral length

  • vt: hight voltage in kilo-volts

  • **simc*: SIMControl object

Other optional emcontrol parameters:

  • aperture: Objective len aperture

  • pix_size: detector pixel size

  • det_size: detector size

  • xaxis: crystal horizontal axis in reciprical space

  • mode: simulation mode: 1- normal, 2-CBED

  • dsize: diffracted beam size

__init__(tilt=DEF_TILT, zone=DEF_ZONE, defl=DEF_DEFL, vt=DEF_KV, cl=DEF_CL, simc=SIMControl())
classmethod from_dict(emc_dict)

Create an EMControl object from a python dict object

Parameters:

emc_dict (dict, required) – Microscope control dict object

Raises:

EMCError, if validation fails

property zone

Starting zone axis

property tilt

Tilt in x and y directions (x,y)

property defl

Shifts in x and y directions (x, y)

property cl

Camera length

property vt

High voltage

property xaxis

Crystal horizontal axis in reciprical space

property simc

Simulation Controls

property aperture

Objective lense aperture

property pix_size

Detector pixel size in microns

property det_size

Detector size in microns

property mode

Simulation mode

property dsize

Diffracted beam size

plot_format()

Format simulation controls in builtin display functions Only plot those parameter that are not defaults

static def_dict()

pyemaps.errors module

Error module for handling various pyemaps data validation and calculation failures.

Note

This module is still in active development and improvements.

exception pyemaps.errors.pyemapsError

Bases: Exception

exception pyemaps.errors.CrystalClassError(message)

Bases: Exception

Crystal object creation, validation and loading errors.

__init__(message)
exception pyemaps.errors.XTLError(fn='', message='')

Bases: Exception

XTL crystal data import errors.

__init__(fn='', message='')
exception pyemaps.errors.CIFError(fn='', message='')

Bases: Exception

CIF crystal data import errors.

__init__(fn='', message='')
exception pyemaps.errors.CellError(message)

Bases: Exception

Cell constant data validation errors.

__init__(message)
exception pyemaps.errors.CellValueError(ty=0, cn='')

Bases: CellError

Details of cell constant data validation errors.

__init__(ty=0, cn='')
exception pyemaps.errors.CellDataError(message='invalid cell data')

Bases: CellError

Details of cell constant data validation errors.

__init__(message='invalid cell data')
exception pyemaps.errors.SPGError(message)

Bases: Exception

Space group data validation errors.

__init__(message)
exception pyemaps.errors.SPGITMumberNotInRangeError(nummax)

Bases: SPGError

Space group IT number validation errors.

__init__(nummax)
exception pyemaps.errors.SPGSettingNotInRangeError(setmax)

Bases: SPGError

Space group setting validation errors.

__init__(setmax)
exception pyemaps.errors.SPGInvalidDataInputError(message='Invalid Space group data entered')

Bases: SPGError

Space group setting validation errors. Duplicate of SPGError.

__init__(message='Invalid Space group data entered')
exception pyemaps.errors.UCError(message='')

Bases: Exception

Atomc data validation errors.

__init__(message='')
exception pyemaps.errors.DPError(message='')

Bases: Exception

Kinematic diffraction pattren object creation errors.

__init__(message='')
exception pyemaps.errors.PointError(message='')

Bases: DPError

Detailed kinematic diffraction pattren object creation errors on Point object creation.

__init__(message='')
exception pyemaps.errors.LineError(message='')

Bases: DPError

Detailed kinematic diffraction pattren object creation errors on Line (Kikuchi or HOLZ) object creation.

__init__(message='')
exception pyemaps.errors.PIndexError(message='')

Bases: DPError

Detailed kinematic diffraction pattren object creation errors on Dfffracted beams Miller index object creation.

__init__(message='')
exception pyemaps.errors.DiskError(message='')

Bases: DPError

Detailed kinematic diffraction pattren object creation errors on Dfffracted beams object creation.

__init__(message='')
exception pyemaps.errors.DPListError(message='')

Bases: Exception

List of diffraction patterns create errors.

__init__(message='')
exception pyemaps.errors.BlochError(message='')

Bases: Exception

Dynamic diffraction pattern generation, creation and validation errors.

__init__(message='')
exception pyemaps.errors.EMCError(message='')

Bases: Exception

Microscope controls objects creation and validation errors.

__init__(message='')
exception pyemaps.errors.BlochListError(message='')

Bases: Exception

List of yynamic diffraction patterns errors.

__init__(message='')
exception pyemaps.errors.StereodiagramError(message='')

Bases: Exception

Stereodiagram generation errors.

__init__(message='')
exception pyemaps.errors.MxtalError(message='')

Bases: Exception

Crystal construction simulation errors.

__init__(message='')
exception pyemaps.errors.XDPImageError(message='')

Bases: Exception

Experimental diffraction pattern image object errors.

__init__(message='')

pyemaps.fileutils module

Fileutils is a helper module in assisting pyemaps file i/o functions. Its methods include reading crystal data files and writing simulation output files.

It also detects pyemaps data home environment variables and directs file i/o accoridng to the rule set in Environment Variables.

pyemaps.fileutils.find_datahome()
pyemaps.fileutils.auto_fn(cn)

Auto-generate file name based on crystal name and time stamp when file is generated from pyemaps simulations.

This can be modified to tune the output to any other specific needs.

Parameters:

cn (string, required) – A crystal name.

Returns:

file name composed of crytsal name and time stamp in yyyymmddmmss format

rtype: string

pyemaps.fileutils.find_pyemaps_datahome(home_type='crystals')

Detects enviroment variable set by PYEMAPS_DATA and return the diretcory set by the variable or return current working directory.

Parameters:

home_type (string, optional) – Type of home directory

Returns:

data home path.

Return type:

string

Folder names depending by home_type input:

  1. crystals: all crystal data files.

  2. bloch: all dynamic simulation output files.

  3. mxtal: all .xyz files saved from crystal constructor.

  4. stereo: all .png files saved from stereodiagram plotting methods

pyemaps.fileutils.compose_ofn(fn, name, ty='diffraction')

Compose output file name based file name and file type.

pyemaps.fileutils.loadCrystalCIFData(fn)

Reads a .cif file for crystal data.

Parameters:

fn – cif file name

Type:

string, required

Returns:

tuple of crystal name and crystal data as dict object

Return type:

dict

Note

This method is still in active development.

pyemaps.fileutils.loadCrystalData(fn, cn=None)

Reading built-in datbase or a .xtl file for crystal data.

Parameters:
  • fn – XTL formatted Crystal file name

  • cn – Crystal name

Type:

string, required

Type:

string, optional

Returns:

tuple of crystal name and crystal data as dict object

Return type:

dict

pyemaps.kdiffs module

Kinematic diffraction module is designed to handle kinematic simulation data. It is composed of Point, Line and Disk class objects.

class pyemaps.kdiffs.Point(p=(0.0, 0.0))

Bases: object

Coordinates of kinematic diffraction pattern object.

__init__(p=(0.0, 0.0))
property x

X coordinate

property y

Y coordinate

class pyemaps.kdiffs.Line(pt1=Point(), pt2=Point(), intensity=0, type=1)

Bases: object

Kikuchi line representation in kinematic diffraction patterns.

__init__(pt1=Point(), pt2=Point(), intensity=0, type=1)
property pt1

The first end point of a Line

property pt2

The second end point of a Line

property type

The type of a Line: Kikuchi line or HOLZ line

property intensity

Line intensity

calOpacity(l, h)

Calculate the line opacity based on its intensity value

0.2 -> lowest intensity 0.35-> highest intensity

to_dict()
class pyemaps.kdiffs.Index(I0=(0, 0, 0))

Bases: object

Miller Indexes of a diffracted beam representation in kinematic diffraction pattern.

__init__(I0=(0, 0, 0))
property I1

The first element of Miller Index of a diffracted beam

property I2

The second element of Miller Index of a diffracted beam

property I3

The third element of Miller Index of a diffracted beam

class pyemaps.kdiffs.Disk(c=Point(), r=0.0, i=Index())

Bases: object

Diffracted beams representation in kinematic diffraction patterns

__init__(c=Point(), r=0.0, i=Index())
property c

The center point of a diffracted beam.

property r

The radius of a diffracted beam.

property idx

The Miller index of a diffracted beam.

to_dict()

Creates a diffracted beam object from a dict pyton object

class pyemaps.kdiffs.diffPattern(diff_dict)

Bases: object

Create a kinematic diffraction pattern based on the pyemaps kinematic simulation output in python dict object.

See :doc:Visualization for how to visualize kinematic diffraction patterns using this object.

__init__(diff_dict)
Parameters:

diff_dict (dict, required) – Only accepts output from pyemaps kinematic diffraction run.

property klines

Kikuchi lines array

property hlines

Holz lines array

property disks

Disks array

property name

Crystal name

property shift

Shifts of the diffraction pattern

property nklines

Number of Kikuchi lines

property nhlines

Number of HOLZ lines

property ndisks

Number of Disks

to_dict()
class pyemaps.kdiffs.Diffraction(name, mode=DEF_MODE)

Bases: object

List of DP objects and its associated EMControl objects.

__init__(name, mode=DEF_MODE)
property name
property mode
property diffList
add(emc, diffP)

Append a new kenematic diffraction pattern with its associated controls

sort()

Sorting diffraction list by controls

clear()

Empty the DP list, leaving it as empty.

Module contents

This file is part of pyemaps

pyemaps is free software for non-comercial use: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

pyemaps is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with pyemaps. If not, see <https://www.gnu.org/licenses/>.

Contact supprort@emlabsoftware.com for any questions and comments.

```

Author: EMLab Solutions, Inc. Date: May 07, 2022