Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Python script to load any format supported by hyperspy directly into GMS 3.4+
'''
Python script to load any format supported by hyperspy directly into GMS
Must be copied and pasted into Gatan DigitalMicrograph (aka Gatan Microscopy Suite) version 3.4+
Call by `load_img(filepath)` at the bottom of the script. Can not be called outside of GMS.
Does not automatically convert the data type to EELS or EDS
Written by Thomas Aarholt, see https://gist.github.com/thomasaarholt/fccf06d56ff84cf76345b44dae30871e for newer versions
Feedback and forks are very welcome.
If the script runs forever, then this is due to a bug with numpy's FFT algorithm.
To fix, in hyperspy\_signals\signal2d.py, move the line
`from skimage.feature.register_translation import _upsampled_dft`
into the first line in `estimate_image_shift` in the same file.
v. 0.3: Added delete statements to ensure python objects don't stay in memory.
v. 0.4: Added explanation for when GMS python freezes due to a numpy/GMS bug.
v. 0.5: Fix bug in offset of axes manager in DM
v. 0.6: Fix wrong order of axes calibrations
v. 0.7: Add automatic recognition of EDS and EELS spectra and support for undefined units
'''
import DigitalMicrograph as DM
import hyperspy.api as hs
from pathlib import Path
import traits
def load_img(path):
s = hs.load(path)
if type(s) is list:
for si in s:
process_signal(si, path=path)
else:
process_signal(s, path=path)
del s
def process_signal(s, path=""):
axes = s.axes_manager._axes
# DM indexes oppositely to numpy, must transpose
# Use hyperspy transpose to avoid having to fiddle with swapping axes
s = s.T
# Create and calibrate DM file
img = DM.CreateImage(s.data.copy()) # (copy to avoid array being a view)
img.SetName(s.metadata.General.title)
# If EDS or EELS, add metadata before showing so that it is recognised as that type
try:
sigtype = s.metadata.Signal.signal_type
if "EDS" in sigtype:
imgTG = img.GetTagGroup()
imgTG.SetTagAsString( "Meta Data:Signal","X-ray")
elif "EELS" in sigtype:
imgTG = img.GetTagGroup()
imgTG.SetTagAsString( "Meta Data:Signal","EELS")
except:
pass
for ax in axes:
offset = ax.offset
scale = ax.scale
unit = ax.units
# blank units are a special trait that GMS can't handle
if type(unit) is traits.trait_base._Undefined:
unit = ""
index = ax.index_in_axes_manager
img.SetDimensionCalibration(index, offset, scale, unit, 0)
img.ShowImage()
del s
del img
# In windows we can put the letter r in front of strings to be able to
# use backslash \ in addresses
load_img(r"C:\Users\username\Documents\test.hspy") # Replace filename here
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.