hyperspy.misc package

Submodules

hyperspy.misc.array_tools module

hyperspy.misc.array_tools.are_aligned(shape1, shape2)

Check if two numpy arrays are aligned.

Parameters:shape2 (shape1,) –
Returns:isaligned
Return type:bool
hyperspy.misc.array_tools.get_array_memory_size_in_GiB(shape, dtype)

Given the size and dtype returns the amount of memory that such an array needs to allocate

Parameters:
  • shape (tuple) –
  • dtype (data-type) – The desired data-type for the array.
hyperspy.misc.array_tools.homogenize_ndim(*args)

Given any number of arrays returns the same arrays reshaped by adding facing dimensions of size 1.

hyperspy.misc.array_tools.rebin(a, new_shape)

Rebin array.

rebin ndarray data into a smaller ndarray of the same rank whose dimensions are factors of the original dimensions. eg. An array with 6 columns and 4 rows can be reduced to have 6,3,2 or 1 columns and 4,2 or 1 rows.

Parameters:
  • a (numpy array) –
  • new_shape (tuple) – shape after binning
Returns:

Return type:

numpy array

Examples

>>> a=rand(6,4); b=rebin(a,(3,2))
>>> a=rand(6); b=rebin(a,(2,))

Notes

Adapted from scipy cookbook

hyperspy.misc.array_tools.sarray2dict(sarray, dictionary=None)

Converts a struct array to an ordered dictionary

Parameters:
  • sarray (struct array) –
  • dictionary (None or dic) – If dictionary is not None the content of sarray will be appended to the given dictonary
Returns:

Return type:

Ordered dictionary

hyperspy.misc.config_dir module

hyperspy.misc.elements module

hyperspy.misc.example_signals_loading module

hyperspy.misc.example_signals_loading.load_1D_EDS_SEM_spectrum()

Load an EDS-SEM spectrum

  • Sample: EDS-TM002 provided by BAM (www.webshop.bam.de)
  • SEM Microscope: Nvision40 Carl Zeiss
  • EDS Detector: X-max 80 from Oxford Instrument
hyperspy.misc.example_signals_loading.load_1D_EDS_TEM_spectrum()

Load an EDS-TEM spectrum

  • Sample: FePt bimetallic nanoparticles
  • SEM Microscope: Tecnai Osiris 200 kV D658 AnalyticalTwin
  • EDS Detector: Super-X 4 detectors Brucker

hyperspy.misc.hspy_warnings module

exception hyperspy.misc.hspy_warnings.VisibleDeprecationWarning

Bases: UserWarning

Visible deprecation warning. By default, python will not show deprecation warnings, so this class provides a visible one.

hyperspy.misc.hyperspy_magics module

class hyperspy.misc.hyperspy_magics.HyperspyMagics(shell=None, **kwargs)

Bases: IPython.core.magic.Magics

hyperspy(line)
%hyperspy [-r] [toolkit]

Load HyperSpy, numpy and matplotlib to work interactively.

%hyperspy runs the following commands in various cases:

>>> # if toolkit is "None" only
>>> import matplotlib
>>> matplotlib.use('Agg')
>>> # if toolkit is "qt4" only
>>> import os
>>> os.environ['QT_API'] = 'pyqt'
>>> # if toolkit is not "None"
>>> %matplotlib [toolkit]
>>> # run in all cases
>>> import numpy as np
>>> import hyperspy.api as hs
>>> import matplotlib.pyplot as plt
positional arguments:
toolkit Name of the matplotlib backend to use. If given, the
corresponding matplotlib backend is used, otherwise it will be the HyperSpy’s default. Available toolkits: {qt4, wx, None, gtk, tk}. Note that gtk and tk toolkits are not fully supported
optional arguments:
-r, --replace After running the the magic as usual, overwrites the current input cell with just executed code that can be run directly without magic
magics = {'cell': {}, 'line': {'hyperspy': 'hyperspy'}}
registered = True

hyperspy.misc.ipython_tools module

hyperspy.misc.ipython_tools.get_interactive_ns()
hyperspy.misc.ipython_tools.get_ipython()

Get the global InteractiveShell instance.

Returns None if no InteractiveShell instance is registered.

hyperspy.misc.ipython_tools.is_it_running_from_ipython()
hyperspy.misc.ipython_tools.turn_logging_off()
hyperspy.misc.ipython_tools.turn_logging_on(verbose=1)

hyperspy.misc.material module

hyperspy.misc.material.atomic_to_weight(atomic_percent, elements='auto')

Convert atomic percent to weight percent.

Parameters:
  • atomic_percent (list of float or list of signals) – The atomic fractions (composition) of the sample.
  • elements (list of str) – A list of element abbreviations, e.g. [‘Al’,’Zn’]. If elements is ‘auto’, take the elements in en each signal metadata of the atomic_percent list.
Returns:

weight_percent – composition in weight percent.

Return type:

as atomic_percent

Examples

Calculate the weight percent of modern bronze given its atomic percent: >>> hs.material.atomic_to_weight([93.2, 6.8], (“Cu”, “Sn”)) array([ 88.00501989, 11.99498011])

hyperspy.misc.material.density_of_mixture_of_pure_elements(weight_percent, elements='auto', mean='harmonic')

Calculate the density of a mixture of elements.

The density of the elements is retrieved from an internal database. The calculation is only valid if there is no interaction between the components.

Parameters:
  • weight_percent (list of float or list of signals) – A list of weight percent for the different elements. If the total is not equal to 100, each weight percent is divided by the sum of the list (normalization).
  • elements (list of str) – A list of element symbols, e.g. [‘Al’, ‘Zn’]. If elements is ‘auto’, take the elements in en each signal metadata of the weight_percent list.
  • mean ('harmonic' or 'weighted') – The type of mean use to estimate the density
Returns:

density

Return type:

The density in g/cm3.

Examples

Calculate the density of modern bronze given its weight percent: >>> hs.material.density_of_mixture_of_pure_elements(

(88, 12),(“Cu”, “Sn”))

8.6903187973131466

hyperspy.misc.material.weight_to_atomic(weight_percent, elements='auto')

Convert weight percent (wt%) to atomic percent (at.%).

Parameters:
  • weight_percent (list of float or list of signals) – The weight fractions (composition) of the sample.
  • elements (list of str) – A list of element abbreviations, e.g. [‘Al’,’Zn’]. If elements is ‘auto’, take the elements in en each signal metadata of th weight_percent list.
Returns:

atomic_percent – Composition in atomic percent.

Return type:

as weight_percent

Examples

Calculate the atomic percent of modern bronze given its weight percent: >>> hs.material.weight_to_atomic((88, 12), (“Cu”, “Sn”)) array([ 93.19698614, 6.80301386])

hyperspy.misc.math_tools module

hyperspy.misc.math_tools.antisymmetrize(a)
hyperspy.misc.math_tools.closest_nice_number(number)
hyperspy.misc.math_tools.get_linear_interpolation(p1, p2, x)

Given two points in 2D returns y for a given x for y = ax + b

Parameters:
  • p1,p2 ((x, y)) –
  • x (float) –
Returns:

y

Return type:

float

hyperspy.misc.math_tools.isfloat(number)

Check if a number or array is of float type.

This is necessary because e.g. isinstance(np.float32(2), float) is False.

hyperspy.misc.math_tools.order_of_magnitude(number)

Order of magnitude of the given number

Parameters:number (float) –
Returns:
Return type:Float
hyperspy.misc.math_tools.symmetrize(a)

hyperspy.misc.physical_constants module

hyperspy.misc.physics_tools module

hyperspy.misc.physics_tools.bragg_scattering_angle(d, E0=100)

Calculate the first order bragg diffraction semiangle.

Parameters:
  • d (float) – interplanar distance in m.
  • E0 (float) – Incident energy in keV
Returns:

  • float (Semiangle of scattering of the first order difracted beam. This is)
  • two times the bragg angle.

hyperspy.misc.physics_tools.effective_Z(Z_list, exponent=2.94)

Effective atomic number of a compound or mixture.

Exponent = 2.94 for X-ray absorption.

Parameters:Z_list (list of tuples) – A list of tuples (f,Z) where f is the number of atoms of the element in the molecule and Z its atomic number
Returns:
Return type:float

hyperspy.misc.rgb_tools module

hyperspy.misc.rgb_tools.is_rgb(array)
hyperspy.misc.rgb_tools.is_rgba(array)
hyperspy.misc.rgb_tools.is_rgbx(array)
hyperspy.misc.rgb_tools.regular_array2rgbx(data)
hyperspy.misc.rgb_tools.rgbx2regular_array(data, plot_friendly=False)

Transforms a RGBx array into a standard one

Parameters:
  • data (numpy array of RGBx dtype) –
  • plot_friendly (bool) – If True change the dtype to float when dtype is not uint8 and normalize the array so that it is ready to be plotted by matplotlib.

hyperspy.misc.signal_tools module

hyperspy.misc.signal_tools.are_signals_aligned(*args)

hyperspy.misc.tv_denoise module

hyperspy.misc.tv_denoise.tv_denoise(im, weight=50, eps=0.0002, keep_type=False, n_iter_max=200)

Perform total-variation denoising on 2-d and 3-d images

Parameters:
  • im (ndarray (2d or 3d) of ints, uints or floats) – input data to be denoised. im can be of any numeric type, but it is cast into an ndarray of floats for the computation of the denoised image.
  • weight (float, optional) – denoising weight. The greater weight, the more denoising (at the expense of fidelity to input)
  • eps (float, optional) –

    relative difference of the value of the cost function that determines the stop criterion. The algorithm stops when:

    (E_(n-1) - E_n) < eps * E_0
  • keep_type (bool, optional (False)) – whether the output has the same dtype as the input array. keep_type is False by default, and the dtype of the output is np.float
  • n_iter_max (int, optional) – maximal number of iterations used for the optimization.
Returns:

out – denoised array

Return type:

ndarray

Notes

The principle of total variation denoising is explained in http://en.wikipedia.org/wiki/Total_variation_denoising

The principle of total variation denoising is to minimize the total variation of the image, which can be roughly described as the integral of the norm of the image gradient. Total variation denoising tends to produce “cartoon-like” images, that is, piecewise-constant images.

This code is an implementation of the algorithm of Rudin, Fatemi and Osher that was proposed by Chambolle in [1].

References

[1]A. Chambolle, An algorithm for total variation minimization and applications, Journal of Mathematical Imaging and Vision, Springer, 2004, 20, 89-97.

Examples

>>> # 2D example using lena
>>> import scipy
>>> lena = scipy.lena().astype(np.float)
>>> lena += 0.5 * lena.std()*np.random.randn(*lena.shape)
>>> denoised_lena = tv_denoise(lena, weight=60)
>>> # 3D example on synthetic data
>>> x, y, z = np.ogrid[0:40, 0:40, 0:40]
>>> mask = (x -22)**2 + (y - 20)**2 + (z - 17)**2 < 8**2
>>> mask = mask.astype(np.float)
>>> mask += 0.2*np.random.randn(*mask.shape)
>>> res = tv_denoise_3d(mask, weight=100)

hyperspy.misc.utils module

class hyperspy.misc.utils.DictionaryTreeBrowser(dictionary=None)

Bases: object

A class to comfortably browse a dictionary using a CLI.

In addition to accessing the values using dictionary syntax the class enables navigating a dictionary that constains nested dictionaries as attribures of nested classes. Also it is an iterator over the (key, value) items. The __repr__ method provides pretty tree printing. Private keys, i.e. keys that starts with an underscore, are not printed, counted when calling len nor iterated.

export : saves the dictionary in pretty tree printing format in a text file.
keys : returns a list of non-private keys.
as_dictionary : returns a dictionary representation of the object.
set_item : easily set items, creating any necessary node on the way.
add_node : adds a node.

Examples

>>> tree = DictionaryTreeBrowser()
>>> tree.set_item("Branch.Leaf1.color", "green")
>>> tree.set_item("Branch.Leaf2.color", "brown")
>>> tree.set_item("Branch.Leaf2.caterpillar", True)
>>> tree.set_item("Branch.Leaf1.caterpillar", False)
>>> tree
└── Branch
    ├── Leaf1
    │   ├── caterpillar = False
    │   └── color = green
    └── Leaf2
        ├── caterpillar = True
        └── color = brown
>>> tree.Branch
├── Leaf1
│   ├── caterpillar = False
│   └── color = green
└── Leaf2
    ├── caterpillar = True
    └── color = brown
>>> for label, leaf in tree.Branch:
        print("%s is %s" % (label, leaf.color))
Leaf1 is green
Leaf2 is brown
>>> tree.Branch.Leaf2.caterpillar
True
>>> "Leaf1" in tree.Branch
True
>>> "Leaf3" in tree.Branch
False
>>>
add_dictionary(dictionary)

Add new items from dictionary.

add_node(node_path)

Adds all the nodes in the given path if they don’t exist.

Parameters:node_path (str) – The nodes must be separated by full stops (periods).

Examples

>>> dict_browser = DictionaryTreeBrowser({})
>>> dict_browser.add_node('First.Second')
>>> dict_browser.First.Second = 3
>>> dict_browser
└── First
    └── Second = 3
as_dictionary()

Returns its dictionary representation.

copy()
deepcopy()
export(filename, encoding='utf8')

Export the dictionary to a text file

Parameters:
  • filename (str) – The name of the file without the extension that is txt by default
  • encoding (valid encoding str) –
get_item(item_path)

Given a path, return True if it exists.

The nodes of the path are separated using periods.

Parameters:item_path (Str) – A string describing the path with each item separated by full stops (periods)

Examples

>>> dict = {'To' : {'be' : True}}
>>> dict_browser = DictionaryTreeBrowser(dict)
>>> dict_browser.has_item('To')
True
>>> dict_browser.has_item('To.be')
True
>>> dict_browser.has_item('To.be.or')
False
has_item(item_path)

Given a path, return True if it exists.

The nodes of the path are separated using periods.

Parameters:item_path (Str) – A string describing the path with each item separated by full stops (periods)

Examples

>>> dict = {'To' : {'be' : True}}
>>> dict_browser = DictionaryTreeBrowser(dict)
>>> dict_browser.has_item('To')
True
>>> dict_browser.has_item('To.be')
True
>>> dict_browser.has_item('To.be.or')
False
keys()

Returns a list of non-private keys.

set_item(item_path, value)

Given the path and value, create the missing nodes in the path and assign to the last one the value

Parameters:item_path (Str) – A string describing the path with each item separated by a full stops (periods)

Examples

>>> dict_browser = DictionaryTreeBrowser({})
>>> dict_browser.set_item('First.Second.Third', 3)
>>> dict_browser
└── First
   └── Second
        └── Third = 3
hyperspy.misc.utils.attrsetter(target, attrs, value)

Sets attribute of the target to specified value, supports nested attributes. Only creates a new attribute if the object supports such behaviour (e.g. DictionaryTreeBrowser does)

Parameters:
  • target (object) –
  • attrs (string) – attributes, separated by periods (e.g. ‘metadata.Signal.Noise_parameters.variance’ )
  • value (object) –

Example

First create a signal and model pair:

>>> s = hs.signals.Signal1D(np.arange(10))
>>> m = s.create_model()
>>> self.signal.data
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

Now set the data of the model with attrsetter >>> attrsetter(m, ‘signal1D.data’, np.arange(10)+2) >>> self.signal.data array([2, 3, 4, 5, 6, 7, 8, 9, 10, 10])

The behaviour is identical to >>> self.signal.data = np.arange(10) + 2

hyperspy.misc.utils.closest_power_of_two(n)
hyperspy.misc.utils.ensure_unicode(stuff, encoding='utf8', encoding2='latin-1')
hyperspy.misc.utils.find_subclasses(mod, cls)

Find all the subclasses in a module.

Parameters:
  • mod (module) –
  • cls (class) –
Returns:

Return type:

dictonary in which key, item = subclass name, subclass

hyperspy.misc.utils.fsdict(nodes, value, dictionary)

Populates the dictionary ‘dic’ in a file system-like fashion creating a dictionary of dictionaries from the items present in the list ‘nodes’ and assigning the value ‘value’ to the innermost dictionary.

‘dic’ will be of the type: dic[‘node1’][‘node2’][‘node3’]...[‘nodeN’] = value where each node is like a directory that contains other directories (nodes) or files (values)

hyperspy.misc.utils.generate_axis(origin, step, N, index=0)

Creates an axis given the origin, step and number of channels

Alternatively, the index of the origin channel can be specified.

Parameters:
  • origin (float) –
  • step (float) –
  • N (number of channels) –
  • index (int) – index of origin
Returns:

Return type:

Numpy array

hyperspy.misc.utils.isiterable(obj)
hyperspy.misc.utils.ordinal(value)

Converts zero or a postive integer (or their string representations) to an ordinal value.

>>> for i in range(1,13):
...     ordinal(i)
...
u'1st'
u'2nd'
u'3rd'
u'4th'
u'5th'
u'6th'
u'7th'
u'8th'
u'9th'
u'10th'
u'11th'
u'12th'
>>> for i in (100, '111', '112',1011):
...     ordinal(i)
...
u'100th'
u'111th'
u'112th'
u'1011th'

Notes

Author: Serdar Tumgoren http://code.activestate.com/recipes/576888-format-a-number-as-an-ordinal/ MIT license

hyperspy.misc.utils.rollelem(a, index, to_index=0)

Roll the specified axis backwards, until it lies in a given position.

Parameters:
  • a (list) – Input list.
  • index (int) – The index of the item to roll backwards. The positions of the items do not change relative to one another.
  • to_index (int, optional) – The item is rolled until it lies before this position. The default, 0, results in a “complete” roll.
Returns:

res – Output list.

Return type:

list

hyperspy.misc.utils.shorten_name(name, req_l)
hyperspy.misc.utils.slugify(value, valid_variable_name=False)

Normalizes string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphens.

Adapted from Django’s “django/template/defaultfilters.py”.

hyperspy.misc.utils.stack(signal_list, axis=None, new_axis_name='stack_element', mmap=False, mmap_dir=None)

Concatenate the signals in the list over a given axis or a new axis.

The title is set to that of the first signal in the list.

Parameters:
  • signal_list (list of Signal instances) –
  • axis ({None, int, str}) – If None, the signals are stacked over a new axis. The data must have the same dimensions. Otherwise the signals are stacked over the axis given by its integer index or its name. The data must have the same shape, except in the dimension corresponding to axis.
  • new_axis_name (string) – The name of the new axis when axis is None. If an axis with this name already exists it automatically append ‘-i’, where i are integers, until it finds a name that is not yet in use.
  • mmap (bool) – If True and stack is True, then the data is stored in a memory-mapped temporary file.The memory-mapped data is stored on disk, and not directly loaded into memory. Memory mapping is especially useful for accessing small fragments of large files without reading the entire file into memory.
  • mmap_dir (string) – If mmap_dir is not None, and stack and mmap are True, the memory mapped file will be created in the given directory, otherwise the default directory is used.
Returns:

signal – signal list)

Return type:

Signal instance (or subclass, determined by the objects in

Examples

>>> data = np.arange(20)
>>> s = hs.stack([hs.signals.Signal1D(data[:10]), hs.signals.Signal1D(data[10:])])
>>> s
<Spectrum, title: Stack of , dimensions: (2, 10)>
>>> s.data
array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]])
hyperspy.misc.utils.str2num(string, **kargs)

Transform a a table in string form into a numpy array

Parameters:string (string) –
Returns:
Return type:numpy array
hyperspy.misc.utils.strlist2enumeration(lst)
hyperspy.misc.utils.swapelem(obj, i, j)

Swaps element having index i with element having index j in object obj IN PLACE.

E.g. >>> L = [‘a’, ‘b’, ‘c’] >>> spwapelem(L, 1, 2) >>> print L

[‘a’, ‘c’, ‘b’]
hyperspy.misc.utils.underline(line, character='-')

Return the line underlined.

hyperspy.misc.utils.unfold_if_multidim(signal)

Unfold the SI if it is 2D

Parameters:signal (Signal instance) –
Returns:
Return type:Boolean. True if the SI was unfolded by the function.
hyperspy.misc.utils.without_nans(data)

Module contents