temul.topotem.polarisation.atom_deviation_from_straight_line_fit(sublattice, axis_number, n, second_fit_rigid=True, plot=False, return_individual_atom_planes=False)
Fits the atomic columns in an atom plane to two straight lines using the
first n and second (last) n atomic columns. See Notes.
The slope of the first fitting will be used for the
second fitting. Setting second_fit_rigid = False will reverse this
behaviour.
Parameters:
sublattice (Atomap Sublattice object)
axis_number (int) – The index of the zone axis (translation symmetry) found by the Atomap
function construct_zone_axes(). For sublattices with heavily
deviating atomic columns, you may need to use
sublattice.construct_zone_axes(atom_plane_tolerance=1).
n (int) – The number of columns used at the beginning and end of each atom plane
to fit a straight line.
second_fit_rigid (bool, default True) – Used to decide whether the first or second fitting’s slope will be
rigid during fitting. With second_fit_rigid=True, the slope of the
second fitting will be defined as the slope as the first fitting. The
y-intercept is free to move.
plot (bool, default False) – Whether to plot the atom plane data, first and second fitting, and the
line constructed halfway between the two.
return_individual_atom_planes (bool) – If set to True, the returned lists will be lists of sublists.
These sublists have information from each atom plane. For example,
the returned x_list will have sublists which contain the x values
from each atom plane.
If set to False (default), the list of sublists is flattened.
Returns:
x, y, u, v – x, y are the original atom position coordinates
sublattice.x_position and sublattice.y_position for
the coordinates included in the chosen
axis_number.
u, v are the polarisation vector components pointing
towards the halfway line from the atom position coordinates.
These can be input to plot_polarisation_vectors()
for visualisation.
If return_individual_atom_planes is True, then the four lists
will be made up of a sublists. See return_individual_atom_planes
for more information.
Computes the distance
of each atomic column from the line halfway between the two fitted lines,
as described in [1]_. This is done for every sublattice atom plane along
the chosen axis_number.
Useful if your image is off-tilt (electron beam is not perfectly
parallel to the atomic columns).
Parameters:
u (1D numpy arrays) – horizontal and vertical components of the (polarisation) vectors.
v (1D numpy arrays) – horizontal and vertical components of the (polarisation) vectors.
method (string, default "com") – method used to correct the vector components. “com” is via the center
of mass of the vectors. “av” is via the average vector.
Delete atom_planes from a zone axis. Can choose whether to delete
every second, third etc. atom plane, and the offset from the zero index.
Parameters:
sublattice (Atomap Sublattice object)
zone_axis_index (int, default 0) – The zone axis you wish to specify. You are indexing
sublattice.zones_axis_average_distances[zone_axis_index]
atom_plane_tolerance (float, default 0.5) – float between 0.0 and 1.0. Closer to 1 means it will find more zones.
See sublattice.construct_zone_axes() for more information.
divisible_by (int, default 3) – If divisible_by is 2, every second atom_plane is deleted,
If divisible_by is 4, every fourth atom_plane is deleted, etc.
offset_from_zero (int, default 0) – The atom_plane from which you start deleting.
If offset_from_zero is 4, the fourth atom_plane will be
the first deleted.
opposite (bool, default False) – If this is set to True, the atom_plane specified by divisible_by
will be kept and all others deleted.
Plot the planes visually using, it may take some time in large images:
zones01_A = sublatticeA.get_all_atom_planes_by_zone_vector(zone_vec_list)
zones01_A.plot()
Fit the atoms in an atom plane to a straight line and find the deviation
of each atom position from that straight line fit.
To plot all zones see plot_atom_deviation_from_all_zone_axes().
Parameters:
sublattice (Atomap Sublattice object)
axis_number (int, default 0) – The index of the zone axis (translation symmetry) found by the Atomap
function construct_zone_axes().
save (string, default '') – If set to save=None, the array will not be saved.
Returns:
Four lists (x, y, u, and v where x,y are the original atom position)
coordinates (simply sublattice.x_position, sublattice.y_position) and
u,v are the polarisation vector components pointing to the new coordinate.
These can be input to plot_polarisation_vectors() for visualisation.
degrees (bool, default False) – Change between degrees and radian. Default is radian.
angle_offset (float, default None) – Rotate the angles by the given amount. The function assumes that if you
set degrees=False then the provided angle_offset is in radians,
and if you set degrees=True then the provided angle_offset is
in degrees.
Return type:
1D NumPy array
temul.topotem.polarisation.get_average_polarisation_in_regions(x, y, u, v, image, divide_into=8)
This function splits the image into the given number of regions and
averages the polarisation of each region.
Parameters:
x (list or 1D NumPy array) – xy coordinates on the image
y (list or 1D NumPy array) – xy coordinates on the image
divide_into (int, default 8) – The number used to divide the image up. If 8, then the image will be
split into an 8x8 grid.
Returns:
x_new, y_new, u_new, v_new – x_new and y_new are the central coordinates of the divided regions.
u_new and v_new are the averaged polarisation vectors.
divide_into (int, default 8) – The number used to divide the image up. If 8, then the image will be
split into an 8x8 grid.
Returns:
x_new, y_new, u_new, v_new – x_new and y_new are the central coordinates of the divided regions.
u_new and v_new are the averaged polarisation vectors.
Calculate the divide_into required to get an averaging of
averaging_by. divide_into can then be used in
temul.topotem.polarisation.get_average_polarisation_in_regions.
Also finds unit cell size and the number of unit cells in the (square)
image along the x axis.
Parameters:
sublattice (Atomap Sublattice)
averaging_by (int or float) – How many unit cells should be averaged. If averaging_by=2, 2x2 unit
cells will be averaged when passing divide_into to
temul.topotem.polarisation.get_average_polarisation_in_regions.
sampling (float) – Pixel sampling of the image for calibration.
zone_axis_index_A (int) – Sublattice zone axis indices which should represent the sides of the
unit cell.
zone_axis_index_B (int) – Sublattice zone axis indices which should represent the sides of the
unit cell.
sampling (float, default None) – If sampling is set, the vector magnitudes (in pix) will be scaled
by sampling (nm/pix).
Return type:
1D NumPy array
Examples
>>> fromtemul.topotem.polarisationimportget_vector_magnitudes>>> importnumpyasnp>>> u,v=[4,3,2,5,6],[8,5,2,1,1]# list input>>> vector_mags=get_vector_magnitudes(u,v)>>> u,v=np.array(u),np.array(v)# numpy input also works>>> vector_mags=get_vector_magnitudes(u,v)>>> sampling=0.0321>>> vector_mags=get_vector_magnitudes(u,v,sampling=sampling)
temul.topotem.polarisation.get_xyuv_from_line_fit(arr, n, second_fit_rigid=True, plot=False)
Fits the data in an array to two straight lines using the
first n and second (last) n array value pairs.
Computes the distance of
each array value pair from the line halfway between the two fitted lines.
The slope of the first fitting will be used for the
second fitting. Setting second_fit_rigid = False will reverse this
behaviour.
Parameters:
arr (2D array-like) – Array-like (e.g., NumPy 2D array) in the form [[x1, y1], [x2, y2]…]
n (int) – The number of arr value pairs used at the beginning and end of the arr
to fit a straight line.
second_fit_rigid (bool, default True) – Used to decide whether the first or second fitting’s slope will be
rigid during fitting. With second_fit_rigid=True, the slope of the
second fitting will be defined as the slope as the first fitting. The
y-intercept is free to move.
plot (bool, default False) – Whether to plot the arr data, first and second fitting, and the
line constructed halfway between the two.
Returns:
x, y, u, v – x, y are the original arr coordinates. u, v are the vector components
pointing towards the halfway line from the arr coordinates.
These can be input to plot_polarisation_vectors() for
visualisation.
Plot the polarisation vectors. These can be found with
find_polarisation_vectors() or Atomap’s
get_polarization_from_second_sublattice() function.
Parameters:
details. (See matplotlib's quiver function for more)
x (list or 1D NumPy array) – xy coordinates of the vectors on the image.
y (list or 1D NumPy array) – xy coordinates of the vectors on the image.
u (list or 1D NumPy array) – uv vector components.
v (list or 1D NumPy array) – uv vector components.
image (2D NumPy array) – image is used to fit the image. Will flip the y axis, as used for
electron microscopy data (top left point is (0, 0) coordinate).
sampling (float, default None) – Pixel sampling (pixel size) of the image for calibration.
units (string, default "pix") – Units used to display the magnitude of the vectors.
plot_style (string, default "vector") – Options are “vector”, “colormap”, “contour”, “colorwheel”,
“polar_colorwheel”. Note that “colorwheel” will automatically plot the
colorbar as an angle. Also note that “polar_colorwheel” will
automatically generate a 2D RGB (HSV) list of colors that match with
the vector components (uv).
overlay (bool, default True) – If set to True, the image will be plotting behind the arrows
unit_vector (bool, default False) – Change the vectors magnitude to unit vectors for plotting purposes.
Magnitude will still be displayed correctly for colormaps etc.
vector_rep (str, default "magnitude") – How the vectors are represented. This can be either their magnitude
or angle. One may want to use angle when plotting a
contour map, i.e. view the contours in terms of angles which can be
useful for visualising regions of different polarisation.
degrees (bool, default False) – Change between degrees and radian. Default is radian.
If plot_style="colorwheel", then setting degrees=True
will convert the angle unit to degree from the default radians.
angle_offset (float, default None) – If using vector_rep="angle" or plot_style="contour", this
angle will rotate the vector angles displayed by the given amount.
Useful when you want to offset the angle of the atom planes relative
to the polarisation.
save (string) – If set to save=None, the image will not be saved.
title (string, default "") – Title of the plot.
color (string, default "r") – Color of the arrows when plot_style="vector" or "contour".
cmap (matplotlib colormap, default "viridis") – Matplotlib cmap used for the vector arrows.
alpha (float, default 1.0) – Transparency of the matplotlib cmap. For plot_style="colormap"
and plot_style="colorwheel", this alpha applies to the vector
arrows. For plot_style="contour" this alpha applies to the
tricontourf map.
image_cmap (matplotlib colormap, default 'gray') – Matplotlib cmap that will be used for the overlay image.
monitor_dpi (int, default 96) – The DPI of the monitor, generally 96 pixels. Used to scale the image
so that large images render correctly. Use a smaller value to enlarge
too-small images. monitor_dpi=None will ignore this param.
no_axis_info (bool, default True) – This will remove the x and y axis labels and ticks from the plot if set
to True.
invert_y_axis (bool, default True) – If set to true, this will flip the y axis, effectively setting the top
left corner of the image as the (0, 0) origin, as in scanning electron
microscopy images.
ticks (colorbar ticks, default None) – None or list of ticks or Locator If None, ticks are determined
automatically from the input.
scalebar (bool or dict, default False) – Add a matplotlib-scalebar to the plot. If set to True the scalebar will
appear similar to that given by Hyperspy’s plot() function. A
custom scalebar can be included as a dictionary and more custom
options can be found in the matplotlib-scalebar package. See below
for an example.
antialiased (bool, default False) – Applies only to plot_style="contour". Essentially removes the
border between regions in the tricontourf map.
levels (int, default 20) – Number of Matplotlib tricontourf levels to be used.
remove_vectors (bool, default False) – Applies only to plot_style="contour". If set to True, do not plot
the vector arrows.
quiver_units (string, default 'width') – The units parameter from the matplotlib quiver function, not to be
confused with the units parameter above for the image units.
parameters (ax.quiver) – See matplotlib’s quiver function for the remaining parameters.
Create a ratio map between two zone axes. Useful to see the tetragonality
or shearing of unit cells.
Parameters:
sublattice (Atomap Sublattice object)
zone_axis_index_A (int) – The zone axes you wish to specify. You are indexing
sublattice.zones_axis_average_distances[zone_axis_index].
The signal created from zone_axis_index_A will be divided by the signal
created from zone_axis_index_B.
zone_axis_index_B (int) – The zone axes you wish to specify. You are indexing
sublattice.zones_axis_average_distances[zone_axis_index].
The signal created from zone_axis_index_A will be divided by the signal
created from zone_axis_index_B.
ideal_ratio_one (bool, default True) – If set to true this will force negative ratio values to be positive.
Useful for seeing the overall tetragonality of a lattice.
sampling (float, default None) – Pixel sampling of the image for calibration.
units (string, default "pix") – Units of the sampling.
vmin (see Matplotlib for details)
vmax (see Matplotlib for details)
cmap (see Matplotlib for details)
title (string, default "Spacings Map")
filename (string, optional) – If filename is set, the strain signal and plot will be saved.
**kwargs (Matplotlib keyword arguments passed to imshow().)
Returns:
Ratio of lattice spacings map as a Hyperspy Signal2D. It will also plot the
Creates an inverse fast Fourier transform (iFFT) from an image and mask
coordinates. Use choose_mask_coordinates to manually choose mask
coordinates in the FFT.
Parameters:
image (Hyperspy 2D Signal)
mask_coords (list of pixel coordinates) – Pixel coordinates of the masking locations. See the example below for
two simple coordinates found using choose_mask_coordinates.
mask_radius (int, default 10) – Radius in pixels of the mask.
image_space (str, default "real") – If the input image is in Fourier/diffraction/reciprocal space already,
set space=”fourier”.
keep_masked_area (bool, default True) – If True, this will set the mask at the mask_coords.
If False, this will set the mask as everything other than the
mask_coords. Can be thought of as inversing the mask.
plot_masked_fft (bool, default False) – If True, the mask used to filter the FFT will be plotted. Good for
checking that the mask is doing what you want. Can fail sometimes due
to matplotlib plotting issues.
Calculates the curvature of the sublattice atom planes along the direction
given by zone_vector_index. In the case of [1]_. below, the curvature
is the inverse of the radius of curvature, and is effectively equal to the
second derivative of the displacement direction of the atoms. Because the
first derivative is negligible, the curvature can be calculated as the
strain gradient [2].
With the parameter func="strain_grad", this function calculates the
strain gradient of the atom planes of a Atomap Sublattice object.
Parameters:
sublattice (Atomap Sublattice object)
zone_vector_index (int) – The index of the zone axis (translation symmetry) found by the Atomap
function construct_zone_axes().
func ('strain_grad' or function) – Function that can be used by scipy.optimize.curve_fit. If
func=’strain_grad’, then the
temul.topotem.lattice_structure_tools.sine_wave_function_strain_gradient
function will be used.
atom_planes (tuple, optional) – The starting and ending atom plane to be computed. Useful if only a
section of the image should be fitted with sine waves. Given in the
form e.g., (0, 3).
sampling (float, optional) – sampling of an image in units of units/pix
units (string, default "pix") – Units of sampling, for display purposes.
vmin (see Matplotlib documentation, default None)
vmax (see Matplotlib documentation, default None)
cmap (see Matplotlib documentation, default None)
title (string, default 'Curvature Map')
filename (string, default None) – Name of the file to be saved.
plot (bool, default False) – If set to True, each atom plane fitting will be plotted along with its
respective atom positions. The fitting parameters (popt) will be
returned as a list.
return_fits (bool, default False) – If set to True, each atom plane fitting will be plotted along with its
respective atom positions. The fitting parameters (popt) will be
returned as a list.
**kwargs – keyword arguments to be passed to scipy.optimize.curve_fit.
Extracts info from input atomic column element configuration
Split an element and its count, then sort the element for
use with other functions.
Parameters:
element (string, default None) – element species and count must be separated by the
first string in the split_symbol list.
separate elements must be separated by the second
string in the split_symbol list.
split_symbol (list of strings, default ['_', '.']) – The symbols used to split the element into its name
and count.
The first string ‘_’ is used to split the name and count
of the element.
The second string is used to split different elements in
an atomic column configuration.
Returns:
list of a list with element_split, element_name, element_count, and
Fid the number of pixels in an area when calling
_get_image_slice_around_atom()
Parameters:
atom (atomap.AtomPosition)
image_data (Numpy 2D array)
percent_to_nn (float, default 0.40) – Determines the boundary of the area surrounding each atomic
column, as fraction of the distance to the nearest neighbour.
Finds the intensity for each atomic column using either max, mean,
min, total or all of them at once.
The intensity values are taken from the area defined by
percent_to_nn.
Results are stored in each Atom_Position object as
amplitude_max_intensity, amplitude_mean_intensity,
amplitude_min_intensity and/or amplitude_total_intensity
which can most easily be accessed through the sublattice object.
See the examples in get_atom_column_amplitude_max_intensity.
Parameters:
sublattice (sublattice object) – The sublattice whose intensities you are finding.
intensity_type (string, default "max") – Determines the method used to find the sublattice intensities.
The available methods are “max”, “mean”, “min”, “total” and
“all”.
remove_background_method (string, default None) – Determines the method used to remove the background_sub
intensities from the image. Options are “average” and “local”.
background_sub (sublattice object, default None) – The sublattice used if remove_background_method is used.
num_points (int, default 3) – If remove_background_method=”local”, num_points is the number
of nearest neighbour values averaged from background_sub
percent_to_nn (float, default 0.40) – Determines the boundary of the area surrounding each atomic
column, as fraction of the distance to the nearest neighbour.
mask_radius (float) – Radius of the atomic column in pixels. If chosen, percent_to_nn
must be None.
Remove the average background from a sublattice intensity using
a background sublattice.
Parameters:
sublattice (sublattice object) – The sublattice whose intensities are of interest.
intensity_type (string) – Determines the method used to find the sublattice intensities.
The available methods are “max”, “mean”, “min” and “all”.
background_sub (sublattice object) – The sublattice used to find the average background.
percent_to_nn (float, default 0.4) – Determines the boundary of the area surrounding each atomic
column, as fraction of the distance to the nearest neighbour.
mask_radius (float) – Radius of the atomic column in pixels. If chosen, percent_to_nn
must be None.
Remove the local background from a sublattice intensity using
a background sublattice.
Parameters:
sublattice (sublattice object) – The sublattice whose intensities are of interest.
intensity_type (string) – Determines the method used to find the sublattice intensities.
The available methods are “max”, “mean”, “min”, “total” and “all”.
background_sub (sublattice object) – The sublattice used to find the local backgrounds.
num_points (int, default 3) – The number of nearest neighbour values averaged from
background_sub
percent_to_nn (float, default 0.40) – Determines the boundary of the area surrounding each atomic
column, as fraction of the distance to the nearest neighbour.
mask_radius (float) – Radius of the atomic column in pixels. If chosen, percent_to_nn
must be None.
Change the elements in a sublattice object to a higher or lower combined
atomic (Z) number.
The aim is to change the sublattice elements so that the experimental image
agrees with the simulated image in a realistic manner.
See image_difference_intensity()
Get the index in sublattice from the image_difference_intensity() output,
which is the image_diff_array input here.
Then, depending on whether the image_diff_array is for atoms that should
be brighter or darker, set a new element to that sublattice atom_position
Parameters:
sublattice (Atomap Sublattice object) – the elements of this sublattice will be changed
image_diff_array (Numpy 2D array) – Contains (p, x, y, intensity) where
p = index of Atom_Position in sublattice
x = Atom_Position.pixel_x
y = Atom_Position.pixel_y
intensity = calculated intensity of atom in sublattice.image
darker_or_brighter (int) – if the element should have a lower combined atomic Z number,
darker_or_brighter = 0.
if the element should have a higher combined atomic Z number,
darker_or_brighter = 1
In other words, the image_diff_array will change the given
sublattice elements to darker or brighter spots by choosing 0 and 1,
respectively.
element_list (list) – list of element configurations
verbose (bool, default False) – If set to True then atom warnings will be printed as output.
Examples
>>> fromtemul.model_creationimportchange_sublattice_atoms_via_intensity>>> importtemul.external.atomap_devel_012.dummy_dataasdummy_data>>> # import atomap.dummy_data as dummy_data>>> sublattice=dummy_data.get_simple_cubic_sublattice()>>> foriinrange(0,len(sublattice.atom_list)):... sublattice.atom_list[i].elements='Mo_1'... sublattice.atom_list[i].z_height=[0.5]>>> element_list=['H_0','Mo_1','Mo_2']>>> image_diff_array=np.array([[5,2,2,20],[1,2,4,7]])>>> # This will change the 5th atom in the sublattice to a lower atomic Z>>> # number, i.e., 'H_0' in the given element_list>>> change_sublattice_atoms_via_intensity(sublattice=sublattice,... image_diff_array=image_diff_array,... darker_or_brighter=0,... element_list=element_list)Changing some atoms
Compare the count of atomap elements in two counter_lists gotten by
count_atoms_in_sublattice_list()
If the counters are the same, then the original atom_lattice is the
same as the refined atom_lattice. It will return the boolean value
True. This can be used to stop refinement loops if neccessary.
This function can also be used to stop a refinement loop by using an
if break loop:
# >>> if compare_count_atoms_in_sublattice_list(counter_list) is True:
# >>> break
Convert from the output of return_z_coordinates(), which is a 1D numpy
array, to a long string, with which I have set up
sublattice.atom_list[i].z_height.
Create a list which represents the peak points of the
intensity distribution for each atom.
works for nanoparticles as well, doesn’t matter what
scaling_exponent you use for nanoparticle. Figure this out!
If the max_element_intensity is set, then the program assumes
that the standard element is the largest available element
combination, and scales the middle and limit intensity lists
so that the middle_intensity_list[-1] == max_element_intensity
Find the differences in a sublattice’s atom_position intensities.
Change the elements of these atom_positions depending on this difference of
intensities.
The aim is to change the sublattice elements so that the experimental image
agrees with the simulated image in a realistic manner.
Parameters:
sublattice (Atomap Sublattice object) – Elements of this sublattice will be refined
sim_image (HyperSpy 2D signal) – The image you wish to refine with, usually an image simulation of the
sublattice.image
element_list (list) – list of element configurations, used for refinement
filename (string, default None) – name with which the image will be saved
percent_to_nn (float, default 0.40) – Determines the boundary of the area surrounding each atomic
column, as fraction of the distance to the nearest neighbour.
mask_radius (float, default None) – Radius of the mask around each atom. If this is not set,
the radius will be the distance to the nearest atom in the
same sublattice times the percent_to_nn value.
Note: if mask_radius is not specified, the Atom_Position objects
must have a populated nearest_neighbor_list.
change_sublattice (bool, default False) – If change_sublattice is set to True, all incorrect element assignments
will be corrected inplace.
verbose (bool, default False) – If set to True then atom warnings will be printed as output.
Find new atomic coordinates by comparing experimental to simulated image.
Changes the sublattice inplace using change_sublattice_pseudo_inplace.
The aim is to change the sublattice elements so that the experimental image
agrees with the simulated image in a realistic manner.
See also image_difference_intensity function and the Model_Refiner class.
Parameters:
sublattice (Atomap sublattice object)
sim_image (simulated image used for comparison with sublattice image)
pixel_threshold (int) – minimum pixel distance from current sublattice atoms. If the new atomic
coordinates are greater than this distance, they will be created.
Choose a pixel_threshold that will not create new atoms in unrealistic
positions.
filename (string, default None) – name with which the image will be saved
percent_to_nn (float, default 0.40) – Determines the boundary of the area surrounding each atomic
column, as fraction of the distance to the nearest neighbour.
mask_radius (float, default None) – Radius of the mask around each atom. If this is not set,
the radius will be the distance to the nearest atom in the
same sublattice times the percent_to_nn value.
Note: if mask_radius is not specified, the Atom_Position objects
must have a populated nearest_neighbor_list.
num_peaks (int, default 5) – number of new atoms to add
add_sublattice (bool, default False) – If set to True, a new sublattice will be created and returned.
The reason it is set to False is so that one can check if new atoms
would be added with the given parameters.
sublattice_name (string, default 'sub_new') – the outputted sublattice object name and sublattice.name the new
sublattice will be given
inplace (bool, default True) – If set to True, the input sublattice will be changed inplace and
the sublattice returned. If set to False, these changes will be output
only to a new sublattice.
verbose (bool) – Setting to True will print out some info as the function is running.
Returns:
Atomap Sublattice object if inplace=False. See the inplace
Find new atomic coordinates by comparing experimental to simulated image.
Create a new sublattice to store the new atomic coordinates.
The aim is to change the sublattice elements so that the experimental image
agrees with the simulated image in a realistic manner.
Parameters:
sublattice_list (list of atomap sublattice objects)
sim_image (simulated image used for comparison with sublattice image)
pixel_threshold (int) – minimum pixel distance from current sublattice atoms. If the new atomic
coordinates are greater than this distance, they will be created.
Choose a pixel_threshold that will not create new atoms in unrealistic
positions.
filename (string, default None) – name with which the image will be saved
percent_to_nn (float, default 0.40) – Determines the boundary of the area surrounding each atomic
column, as fraction of the distance to the nearest neighbour.
mask_radius (float, default None) – Radius of the mask around each atom. If this is not set,
the radius will be the distance to the nearest atom in the
same sublattice times the percent_to_nn value.
Note: if mask_radius is not specified, the Atom_Position objects
must have a populated nearest_neighbor_list.
num_peaks (int, default 5) – number of new atoms to add
add_sublattice (bool, default False) – If set to True, a new sublattice will be created and returned.
The reason it is set to False is so that one can check if new atoms
would be added with the given parameters.
sublattice_name (string, default 'sub_new') – the outputted sublattice object name and sublattice.name the new
sublattice will be given
Return type:
Atomap Sublattice object
Examples
>>> fromtemul.model_creationimportimage_difference_position>>> importtemul.external.atomap_devel_012.dummy_dataasdummy_data>>> # import atomap.dummy_data as dummy_data>>> sublattice=dummy_data.get_simple_cubic_with_vacancies_sublattice(... image_noise=True)>>> sim_image=dummy_data.get_simple_cubic_signal()>>> foriinrange(0,len(sublattice.atom_list)):... sublattice.atom_list[i].elements='Mo_1'... sublattice.atom_list[i].z_height='0.5'>>> # Check without adding a new sublattice>>> image_difference_position_new_sub(sublattice_list=[sublattice],... sim_image=sim_image,... pixel_threshold=1,... percent_to_nn=None,... mask_radius=5,... num_peaks=5,... add_sublattice=False)>>> # Add a new sublattice>>> # if you have problems with mask_radius, increase it!>>> # Just a gaussian fitting issue, could turn it off!>>> sub_new=image_difference_position_new_sub(... sublattice_list=[sublattice],... sim_image=sim_image,... pixel_threshold=10,... num_peaks=5,... add_sublattice=True)New Atoms Found! Adding to a new sublattice
Produce fractional z-dimension coordinates for a given thickness and bond
length.
Parameters:
z_thickness (number) – Size (Angstrom) of the z-dimension.
z_bond_length (number) – Size (Angstrom) of the bond length between adjacent atoms in the
z-dimension.
number_atoms_z (integer, default None) – number of atoms in the z-dimension. If this is set to an interger
value, it will override the use of z_thickness.
centered_atoms (bool, default True) – If set to True, the z_coordinates will be centered about 0.5.
If set to False, the z_coordinate will start at 0.0.
Find new atomic coordinates by comparing experimental to simulated image.
Create a new sublattice to store the new atomic coordinates.
The aim is to change the sublattice elements so that the experimental image
agrees with the simulated image in a realistic manner. See [1]_.
Parameters:
numerator_sublattice (Sublattice object) – Sublattice from which the numerator intensity will be calculated.
numerator_element (string) – Element from which the numerator atomic number will be taken.
denominator_sublattice (Sublattice object) – Sublattice from which the denominator intensity will be calculated.
denominator_element (string) – Element from which the denominator atomic number will be taken.
intensity_type (string) – Determines the method used to find the sublattice intensities.
The available methods are “max”, “mean”, “min”, “total” and
“all”.
method (string) – Method used to calculate the intensity of the sublattices. Options are
“mean” or “mode”.
remove_background_method (string) – Determines the method used to remove the background_sublattice
intensities from the image. Options are “average” and “local”.
background_sub (Sublattice object) – The sublattice to be used if remove_background_method is used.
num_points (int) – If remove_background_method=”local”, num_points is the number
of nearest neighbour values averaged from background_sublattice.
percent_to_nn (float, default 0.40) – Determines the boundary of the area surrounding each atomic
column, as fraction of the distance to the nearest neighbour.
mask_radius (float) – Radius of the atomic column in pixels. If chosen, percent_to_nn
must be None.
split_symbol (string, default '_') – The symbols used to split the element into its name
and count.
The first string ‘_’ is used to split the name and count
of the element.
The second string has not been implemented within this function.
>>> sub_new=image_difference_position_new_sub(... sublattice_list=[sublattice],... sim_image=sim_image,... pixel_threshold=10,... num_peaks=5,... add_sublattice=True)New Atoms Found! Adding to a new sublattice
Calibrates the intensity of an image by using the brightest sublattice.
The mean intensity of that sublattice is set to 1.
Parameters:
image (Hyperspy Signal2D) – Image you wish to calibrate.
cropping_area (list of 2 floats) – The best method of choosing the area is by using the function
“choose_points_on_image(image.data)”. Choose two points on the
image. First point is top left of area, second point is bottom right.
separation (int, default 8) – Pixel separation between atoms as used by Atomap.
reference_image (Hyperspy Signal2D) – Image with which image is compared.
scalebar_true (bool, default True) – If set to True, the function assumes that image.axes_manager is
calibrated to a unit other than pixel.
mask_radius (int, default None) – Radius in pixels of the mask.
percent_to_nn (float, default 0.2) – Determines the boundary of the area surrounding each atomic
column, as fraction of the distance to the nearest neighbour.
refine (bool, default False) – If set to True, the atom positions found for the calibration will be
refined.
filename (str, default None) – If set to a string, the image will be saved.
Return type:
Nothing, but the mean intensity of the brightest sublattice is set to 1.
Examples
>>> fromtemul.dummy_dataimportget_simple_cubic_signal>>> importtemul.apiastml>>> importmatplotlib.pyplotasplt>>> image=get_simple_cubic_signal()>>> image.plot()>>> crop_a=tml.choose_points_on_image(image.data)# manually>>> crop_a=[[10,10],[100,100]]# use above line if trying yourself!
Gaussian blur an image for comparison with a reference image.
Good for finding the best gaussian blur for a simulation by
comparing to an experimental image.
See measure_image_errors() and load_and_compare_images().
Parameters:
image_to_filter (Hyperspy Signal2D) – Image you wish to automatically filter.
reference_image (Hyperspy Signal2D) – Image with which image_to_filter is compared.
delta_image_filter (float) – The increment of the Gaussian sigma used.
max_sigma (float, default 6) – The largest (limiting) Gaussian sigma used.
cropping_area (list of 2 floats, default [[0,0], [50,50]]) – The best method of choosing the area is by using the function
“choose_points_on_image(image.data)”. Choose two points on the
image. First point is top left of area, second point is bottom right.
separation (int, default 8) – Pixel separation between atoms as used by Atomap.
filename (str, default None) – If set to a string, the plotted and filtered image will be saved.
percent_to_nn (float, default 0.4) – Determines the boundary of the area surrounding each atomic
column, as fraction of the distance to the nearest neighbour.
mask_radius (int, default None) – Radius in pixels of the mask. If set, then set percent_to_nn=None.
refine (bool, default False) – If set to True, the
calibrate_intensity_distance_with_sublattice_roi
calibration will refine the atom positions for each calibration. May
make the function very slow depending on the size of
image_to_filter and cropping_area.
Return type:
Hyperspy Signal2D (filtered image) and float (ideal Gaussian sigma).
Crop a Hyperspy Signal2D by providing the cropping_area. See the
example below.
Parameters:
image (Hyperspy Signal2D) – Image you wish to crop
cropping_area (list of 2 floats) – The best method of choosing the area is by using the function
“choose_points_on_image(image.data)”. Choose two points on the
image. First point is top left of area, second point is bottom right.
scalebar_true (bool, default True) – If set to True, the function assumes that image.axes_manager is
calibrated to a unit other than pixel.
filename (str, default None) – If set to a string, the images and cropping variables will be saved.
fwhm_neg (float) – Initial guess in pixels of full width at half maximum (fwhm) of
inner (negative) and outer (positive) Gaussian to be applied to fft,
respectively.
Use the visualise_dg_filter function to find the optimium values.
fwhm_pos (float) – Initial guess in pixels of full width at half maximum (fwhm) of
inner (negative) and outer (positive) Gaussian to be applied to fft,
respectively.
Use the visualise_dg_filter function to find the optimium values.
neg_min (float, default 0.9) – Effective amplitude of the negative Gaussian.
Filter an image with an double Gaussian (band-pass) filter. The function
will automatically find the optimum magnitude of the negative inner
Gaussian.
Parameters:
image (Hyperspy Signal2D) – Image to be filtered.
d_inner (float) – Inner diameter of the FFT spots. Effectively the diameter of the
negative Gaussian.
d_outer (float) – Outer diameter of the FFT spots. Effectively the diameter of the
positive Gaussian.
delta (float, default 0.05) – Increment of the automatic filtering with the negative Gaussian.
Setting this very small will slow down the function, but too high will
not allow the function to calculate negative Gaussians near zero.
sampling (float) – image sampling in units/pixel. If set to None, the image.axes_manager
will be used.
units (str) – Real space units. sampling should then be the value of
these units/pixel. If set to None, the image.axes_manager
will be used.
filename (str, default None) – If set to a string, the following files will be plotted and saved:
negative Gaussian optimumisation, negative Gaussian, positive Gaussian,
double Gaussian, FFT and double Gaussian convolution, filtered image,
filtered variables table.
The same as atomap’s integrate, except instead of summing the
region around an atom, it removes the value from all pixels in
that region.
For example, with this you can remove the local background intensity
by setting reduce_func=np.min.
Parameters:
reduce_func (ufunc, default np.min) – function used to reduce the pixel values around each atom
to a float.
function. (For the other parameters see Atomap's integrate)
Calculates mean and standard deviation of the distance from each atom to
its nearest neighbours.
Parameters:
sublattice (Atomap Sublattice object)
nearest_neighbours (int, default 5) – The number of nearest neighbours used to calculate the mean distance
from an atom. As in atomap, choosing 5 gets the 4 nearest
neighbours.
sampling (float, default None) – The image sampling in units/pixel. If set to None then the values
returned are given in pixels.
This may be changed in future versions if Atomap’s Sublattice pixel
attribute is updated.
Returns:
Two lists
Return type:
list of mean distances, list of standard deviations.
Use the initially found centre (mean/mode) value of a sublattice
histogram (e.g., Mo_1 in an Mo sublattice) as an input mean for a
gaussian fit of the data.
Parameters:
xdata (see scipy.optimize.curve_fit)
ydata (see scipy.optimize.curve_fit)
amp (see fit_1D_gaussian_to_data() for more details)
mu (see fit_1D_gaussian_to_data() for more details)
sigma (see fit_1D_gaussian_to_data() for more details)
Returns:
optimised parameters (popt) and estimated covariance (pcov) of the
Sets the ‘refine_position’ attribute of each Atom Position in a
sublattice using a range of intensities.
Parameters:
sublattice (Atomap Sublattice object)
min_cut_off_percent (float, default None) – The lower end of the intensity range is defined as
min_cut_off_percent * method value of max intensity list of
sublattice.
max_cut_off_percent (float, default None) – The upper end of the intensity range is defined as
max_cut_off_percent * method value of max intensity list of
sublattice.
range_type (str, default 'internal') – “internal” provides the refine_position attribute for each
AtomPosition as True if the intensity of that Atom Position
lies between the lower and upper limits defined by
min_cut_off_percent and max_cut_off_percent.
“external” provides the refine_position attribute for each
AtomPosition as True if the intensity of that Atom Position
lies outside the lower and upper limits defined by
min_cut_off_percent and max_cut_off_percent.
method (str, default 'mode') – The method used to aggregate the intensity of the sublattice positions
max intensity list. Options are “mode” and “mean”
percent_to_nn (float, default 0.05) – Determines the boundary of the area surrounding each atomic
column, as fraction of the distance to the nearest neighbour.
mask_radius (int, default None) – Radius in pixels of the mask.
filename (str, default None) – If set to a string, the Atomap refine_position image will be saved.
Return type:
list of the AtomPosition.refine_position=False attribute.
Examples
>>> fromtemul.dummy_dataimport(... get_simple_cubic_sublattice_positions_on_vac)>>> importtemul.apiastml>>> sublattice=get_simple_cubic_sublattice_positions_on_vac()>>> sublattice.find_nearest_neighbors()>>> sublattice.plot()>>> min_cut_off_percent=0.75>>> max_cut_off_percent=1.25>>> false_list_sublattice=tml.toggle_atom_refine_position_automatically(... sublattice,min_cut_off_percent,max_cut_off_percent,... range_type='internal',method='mode',percent_to_nn=0.05)>>> len(false_list_sublattice)# check how many atoms will not be refined12
Visually check which atoms will not be refined (red dots)
image (Hyperspy Signal2D) – This image.axes_manager scale should be calibrated.
d_inner (float, default 7.7) – Initial ‘guess’ of full width at half maximum (fwhm) of
inner (negative) gaussian to be applied to fft.
Can be changed with sliders during visualisation.
d_outer (float, default 14) – Initial ‘guess’ of full width at half maximum (fwhm) of
outer (positive) gaussian to be applied to fft.
Can be changed with sliders during visualisation.
slider_min (float, default 0.1) – Minimum value on sliders
slider_max (float, default 300) – Maximum value on sliders
slider_step (float, default 0.1) – Step size on sliders
plot_lims (tuple, default (0, 1)) – Used to plot a smaller section of the FFT image, which can be useful if
the information is very small (far away!). Default plots the whole
image.
Color sequences that are useful for creating matplotlib colormaps.
Info on “zesty” and other options:
venngage.com/blog/color-blind-friendly-palette/
Info on “r_safe”:
Google: r-plot-color-combinations-that-are-colorblind-accessible
Parameters:
palette (str) – Options are “zesty” (4 colours), and “r_safe” (12 colours).
Plots two line profiles on one image with the line profile intensities
in a subfigure.
See skimage PR PinkShnack for details on implementing profile_line
in skimage: https://github.com/scikit-image/scikit-image/pull/4206
Parameters:
image (2D Hyperspy signal)
line_profile_positions (list of lists) – two line profile coordinates. Use atomap’s am.add_atoms_with_gui()
function to get these. The first two dots will trace the first line
profile etc.
Could be extended to n positions with a basic loop.
linewidth (int, default 1) – see profile_line for parameter details.
if set to ‘Auto’ the function will attempt to find the sampling of
image from image.axes_manager[0].scale.
arrowstring, default None
If set, arrows will be plotting on the image. Options are ‘h’ and
‘v’ for horizontal and vertical arrows, respectively.
linetrace (int, default None) – If set, the line profile will be plotted on the image.
The thickness of the linetrace will be linewidth*linetrace.
Name could be improved maybe.
kwargs (Matplotlib keyword arguments passed to imshow())
Plots two line profiles on two images separately with the line
profile intensities in a subfigure.
See skimage PR PinkShnack for details on implementing profile_line
in skimage: https://github.com/scikit-image/scikit-image/pull/4206
Parameters:
imageA (2D Hyperspy signal)
imageB (2D Hyperspy signal)
line_profile_positions (list of lists) – one line profile coordinate. Use atomap’s am.add_atoms_with_gui()
function to get these. The two dots will trace the line profile.
See Examples below for example.
filename (string, default None) – If this is set to a name (string), the image will be saved with that
name.
reduce_func (ufunc, default np.mean) – See skimage’s profile_line reduce_func parameter for details.
linewidth (int, default 1) – see profile_line for parameter details.
sampling (float, default 'auto') – if set to ‘auto’ the function will attempt to find the sampling of
image from image.axes_manager[0].scale.
units (string, default 'nm')
crop_offset (int, default 20) – number of pixels away from the line_profile_positions
coordinates the image crop will be taken.
title (string, default "Intensity Profile") – Title of the plot
marker_A (Matplotlib marker)
marker_B (Matplotlib marker)
arrow_markersize (Matplotlib markersize)
figsize (see Matplotlib for details)
imageB_intensity_offset (float, default 0) – Adds a y axis offset for comparison purposes.
To use the new skimage functionality try the reduce_func parameter:
>>> importnumpyasnp>>> reduce_func=np.sum# can be any ufunc!>>> tml.compare_images_line_profile_two_images(... imageA,imageB,line_profile_positions,reduce_func=reduce_func,... linewidth=3,sampling=0.012,crop_offset=30)
By inputting the top-left and bottom-right coordinates of a rectangle, this
function will add a border buffer (crop_offset) which can be used for
cropping of regions in a plot.
See compare_images_line_profile_two_images for use-case
make the color_list from the HSV/RGB colorwheel.
This color_list will be the same length as u and as v.
It works by indexing the angle of the RGB (hue in HSV) array,
then indexing the magnitude (r) in the RGB (value in HSV) array,
leaving only a single RGB color for each vector.
Change from hexidecimal color values to rgb color values.
Grabs starting two, middle two, last two values in hex, multiplies by
16^1 and 16^0 for the first and second, respectively.
Parameters:
hex_values (list) – A list of hexidecimal color values as strings e.g., ‘#F5793A’
Create a matplotlib cmap from a palette with the help of
matplotlib.colors.from_levels_and_colors()
>>> frommatplotlib.colorsimportfrom_levels_and_colors>>> zest=tml.hex_to_rgb(tml.color_palettes('zesty'))>>> zest.append(zest[0])# make the top and bottom colour the same>>> cmap,norm=from_levels_and_colors(... levels=[0,1,2,3,4,5],colors=tml.rgb_to_dec(zest))
image (array-like, default None) – The first sublattice image is used if image=None.
vac_or_implants (string, default None) – vac_or_implants options are “implants” and “vac”.
elements_dict_other (dict, default None) – A dictionary of {element_config1: energy1, element_config2: energy2, }
The default is Se antisites in monolayer MoS2.
filename (string, default "energy_map") – Name with which to save the plot.
cmap (Matplotlib colormap, default "plasma")
levels (int, default 20) – Number of Matplotlib contour map levels.
top_level_directory (string) – The top-level directory in which the emd files exist. The default
glob_search will search this directory and all subdirectories.
glob_search (string) – Glob search string, see glob for more details:
https://docs.python.org/2/library/glob.html
Default will search this directory and all subdirectories.
overwrite (bool, default True) – Overwrite if the extension_to_save file already exists.
Convert from Vesta outputted xyz file format to the prismatic-style xyz
format.
Lose some information from the .cif or .vesta file but okay for now.
Develop your own converter if you need rms and occupancy! Lots to do.
vesta_xyz_filename (string) – name of the vesta outputted xyz file. See vesta > export > xyz
prismatic_xyz_filename (string) – name to be given to the outputted prismatic xyz file
delimiter (pandas.read_csv input parameters) – See pandas.read_csv for documentation
Note that the delimiters here are only available if you use
engine=’python’
header (pandas.read_csv input parameters) – See pandas.read_csv for documentation
Note that the delimiters here are only available if you use
engine=’python’
skiprows (pandas.read_csv input parameters) – See pandas.read_csv for documentation
Note that the delimiters here are only available if you use
engine=’python’
engine (pandas.read_csv input parameters) – See pandas.read_csv for documentation
Note that the delimiters here are only available if you use
engine=’python’
occupancy (see prismatic documentation) – if you want a file format that will retain these atomic attributes,
use a format other than vesta xyz. Maybe .cif or .vesta keeps these?
rms_thermal_vib (see prismatic documentation) – if you want a file format that will retain these atomic attributes,
use a format other than vesta xyz. Maybe .cif or .vesta keeps these?
header_comment (string) – header comment for the file.
save (bool, default True) – whether to output the file as a prismatic formatted xyz file with the
name of the file given by “prismatic_xyz_filename”.
Generate a test image signal of a simple cubic atomic structure.
Parameters:
image_noise (bool, default False) – If set to True, will add Gaussian noise to the image.
amplitude (int, list of ints, default 1) – If amplitude is set to an int, that int will be applied to all atoms in
the sublattice.
If amplitude is set to a list, the atoms will be a distribution set by
np.random.randint between the min and max int.
with_vacancies (bool, default False) – If set to True, the returned signal or sublattice will have some
vacancies.
Generate a test sublattice of a simple cubic atomic structure.
Parameters:
image_noise (bool, default False) – If set to True, will add Gaussian noise to the image.
amplitude (int, list of ints, default 1) – If amplitude is set to an int, that int will be applied to all atoms in
the sublattice.
If amplitude is set to a list, the atoms will be a distribution set by
np.random.randint between the min and max int.
with_vacancies (bool, default False) – If set to True, the returned signal or sublattice will have some
vacancies.
Check how the arrows will be plotted on a colorwheel.
Note that for STEM images, the y axis is reversed. This is taken into
account in the plot_polarisation_vectors function, but not here.
Parameters:
image_noise (default False) – If True, will add Gaussian noise to the image.