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.dict2sarray(dictionary, sarray=None, dtype=None)

Populates a struct array from a dictionary

Parameters:
  • dictionary (dict) –
  • sarray (struct array or None) – Either sarray or dtype must be given. If sarray is given, it is populated from the dictionary.
  • dtype (None, numpy dtype or dtype list) – If sarray is None, dtype must be given. If so, a new struct array is created according to the dtype, which is then populated.
Returns:

Return type:

Structure array

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.jit_ifnumba(func)
hyperspy.misc.array_tools.rebin(a, new_shape=None, scale=None, crop=True)

Rebin array.

rebin ndarray data into a smaller or larger array based on a linear interpolation. Specify either a new_shape or a scale. Scale of 1== no binning. Scale less than one results in up-sampling.

Parameters:
  • a (numpy array) –
  • new_shape (a list of floats or integer, default None) – For each dimension specify the new_shape of the np.array. This will then be converted into a scale.
  • scale (a list of floats or integer, default None) – For each dimension specify the new:old pixel ratio, e.g. a ratio of 1 is no binning and a ratio of 2 means that each pixel in the new spectrum is twice the size of the pixels in the old spectrum. The length of the list should match the dimension of the numpy array. *Note : Only one of scale or new_shape should be specified otherwise the function will not run*
  • crop (bool, default True) –

    When binning by a non-integer number of pixels it is likely that the final row in each dimension contains less than the full quota to fill one pixel.

    e.g. 5*5 array binned by 2.1 will produce two rows containing 2.1 pixels and one row containing only 0.8 pixels worth. Selection of crop=’True’ or crop=’False’ determines whether or not this ‘black’ line is cropped from the final binned array or not.

    Please note that if crop=False is used, the final row in each dimension may appear black, if a fractional number of pixels are left over. It can be removed but has been left to preserve total counts before and after binning.

Returns:

Return type:

numpy array

Examples

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

Notes

Fast re_bin function 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 dict) – 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.date_time_tools module

hyperspy.misc.date_time_tools.ISO_format_to_serial_date(date, time, timezone='UTC')

Convert ISO format to a serial date.

hyperspy.misc.date_time_tools.datetime_to_serial_date(dt)

Convert datetime.datetime object to a serial date.

hyperspy.misc.date_time_tools.get_date_time_from_metadata(metadata, formatting='ISO')

Get the date and time from a metadata tree.

Parameters:
  • metadata (metadata object) –
  • formatting (string, ('ISO', 'datetime', 'datetime64')) – Default: ‘ISO’. This parameter set the formatting of the date, and the time, it can be ISO 8601 string, datetime.datetime or a numpy.datetime64 object. In the later case, the time zone is not supported.
Returns:

Return type:

string, datetime.datetime or numpy.datetime64 object

Example

>>> s = hs.load("example1.msa")
>>> s.metadata
    ├── General
    │   ├── date = 1991-10-01
    │   ├── original_filename = example1.msa
    │   ├── time = 12:00:00
    │   └── title = NIO EELS OK SHELL
>>> s = get_date_time_from_metadata(s.metadata)
'1991-10-01T12:00:00'
>>> s = get_date_time_from_metadata(s.metadata, formatting='ISO')
'1991-10-01T12:00:00'
>>> s = get_date_time_from_metadata(s.metadata, formatting='datetime')
>>> s = get_date_time_from_metadata(s.metadata, formatting='datetime64')
hyperspy.misc.date_time_tools.serial_date_to_ISO_format(serial)

Convert serial_date to a tuple of string (date, time, time_zone) in ISO format. By default, the serial date is converted in local time zone.

hyperspy.misc.date_time_tools.serial_date_to_datetime(serial)

Convert serial date to a datetime.datetime object.

hyperspy.misc.date_time_tools.update_date_time_in_metadata(dt, metadata)

Update the date and time in a metadata tree.

Parameters:
  • dt (date and time information: it can be a ISO 8601 string,) – a datetime.datetime or a numpy.datetime64 object
  • metadata (metadata object to update) –
Returns:

Return type:

metadata object

Example

>>> s = hs.load("example1.msa")
>>> dt = '2016-12-12T12:12:12-05:00'
>>> s.metadata = update_date_time_in_metadata(dt, s.metadata)
>>> s.metadata
    ├── General
    │   ├── date = 2016-12-12
    │   ├── original_filename = example1.msa
    │   ├── time = 12:12:12
    │   ├── time_zone = 'EST'
    │   └── title = NIO EELS OK SHELL

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

Notes

  • 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

Notes

  • Sample: FePt bimetallic nanoparticles
  • SEM Microscope: Tecnai Osiris 200 kV D658 AnalyticalTwin
  • EDS Detector: Super-X 4 detectors Brucker
hyperspy.misc.example_signals_loading.load_object_hologram()

Load an object hologram image

Notes

  • Sample: Fe needle with YOx nanoparticle inclusions [Migunov, V. et al.

Model-independent measurement of the charge density distribution along an Fe atom probe needle using off-axis electron holography without mean inner potential effects. Journal of Applied Physics 117, 134301 (2015). https://doi.org/10.1063/1.4916609] - TEM Microscope: FEI Titan G2 60-300 HOLO [Boothroyd, C. et al. FEI Titan G2 60-300 HOLO. Journal of large-scale research facilities JLSRF 2, 44 (2016). https://doi.org/10.17815/jlsrf-2-70]

hyperspy.misc.example_signals_loading.load_reference_hologram()

Load a reference hologram image

Notes

  • Sample: Fe needle with YOx nanoparticle inclusions [Migunov, V. et al.

Model-independent measurement of the charge density distribution along an Fe atom probe needle using off-axis electron holography without mean inner potential effects. Journal of Applied Physics 117, 134301 (2015). https://doi.org/10.1063/1.4916609] - TEM Microscope: FEI Titan G2 60-300 HOLO [Boothroyd, C. et al. FEI Titan G2 60-300 HOLO. Journal of large-scale research facilities JLSRF 2, 44 (2016). https://doi.org/10.17815/jlsrf-2-70]

hyperspy.misc.export_dictionary module

hyperspy.misc.export_dictionary.check_that_flags_make_sense(flags)
hyperspy.misc.export_dictionary.export_to_dictionary(target, whitelist, dic, fullcopy=True)

Exports attributes of target from whitelist.keys() to dictionary dic All values are references only by default.

Parameters:
  • target (object) – must contain the (nested) attributes of the whitelist.keys()
  • whitelist (dictionary) –

    A dictionary, keys of which are used as attributes for exporting. Key ‘self’ is only available with tag ‘id’, when the id of the target is saved. The values are either None, or a tuple, where:

    • the first item a string, which containts flags, separated by

    commas. - the second item is None if no ‘init’ flag is given, otherwise the object required for the initialization.

    The flag conventions are as follows: * ‘init’:

    object used for initialization of the target. The object is saved in the tuple in whitelist
    • ’fn’:
      the targeted attribute is a function, and may be pickled. A tuple of (thing, value) will be exported to the dictionary, where thing is None if function is passed as-is, and True if dill package is used to pickle the function, with the value as the result of the pickle.
    • ’id’:
      the id of the targeted attribute is exported (e.g. id(target.name))
    • ’sig’:
      The targeted attribute is a signal, and will be converted to a dictionary if fullcopy=True
  • dic (dictionary) – A dictionary where the object will be exported
  • fullcopy (bool) – Copies of objects are stored, not references. If any found, functions will be pickled and signals converted to dictionaries
hyperspy.misc.export_dictionary.load_from_dictionary(target, dic)

Loads attributes of target to dictionary dic The attribute list is read from dic[‘_whitelist’].keys()

Parameters:
  • target (object) – must contain the (nested) attributes of the whitelist.keys()
  • dic (dictionary) –

    A dictionary, containing field ‘_whitelist’, which is a dictionary with all keys that were exported, with values being flag strings. The convention of the flags is as follows: * ‘init’:

    object used for initialization of the target. Will be copied to the _whitelist after loading
    • ’fn’:
      the targeted attribute is a function, and may have been pickled (preferably with dill package).
    • ’id’:
      the id of the original object was exported and the attribute will not be set. The key has to be ‘_id_’
    • ’sig’:
      The targeted attribute was a signal, and may have been converted to a dictionary if fullcopy=True
hyperspy.misc.export_dictionary.parse_flag_string(flags)
hyperspy.misc.export_dictionary.reconstruct_object(flags, value)

Reconstructs the value (if necessary) after having saved it in a dictionary

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(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([88, 12],[‘Cu’, ‘Sn’]) 8.6903187973131466

hyperspy.misc.material.mass_absorption_coefficient(element, energies)

Mass absorption coefficient (mu/rho) of a X-ray absorbed in a pure material.

The mass absorption is retrieved from the database of Chantler2005

Parameters:
  • element (str) – The element symbol of the absorber, e.g. ‘Al’.
  • energies (float or list of float or str or list of str) – The energy or energies of the X-ray in keV, or the name of the X-rays, e.g. ‘Al_Ka’.
Returns:

Return type:

mass absorption coefficient(s) in cm^2/g

Examples

>>> hs.material.mass_absorption_coefficient(
>>>     element='Al', energies=['C_Ka','Al_Ka'])
array([ 26330.38933818,    372.02616732])

See also

hs.material.mass_absorption_mixture()

Note

See http://physics.nist.gov/ffast Chantler, C.T., Olsen, K., Dragoset, R.A., Kishore, A.R., Kotochigova, S.A., and Zucker, D.S. (2005), X-Ray Form Factor, Attenuation and Scattering Tables (version 2.1).

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

Calculate the mass absorption coefficient for X-ray absorbed in a mixture of elements.

The mass absorption coefficient is calculated as a weighted mean of the weight percent and is retrieved from the database of Chantler2005.

Parameters:
  • weight_percent (list of float or list of signals) – The composition of the absorber(s) in weight percent. The first dimension of the matrix corresponds to the elements.
  • elements (list of str or 'auto') – The list of element symbol of the absorber, e.g. [‘Al’,’Zn’]. If elements is ‘auto’, take the elements in each signal metadata of the weight_percent list.
  • energies (list of float or list of str or 'auto') – The energy or energies of the X-ray in keV, or the name of the X-rays, e.g. ‘Al_Ka’. If ‘auto’, take the lines in each signal metadata of the weight_percent list.

Examples

>>> hs.material.mass_absorption_mixture(
>>>     elements=['Al','Zn'], weight_percent=[50,50], energies='Al_Ka')
2587.41616439
Returns:
  • float or array of float
  • mass absorption coefficient(s) in cm^2/g

See also

hs.material.mass_absorption_coefficient()

Note

See http://physics.nist.gov/ffast Chantler, C.T., Olsen, K., Dragoset, R.A., Kishore, A.R., Kotochigova, S.A., and Zucker, D.S. (2005), X-Ray Form Factor, Attenuation and Scattering Tables (version 2.1).

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.anyfloatin(things)

Check if iterable contains any non integer.

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, ignore_axis=None)
hyperspy.misc.signal_tools.broadcast_signals(*args, ignore_axis=None)

Broadcasts all passed signals according to the HyperSpy broadcasting rules: signal and navigation spaces are each separately broadcasted according to the numpy broadcasting rules. One axis can be ignored and left untouched (or set to be size 1) across all signals.

Parameters:
  • *args (BaseSignal) – Signals to broadcast together
  • ignore_axis ({None, str, int, Axis}) – The axis to be ignored when broadcasting
Returns:

Return type:

list of signals

hyperspy.misc.slicing module

class hyperspy.misc.slicing.FancySlicing

Bases: object

class hyperspy.misc.slicing.SpecialSlicers(obj, isNavigation)

Bases: object

hyperspy.misc.slicing.copy_slice_from_whitelist(_from, _to, dims, both_slices, isNav, order=None)

Copies things from one object to another, according to whitelist, slicing where required.

Parameters:
  • _from (object) – Original object
  • _to (object) – Target object
  • dims (tuple) – (navigation_dimensions, signal_dimensions) of the original object that is sliced
  • both_slices (tuple) – (original_slices, array_slices) of the operation that is performed
  • isNav (bool) – if the slicing operation is performed on navigation dimensions of the object
  • order (tuple, None) – if given, performs the copying in the order given. If not all attributes given, the rest is random (the order a whitelist.keys() returns them). If given in the object, _slicing_order is looked up.

hyperspy.misc.test_utils module

hyperspy.misc.test_utils.all_warnings()

Context for use in testing to ensure that all warnings are raised. .. rubric:: Examples

>>> import warnings
>>> def foo():
...     warnings.warn(RuntimeWarning("bar"))
We raise the warning once, while the warning filter is set to "once".
Hereafter, the warning is invisible, even with custom filters:
>>> with warnings.catch_warnings():
...     warnings.simplefilter('once')
...     foo()
We can now run ``foo()`` without a warning being raised:
>>> from numpy.testing import assert_warns
>>> foo()
To catch the warning, we call in the help of ``all_warnings``:
>>> with all_warnings():
...     assert_warns(RuntimeWarning, foo)
hyperspy.misc.test_utils.assert_deep_almost_equal(actual, expected, *args, **kwargs)

Assert that two complex structures have almost equal contents. Compares lists, dicts and tuples recursively. Checks numeric values using assert_allclose() and checks all other values with assert_equal(). Accepts additional positional and keyword arguments and pass those intact to assert_allclose() (that’s how you specify comparison precision). :param actual: :type actual: lists, dicts or tuples :param expected: :type expected: lists, dicts or tuples

hyperspy.misc.test_utils.assert_warns(message=None, category=None)

Context for use in testing to catch known warnings matching regexes

Parameters:
  • message ((list of) strings or compiled regexes) – Regexes for the desired warning to catch
  • category (type or list of types) – Warning categories for the desired warning to catch

Examples

>>> from skimage import data, img_as_ubyte, img_as_float
>>> with assert_warns(['precision loss']):
...     d = img_as_ubyte(img_as_float(data.coins()))

Notes

Upon exiting, it checks the recorded warnings for the desired matching pattern(s). Raises a ValueError if any match was not found or an unexpected warning was raised. Allows for three types of behaviors: “and”, “or”, and “optional” matches. This is done to accomodate different build enviroments or loop conditions that may produce different warnings. The behaviors can be combined. If you pass multiple patterns, you get an orderless “and”, where all of the warnings must be raised. If you use the “|” operator in a pattern, you can catch one of several warnings. Finally, you can use “|AZ” in a pattern to signify it as optional.

hyperspy.misc.test_utils.check_running_tests_in_CI()
hyperspy.misc.test_utils.ignore_warning(message='', category=None)
hyperspy.misc.test_utils.sanitize_dict(dictionary)

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 ascent
>>> import scipy
>>> ascent = scipy.misc.ascent().astype(np.float)
>>> ascent += 0.5 * ascent.std()*np.random.randn(*ascent.shape)
>>> denoised_ascent = tv_denoise(ascent, 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, double_lines=False)

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, double_lines=False)

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, default=None)

Given a path, return it’s value if it exists, or default value if missing.

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)
  • default – The value to return if the path does not exist.

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.add_scalar_axis(signal)
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()
>>> m.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.create_map_objects(function, nav_size, iterating_kwargs, **kwargs)

To be used in _map_iterate of BaseSignal and LazySignal.

Moved to a separate method to reduce code duplication.

hyperspy.misc.utils.deprecation_warning(msg)
hyperspy.misc.utils.dummy_context_manager(*args, **kwargs)
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.iterable_not_string(thing)
hyperspy.misc.utils.map_result_construction(signal, inplace, result, ragged, sig_shape=None, lazy=False)
hyperspy.misc.utils.multiply(iterable)

Return product of sequence of numbers.

Equivalent of functools.reduce(operator.mul, iterable, 1).

>>> product([2**8, 2**30])
274877906944
>>> product([])
1
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)
...
'1st'
'2nd'
'3rd'
'4th'
'5th'
'6th'
'7th'
'8th'
'9th'
'10th'
'11th'
'12th'
>>> for i in (100, '111', '112',1011):
...     ordinal(i)
...
'100th'
'111th'
'112th'
'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.signal_range_from_roi(signal_range)
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', lazy=None, **kwargs)

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 BaseSignal 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.
  • lazy ({bool, None}) – Returns a LazySignal if True. If None, only returns lazy rezult if at least one is lazy.
Returns:

signal – signal list)

Return type:

BaseSignal 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
<Signal1D, 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.stash_active_state(model)
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.transpose(*args, signal_axes=None, navigation_axes=None, optimize=False)

Transposes all passed signals according to the specified options.

For parameters see BaseSignal.transpose.

Examples

>>> signal_iterable = [hs.signals.BaseSignal(np.random.random((2,)*(i+1)))
                       for i in range(3)]
>>> signal_iterable
[<BaseSignal, title: , dimensions: (|2)>,
 <BaseSignal, title: , dimensions: (|2, 2)>,
 <BaseSignal, title: , dimensions: (|2, 2, 2)>]
>>> hs.transpose(*signal_iterable, signal_axes=1)
[<BaseSignal, title: , dimensions: (|2)>,
 <BaseSignal, title: , dimensions: (2|2)>,
 <BaseSignal, title: , dimensions: (2, 2|2)>]
>>> hs.transpose(signal1, signal2, signal3, signal_axes=["Energy"])
hyperspy.misc.utils.underline(line, character='-')

Return the line underlined.

Module contents